from __future__ import annotations
import re
from typing import Any
_FFMPEG_PROGRESS_RE = re.compile(
r"frame=\s*(?P\d+).*?"
r"time=(?P\d+):(?P\d+):(?P\d+(?:\.\d+)?).*?"
r"speed=\s*(?P\d+(?:\.\d+)?)x",
re.IGNORECASE,
)
def normalize_log_text(text: str) -> str:
if not text:
return ""
return text.replace("\r\n", "\n").replace("\r", "\n")
def tail_log_text(text: str, max_lines: int) -> str:
normalized = normalize_log_text(text)
lines = normalized.splitlines()
if not lines:
return ""
return "\n".join(lines[-max_lines:]) + "\n"
def process_family(process_name: str) -> str:
low = (process_name or "").strip().lower()
if low.startswith("youtube") or low.startswith("douyin_youtube"):
return "youtube"
if low.startswith("tiktok"):
return "tiktok"
if low.startswith("obs"):
return "obs"
return "generic"
def _has_any(text: str, patterns: tuple[str, ...]) -> bool:
return any(p in text for p in patterns)
def _looks_like_youtube_key_rejected(tail: str) -> bool:
youtube_output = _has_any(
tail,
(
"rtmps://a.rtmps.youtube.com/live2/",
"rtmp://a.rtmp.youtube.com/live2/",
"youtube.com/live2/",
),
)
if not youtube_output:
return False
if not _has_any(tail, ("error opening output", "error opening output file", "error opening output files")):
return False
return _has_any(
tail,
(
"io error: end of file",
"input/output error",
"error in the pull function",
"tls @",
"401",
"403",
"unauthorized",
"forbidden",
),
)
def _looks_like_ffmpeg_progress(tail: str) -> bool:
return "frame=" in tail and "time=" in tail and _has_any(tail, ("bitrate=", "speed="))
def _looks_like_ffmpeg_starting(tail: str) -> bool:
return _has_any(
tail,
(
"starting ffmpeg",
"ffmpeg command",
"opening input",
"opening output",
"rtmps://a.rtmps.youtube.com/live2/",
"rtmp://a.rtmp.youtube.com/live2/",
"youtube.com/live2/",
),
)
def _ffmpeg_progress_samples(tail: str) -> list[dict[str, float | int]]:
samples: list[dict[str, float | int]] = []
for match in _FFMPEG_PROGRESS_RE.finditer(tail or ""):
try:
frame = int(match.group("frame"))
media_time = (
int(match.group("h")) * 3600
+ int(match.group("m")) * 60
+ float(match.group("s"))
)
speed = float(match.group("speed"))
except (TypeError, ValueError):
continue
samples.append({"frame": frame, "time": media_time, "speed": speed})
return samples[-8:]
def _ffmpeg_progress_stalled(samples: list[dict[str, float | int]]) -> bool:
if len(samples) < 3:
return False
tail = samples[-3:]
frames = {int(row["frame"]) for row in tail}
times = {round(float(row["time"]), 2) for row in tail}
return len(frames) == 1 and len(times) == 1
def _ffmpeg_speed_low(samples: list[dict[str, float | int]], threshold: float = 0.98) -> bool:
if len(samples) < 4:
return False
tail = samples[-4:]
if not all(float(row["speed"]) < threshold for row in tail):
return False
return int(tail[-1]["frame"]) > int(tail[0]["frame"]) or float(tail[-1]["time"]) > float(tail[0]["time"])
def coerce_declared_process_status(backend_mode: str, process_status: str, declared: bool) -> str:
status = (process_status or "").strip().lower()
mode = (backend_mode or "").strip().lower()
if declared and mode == "local" and status == "not_found":
return "configured"
return status
def summarize_process_activity(
process_name: str,
process_status: str,
recent_log: str,
recent_error: str,
*,
log_age_seconds: float | None = None,
ffmpeg_pids: list[int] | None = None,
) -> dict[str, Any]:
pids = sorted({int(pid) for pid in (ffmpeg_pids or []) if int(pid) > 0})
status = (process_status or "").strip().lower()
family = process_family(process_name)
tail = normalize_log_text(f"{recent_log}\n{recent_error}")[-8000:].lower()
progress_samples = _ffmpeg_progress_samples(tail)
latest_progress = progress_samples[-1] if progress_samples else {}
progress_stalled = _ffmpeg_progress_stalled(progress_samples)
speed_low = _ffmpeg_speed_low(progress_samples)
business_status = "inactive"
business_note = "Process is not running"
log_recent = log_age_seconds is None or log_age_seconds <= 20
has_recent_ffmpeg_progress = _looks_like_ffmpeg_progress(tail) and log_recent
has_ffmpeg_worker = bool(pids)
if family == "youtube" and not has_recent_ffmpeg_progress and _looks_like_youtube_key_rejected(tail):
business_status = "youtube_key_rejected"
business_note = (
"YouTube rejected the RTMPS output. The stream key is likely invalid, expired, "
"or not for this live event; if the key is correct, check network/proxy access to YouTube RTMPS."
)
elif status in {"online", "running"}:
if _has_any(tail, ("请在 ", "配置 key", "stream_key", "key=你的stream_key")):
business_status = "misconfigured"
business_note = "YouTube stream key is missing or invalid"
elif family == "youtube" and has_recent_ffmpeg_progress and has_ffmpeg_worker and progress_stalled:
business_status = "source_stalled"
business_note = "FFmpeg is running, but frame/time progress is stalled"
elif family == "youtube" and has_recent_ffmpeg_progress and has_ffmpeg_worker and speed_low:
business_status = "relay_slow"
business_note = "FFmpeg is running, but recent relay speed is below realtime"
elif has_recent_ffmpeg_progress:
business_status = "streaming"
business_note = "FFmpeg relay is emitting video frames"
elif family == "youtube" and has_ffmpeg_worker and _looks_like_ffmpeg_starting(tail) and log_recent:
business_status = "relay_starting"
business_note = "FFmpeg worker is present, but no video progress has been observed yet"
elif log_age_seconds is not None and log_age_seconds > 180:
business_status = "stale"
business_note = "Process is online but the log heartbeat is stale"
elif family == "youtube" and _has_any(
tail,
("等待直播", "循环等待", "检测直播间中", "没有正在监测的直播", "无录制任务", "网址内容获取失败"),
):
business_status = "waiting_source"
business_note = "Waiting for the upstream live source"
elif family == "youtube" and _has_any(
tail,
("开始推流到 youtube", "推流到 youtube", "正在直播中"),
):
business_status = "source_live"
business_note = "Upstream live detected, but no active relay worker is running"
elif "traceback" in tail or " error " in tail or "[error]" in tail or "错误信息" in tail:
business_status = "error"
business_note = "Recent error detected in the process log"
else:
business_status = "monitoring"
business_note = "Process is online and monitoring the source"
elif status == "configured":
business_status = "ready"
business_note = "Process is configured but not running"
elif status in {"stopped", "stopping"}:
business_note = "Process is stopped"
elif status == "invalid":
business_note = "Invalid process name"
return {
"business_status": business_status,
"business_note": business_note,
"ffmpeg_pids": pids,
"ffmpeg_active": bool(pids),
"log_age_seconds": log_age_seconds,
"ffmpeg_frame": latest_progress.get("frame"),
"ffmpeg_time_seconds": latest_progress.get("time"),
"ffmpeg_speed": latest_progress.get("speed"),
"ffmpeg_progress_stalled": progress_stalled,
"ffmpeg_speed_low": speed_low,
"is_pushing": business_status in {"streaming", "relay_slow"}
or (business_status == "source_stalled" and has_recent_ffmpeg_progress and has_ffmpeg_worker),
}