Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 187 additions & 6 deletions app/core/recording/stream_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import subprocess
import sys
import time
from datetime import datetime
from datetime import datetime, timedelta
from typing import TypeVar

from ...messages import desktop_notify, message_pusher
Expand Down Expand Up @@ -33,6 +33,10 @@ def __init__(self, services, recording, recording_info):
self.recording_info = recording_info
self.subprocess_start_info = services.subprocess_start_up_info
self.should_stop = False # manually stopped
# Set when the recording was stopped because the stream source itself
# degraded (persistent corruption / connection rotation, issue #450):
# unlike a manual stop, the room must be re-checked and restarted.
self.degraded = False

self.user_config = self.settings.user_config
self.account_config = self.settings.accounts_config
Expand Down Expand Up @@ -340,11 +344,15 @@ async def remove_active_recorder(self):
logger.error(f"Failed to remove recorder instance: {e}")

async def recheck_live_status(self):
if not self.should_stop:
# not manually stopped
if not self.should_stop or self.degraded:
# not manually stopped (degraded/rotated connections must recheck,
# so the room restarts with a fresh stream URL — issue #450).
# Degraded restarts also bypass the minimum-duration gate (a short
# rotation must not poison the room into RECORDING_ERROR) and the
# flv-preferred exclusion (we stopped on purpose, not by accident).
recording_duration = time.time() - self.recording_start_time
if recording_duration > self.min_valid_recording_duration:
if self.services.recording_enabled and not self.is_flv_preferred_platform:
if recording_duration > self.min_valid_recording_duration or self.degraded:
if self.services.recording_enabled and (not self.is_flv_preferred_platform or self.degraded):
self.services.run_coro(self.services.recording_manager.check_if_live(self.recording))
else:
self.recording.status_info = RecordingStatus.RECORDING_ERROR
Expand All @@ -365,6 +373,139 @@ async def _capture_stream_tail(
del tail[:-max_bytes]
return bytes(tail)

async def _monitor_stderr(
self,
stream: asyncio.StreamReader | None,
state: dict,
max_bytes: int = 64 * 1024,
) -> bytes:
"""Drain ffmpeg stderr like _capture_stream_tail, and timestamp every
corruption-related line so the recording loop can detect a degraded
stream (persistent CDN/session rot) and restart the connection.

Copy-mode recording cannot repair corrupted packets — it either drops
them (content gaps, frozen/smeared GOPs, issue #450) or passes them
through — so the only effective fix is noticing the rot early and
reconnecting for a fresh stream URL.
"""
if stream is None or max_bytes <= 0:
return b""
timestamps: list[float] = state.setdefault("corruption_events", [])
# Count per *line*, buffering across reads: a message split at a chunk
# boundary would otherwise be missed, and several errors inside one
# chunk would be counted once.
pending = bytearray()
tail = bytearray()

def count_line(line: bytes) -> None:
if b"corrupt" in line or b"invalid data found" in line:
timestamps.append(time.time())

while chunk := await stream.read(4096):
tail.extend(chunk)
if len(tail) > max_bytes:
del tail[:-max_bytes]
pending.extend(chunk)
while True:
nl = pending.find(b"\n")
if nl < 0:
break
count_line(bytes(pending[:nl]).lower())
del pending[: nl + 1]
if pending:
count_line(bytes(pending).lower())
return bytes(tail)

def _degraded_threshold(self) -> int:
"""Configured corruption-line threshold per 60s window; 0 disables.
Values are taken verbatim (no ``or`` fallback) so 0 keeps working."""
raw = self.user_config.get("stream_error_threshold", 30)
if raw is None:
return 30
try:
return int(raw)
except (TypeError, ValueError):
return 30

def _check_degraded_stream(self, stderr_state: dict) -> bool:
"""True when corruption messages keep arriving — the stream source
itself has gone bad and the recorder should reconnect."""
threshold = self._degraded_threshold()
if threshold <= 0:
return False
events = stderr_state.get("corruption_events") or []
if not events:
return False
window_start = time.time() - 60
recent = [t for t in events if t >= window_start]
# Trim on read: events older than the window are dropped and the list
# is capped relative to the threshold (so a large configured threshold
# can never silently exceed a hard cap and disable detection).
stderr_state["corruption_events"] = recent[-(threshold * 3 + 100) :]
return len(recent) >= threshold

def _check_connection_rotation(self) -> bool:
"""Enforce an optional maximum age for a single pull connection.

Long-lived CDN sessions tend to rot after a while (frozen picture,
corrupt packets — issue #450). Rotating the connection proactively
fetches a fresh stream URL before quality degrades. 0 disables."""
try:
max_age = float(self.user_config.get("max_stream_connection_duration", 0) or 0)
except (TypeError, ValueError):
max_age = 0.0
if max_age <= 0 or not self.recording_start_time:
return False
return (time.time() - self.recording_start_time) >= max_age

DEGRADED_RESTART_WINDOW = 600 # seconds
DEGRADED_RESTART_MAX = 3

def _register_degraded_restart(self) -> bool:
"""Circuit breaker against restart storms.

If the platform keeps serving a rotten stream, a naive
detect→reconnect loop would cycle forever (minute-scale files,
repeated notifications, disk churn). After 3 degraded restarts
within 10 minutes the breaker opens: the recording still stops, but
no automatic restart is scheduled — the periodic live check takes
over with its normal cadence."""
now = time.time()
previous = getattr(self.recording, "degraded_restarts", [])
restarts = [t for t in previous if now - t < self.DEGRADED_RESTART_WINDOW]
if len(restarts) >= self.DEGRADED_RESTART_MAX:
logger.error(
f"Degraded-stream restart circuit breaker open for {self.live_url}: "
f"{len(restarts)} restarts within {self.DEGRADED_RESTART_WINDOW}s, giving up automatic restart"
)
return False
restarts.append(now)
self.recording.degraded_restarts = restarts
return True

async def _finish_degraded_restart(self) -> None:
"""Same-live continuation for degraded/rotation restarts.

A rotation is NOT a new live session: is_live and the notified_* flags
are kept (so check_if_live won't re-send 'live started' notifications),
and the recorded duration is banked before the next start_update()
resets the counters. Converts/scripts are skipped for intermediate
segments to avoid firing upload-style post-processing once per
rotation."""
try:
banked = timedelta(seconds=max(0.0, time.time() - self.recording_start_time))
current = self.recording.cumulative_duration
self.recording.cumulative_duration = (current if current is not None else timedelta()) + banked
except (AttributeError, TypeError) as e:
logger.debug(f"Failed to bank recording duration on degraded restart: {e}")
self.recording.status_info = RecordingStatus.MONITORING
try:
self.services.broadcast_card_update(self.recording)
self.services.broadcast_pubsub("update", self.recording)
except Exception as e:
logger.debug(f"Failed to update UI on degraded restart: {e}")
await self.recheck_live_status()

async def start_ffmpeg(
self,
record_name: str,
Expand All @@ -380,8 +521,10 @@ async def start_ffmpeg(

logger.info(f"Starting ffmpeg recording - recorder id: {id(self)}, rec_id: {self.recording.rec_id}")
self.should_stop = False
self.degraded = False
process = None
stderr_task = None
stderr_state: dict = {}

try:
save_file_path = ffmpeg_command[-1]
Expand All @@ -393,7 +536,7 @@ async def start_ffmpeg(
stderr=asyncio.subprocess.PIPE,
startupinfo=self.subprocess_start_info,
)
stderr_task = asyncio.create_task(self._capture_stream_tail(process.stderr))
stderr_task = asyncio.create_task(self._monitor_stderr(process.stderr, stderr_state))

self.services.process_manager.add_process(process)
self.recording.status_info = RecordingStatus.RECORDING
Expand All @@ -403,6 +546,27 @@ async def start_ffmpeg(
self.recording_start_time = time.time()

while True:
# Degraded-stream rotation (issue #450): copy mode cannot repair
# corrupt packets, so reconnect for a fresh stream URL when the
# source keeps producing them, or when the connection hit the
# optional maximum age. The stop path below finishes gracefully
# and recheck_live_status() restarts the room. The circuit
# breaker caps how often this may happen (restart storms).
if not self.should_stop:
restart_reason = None
if self._check_degraded_stream(stderr_state):
restart_reason = "degraded (persistent corruption)"
elif self._check_connection_rotation():
restart_reason = "connection rotation"
if restart_reason:
logger.warning(f"Stopping recording for {restart_reason}: {live_url}")
self.should_stop = True
if self._register_degraded_restart():
self.degraded = True
# breaker open → degraded stays False: the recording
# still stops (the stream really is bad) but no auto
# restart is scheduled; the periodic check takes over.

if self.should_stop or self.recording.force_stop or not self.services.recording_enabled:
logger.info(f"Preparing to End Recording: {live_url}")
await self.remove_active_recorder()
Expand Down Expand Up @@ -445,6 +609,14 @@ async def start_ffmpeg(
return_code = process.returncode
safe_return_codes = {0, 255}

if self.degraded:
# Same-live continuation on *every* exit path — including a
# killed/timed-out ffmpeg (returncode outside the safe set),
# which is precisely what a rotten stream tends to cause.
# Bank duration, keep notification state, schedule restart.
await self._finish_degraded_restart()
return True

if return_code not in safe_return_codes:
error_output = stderr.decode(errors="replace").strip()
if error_output:
Expand Down Expand Up @@ -510,6 +682,14 @@ async def start_ffmpeg(

except Exception as e:
logger.error(f"An error occurred during the subprocess execution: {e}")
if self.degraded:
# Degraded stop whose graceful finish itself failed (e.g. broken
# stdin pipe on an already-stuck process): still restart rather
# than reporting a recording error and stalling the room.
self.recording.is_recording = False
await self.remove_active_recorder()
await self._finish_degraded_restart()
return True
self._handle_recording_error(record_name, self._["no_ffmpeg_tip"], duration=4000)
return False
finally:
Expand Down Expand Up @@ -712,6 +892,7 @@ async def start_direct_download(

logger.info(f"Starting direct download - recorder id: {id(self)}, rec_id: {self.recording.rec_id}")
self.should_stop = False
self.degraded = False

try:
await self.direct_downloader.start_download()
Expand Down
Loading