From 4abed7b8f065aec5eb859cc10525a3dd24148d2f Mon Sep 17 00:00:00 2001 From: eric Date: Sun, 14 Jun 2026 02:21:53 -0500 Subject: [PATCH] 's' --- d2ypp2/douyin_youtube_ffplay.py | 64 +++++++++++++++------- d2ypp2/src/youtube_quality_guard.py | 5 +- d2ypp2/tests/test_youtube_quality_guard.py | 20 +++++++ d2ypp2/youtube.py | 7 +++ 4 files changed, 75 insertions(+), 21 deletions(-) diff --git a/d2ypp2/douyin_youtube_ffplay.py b/d2ypp2/douyin_youtube_ffplay.py index eb1ff33..cb4b65d 100644 --- a/d2ypp2/douyin_youtube_ffplay.py +++ b/d2ypp2/douyin_youtube_ffplay.py @@ -35,6 +35,21 @@ _FFMPEG_STATIC_CACHE: dict[str, bool] = {} _FFMPEG_PROTOCOLS_CACHE: dict[str, str] = {} +def _youtube_bitrate_triplet(kbps: int) -> tuple[str, str, str]: + """YouTube Live prefers CBR; keep maxrate equal to target and use a 2s VBV buffer.""" + n = max(1500, min(int(kbps), 9000)) + return f"{n}k", f"{n}k", f"{n * 2}k" + + +def _ffmpeg_stats_period_seconds(default: int = 5) -> str: + raw = os.environ.get("LIVE_FFMPEG_STATS_PERIOD") or os.environ.get("YOUTUBE_FFMPEG_STATS_PERIOD") or str(default) + try: + value = int(float(str(raw).strip())) + except (TypeError, ValueError): + value = default + return str(max(1, min(value, 60))) + + def _ffmpeg_display_name(ffmpeg_bin: str) -> str: return ffmpeg_bin or "ffmpeg" @@ -71,7 +86,7 @@ def _ffmpeg_supports_stats_period(ffmpeg_bin: str = "ffmpeg") -> bool: def _ffmpeg_stats_args(ffmpeg_bin: str = "ffmpeg") -> list[str]: if _ffmpeg_supports_stats_period(ffmpeg_bin): - return ["-stats", "-stats_period", "1"] + return ["-stats", "-stats_period", _ffmpeg_stats_period_seconds()] print(f"[WARN] {_ffmpeg_display_name(ffmpeg_bin)} 不支持 -stats_period,已降级为 -stats") return ["-stats"] @@ -198,11 +213,12 @@ def _resolve_youtube_push_config_file(config_file: str | None = None, *, base_di def _load_youtube_push_settings(config_file: str) -> dict[str, str | bool]: + b_v, maxrate, bufsize = _youtube_bitrate_triplet(4000) settings: dict[str, str | bool] = { "use_rtmps": True, - "b_v": "4000k", - "maxrate": "4500k", - "bufsize": "8000k", + "b_v": b_v, + "maxrate": maxrate, + "bufsize": bufsize, "stream_key": "", "fast_audio": True, } @@ -222,10 +238,7 @@ def _load_youtube_push_settings(config_file: str) -> dict[str, str | bool]: settings["fast_audio"] = v.lower() in ("1", "true", "yes", "是", "开", "on") elif k == "bitrate" and v: try: - n = int(v) - settings["b_v"] = f"{n}k" - settings["maxrate"] = f"{min(n * 12 // 10, 8000)}k" - settings["bufsize"] = f"{n * 2}k" + settings["b_v"], settings["maxrate"], settings["bufsize"] = _youtube_bitrate_triplet(int(v)) except ValueError: pass elif (k == "key" or k == "stream_key") and v and not v.startswith("#"): @@ -542,8 +555,8 @@ def start_douyin_youtube_ffplay( rtmps_base = os.environ.get("YOUTUBE_RTMPS_BASE", "rtmps://a.rtmps.youtube.com/live2/") rtmp_base = os.environ.get("YOUTUBE_RTMP_BASE", "rtmp://a.rtmp.youtube.com/live2/") use_rtmps = True - # 720p 竖屏,符合 YouTube 推荐:4–6 Mbps、2s 关键帧、AAC 128k - b_v, maxrate, bufsize = "4000k", "4500k", "8000k" + # 720p 竖屏直播基线:H.264 CBR、30fps、2s 关键帧、AAC 128k/48kHz。 + b_v, maxrate, bufsize = _youtube_bitrate_triplet(4000) stream_key = None push_proxy = "" push_proxy_mode = "" @@ -569,8 +582,7 @@ def start_douyin_youtube_ffplay( fast_audio = v.lower() in ("1", "true", "yes", "是", "开", "on") elif k == "bitrate" and v: try: - n = int(v) - b_v, maxrate, bufsize = f"{n}k", f"{min(n * 12 // 10, 8000)}k", f"{n * 2}k" + b_v, maxrate, bufsize = _youtube_bitrate_triplet(int(v)) except ValueError: pass elif (k == "key" or k == "stream_key") and v and not v.startswith("#"): @@ -665,7 +677,7 @@ def start_douyin_youtube_ffplay( codec_v = "libx264" video_args = [ "-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0", - "-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize, + "-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize, ] _config_dir = os.path.dirname(os.path.abspath(config_file)) @@ -746,7 +758,7 @@ def start_douyin_youtube_ffplay( print(f"[WARN] {_enc_note}") if _selected_enc: codec_v = _selected_enc - video_args = ["-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize] + video_args = ["-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize] _hw_enc_active = True print(f"[INFO] 使用 config/hardware.env LIVE_VIDEO_ENCODER={codec_v}(板载硬件编码)") except Exception as e: @@ -767,7 +779,7 @@ def start_douyin_youtube_ffplay( codec_v = "h264_nvenc" video_args = [ "-profile:v", "high", "-level", "4.0", - "-tune", "ll", "-rc", "cbr", "-b:v", b_v, + "-tune", "ll", "-rc", "cbr", "-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize, ] print("[INFO] 检测到 NVIDIA GPU → 使用 NVENC 硬件加速") @@ -828,7 +840,7 @@ def start_douyin_youtube_ffplay( _video_mid = ["-vsync", "cfr", "-g", "60", "-keyint_min", "60", "-r", "30", "-bf", "0", "-sc_threshold", "0"] if codec_v == "libx264": - _video_mid += ["-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0"] + _video_mid += ["-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0:keyint=60:min-keyint=60:nal-hrd=cbr"] # -re:按源时间戳节奏拉流,避免突发过快;不用 realtime/arealtime(输入抖动时易让 YouTube 判为数据不足) _vf_pad = ( "fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=bilinear," @@ -847,12 +859,17 @@ def start_douyin_youtube_ffplay( codec_v = "libx264" video_args = [ "-preset", "ultrafast", "-tune", "zerolatency", "-profile:v", "high", "-level", "4.0", - "-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize, + "-b:v", b_v, "-minrate", b_v, "-maxrate", maxrate, "-bufsize", bufsize, ] _hw_enc_active = False _input_path = os.path.normpath(os.path.expanduser(real_url)) _input_is_file = os.path.isfile(_input_path) _stats_args = _ffmpeg_stats_args(ffmpeg_bin) + print( + "[INFO] YouTube Live profile: " + f"{'RTMPS' if youtube_rtmp.startswith('rtmps://') else 'RTMP'} | " + f"H.264 {codec_v} CBR {b_v} | 720x1280@30 | keyint=2s | AAC 128k/48kHz | real-time input pacing" + ) if _input_is_file: ffmpeg_command = [ ffmpeg_bin, "-y", "-loglevel", "info", "-nostdin", @@ -889,6 +906,7 @@ 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, @@ -948,6 +966,7 @@ def start_douyin_youtube_ffplay( start_time = last_frame_time = time.time() last_progress_frame = -1 last_progress_time = -1.0 + last_ffmpeg_log_time = 0.0 while True: try: @@ -965,15 +984,20 @@ def start_douyin_youtube_ffplay( break continue - line = line.strip() + line = re.sub(r"[\r\n]+", " ", line).strip() if line.startswith("__ERR__READER__"): print(f"[ERROR] stderr reader 异常: {line}") continue if line: - proc.last_out_ts = time.time() - print(f"[FFmpeg] {line}") + now_ts = time.time() + proc.last_out_ts = now_ts line_lower = line.lower() + is_progress_line = "frame=" in line_lower and ("time=" in line_lower or "speed=" in line_lower) + if not is_progress_line or now_ts - last_ffmpeg_log_time >= 15: + print(f"[FFmpeg] {line}") + if is_progress_line: + last_ffmpeg_log_time = now_ts if any(kw in line_lower for kw in TERMINAL_KEYWORDS): print("[ERROR] 判定直播结束或平台明确拒绝,停止推流") diff --git a/d2ypp2/src/youtube_quality_guard.py b/d2ypp2/src/youtube_quality_guard.py index 2b3afcd..02820ab 100644 --- a/d2ypp2/src/youtube_quality_guard.py +++ b/d2ypp2/src/youtube_quality_guard.py @@ -91,6 +91,9 @@ def _process_score(row: dict[str, Any], metrics: dict[str, Any]) -> tuple[int, l if isinstance(speed, (int, float)) and speed < 0.98: score -= 18 issues.append({"level": "warning", "text": f"编码速度 {speed:.2f}x,低于实时直播要求"}) + elif isinstance(speed, (int, float)) and speed > 1.10: + score -= 12 + issues.append({"level": "warning", "text": f"推流速度 {speed:.2f}x,高于实时节奏;检查 FFmpeg 是否缺少 -re"}) fps = metrics.get("fps") if isinstance(fps, (int, float)) and fps > 0 and fps < 24: @@ -200,7 +203,7 @@ def build_youtube_quality_guard_report( "ffmpeg_profile": { "target": "1080p30/RTMPS/AAC/stable input copy when possible", "guardrails": [ - "保持 speed >= 1.00x", + "保持 FFmpeg speed 接近 1.00x", "长直播优先稳定码率与低错误率,而不是频繁重启", "Studio 弹窗、健康度、观众数必须持续采样", "源直播间断流时自动记录事件并提示切换备用 URL", diff --git a/d2ypp2/tests/test_youtube_quality_guard.py b/d2ypp2/tests/test_youtube_quality_guard.py index 65836a2..824b2b4 100644 --- a/d2ypp2/tests/test_youtube_quality_guard.py +++ b/d2ypp2/tests/test_youtube_quality_guard.py @@ -41,6 +41,26 @@ class YoutubeQualityGuardTests(unittest.TestCase): self.assertIn("FFmpeg 未检测到", report["lanes"][0]["issues"][0]["text"]) self.assertEqual(report["lanes"][0]["source_display"], "抖音直播间 123") + def test_quality_report_flags_ffmpeg_running_faster_than_realtime(self) -> None: + report = build_youtube_quality_guard_report( + [ + { + "pm2": "youtube2__lane1", + "label": "线路 1", + "process_status": "online", + "business_status": "streaming", + "ffmpeg_active": True, + "is_pushing": True, + "recent_log": "[FFmpeg] frame=179045 fps=51 time=01:39:28.21 bitrate=2496.7kbits/s speed=1.68x", + "recent_error": "", + } + ], + config_by_process={"youtube2__lane1": {"youtube_ini_text": "[youtube]\nkey = demo\nrtmps = 是\n", "url_lines": "https://live.douyin.com/123\n"}}, + ) + + issue_text = " ".join(issue["text"] for issue in report["lanes"][0]["issues"]) + self.assertIn("高于实时节奏", issue_text) + def test_quality_report_passes_human_source_display(self) -> None: report = build_youtube_quality_guard_report( [ diff --git a/d2ypp2/youtube.py b/d2ypp2/youtube.py index ee50cab..d409239 100644 --- a/d2ypp2/youtube.py +++ b/d2ypp2/youtube.py @@ -174,6 +174,13 @@ def display_info() -> None: line = line[:terminal_width-8] + "..." display_lines.append(line) + # PM2/journal logs are not an interactive terminal; carriage-return redraws + # get glued to FFmpeg progress lines and make the live log unreadable. + if not sys.stdout.isatty(): + print(" | ".join(display_lines), flush=True) + time.sleep(15) + continue + # 删除旧内容 + 打印新内容 if _last_lines_count > len(display_lines): _clear_lines(_last_lines_count - 1)