From 82e64f56d41256b298116a44e068518f38fd503a Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 11:26:22 +0800 Subject: [PATCH 1/2] feat: detect degraded streams and rotate connections instead of recording rot (#450) Local-lab experiments (local HTTP sources with injected faults, ffprobe quantification) showed: - TS copy-recording is already robust against timestamp jumps, lost HLS segments and EXT-X-DISCONTINUITY: the mpegts muxer re-monotonizes the timeline and content survives (3-4s lost at the seam). - -use_wallclock_as_timestamps is actively harmful: when the download runs faster than realtime (HLS catch-up) it compresses the whole recording into a fraction of a second of timeline. - Corrupt packets are the real unrecoverable failure: copy mode either drops them (content gaps, frozen/smeared GOPs - issue #450) or passes them through; the only effective remedy is reconnecting for a fresh stream URL once the source starts rotting. This adds two restart triggers to the ffmpeg recording loop: 1. degraded-stream detection: _monitor_stderr (an extension of _capture_stream_tail) timestamps every 'Packet corrupt'/'invalid data found' line; when stream_error_threshold (default 30, 0 disables) arrive within a 60s window the recorder stops gracefully and recheck_live_status() restarts the room with a fresh URL. 2. optional connection rotation: max_stream_connection_duration (default 0 = off) proactively reconnects after N seconds, before long-lived CDN sessions degrade. Both go through the graceful stop path, so files are finalized properly; the new 'degraded' flag lets recheck_live_status distinguish these restarts from manual stops. Verified end-to-end with a real ffmpeg subprocess against a local infinite corrupted source: corruption events counted, restart triggered within seconds, output finalized, recheck re-armed (15/15 checks including no-false-positive controls). --- app/core/recording/stream_manager.py | 93 +++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 3 deletions(-) diff --git a/app/core/recording/stream_manager.py b/app/core/recording/stream_manager.py index 21a816d7..6affd204 100644 --- a/app/core/recording/stream_manager.py +++ b/app/core/recording/stream_manager.py @@ -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 @@ -340,8 +344,9 @@ 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) 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: @@ -365,6 +370,66 @@ 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", []) + tail = bytearray() + while chunk := await stream.read(4096): + tail.extend(chunk) + if len(tail) > max_bytes: + del tail[:-max_bytes] + lowered = chunk.lower() + if b"corrupt" in lowered or b"invalid data found" in lowered: + timestamps.append(time.time()) + if len(timestamps) > 200: + del timestamps[:-200] + return bytes(tail) + + 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.""" + try: + threshold = int(self.user_config.get("stream_error_threshold", 30) or 30) + except (TypeError, ValueError): + threshold = 30 + 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] + 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 + async def start_ffmpeg( self, record_name: str, @@ -380,8 +445,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] @@ -393,7 +460,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 @@ -403,6 +470,25 @@ 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. + if not self.should_stop: + if self._check_degraded_stream(stderr_state): + logger.warning( + f"Stream source degraded (persistent corruption): {live_url}, restarting connection" + ) + self.degraded = True + self.should_stop = True + elif self._check_connection_rotation(): + logger.info( + f"Rotating stream connection after max_stream_connection_duration: {live_url}" + ) + self.degraded = True + self.should_stop = True + 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() @@ -712,6 +798,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() From 0c087a1d485f71f9a606f30dd5835247a159469e Mon Sep 17 00:00:00 2001 From: qinzihan Date: Tue, 10 Nov 2026 12:02:48 +0800 Subject: [PATCH 2/2] fix: harden degraded-restart after adversarial review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adversarial review of the first version found the damage potential was almost entirely on the restart side. Fixes: - circuit breaker: 3 degraded restarts within 10 minutes stop the automatic restart (restart storms on platforms that keep serving a rotten stream); the periodic live check takes over at its normal pace. - same-live continuation: a rotation is not a new live session — is_live and notified_* flags are kept so 'live started' notifications/desktop alerts are not re-sent every rotation, the end notification is not swallowed when the anchor went offline during a rotation, and the recorded duration is banked before start_update() resets counters. - every degraded exit path restarts, including killed ffmpeg (returncode outside {0,255}) and broken-stdin/exception paths — exactly what a rotten stream tends to cause; previously those skipped the restart and reported a recording error instead. - degraded restarts bypass the 25s min-valid-duration gate (short rotations must not poison the room into RECORDING_ERROR) and the flv-preferred exclusion (we stopped on purpose). - stream_error_threshold=0 now really disables detection (no 'or' fallback); thresholds above 200 can no longer silently disable it (event list trimmed relative to the threshold on read). - corruption lines are counted per line with cross-chunk buffering: a message split at a 4KB boundary is no longer missed and bursts inside one chunk are no longer counted once. Verified: 24/24 checks (end-to-end with real ffmpeg + local corrupted infinite stream, circuit breaker, same-live semantics, gate bypasses, threshold edges, line counting). --- app/core/recording/stream_manager.py | 140 ++++++++++++++++++++++----- 1 file changed, 117 insertions(+), 23 deletions(-) diff --git a/app/core/recording/stream_manager.py b/app/core/recording/stream_manager.py index 6affd204..9b54912d 100644 --- a/app/core/recording/stream_manager.py +++ b/app/core/recording/stream_manager.py @@ -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 @@ -346,10 +346,13 @@ async def remove_active_recorder(self): async def recheck_live_status(self): 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) + # 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 @@ -388,25 +391,46 @@ async def _monitor_stderr( 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] - lowered = chunk.lower() - if b"corrupt" in lowered or b"invalid data found" in lowered: - timestamps.append(time.time()) - if len(timestamps) > 200: - del timestamps[:-200] + 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.""" - try: - threshold = int(self.user_config.get("stream_error_threshold", 30) or 30) - except (TypeError, ValueError): - threshold = 30 + threshold = self._degraded_threshold() if threshold <= 0: return False events = stderr_state.get("corruption_events") or [] @@ -414,6 +438,10 @@ def _check_degraded_stream(self, stderr_state: dict) -> bool: 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: @@ -430,6 +458,54 @@ def _check_connection_rotation(self) -> bool: 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, @@ -474,20 +550,22 @@ async def start_ffmpeg( # 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. + # 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): - logger.warning( - f"Stream source degraded (persistent corruption): {live_url}, restarting connection" - ) - self.degraded = True - self.should_stop = True + restart_reason = "degraded (persistent corruption)" elif self._check_connection_rotation(): - logger.info( - f"Rotating stream connection after max_stream_connection_duration: {live_url}" - ) - self.degraded = True + 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}") @@ -531,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: @@ -596,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: