from __future__ import annotations import re import time from typing import Any from src.douyin_source_display import extract_douyin_source_meta _FFMPEG_KV_RE = re.compile(r"(?Pframe|fps|bitrate|speed|drop|dup)\s*=\s*(?P[^\s]+)", re.IGNORECASE) _TIME_RE = re.compile(r"time\s*=\s*(?P\d{2}:\d{2}:\d{2}(?:\.\d+)?)", re.IGNORECASE) _URL_RE = re.compile(r"https?://[^\s\"'<>]+", re.IGNORECASE) def _as_float(value: Any) -> float | None: text = str(value or "").strip().lower().replace("x", "").replace("kbits/s", "").replace("kb/s", "") text = text.replace(",", "") match = re.search(r"-?\d+(?:\.\d+)?", text) if not match: return None try: return float(match.group(0)) except ValueError: return None def _as_int(value: Any) -> int | None: parsed = _as_float(value) return None if parsed is None else max(0, int(parsed)) def parse_ffmpeg_metrics(*texts: str) -> dict[str, Any]: raw = "\n".join(str(item or "") for item in texts) tail = raw[-16000:] metrics: dict[str, Any] = {} for match in _FFMPEG_KV_RE.finditer(tail): key = match.group("key").lower() value = match.group("value") if key in {"frame", "drop", "dup"}: metrics[key] = _as_int(value) elif key in {"fps", "speed", "bitrate"}: metrics[key] = _as_float(value) time_match = None for time_match in _TIME_RE.finditer(tail): pass if time_match: metrics["encoded_time"] = time_match.group("value") lower = tail.lower() metrics["error_count"] = sum( lower.count(token) for token in ( "error", "failed", "connection refused", "timed out", "server returned", "broken pipe", "invalid data", "non-monotonous dts", "too many packets buffered", ) ) metrics["reconnect_count"] = sum(lower.count(token) for token in ("reconnect", "retry", "connection reset")) return metrics def _count_urls(text: str) -> int: return len(_URL_RE.findall(str(text or ""))) def _ini_has_enabled_rtmps(text: str) -> bool: lower = str(text or "").lower() return any(token in lower for token in ("rtmps = 是", "rtmps=true", "rtmps = true", "rtmps=1", "rtmps = 1")) def _ini_has_key(text: str) -> bool: return bool(re.search(r"^\s*key\s*=\s*\S+", str(text or ""), re.IGNORECASE | re.MULTILINE)) def _process_score(row: dict[str, Any], metrics: dict[str, Any]) -> tuple[int, list[dict[str, str]]]: score = 100 issues: list[dict[str, str]] = [] if not row.get("ffmpeg_active") and not row.get("is_pushing"): score -= 35 issues.append({"level": "critical", "text": "FFmpeg 未检测到推流进程"}) if not row.get("is_pushing"): score -= 25 issues.append({"level": "critical", "text": "当前没有稳定推流输出"}) speed = metrics.get("speed") if isinstance(speed, (int, float)) and speed < 0.98: score -= 18 issues.append({"level": "warning", "text": f"编码速度 {speed:.2f}x,低于实时直播要求"}) fps = metrics.get("fps") if isinstance(fps, (int, float)) and fps > 0 and fps < 24: score -= 10 issues.append({"level": "warning", "text": f"帧率偏低:{fps:.1f} fps"}) if int(metrics.get("error_count") or 0) > 0: score -= min(30, int(metrics.get("error_count") or 0) * 6) issues.append({"level": "warning", "text": "日志出现 FFmpeg/网络错误"}) if int(metrics.get("reconnect_count") or 0) > 2: score -= 10 issues.append({"level": "warning", "text": "源站或网络发生多次重连"}) if not issues and row.get("is_pushing"): issues.append({"level": "ok", "text": "推流链路正常,保持稳定即可"}) return max(0, min(100, score)), issues def build_youtube_quality_guard_report( rows: list[dict[str, Any]], *, live_summary: dict[str, Any] | None = None, config_by_process: dict[str, dict[str, str]] | None = None, ) -> dict[str, Any]: live_summary = live_summary or {} config_by_process = config_by_process or {} lanes: list[dict[str, Any]] = [] recommendations: list[dict[str, str]] = [] for row in rows: process = str(row.get("pm2") or row.get("process") or "") metrics = parse_ffmpeg_metrics(str(row.get("recent_log") or ""), str(row.get("recent_error") or "")) score, issues = _process_score(row, metrics) cfg = config_by_process.get(process) or {} source_meta = extract_douyin_source_meta(cfg.get("url_lines", ""), str(row.get("recent_log") or "")) source_title = str(source_meta.get("source_title") or row.get("source_title") or "").strip() source_room_id = str(source_meta.get("source_room_id") or row.get("source_room_id") or "").strip() source_url = str(source_meta.get("source_url") or row.get("source_url") or "").strip() source_display = str( source_meta.get("source_display") or row.get("source_display") or source_title or (f"抖音直播间 {source_room_id}" if source_room_id else "") ).strip() url_count = _count_urls(cfg.get("url_lines", "")) has_key = _ini_has_key(cfg.get("youtube_ini_text", "")) rtmps = _ini_has_enabled_rtmps(cfg.get("youtube_ini_text", "")) if not has_key: score = max(0, score - 30) issues.append({"level": "critical", "text": "YouTube 推流 key 未配置"}) if not rtmps: score = max(0, score - 8) issues.append({"level": "warning", "text": "建议使用 RTMPS 推流"}) if url_count == 0: score = max(0, score - 15) issues.append({"level": "warning", "text": "没有配置转播源 URL"}) lanes.append( { "process": process, "label": row.get("label") or process, "source_title": source_title, "source_room_id": source_room_id, "source_url": source_url, "source_display": source_display, "status": row.get("business_status") or row.get("process_status") or "", "is_pushing": bool(row.get("is_pushing")), "ffmpeg_active": bool(row.get("ffmpeg_active")), "score": score, "metrics": metrics, "url_count": url_count, "rtmps": rtmps, "has_stream_key": has_key, "issues": issues[:6], } ) active_events = int(((live_summary.get("stats") or {}).get("active_events") or len(live_summary.get("active") or [])) or 0) sample_count = int(((live_summary.get("stats") or {}).get("sample_count") or 0) or 0) viewer_peak = int(((live_summary.get("stats") or {}).get("viewer_peak") or 0) or 0) pushing_count = sum(1 for lane in lanes if lane["is_pushing"]) score = int(sum(lane["score"] for lane in lanes) / len(lanes)) if lanes else 0 if pushing_count == 0: recommendations.append({"level": "critical", "text": "没有正在推流的 YouTube 线路;推荐系统首先需要稳定不断流的直播信号"}) if active_events == 0 and pushing_count > 0: recommendations.append({"level": "warning", "text": "推流已存在但事件中心未形成活动事件,检查状态采集/Chrome 插件"}) if sample_count == 0: recommendations.append({"level": "warning", "text": "没有 Studio 页面采样;请在 Neko 打开 YouTube Studio 并保持插件启用"}) if all(lane.get("rtmps") for lane in lanes) and lanes: recommendations.append({"level": "ok", "text": "RTMPS 已启用,适合长期稳定直播"}) if viewer_peak > 0: recommendations.append({"level": "ok", "text": f"已采集到观众峰值 {viewer_peak},数据闭环正常"}) return { "generated_at": time.time(), "score": max(0, min(100, score)), "summary": { "lanes": len(lanes), "pushing_lanes": pushing_count, "active_events": active_events, "sample_count": sample_count, "viewer_peak": viewer_peak, }, "lanes": lanes, "recommendations": recommendations[:10], "ffmpeg_profile": { "target": "1080p30/RTMPS/AAC/stable input copy when possible", "guardrails": [ "保持 speed >= 1.00x", "长直播优先稳定码率与低错误率,而不是频繁重启", "Studio 弹窗、健康度、观众数必须持续采样", "源直播间断流时自动记录事件并提示切换备用 URL", ], }, }