This commit is contained in:
eric 2026-06-03 20:42:10 -05:00
parent 42327263e2
commit faaf0a61b0
33 changed files with 537 additions and 104 deletions

View File

@ -24,6 +24,11 @@ class StreamEnded(Exception):
pass
class SourceStalled(Exception):
"""当前直播源 URL 无进度,交回外层重新抓取源地址。"""
pass
_FFMPEG_STATS_PERIOD_OK: dict[str, bool] = {}
_FFMPEG_FILTERS_CACHE: dict[str, str] = {}
_FFMPEG_STATIC_CACHE: dict[str, bool] = {}
@ -132,6 +137,27 @@ def _stderr_reader_thread(proc, q):
pass
def _ffmpeg_progress_values(line: str) -> tuple[int | None, float | None]:
frame = None
media_time = None
m = re.search(r"frame=\s*(\d+)", line)
if m:
try:
frame = int(m.group(1))
except ValueError:
frame = None
m = re.search(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)", line)
if m:
try:
media_time = int(m.group(1)) * 3600 + int(m.group(2)) * 60 + float(m.group(3))
except ValueError:
media_time = None
return frame, media_time
def cleanup_proc(proc):
try:
if proc and proc.poll() is None:
@ -459,6 +485,11 @@ def _proxychains_command(ffmpeg_command: list[str], push_proxy: str, proxy_mode:
return ["proxychains4", "-q", "-f", conf, *ffmpeg_command]
def _record_cleanup_url(real_url: str, record_url: str | None) -> str:
original = (record_url or "").strip()
return original or real_url
def start_douyin_youtube_ffplay(
title: str,
anchor_name: str,
@ -471,6 +502,7 @@ def start_douyin_youtube_ffplay(
clear_record_info,
color_obj,
config_file: str | None = None,
record_url: str | None = None,
):
"""
抖音 → YouTube 推流主函数(单路推流)
@ -829,7 +861,6 @@ def start_douyin_youtube_ffplay(
"-filter_threads", _filter_threads,
*_ffmpeg_pre_input,
"-headers", douyin_headers,
"-re",
"-i", real_url,
# bilinear 比 lanczos 轻很多,利于 speed 稳定在 ≥1.0x
"-vf", _vf_pad,
@ -884,6 +915,8 @@ def start_douyin_youtube_ffplay(
reader_t.start()
start_time = last_frame_time = time.time()
last_progress_frame = -1
last_progress_time = -1.0
while True:
try:
@ -891,9 +924,9 @@ def start_douyin_youtube_ffplay(
line = stderr_q.get(timeout=STDERR_QUEUE_TIMEOUT)
except queue.Empty:
if time.time() - getattr(proc, "last_out_ts", time.time()) > STALE_OUTPUT_SECONDS:
print("[WARN] 长时间无任何日志,强制重启进程")
print("[WARN] 长时间无任何日志,交回监控循环重新获取直播源")
cleanup_proc(proc)
break
raise SourceStalled()
continue
if line is None:
@ -922,17 +955,25 @@ def start_douyin_youtube_ffplay(
retry_delay = min(max(retry_delay, INITIAL_RETRY_DELAY) * 2, MAX_RETRY_DELAY)
break
if re.search(r'frame=\s*\d+', line_lower) or "fps=" in line_lower:
last_frame_time = time.time()
retry_delay = INITIAL_RETRY_DELAY
frame, media_time = _ffmpeg_progress_values(line_lower)
if frame is not None or media_time is not None:
frame_advanced = frame is not None and frame > last_progress_frame
time_advanced = media_time is not None and media_time > last_progress_time + 0.01
if frame_advanced or time_advanced:
last_frame_time = time.time()
retry_delay = INITIAL_RETRY_DELAY
if frame is not None:
last_progress_frame = frame
if media_time is not None:
last_progress_time = media_time
if time.time() - start_time > START_CHECK_AFTER:
if time.time() - last_frame_time > NO_FRAME_TIMEOUT:
print(f"[WARN] 连续 {NO_FRAME_TIMEOUT}s 无新帧,判定主播已下播")
print(f"[WARN] 连续 {NO_FRAME_TIMEOUT}s 无新帧,交回监控循环重新获取直播源")
cleanup_proc(proc)
raise StreamEnded()
raise SourceStalled()
except StreamEnded:
except (StreamEnded, SourceStalled):
raise
except Exception as e:
print(f"[ERROR] 内层异常: {e}")
@ -947,6 +988,10 @@ def start_douyin_youtube_ffplay(
print(f"[INFO] 主播已下播,停止 YouTube 转推 → {record_name}")
break
except SourceStalled:
print(f"[WARN] 当前直播源无进度,返回监控循环刷新源地址 → {record_name}")
break
except Exception as e:
print(f"[ERROR] 外层异常: {e}")
traceback.print_exc()
@ -962,7 +1007,7 @@ def start_douyin_youtube_ffplay(
try:
recording_time_list.pop(record_name, None)
# 统一由 clear_record_info 维护 running_list / monitoring / url_comments
clear_record_info(record_name, real_url)
clear_record_info(record_name, _record_cleanup_url(real_url, record_url))
except Exception:
pass

0
d2ypp2/install.sh Normal file → Executable file
View File

View File

@ -426,6 +426,9 @@ load_env() {
NTFY_PORT="${NTFY_PORT:-8089}"
NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}"
NTFY_CACHE_DIR="${NTFY_CACHE_DIR:-/var/lib/live-ntfy/cache}"
export HOMEASSISTANT_IMAGE HOMEASSISTANT_PORT HOMEASSISTANT_CONFIG_DIR
export FRIGATE_IMAGE FRIGATE_WEB_PORT FRIGATE_RTSP_PORT FRIGATE_WEBRTC_PORT FRIGATE_SHM_SIZE FRIGATE_CONFIG_DIR FRIGATE_MEDIA_DIR FRIGATE_PRIVILEGED
export NTFY_IMAGE NTFY_PORT NTFY_CONFIG_DIR NTFY_CACHE_DIR
ENABLE_COTURN="${ENABLE_COTURN:-0}"
COTURN_IMAGE="${COTURN_IMAGE:-coturn/coturn:latest}"
COTURN_PORT="${COTURN_PORT:-3478}"

View File

@ -150,6 +150,9 @@ NTFY_IMAGE="${NTFY_IMAGE:-binwiederhier/ntfy:latest}"
NTFY_PORT="${NTFY_PORT:-8089}"
NTFY_CONFIG_DIR="${NTFY_CONFIG_DIR:-/var/lib/live-ntfy/config}"
NTFY_CACHE_DIR="${NTFY_CACHE_DIR:-/var/lib/live-ntfy/cache}"
export HOMEASSISTANT_IMAGE HOMEASSISTANT_PORT HOMEASSISTANT_CONFIG_DIR
export FRIGATE_IMAGE FRIGATE_WEB_PORT FRIGATE_RTSP_PORT FRIGATE_WEBRTC_PORT FRIGATE_SHM_SIZE FRIGATE_CONFIG_DIR FRIGATE_MEDIA_DIR FRIGATE_PRIVILEGED
export NTFY_IMAGE NTFY_PORT NTFY_CONFIG_DIR NTFY_CACHE_DIR
ENABLE_COTURN="${ENABLE_COTURN:-0}"
COTURN_IMAGE="${COTURN_IMAGE:-coturn/coturn:latest}"
COTURN_PORT="${COTURN_PORT:-3478}"
@ -1840,8 +1843,13 @@ service_neko_status() {
if ! neko_nat1to1_is_usable "${NEKO_WEBRTC_NAT1TO1:-}"; then
NEKO_WEBRTC_NAT1TO1="$(detect_preferred_lan_ip || true)"
fi
browser_proxy="${NEKO_BROWSER_PROXY:-$(resolve_neko_browser_proxy)}"
[ -n "$browser_proxy" ] || browser_proxy=direct
browser_proxy="${NEKO_BROWSER_PROXY:-}"
if [ -z "$browser_proxy" ]; then
case "$SHELLCRASH_ATTACH_NEKO" in
0|false|FALSE|off|OFF|none|NONE|direct|DIRECT) browser_proxy=direct ;;
*) browser_proxy=auto ;;
esac
fi
kv detail "image=$(resolve_neko_image); supervisor_conf=$(resolve_neko_supervisor_conf); start_url=${NEKO_START_URL}; nat1to1=${NEKO_WEBRTC_NAT1TO1:-unset}; instances=${running_count}/${total_count}; ports=${ports%,}; profiles=${profiles%,}; screen=${NEKO_DESKTOP_SCREEN}; shm=${NEKO_SHM_SIZE}; fps=${NEKO_MAX_FPS}; bitrate=${NEKO_VIDEO_BITRATE}; render=${NEKO_BROWSER_RENDER_MODE}; proxy=${browser_proxy}; containers=${states}"
}

View File

@ -35,6 +35,13 @@ SHELLCRASH_WEB_PANEL_PATH = "/ui/"
_PRO_URL_CONFIG_INI = re.compile(r"^URL_config\.[a-zA-Z0-9_.-]+\.ini$")
_PRO_YOUTUBE_INI = re.compile(r"^youtube\.[a-zA-Z0-9_.-]+\.ini$")
_NETWORK_RATE_CACHE: dict[str, Any] = {"timestamp": 0.0, "interfaces": {}}
_SERVICE_STATUS_CACHE_TTL_SECONDS = 8.0
_SERVICE_STATUS_CACHE: tuple[float, list[dict[str, Any]]] | None = None
def invalidate_service_status_cache() -> None:
global _SERVICE_STATUS_CACHE
_SERVICE_STATUS_CACHE = None
@dataclass(frozen=True)
@ -560,10 +567,10 @@ def _default_service_status(spec: ServiceSpec, detail: str) -> dict:
}
async def query_service(spec: ServiceSpec) -> dict:
async def query_service(spec: ServiceSpec, *, timeout: float = 20.0) -> dict:
if not SERVICE_CTL.is_file():
return _default_service_status(spec, "Service controller script is missing")
code, output = await _run_command([BASH_BIN, str(SERVICE_CTL), spec.service_id, "status"])
code, output = await _run_command([BASH_BIN, str(SERVICE_CTL), spec.service_id, "status"], timeout=timeout)
if code != 0:
return _default_service_status(spec, output or "Status command failed")
info = _parse_kv_output(output)
@ -582,8 +589,14 @@ async def query_service(spec: ServiceSpec) -> dict:
}
async def query_services() -> list[dict]:
return list(await asyncio.gather(*(query_service(spec) for spec in SERVICE_SPECS)))
async def query_services(*, timeout: float = 3.0) -> list[dict]:
global _SERVICE_STATUS_CACHE
now = time.monotonic()
if _SERVICE_STATUS_CACHE and now - _SERVICE_STATUS_CACHE[0] <= _SERVICE_STATUS_CACHE_TTL_SECONDS:
return [dict(row) for row in _SERVICE_STATUS_CACHE[1]]
rows = list(await asyncio.gather(*(query_service(spec, timeout=timeout) for spec in SERVICE_SPECS)))
_SERVICE_STATUS_CACHE = (time.monotonic(), [dict(row) for row in rows])
return rows
async def service_action(service_id: str, action: str) -> dict:
@ -597,6 +610,7 @@ async def service_action(service_id: str, action: str) -> dict:
if action == "status":
return await query_service(spec)
invalidate_service_status_cache()
cmd = [BASH_BIN, str(SERVICE_CTL), service_id, action]
code, output = await _run_command(cmd, timeout=45.0)
info = _parse_kv_output(output)
@ -609,6 +623,7 @@ async def service_action(service_id: str, action: str) -> dict:
"detail": output,
}
status = await query_service(spec)
invalidate_service_status_cache()
status["message"] = message or f"{action} completed"
return status

View File

@ -53,6 +53,10 @@ _process_backend: WebProcessBackend | None = None
_monitor_entries: list[dict[str, Any]] = []
_monitor_entries_provider: Callable[[], list[dict[str, Any]] | tuple[dict[str, Any], ...]] | None = None
_repo_root: Path | None = None
_DASHBOARD_CACHE_TTL_SECONDS = 1.0
_dashboard_cache: tuple[float, dict[str, Any]] | None = None
_TAIL_READ_CHUNK_BYTES = 16 * 1024
_TAIL_READ_MAX_BYTES = 192 * 1024
def configure_hub(
@ -60,7 +64,7 @@ def configure_hub(
monitor_entries: list[dict[str, Any]] | Callable[[], list[dict[str, Any]] | tuple[dict[str, Any], ...]],
repo_root: Optional[Path] = None,
) -> None:
global _process_backend, _monitor_entries, _monitor_entries_provider, _repo_root
global _process_backend, _monitor_entries, _monitor_entries_provider, _repo_root, _dashboard_cache
_process_backend = process_backend
if callable(monitor_entries):
_monitor_entries_provider = monitor_entries
@ -69,6 +73,7 @@ def configure_hub(
_monitor_entries_provider = None
_monitor_entries = list(monitor_entries)
_repo_root = repo_root.resolve() if repo_root is not None else None
_dashboard_cache = None
def hub_monitor_entries() -> list[dict[str, Any]]:
@ -80,6 +85,13 @@ def hub_monitor_entries() -> list[dict[str, Any]]:
return list(_monitor_entries)
async def _dashboard_or(awaitable, default: Any, timeout: float) -> Any:
try:
return await asyncio.wait_for(awaitable, timeout=timeout)
except Exception:
return default
def _coerce_hub_process_info(pb: WebProcessBackend, entry: dict[str, Any], info: dict[str, Any]) -> dict[str, Any]:
next_status = coerce_declared_process_status(
pb.mode,
@ -94,19 +106,43 @@ def _coerce_hub_process_info(pb: WebProcessBackend, entry: dict[str, Any], info:
def _tail_file_lines(path: str | None, max_lines: int, max_age_seconds: int | None = None) -> list[str]:
if not path:
if not path or max_lines <= 0:
return []
file_path = Path(path)
if not file_path.is_file():
return []
try:
stat = file_path.stat()
if not file_path.is_file():
return []
if max_age_seconds is not None and max(0, time.time() - stat.st_mtime) > max_age_seconds:
return []
lines = file_path.read_text(encoding="utf-8", errors="ignore").splitlines()
if stat.st_size <= 0:
return []
max_bytes = min(stat.st_size, _TAIL_READ_MAX_BYTES)
chunks: list[bytes] = []
bytes_read = 0
position = stat.st_size
newline_count = 0
with file_path.open("rb") as handle:
while position > 0 and bytes_read < max_bytes:
chunk_size = min(_TAIL_READ_CHUNK_BYTES, position, max_bytes - bytes_read)
position -= chunk_size
handle.seek(position)
chunk = handle.read(chunk_size)
if not chunk:
break
chunks.append(chunk)
bytes_read += len(chunk)
newline_count += chunk.count(b"\n")
if newline_count >= max_lines + 1:
break
except OSError:
return []
lines = [line.rstrip() for line in lines if line.strip()]
if not chunks:
return []
decoded_lines = b"".join(reversed(chunks)).decode("utf-8", errors="ignore").splitlines()
if position > 0 and decoded_lines:
decoded_lines = decoded_lines[1:]
lines = [line.rstrip() for line in decoded_lines if line.strip()]
return lines[-max_lines:] if len(lines) > max_lines else lines
@ -196,15 +232,20 @@ class YoutubeLiveCloseBody(BaseModel):
@router.get("/dashboard")
async def hub_dashboard() -> dict[str, Any]:
global _dashboard_cache
now = time.monotonic()
if _dashboard_cache and now - _dashboard_cache[0] <= _DASHBOARD_CACHE_TTL_SECONDS:
return _dashboard_cache[1]
snap = system_snapshot()
services = await query_services()
services = await _dashboard_or(query_services(timeout=3.0), [], 3.5)
if adb_available():
devices = await list_android_devices()
devices = await _dashboard_or(list_android_devices(), [], 1.5)
else:
devices = []
stack = stack_summary()
try:
probes = await stack_stream_probes()
probes = await _dashboard_or(stack_stream_probes(), {"srs": {}, "neko": {}, "error": "probe_timeout"}, 2.0)
except Exception:
probes = {"srs": {}, "neko": {}, "error": "probe_failed"}
@ -280,11 +321,11 @@ async def hub_dashboard() -> dict[str, Any]:
if not pm2_tail:
pm2_tail = fallback_live_event_lines(live_status.get("processes") or [], 16)
net_stats = network_iface_stats()
hardware = await load_hardware_profile(False)
redroid = await redroid_runtime_summary()
hdmi = await hdmi_capture_summary()
hardware = await _dashboard_or(load_hardware_profile(False), {}, 2.0)
redroid = await _dashboard_or(redroid_runtime_summary(), {}, 2.0)
hdmi = await _dashboard_or(hdmi_capture_summary(), {}, 2.0)
return {
payload = {
"snapshot": snap,
"hardware": hardware,
"stack": stack,
@ -312,6 +353,8 @@ async def hub_dashboard() -> dict[str, Any]:
],
},
}
_dashboard_cache = (time.monotonic(), payload)
return payload
@router.get("/config")

View File

@ -1,8 +1,17 @@
from __future__ import annotations
import re
from typing import Any
_FFMPEG_PROGRESS_RE = re.compile(
r"frame=\s*(?P<frame>\d+).*?"
r"time=(?P<h>\d+):(?P<m>\d+):(?P<s>\d+(?:\.\d+)?).*?"
r"speed=\s*(?P<speed>\d+(?:\.\d+)?)x",
re.IGNORECASE,
)
def normalize_log_text(text: str) -> str:
if not text:
return ""
@ -64,6 +73,41 @@ def _looks_like_ffmpeg_progress(tail: str) -> bool:
return "frame=" in tail and "time=" in tail and _has_any(tail, ("bitrate=", "speed="))
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()
@ -85,6 +129,10 @@ def summarize_process_activity(
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"
@ -102,6 +150,12 @@ def summarize_process_activity(
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 pids and progress_stalled:
business_status = "source_stalled"
business_note = "FFmpeg is running, but frame/time progress is stalled"
elif family == "youtube" and pids and speed_low:
business_status = "relay_slow"
business_note = "FFmpeg is running, but recent relay speed is below realtime"
elif pids or has_recent_ffmpeg_progress:
business_status = "streaming"
business_note = "FFmpeg relay worker is running" if pids else "FFmpeg relay is emitting video frames"
@ -140,5 +194,10 @@ def summarize_process_activity(
"ffmpeg_pids": pids,
"ffmpeg_active": bool(pids),
"log_age_seconds": log_age_seconds,
"is_pushing": business_status == "streaming",
"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"},
}

View File

@ -556,16 +556,18 @@ class WebProcessBackend:
self._pm2_last_daemon_pid: Optional[int] = None
self._pm2_last_resurrect_attempt: float = 0.0
self._pm2_last_start_attempt: dict[str, float] = {}
self._pm2_jlist_cache_ttl: float = 0.35
self._pm2_jlist_cache_ttl: float = 0.8
self._pm2_jlist_stale_grace: float = 2.0
self._pm2_jlist_cached_at: float = 0.0
self._pm2_jlist_cache: list[dict[str, Any]] | None = None
self._pm2_dump_cache_ttl: float = 5.0
self._pm2_dump_cached_at: float = 0.0
self._pm2_dump_names_cache: set[str] | None = None
self._proc_runtime_cache_ttl: float = 0.35
self._proc_runtime_cache_ttl: float = 0.8
self._proc_runtime_cached_at: float = 0.0
self._proc_runtime_cache: dict[str, dict[str, Any]] | None = None
self._ffmpeg_pid_cache_ttl: float = 0.8
self._ffmpeg_pid_cache: dict[tuple[str, int], tuple[float, list[int]]] = {}
async def refresh_mode(self) -> None:
self._use_pm2 = await pm2_available()
@ -594,6 +596,7 @@ class WebProcessBackend:
self._pm2_dump_cached_at = 0.0
self._proc_runtime_cache = None
self._proc_runtime_cached_at = 0.0
self._ffmpeg_pid_cache.clear()
def _pm2_home_dir(self) -> Path:
raw = (os.environ.get("PM2_HOME") or "").strip()
@ -1029,7 +1032,14 @@ class WebProcessBackend:
pgid = os.getpgid(pid)
except OSError:
pgid = None
return _linux_ffmpeg_pids_for_process_tree(pid, root_pgid=pgid)
cache_key = (str(process or "").strip(), pid)
now = time.monotonic()
cached = self._ffmpeg_pid_cache.get(cache_key)
if cached and now - cached[0] <= self._ffmpeg_pid_cache_ttl:
return list(cached[1])
result = await asyncio.to_thread(_linux_ffmpeg_pids_for_process_tree, pid, root_pgid=pgid)
self._ffmpeg_pid_cache[cache_key] = (now, list(result))
return result
async def _pm2_save(self) -> None:
if not self._use_pm2:

View File

@ -29,6 +29,24 @@ class HubRoutesTests(unittest.TestCase):
self.assertTrue(lines[0].startswith("[YouTube stderr]"))
self.assertTrue(lines[-1].endswith("stream ready"))
def test_fallback_live_event_lines_reads_large_logs_from_tail(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
out_path = Path(tmp) / "youtube-out.log"
out_path.write_text(
"".join(f"old line {i:05d}\n" for i in range(50000)) + "fresh one\nfresh two\n",
encoding="utf-8",
)
rows = [
{
"label": "YouTube",
"pm2": "youtube",
"out_path": str(out_path),
"err_path": None,
}
]
lines = fallback_live_event_lines(rows, max_lines=2)
self.assertEqual(lines, ["[YouTube stdout] fresh one", "[YouTube stdout] fresh two"])
def test_hub_dashboard_marks_local_declared_process_as_configured(self) -> None:
backend = type("StubBackend", (), {})()
backend.mode = "local"

View File

@ -112,6 +112,45 @@ class ProcessRuntimeStatusTests(unittest.TestCase):
self.assertEqual(state["business_status"], "streaming")
self.assertTrue(state["is_pushing"])
def test_summarize_process_activity_marks_source_stalled_when_progress_repeats(self) -> None:
state = summarize_process_activity(
"youtube",
"online",
"\n".join(
(
"[FFmpeg] frame= 2475 fps= 28 time=00:01:22.50 bitrate=4203.5kbits/s speed=0.948x",
"[FFmpeg] frame= 2475 fps= 28 time=00:01:22.50 bitrate=4203.5kbits/s speed=0.937x",
"[FFmpeg] frame= 2475 fps= 27 time=00:01:22.50 bitrate=4203.5kbits/s speed=0.927x",
)
),
"",
log_age_seconds=1.0,
ffmpeg_pids=[1234],
)
self.assertEqual(state["business_status"], "source_stalled")
self.assertFalse(state["is_pushing"])
self.assertTrue(state["ffmpeg_progress_stalled"])
def test_summarize_process_activity_marks_relay_slow_when_speed_stays_low(self) -> None:
state = summarize_process_activity(
"youtube",
"online",
"\n".join(
(
"[FFmpeg] frame= 1000 fps= 28 time=00:00:33.33 bitrate=4200.0kbits/s speed=0.95x",
"[FFmpeg] frame= 1028 fps= 28 time=00:00:34.26 bitrate=4200.0kbits/s speed=0.95x",
"[FFmpeg] frame= 1056 fps= 28 time=00:00:35.20 bitrate=4200.0kbits/s speed=0.96x",
"[FFmpeg] frame= 1084 fps= 28 time=00:00:36.13 bitrate=4200.0kbits/s speed=0.96x",
)
),
"",
log_age_seconds=1.0,
ffmpeg_pids=[1234],
)
self.assertEqual(state["business_status"], "relay_slow")
self.assertTrue(state["is_pushing"])
self.assertTrue(state["ffmpeg_speed_low"])
def test_summarize_process_activity_marks_stale_when_heartbeat_is_old(self) -> None:
state = summarize_process_activity(
"youtube",

View File

@ -106,6 +106,20 @@ class WebDynamicProcessesTests(unittest.TestCase):
self.assertIn("已在控制台配置", payload["recent_log"])
self.assertTrue(payload["raw_status"].startswith("进程「youtube」已在控制台配置"))
def test_status_light_skips_full_status_snapshot(self) -> None:
original_use_pm2 = web.process_backend._use_pm2
web.process_backend._use_pm2 = False
try:
with patch.object(web.process_backend, "full_status_raw", AsyncMock(side_effect=AssertionError("slow path"))):
with patch("web.get_process_info", AsyncMock(return_value={"process_status": "not_found", "out_path": None, "err_path": None})):
response = asyncio.run(web.status("youtube", light=True))
finally:
web.process_backend._use_pm2 = original_use_pm2
payload = json.loads(response.body)
self.assertEqual(payload["process_status"], "configured")
self.assertEqual(payload["business_status"], "ready")
def test_process_monitor_includes_runtime_snapshot_for_local_configured_process(self) -> None:
original_use_pm2 = web.process_backend._use_pm2
web.process_backend._use_pm2 = False
@ -126,6 +140,28 @@ class WebDynamicProcessesTests(unittest.TestCase):
self.assertEqual(youtube_row["business_status"], "ready")
self.assertFalse(youtube_row["is_pushing"])
def test_process_monitor_light_uses_short_cache(self) -> None:
original_use_pm2 = web.process_backend._use_pm2
web.process_backend._use_pm2 = False
web._clear_process_monitor_cache()
process_infos = AsyncMock(
return_value={"youtube2__cache_test": {"process_status": "stopped", "out_path": None, "err_path": None}}
)
try:
with patch("web.process_monitor_entries", return_value=(
{"pm2": "youtube2__cache_test", "script": "youtube.py", "label": "Cache Test"},
)):
with patch.object(web.process_backend, "ensure_mode", AsyncMock()):
with patch.object(web.process_backend, "process_infos", process_infos):
first = asyncio.run(web.process_monitor(family="youtube", light=True))
second = asyncio.run(web.process_monitor(family="youtube", light=True))
finally:
web._clear_process_monitor_cache()
web.process_backend._use_pm2 = original_use_pm2
self.assertEqual(first, second)
process_infos.assert_awaited_once()
def test_process_monitor_family_filter_returns_youtube_rows_only(self) -> None:
original_use_pm2 = web.process_backend._use_pm2
web.process_backend._use_pm2 = False

View File

@ -30,7 +30,19 @@ class YoutubeRuntimeTests(unittest.TestCase):
self.assertEqual(settings["b_v"], "4000k")
self.assertEqual(settings["maxrate"], "4500k")
self.assertEqual(settings["bufsize"], "8000k")
self.assertFalse(settings["fast_audio"])
self.assertTrue(settings["fast_audio"])
def test_record_cleanup_url_prefers_original_monitor_url(self) -> None:
from douyin_youtube_ffplay import _record_cleanup_url
self.assertEqual(
_record_cleanup_url(
"https://pull.example.com/live.flv?expire=123",
"https://live.douyin.com/123456",
),
"https://live.douyin.com/123456",
)
self.assertEqual(_record_cleanup_url("https://pull.example.com/live.flv", ""), "https://pull.example.com/live.flv")
def test_arm_falls_back_from_vaapi_to_v4l2m2m(self) -> None:
enc, note = resolve_live_video_encoder(

View File

@ -78,6 +78,14 @@ function isViewKey(value: string | null): value is ViewKey {
return !!value && VIEW_KEYS.includes(value as ViewKey);
}
function initialViewKey(): ViewKey {
if (typeof window === "undefined") return "dashboard";
const requested = new URLSearchParams(window.location.search).get("view");
if (isViewKey(requested)) return requested;
if (window.location.pathname.replace(/\/$/, "") === "/youtube-events") return "live_youtube";
return "dashboard";
}
const apiBase = () =>
(typeof process !== "undefined" && process.env.NEXT_PUBLIC_API_URL) || "";
@ -516,6 +524,7 @@ export default function LiveControlApp() {
const [lang, setLang] = useState<Lang>("zh");
const [portalTheme, setPortalTheme] = useState<PortalTheme>("dark");
const [view, setView] = useState<ViewKey>("dashboard");
const [viewReady, setViewReady] = useState(false);
const [mobileNav, setMobileNav] = useState(false);
const [dash, setDash] = useState<HubDashboard | null>(null);
const [dashErr, setDashErr] = useState<string | null>(null);
@ -653,9 +662,8 @@ export default function LiveControlApp() {
}, [fetchJson, processMonitorPath]);
useEffect(() => {
const initialView = new URLSearchParams(window.location.search).get("view");
if (isViewKey(initialView)) setView(initialView);
else if (window.location.pathname.replace(/\/$/, "") === "/youtube-events") setView("live_youtube");
setView(initialViewKey());
setViewReady(true);
const s = window.localStorage.getItem("live-hub-lang");
if (s === "zh" || s === "en") setLang(s);
const th = window.localStorage.getItem("live-hub-theme");
@ -663,6 +671,7 @@ export default function LiveControlApp() {
}, []);
useEffect(() => {
if (!viewReady) return;
const url = new URL(window.location.href);
if (view === "dashboard") {
url.searchParams.delete("view");
@ -670,7 +679,7 @@ export default function LiveControlApp() {
url.searchParams.set("view", view);
}
window.history.replaceState(null, "", url.toString());
}, [view]);
}, [view, viewReady]);
useEffect(() => {
window.localStorage.setItem("live-hub-lang", lang);
@ -725,28 +734,34 @@ export default function LiveControlApp() {
}, []);
useEffect(() => {
if (!viewReady) return;
if (view === "live_youtube" || view === "live_tiktok") {
setLoading(false);
return;
}
void refreshDashboard();
}, [refreshDashboard]);
}, [refreshDashboard, view, viewReady]);
useEffect(() => {
if (!viewReady) return;
void refreshProcessMonitor();
}, [refreshProcessMonitor]);
}, [refreshProcessMonitor, viewReady]);
useEffect(() => {
if (!autoRefreshEnabled || !pageVisible || view === "live_youtube" || view === "live_tiktok") return;
if (!viewReady || !autoRefreshEnabled || !pageVisible || view === "live_youtube" || view === "live_tiktok") return;
const id = window.setInterval(() => {
void refreshDashboard();
}, 10000);
return () => clearInterval(id);
}, [autoRefreshEnabled, pageVisible, refreshDashboard, view]);
}, [autoRefreshEnabled, pageVisible, refreshDashboard, view, viewReady]);
useEffect(() => {
if (!autoRefreshEnabled || !pageVisible) return;
if (!viewReady || !autoRefreshEnabled || !pageVisible) return;
const id = window.setInterval(() => {
void refreshProcessMonitor();
}, view === "live_youtube" || view === "live_tiktok" ? 700 : 4000);
return () => clearInterval(id);
}, [autoRefreshEnabled, pageVisible, refreshProcessMonitor, view]);
}, [autoRefreshEnabled, pageVisible, refreshProcessMonitor, view, viewReady]);
useEffect(() => {
currentProcRef.current = currentProc;

View File

@ -135,7 +135,7 @@ export function LiveProcessLiveLogCard({
const requestId = ++requestSeqRef.current;
try {
const data = await fetchJson<StatusPayload>(
`/status?process=${encodeURIComponent(targetProc)}`,
`/status?process=${encodeURIComponent(targetProc)}&light=1`,
);
if (requestId !== requestSeqRef.current || targetProc !== currentProcRef.current.trim()) return;
const ps = data.process_status || "unknown";

View File

@ -202,6 +202,12 @@ type LiveProcRow = {
process_status?: string;
business_status?: string;
business_note?: string;
ffmpeg_active?: boolean;
ffmpeg_speed?: number | null;
ffmpeg_frame?: number | null;
ffmpeg_time_seconds?: number | null;
ffmpeg_progress_stalled?: boolean;
ffmpeg_speed_low?: boolean;
is_pushing?: boolean;
source_title?: string;
source_room_id?: string;
@ -332,6 +338,8 @@ function businessStatusLabel(row: LiveProcRow | undefined, t: TFn): string {
const business = (row?.business_status || "").trim().toLowerCase();
if (business === "ready") return t("已配置", "Ready");
if (business === "streaming") return t("推流中", "Pushing");
if (business === "source_stalled") return t("源卡住", "Source stalled");
if (business === "relay_slow") return t("低速推流", "Relay slow");
if (business === "waiting_source") return t("等待上游", "Waiting source");
if (business === "source_live") return t("源已开播,转推未起", "Source live, relay down");
if (business === "monitoring") return t("监控中", "Monitoring");
@ -347,6 +355,8 @@ function businessStatusBadgeClass(row: LiveProcRow | undefined): string {
const business = (row?.business_status || "").trim().toLowerCase();
if (business === "ready") return "bg-sky-500/15 text-sky-100 ring-sky-500/25";
if (business === "streaming") return "bg-emerald-500/15 text-emerald-200 ring-emerald-500/30";
if (business === "relay_slow") return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
if (business === "source_stalled") return "bg-rose-500/15 text-rose-100 ring-rose-500/25";
if (business === "waiting_source" || business === "monitoring") {
return "bg-amber-500/15 text-amber-100 ring-amber-500/25";
}
@ -654,6 +664,7 @@ export function LiveYoutubeUnmannedView({
const [liveEventLoading, setLiveEventLoading] = useState(false);
const [qualityGuard, setQualityGuard] = useState<YoutubeQualityGuard | null>(null);
const [qualityGuardLoading, setQualityGuardLoading] = useState(false);
const [pageVisible, setPageVisible] = useState(true);
const [nekoBusy, setNekoBusy] = useState<string | null>(null);
const [nekoActionNote, setNekoActionNote] = useState<string | null>(null);
const urlListDirtyRef = useRef(false);
@ -678,6 +689,13 @@ export function LiveYoutubeUnmannedView({
setProUrlDraft(next);
}, []);
useEffect(() => {
const onVis = () => setPageVisible(document.visibilityState === "visible");
onVis();
document.addEventListener("visibilitychange", onVis);
return () => document.removeEventListener("visibilitychange", onVis);
}, []);
useEffect(() => {
urlListDirtyRef.current = false;
}, [currentProc]);
@ -1237,8 +1255,8 @@ export function LiveYoutubeUnmannedView({
}
: row,
);
applyChannelsLocal(next);
await syncChannelsRemote(next, { force: true });
applyChannelsLocal(next);
setLaneDrafts((prev) => ({
...prev,
[active.id]: {
@ -1597,10 +1615,11 @@ export function LiveYoutubeUnmannedView({
);
useEffect(() => {
if (!pageVisible) return;
void refreshLiveEvents(null);
const id = window.setInterval(() => void refreshLiveEvents(), 4000);
return () => window.clearInterval(id);
}, [refreshLiveEvents]);
}, [pageVisible, refreshLiveEvents]);
const refreshQualityGuard = useCallback(async () => {
setQualityGuardLoading(true);
@ -1615,10 +1634,11 @@ export function LiveYoutubeUnmannedView({
}, [fetchJson]);
useEffect(() => {
if (!pageVisible) return;
void refreshQualityGuard();
const id = window.setInterval(() => void refreshQualityGuard(), 6000);
return () => window.clearInterval(id);
}, [refreshQualityGuard]);
}, [pageVisible, refreshQualityGuard]);
const lock = !!busy || ytIniLoading || urlReloading || urlOptimizing || laneSaving;
@ -2531,6 +2551,8 @@ export function LiveYoutubeUnmannedView({
</div>
<p className="mt-3 text-center text-xs text-zinc-400">
{t("当前状态", "Current state")}: {businessStatusLabel(singleRow, t)}
{typeof singleRow?.ffmpeg_speed === "number" ? ` | speed ${singleRow.ffmpeg_speed.toFixed(2)}x` : ""}
{typeof singleRow?.ffmpeg_frame === "number" ? ` | frame ${singleRow.ffmpeg_frame}` : ""}
</p>
<p className="mt-2 text-center text-sm font-semibold text-white">
{singleSourceDisplay || t("未配置抖音直播源", "No Douyin source configured")}
@ -2570,6 +2592,8 @@ export function LiveYoutubeUnmannedView({
const laneNeko = resolveNekoBrowserLink(nekoLinks, laneIndex).link;
const laneName = cleanLaneName(c.name, laneIndex >= 0 ? laneIndex : 0);
const laneDisplay = douyinSourceDisplayFor(row, laneUrlText);
const speedText = typeof row?.ffmpeg_speed === "number" ? `speed ${row.ffmpeg_speed.toFixed(2)}x` : "";
const frameText = typeof row?.ffmpeg_frame === "number" ? `frame ${row.ffmpeg_frame}` : "";
return (
<div
key={c.id}
@ -2622,6 +2646,22 @@ export function LiveYoutubeUnmannedView({
<span>
DY {douyinUrls.length}
</span>
{speedText ? (
<>
<span className="text-zinc-600">·</span>
<span className={row?.ffmpeg_speed_low ? "text-amber-300" : "text-zinc-500"}>
{speedText}
</span>
</>
) : null}
{frameText ? (
<>
<span className="text-zinc-600">·</span>
<span className={row?.ffmpeg_progress_stalled ? "text-rose-300" : "text-zinc-500"}>
{frameText}
</span>
</>
) : null}
</div>
{dUrl ? (
<a

View File

@ -0,0 +1,7 @@
{
"built_at": 1780533623.4086378,
"source_mtime": 1780533327.0086436,
"source_hash": "9f39c94844ba717c7800d36129f9d561391f141b4b068cf8d9381262f17b5418",
"toolchain": "local",
"node_major": 22
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,6 @@
3:I[3946,["500","static/chunks/500-ea37cc8de90441f7.js","246","static/chunks/246-a56380dcf5ea0340.js","357","static/chunks/app/android/page-5f87422c86e34807.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["qH1zlSt29jtuHZ9NIMYFr",[[["",{"children":["android",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["android",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","android","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["kgMwLiIofCnU7PCYPre3S",[[["",{"children":["android",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["android",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","android","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,6 @@
3:I[6367,["500","static/chunks/500-ea37cc8de90441f7.js","246","static/chunks/246-a56380dcf5ea0340.js","443","static/chunks/app/console/page-f5a0052a001f3016.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["qH1zlSt29jtuHZ9NIMYFr",[[["",{"children":["console",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["console",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","console","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["kgMwLiIofCnU7PCYPre3S",[[["",{"children":["console",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["console",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","console","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
2:I[9107,[],"ClientPageRoot"]
3:I[7340,["500","static/chunks/500-ea37cc8de90441f7.js","166","static/chunks/166-6b01e1456a874782.js","246","static/chunks/246-a56380dcf5ea0340.js","644","static/chunks/644-b670e35fa0cddabc.js","931","static/chunks/app/page-58e06160be396c5b.js"],"default",1]
3:I[7340,["500","static/chunks/500-ea37cc8de90441f7.js","166","static/chunks/166-6b01e1456a874782.js","246","static/chunks/246-a56380dcf5ea0340.js","644","static/chunks/644-7e5dfcc592ce32c1.js","931","static/chunks/app/page-58e06160be396c5b.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["qH1zlSt29jtuHZ9NIMYFr",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["kgMwLiIofCnU7PCYPre3S",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,6 @@
3:I[3398,["500","static/chunks/500-ea37cc8de90441f7.js","246","static/chunks/246-a56380dcf5ea0340.js","6","static/chunks/app/shellcrash/page-0c73522b1d5c8dc1.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["qH1zlSt29jtuHZ9NIMYFr",[[["",{"children":["shellcrash",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["shellcrash",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","shellcrash","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["kgMwLiIofCnU7PCYPre3S",[[["",{"children":["shellcrash",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["shellcrash",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","shellcrash","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

File diff suppressed because one or more lines are too long

View File

@ -1,7 +1,7 @@
2:I[9107,[],"ClientPageRoot"]
3:I[316,["500","static/chunks/500-ea37cc8de90441f7.js","166","static/chunks/166-6b01e1456a874782.js","246","static/chunks/246-a56380dcf5ea0340.js","644","static/chunks/644-b670e35fa0cddabc.js","851","static/chunks/app/youtube-events/page-de7151b95af37543.js"],"default",1]
3:I[316,["500","static/chunks/500-ea37cc8de90441f7.js","166","static/chunks/166-6b01e1456a874782.js","246","static/chunks/246-a56380dcf5ea0340.js","644","static/chunks/644-7e5dfcc592ce32c1.js","851","static/chunks/app/youtube-events/page-de7151b95af37543.js"],"default",1]
4:I[4707,[],""]
5:I[6423,[],""]
0:["qH1zlSt29jtuHZ9NIMYFr",[[["",{"children":["youtube-events",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["youtube-events",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","youtube-events","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
0:["kgMwLiIofCnU7PCYPre3S",[[["",{"children":["youtube-events",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["youtube-events",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","youtube-events","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d69107dc7d1c5fad.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"zh-CN","data-theme":"dark","suppressHydrationWarning":true,"children":["$","body",null,{"className":"__variable_1e4310 __variable_c3aa02 font-sans antialiased","children":[["$","div",null,{"className":"app-bg-layer","aria-hidden":true}],["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]]}]}]],null],null],["$L6",null]]]]
6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"无人直播系统 · live.local"}],["$","meta","3",{"name":"description","content":"Linux ARM/x86 一键部署的无人直播控制台:YouTube 转播、TikTok HDMI、SRS、Neko 与系统服务"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]]
1:null

View File

@ -17,6 +17,7 @@ from pydantic import BaseModel, Field
from fastapi import FastAPI, File, Query, Request, UploadFile, WebSocket
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
@ -111,8 +112,16 @@ DEFAULT_LOG_DIR = BASE_DIR / ".pm2" / "logs"
CONSOLE_OUT = BASE_DIR / "web-console" / "out"
MAX_LOG_LINES = 300
LOG_TAIL_MAX_BYTES = 192 * 1024
LOG_TAIL_CHUNK_BYTES = 16 * 1024
PROCESS_MONITOR_CACHE_TTL_SECONDS = 0.8
YOUTUBE_EVENT_STATUS_OBSERVE_SECONDS = 5.0
_YOUTUBE_EVENT_STATUS_CACHE: dict[str, float] = {}
_PROCESS_MONITOR_CACHE: dict[tuple[str, bool, tuple[str, ...]], tuple[float, dict[str, Any]]] = {}
def _clear_process_monitor_cache() -> None:
_PROCESS_MONITOR_CACHE.clear()
MAX_TIKTOK_REPLAY_UPLOAD = 2 * 1024 * 1024 * 1024
_TIKTOK_REPLAY_EXT = frozenset({".mp4", ".mkv", ".ts", ".flv", ".mov", ".m4v", ".webm"})
@ -746,11 +755,19 @@ async def _youtube_quality_guard_payload() -> dict[str, Any]:
async def build_row(entry: dict[str, str]) -> dict[str, Any]:
name = str(entry.get("pm2") or "").strip()
info = _coerce_local_configured_process(name, infos.get(name) or {})
recent_log, recent_error = await asyncio.gather(
recent_log, recent_error, ffmpeg_pids = await asyncio.gather(
read_log_path_normalized(info.get("out_path"), 80),
read_log_path_normalized(info.get("err_path"), 80),
process_backend.live_ffmpeg_pids(name, info),
)
snapshot = await _process_monitor_snapshot_from_info(
entry,
info,
light=False,
recent_log_override=recent_log,
recent_error_override=recent_error,
ffmpeg_pids_override=ffmpeg_pids,
)
snapshot = await _process_monitor_snapshot_from_info(entry, info, light=False)
snapshot["recent_log"] = recent_log[-12000:]
snapshot["recent_error"] = recent_error[-8000:]
return snapshot
@ -784,6 +801,7 @@ app.add_middleware(
allow_methods=["GET", "POST", "OPTIONS"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=1024)
_NO_STORE_HEADERS = {
"Cache-Control": "no-store, max-age=0, must-revalidate",
@ -929,12 +947,38 @@ async def read_log_path(path: Optional[str], lines: int) -> str:
return f"读取日志失败 ({path}): {str(e)}\n"
def _read_log_tail_bytes(log_file: Path, max_bytes: int = 512 * 1024) -> str:
def _read_log_tail_text(
log_file: Path,
lines: int,
*,
max_bytes: int = LOG_TAIL_MAX_BYTES,
chunk_bytes: int = LOG_TAIL_CHUNK_BYTES,
) -> str:
if lines <= 0:
return ""
size = log_file.stat().st_size
if size <= 0:
return ""
chunks: list[bytes] = []
newline_count = 0
remaining = min(size, max_bytes)
with log_file.open("rb") as f:
if size > max_bytes:
f.seek(-max_bytes, os.SEEK_END)
return f.read().decode("utf-8", errors="ignore")
pos = size
while remaining > 0 and pos > 0:
step = min(chunk_bytes, remaining, pos)
pos -= step
f.seek(pos)
chunk = f.read(step)
if not chunk:
break
chunks.append(chunk)
newline_count += chunk.count(b"\n")
remaining -= len(chunk)
if newline_count >= lines + 1:
break
if not chunks:
return ""
return tail_log_text(b"".join(reversed(chunks)).decode("utf-8", errors="ignore"), lines)
def _newest_log_age_seconds(*paths: Optional[str]) -> float | None:
@ -967,8 +1011,7 @@ async def read_log_path_normalized(path: Optional[str], lines: int) -> str:
if not log_file.exists():
return f"日志文件不存在: {path}\n"
try:
text = await asyncio.to_thread(_read_log_tail_bytes, log_file)
tailed = tail_log_text(text, lines)
tailed = await asyncio.to_thread(_read_log_tail_text, log_file, lines)
return tailed if tailed else "无日志内容\n"
except OSError as e:
return f"读取日志失败 ({path}): {str(e)}\n"
@ -1751,6 +1794,9 @@ async def _process_monitor_snapshot_from_info(
info: dict[str, Any],
*,
light: bool = False,
recent_log_override: str | None = None,
recent_error_override: str | None = None,
ffmpeg_pids_override: list[int] | None = None,
) -> dict[str, Any]:
name = str(entry.get("pm2") or "").strip()
info = _coerce_local_configured_process(name, info)
@ -1760,7 +1806,10 @@ async def _process_monitor_snapshot_from_info(
log_lines = 12 if light else 40
error_lines = 8 if light else 40
if read_logs:
if recent_log_override is not None and recent_error_override is not None:
recent_log = recent_log_override
recent_error = recent_error_override
elif read_logs:
recent_log, recent_error = await asyncio.gather(
read_log_path_normalized(info.get("out_path"), log_lines),
read_log_path_normalized(info.get("err_path"), error_lines),
@ -1769,7 +1818,9 @@ async def _process_monitor_snapshot_from_info(
recent_log = ""
recent_error = ""
ffmpeg_pids = await process_backend.live_ffmpeg_pids(name, info) if online else []
ffmpeg_pids = ffmpeg_pids_override if ffmpeg_pids_override is not None else (
await process_backend.live_ffmpeg_pids(name, info) if online else []
)
activity = summarize_process_activity(
name,
str(info.get("process_status") or ""),
@ -1787,6 +1838,11 @@ async def _process_monitor_snapshot_from_info(
"business_status": str(activity.get("business_status") or ""),
"business_note": str(activity.get("business_note") or ""),
"ffmpeg_active": bool(activity.get("ffmpeg_active")),
"ffmpeg_speed": activity.get("ffmpeg_speed"),
"ffmpeg_frame": activity.get("ffmpeg_frame"),
"ffmpeg_time_seconds": activity.get("ffmpeg_time_seconds"),
"ffmpeg_progress_stalled": bool(activity.get("ffmpeg_progress_stalled")),
"ffmpeg_speed_low": bool(activity.get("ffmpeg_speed_low")),
"is_pushing": bool(activity.get("is_pushing")),
**source_meta,
}
@ -1818,6 +1874,7 @@ async def start(process: str = Query(..., description="进程名")):
return JSONResponse({"output": preflight_message}, status_code=400)
stopped = await _stop_other_hdmi_sink_processes(process)
output = await process_backend.start(process, sc)
_clear_process_monitor_cache()
with suppress(Exception):
await _record_youtube_control_event(process, "start", sc, preflight_message)
prefix = (preflight_message + "\n") if preflight_message else ""
@ -1855,6 +1912,7 @@ async def stop(process: str = Query(..., description="进程名")):
os.kill(root_pid, signal.SIGKILL)
with suppress(Exception):
await _record_youtube_control_event(process, "stop", sc, "manual stop")
_clear_process_monitor_cache()
return JSONResponse(
{
@ -1888,6 +1946,7 @@ async def restart(process: str = Query(..., description="进程名")):
if not process.startswith("web"):
await force_kill_ffmpeg(process, BASE_DIR, root_pid=root_pid, root_pgid=root_pgid)
output = await process_backend.restart(process, sc)
_clear_process_monitor_cache()
with suppress(Exception):
await _record_youtube_control_event(process, "restart", sc, preflight_message)
prefix = (preflight_message + "\n") if preflight_message else ""
@ -1902,7 +1961,10 @@ async def restart_post(body: ProcessNameBody):
@app.get("/status")
async def status(process: str = Query(..., description="进程名")):
async def status(
process: str = Query(..., description="进程名"),
light: bool = Query(False, description="轻量模式:跳过全量进程表和状态观察写入"),
):
if not is_valid_control_process(process):
return JSONResponse(
{
@ -1913,23 +1975,40 @@ async def status(process: str = Query(..., description="进程名")):
}
)
full_status_raw = await process_backend.full_status_raw()
full_status = strip_ansi_codes(full_status_raw)
full_status_task = asyncio.create_task(process_backend.full_status_raw()) if not light else None
info = await get_process_info(process)
info = _coerce_local_configured_process(process, info)
recent_log = await read_log_path_normalized(info.get("out_path"), MAX_LOG_LINES)
recent_error = await read_log_path_normalized(info.get("err_path"), MAX_LOG_LINES)
full_status = strip_ansi_codes(await full_status_task) if full_status_task else ""
ffmpeg_pids: list[int] = []
process_status = str(info.get("process_status") or "")
if process_status == "not_found":
recent_log = _not_found_hint(process) + "\n"
recent_error = ""
if not full_status:
full_status = recent_log.strip()
elif process_status == "configured":
configured_hint = _configured_hint(process)
recent_log = configured_hint + "\n"
recent_error = ""
full_status = configured_hint
else:
recent_log, recent_error, ffmpeg_pids = await asyncio.gather(
read_log_path_normalized(info.get("out_path"), MAX_LOG_LINES),
read_log_path_normalized(info.get("err_path"), MAX_LOG_LINES),
process_backend.live_ffmpeg_pids(process, info),
)
activity = summarize_process_activity(
process,
str(info.get("process_status") or ""),
process_status,
recent_log,
recent_error,
log_age_seconds=_newest_log_age_seconds(info.get("out_path"), info.get("err_path")),
ffmpeg_pids=await process_backend.live_ffmpeg_pids(process),
ffmpeg_pids=ffmpeg_pids,
)
sc = script_for_pm2_or_pro(process) or ""
if sc and is_youtube_script(sc):
if sc and is_youtube_script(sc) and not light:
with suppress(Exception):
await _record_youtube_status_observation(
process,
@ -1942,15 +2021,6 @@ async def status(process: str = Query(..., description="进程名")):
},
)
if info["process_status"] == "not_found":
recent_log = _not_found_hint(process) + "\n"
recent_error = ""
elif info["process_status"] == "configured":
configured_hint = _configured_hint(process)
recent_log = configured_hint + "\n"
recent_error = ""
full_status = configured_hint
source_meta = _youtube_source_meta(process, recent_log)
return JSONResponse(
{
@ -1974,6 +2044,12 @@ async def process_monitor(
light_value = bool(light) if isinstance(light, bool) else False
entries = [dict(p) for p in process_monitor_entries() if _process_monitor_family_matches(p, family_value)]
names = [str(entry.get("pm2") or "").strip() for entry in entries if str(entry.get("pm2") or "").strip()]
cache_key = ((family_value or "").strip().lower(), light_value, tuple(names))
if light_value:
cached = _PROCESS_MONITOR_CACHE.get(cache_key)
now = time.monotonic()
if cached and now - cached[0] <= PROCESS_MONITOR_CACHE_TTL_SECONDS:
return cached[1]
infos = await process_backend.process_infos(names)
async def build_snapshot(entry: dict[str, str]) -> dict[str, Any]:
@ -1998,12 +2074,15 @@ async def process_monitor(
"is_pushing": False,
}
)
return {
payload = {
"entries": snapshots,
"process_backend": process_backend.mode,
"family": (family_value or "all").strip().lower() or "all",
"light": light_value,
}
if light_value:
_PROCESS_MONITOR_CACHE[cache_key] = (time.monotonic(), payload)
return payload
@app.get("/favicon.ico", include_in_schema=False)

View File

@ -1628,21 +1628,25 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
error_window.append(1)
else:
from douyin_youtube_ffplay import start_douyin_youtube_ffplay
try:
from douyin_youtube_ffplay import start_douyin_youtube_ffplay
start_douyin_youtube_ffplay(
title=title_in_name,
anchor_name=anchor_name,
real_url=real_url,
rec_info=rec_info,
record_name=record_name,
recording=recording,
recording_time_list=recording_time_list,
running_list=running_list,
clear_record_info=clear_record_info,
color_obj=color_obj,
config_file=config_file,
)
start_douyin_youtube_ffplay(
title=title_in_name,
anchor_name=anchor_name,
real_url=real_url,
rec_info=rec_info,
record_name=record_name,
recording=recording,
recording_time_list=recording_time_list,
running_list=running_list,
clear_record_info=clear_record_info,
color_obj=color_obj,
config_file=config_file,
record_url=record_url,
)
finally:
clear_record_info(record_name, record_url)
count_time = time.time()