Skip to content

feat: 劣化流检测与连接轮换 — 根治长时间录制后画面卡成一团(#450) - #520

Open
zzuu080603 wants to merge 2 commits into
ihmily:mainfrom
zzuu080603:fix/degraded-stream-restart
Open

zzuu080603 wants to merge 2 commits into
ihmily:mainfrom
zzuu080603:fix/degraded-stream-restart

Conversation

@zzuu080603

Copy link
Copy Markdown

📜 标题(Title)

🔍 描述(Description)

实验背景(本地流媒体实验室)

为定位 #450(录 1 小时后画面卡成一团/闪频)、#484(HLS 录制卡顿)、#474(音画不同步/加速),搭建了本地实验环境:HTTP 服务器模拟直播源 + 三类故障注入(时间戳跳变/HLS 丢段与 DISCONTINUITY/坏数据)+ ffprobe 量化(时长、帧数、时间轴空洞、音画漂移)。结论:

  1. TS 直录对时间戳类故障已稳健:换流回退、HLS 丢段(404)、EXT-X-DISCONTINUITY 场景下,mpegts muxer 会把时间轴重新单调化,内容基本完整保留(衔接处损失 3-4s)。🐛[BUG] 微博录制出来的视频会卡顿 #484/🐛[BUG] WIN10录制视频出现画面音频不同步,画面偶尔卡顿加速的问题 #474 的 TS 直出路径不是参数问题。
  2. -use_wallclock_as_timestamps 有害无益:下载快于实时(HLS 追赶)时,它把整段录制压进极短的时间轴(实验中 748 帧被压进 0.2 秒)——这正是『画面加速』的形态。留此结论防止未来引入。
  3. 坏数据是真正不可恢复的故障:copy 模式要么丢弃坏包(内容缺口、GOP 冻结/花屏,🐛[BUG] 新版本录制过程中会出现数据流损坏,闪频录制错误情况 #450 的形态)要么透传;唯一有效的修复是发现流源劣化后重连获取新的流地址——这正是 🐛[BUG] 新版本录制过程中会出现数据流损坏,闪频录制错误情况 #450 评论区社区建议的方向。

本 PR 的修复(StreamCap 层,不动 ffmpeg 参数)

  1. 劣化流检测重启:_monitor_stderr(扩展自 _capture_stream_tail)对 stderr 中每条 Packet corrupt/invalid data found 记录时间戳;60 秒窗口内达到 stream_error_threshold(默认 30,0 禁用)条即判定流源劣化 → 走已有的优雅停止路径(正确收尾文件)→ recheck_live_status 以新标志 degraded 放行,自动用新的流地址重启录制。
  2. 可选连接轮换:max_stream_connection_duration(默认 0=关闭)超时主动轮换连接,在 CDN 会话劣化之前拿到新地址,防患于未然。

两个触发都复用优雅停止链路(写 q → 等待 → 兜底 kill),文件完整 finalize,不产生损坏文件。

📝 类型(Type of Change)

  • 修复Bug
  • 新功能
  • 代码风格更新(格式化,局部变量)
  • 重构(改进代码结构)
  • 构建相关更改(依赖项,构建脚本等)
  • 其他:_ _

🏗️ 测试(Testing)

端到端(真实 ffmpeg 子进程 + 本地无限坏流 HTTP 源),15/15 通过:

  • 坏流 → 腐败计数 → 阈值触发 → should_stop/degraded 置位 → 优雅停止(输出文件完整)→ recheck_live_status 放行并调用 check_if_live 重启,全程 6.1s
  • 对照组:正常 warning(Non-monotonic DTS 等)不计数、不误触发;阈值 0 禁用;连接轮换的触发/未到期/禁用三态
  • ruff 通过

实验数据可复现:实验脚本含本地 HTTP 服务器造流、故障注入与 ffprobe 量化方法,欢迎审查复验。

📋 检查清单(Checklist)

  • 我已经阅读贡献指南文档(仓库无独立 CONTRIBUTING.md,按 PR 模板执行)
  • 我的更改没有产生新的警告(ruff 通过)
  • 我已经添加了覆盖我更改的测试(15 项端到端+对照验证)
  • 我已经相应地更新了文档(如果适用)(新增配置项 stream_error_threshold/max_stream_connection_duration 为可选高级项,默认行为不变)
  • 我遵循了这个项目的代码风格

Fixes #450
Helps #484
Helps #474

qinzihan added 2 commits November 10, 2026 11:28
…ding rot (ihmily#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 ihmily#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).
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).
@zzuu080603

Copy link
Copy Markdown
Author

对本 PR 做了一轮对抗性审查(red-team),发现初版的重启侧存在多个严重问题,已在 commit 0c087a1 全部修复:

  1. 重启风暴无熔断 → 新增熔断:10 分钟内 3 次劣化重启后停止自动重启,交还周期检测
  2. 轮换被当作重新开播 → 同场直播语义:保留 is_live/notified_*(不重发开播通知/桌面提醒、不吞下播通知),录制时长先补记再由 start_update 重置
  3. kill/异常路径丢失重启(劣化最严重时优雅停止恰最易失败)→ 所有 degraded 退出路径(returncode 异常、BrokenPipe、except)统一走重启收尾
  4. douyin/tiktok 净回归(recheck 被 flv-preferred 拦截)与 短轮换 <25s 死循环(min-valid 门槛)→ degraded 重启显式绕过两道拦截
  5. stream_error_threshold: 0 禁用失效(or 回退吞 0)与 阈值 >200 静默失效(事件列表硬 cap)→ 修复
  6. stderr 按块匹配漏检(跨 4KB 边界漏计、单块多条只计 1)→ 改为行级计数 + 跨块缓冲

验证扩至 24/24(端到端真实 ffmpeg + 熔断/同场语义/门槛绕过/阈值边界/行计数)。

另注:本 PR 与 #515(stalled 检测)都修改了 recheck_live_status 的守卫条件,合并时需保留两种标志(or self.degraded or self.stalled),两个检测本身互不冲突。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛[BUG] 新版本录制过程中会出现数据流损坏,闪频录制错误情况

1 participant