diff --git a/config/youtube.ini b/config/youtube.ini index 9d34b07..e9156c8 100644 --- a/config/youtube.ini +++ b/config/youtube.ini @@ -1,3 +1,9 @@ [youtube] -# 只写 stream key(推荐方式) -key = x04z-564w-aks7-embw-30y4 \ No newline at end of file +# 必填:YouTube 直播推流 key(在 YouTube 工作室 → 创建 → 流式传输 获取) +key = x04z-564w-aks7-embw-30y4 + +# 可选:是否使用 RTMPS 加密推流,填 否 则用 RTMP(默认 RTMPS) +; rtmps = 否 + +# 可选:视频比特率 kbps,720p 推荐 4000-6000(YouTube 官方 4-6 Mbps) +; bitrate = 4500 \ No newline at end of file diff --git a/docs/YOUTUBE_LIVE_SEO.md b/docs/YOUTUBE_LIVE_SEO.md new file mode 100644 index 0000000..0b85f03 --- /dev/null +++ b/docs/YOUTUBE_LIVE_SEO.md @@ -0,0 +1,50 @@ +# YouTube Live 转播优化与 SEO 指南 + +## 一、推流技术参数(已自动优化) + +- **分辨率**:720p 竖屏 (720×1280) +- **比特率**:4.5 Mbps(可在 config/youtube.ini 的 bitrate 调整) +- **关键帧**:2 秒(符合 YouTube 推荐) +- **音频**:AAC 128kbps 48kHz 立体声 +- **协议**:RTMPS 加密推流(推荐) +- **防版权**:开源音频处理链(降噪 + 带通 + EQ + 相位扰动) + +## 二、YouTube 直播 SEO 与推荐权重 + +直播标题、描述、标签在 **YouTube 工作室** 创建直播时设置,推流程序无法修改。以下为提升推荐权重的建议: + +### 标题(前 60 字最关键) + +- 主关键词放前面,如:`LIVE 摆摊日常 | 路边直播` +- 可加实时感词汇:LIVE、直播、实时、正在直播 +- 避免堆砌关键词,保持可读性 + +### 描述(前 125 字影响搜索) + +- 首段包含主关键词和内容概要 +- 可说明:转播自抖音、直播内容类型、时间等 + +### 标签 + +- 5–15 个相关标签,如:live stream, 摆摊, 路边直播, 抖音转播 +- 与标题、描述语义一致 + +### 算法相关因素 + +- **观看时长**:用户停留越久,推荐越高 +- **互动**:点赞、评论、分享 +- **画质与音质**:清晰稳定的流有助于留存 + +## 三、config/youtube.ini 配置说明 + +| 配置项 | 说明 | 示例 | +|--------|------|------| +| key | 必填,YouTube stream key | key = xxxx-xxxx-xxxx | +| rtmps | 是否用 RTMPS(默认是) | rtmps = 否 | +| bitrate | 视频比特率 kbps | bitrate = 4500 | + +## 四、稳定性建议 + +1. 网络:上行带宽 ≥ 6 Mbps,建议有线 +2. 推流前在 YouTube 工作室完成标题、描述、标签设置 +3. 定期检查 config/youtube.ini 中的 stream key 是否有效 diff --git a/douyin_youtube_ffplay.py b/douyin_youtube_ffplay.py index 9f492ac..cf1ad46 100644 --- a/douyin_youtube_ffplay.py +++ b/douyin_youtube_ffplay.py @@ -79,25 +79,38 @@ def start_douyin_youtube_ffplay( 只从 config/youtube.ini 读取一个 stream key(取第一个有效值) """ - # ====================== 读取 YouTube stream key 配置 ====================== + # ====================== 读取 YouTube 配置 ====================== config_file = "config/youtube.ini" + rtmps_base = "rtmps://a.rtmp.youtube.com/live2/" rtmp_base = "rtmp://a.rtmp.youtube.com/live2/" - default_key = "qxvb-r47b-r5ju-6ud3-6k7z" # 备用默认 key - youtube_rtmp = rtmp_base + default_key # 默认值 + use_rtmps = True + b_v, maxrate, bufsize = "4500k", "5500k", "9000k" + stream_key = None if os.path.exists(config_file): config = configparser.ConfigParser() config.read(config_file, encoding="utf-8") if config.has_section("youtube"): - for key_name, value in config.items("youtube"): - value = value.strip() - if value: - if value.startswith("rtmp://"): - youtube_rtmp = value - else: - youtube_rtmp = rtmp_base + value - print(f"[INFO] 从 {config_file} 读取 YouTube stream key: {youtube_rtmp}") - break # 只取第一个有效 key,保持单路推流(不加多路逻辑) + for k, v in config.items("youtube"): + v = (v or "").strip() + if k == "rtmps" and v.lower() in ("0", "false", "否"): + use_rtmps = False + 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" + except ValueError: + pass + elif (k == "key" or k == "stream_key") and v and not v.startswith("#"): + stream_key = v + if stream_key: + if stream_key.startswith("rtmp://") or stream_key.startswith("rtmps://"): + youtube_rtmp = stream_key + else: + youtube_rtmp = (rtmps_base if use_rtmps else rtmp_base) + stream_key + print(f"[INFO] 从 {config_file} 读取 YouTube 推流地址") + else: + raise ValueError(f"请在 {config_file} 中配置 key=你的stream_key") # ====================== 常量配置 ====================== MAX_RETRY_DELAY = 90 @@ -106,6 +119,7 @@ def start_douyin_youtube_ffplay( NO_FRAME_TIMEOUT = 120 START_CHECK_AFTER = 25 STALE_OUTPUT_SECONDS = 40 + RECONNECT_DELAY_MAX = 10 END_KEYWORDS = [ "connection reset by peer", @@ -113,6 +127,7 @@ def start_douyin_youtube_ffplay( "invalid data found", "server returned 403", "server returned 404", + "server returned 500", "ingestion error", "access denied", "packet too short", @@ -120,6 +135,10 @@ def start_douyin_youtube_ffplay( "live has ended", "no route to host", "connection timed out", + "connection refused", + "error writing output", + "broken pipe", + "i/o error", ] douyin_headers = ( @@ -134,10 +153,10 @@ def start_douyin_youtube_ffplay( stream_title = sanitize_title(f"{anchor_name}{('_' + clean_title) if clean_title else ''}_{timestamp_str}") print(f"[INFO] {rec_info} 开始推流到 YouTube: {stream_title}") - # ====================== NVENC 检测 ====================== + # ====================== NVENC 检测(符合 YouTube 推荐比特率)====================== codec_v = "libx264" - preset_v = "veryfast" - tune_param = ["-tune", "zerolatency"] + video_args = ["-preset", "fast", "-profile:v", "high", "-level", "4.0", + "-b:v", b_v, "-maxrate", maxrate, "-bufsize", bufsize] try: if platform.system().lower() in ["windows", "linux"]: check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5) @@ -145,280 +164,74 @@ def start_douyin_youtube_ffplay( enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True, timeout=5) if "h264_nvenc" in (enc.stdout or ""): codec_v = "h264_nvenc" - preset_v = "p5" - tune_param = ["-tune", "ll", "-rc", "vbr", "-cq", "21", "-b:v", "2500k"] + video_args = ["-profile:v", "high", "-level", "4.0", + "-tune", "ll", "-rc", "vbr", "-cq", "21", "-b:v", b_v] print("[INFO] 检测到 NVIDIA GPU → 使用 NVENC 硬件加速") except Exception as e: print(f"[WARN] NVENC 检测失败,回退软件编码: {e}") - # 720p (最原始) + # ====================== 开源音频处理:背景音乐弱化 + 防版权 ====================== + # 优先 RNNoise(arnndn),无模型则用 afftdn;aphaser 相位扰动可干扰 Content ID 指纹 + _script_dir = os.path.dirname(os.path.abspath(__file__)) + _arnndn_paths = [ + os.path.join(_script_dir, "arnndn-models", "cb.rnnn"), + os.path.join(os.path.dirname(_script_dir), "arnndn-models", "cb.rnnn"), + "arnndn-models/cb.rnnn", + ] + _arnndn_model = None + for _p in _arnndn_paths: + if os.path.isfile(_p): + _arnndn_model = os.path.normpath(_p) + break + if _arnndn_model: + print(f"[INFO] 使用 RNNoise 降噪模型: {_arnndn_model}") + _af_denoise = f"arnndn=m={_arnndn_model}:mix=0.82," + else: + print("[INFO] 未找到 arnndn 模型,使用 afftdn 降噪(可克隆 richardpl/arnndn-models 到 arnndn-models/)") + _af_denoise = "afftdn=nf=-26:tn=1," + + _af_chain = ( + _af_denoise + + "highpass=f=120,lowpass=f=4800," + + "equalizer=f=180:width_type=o:width=2.2:g=-10," + + "equalizer=f=400:width_type=o:width=1.8:g=-6," + + "equalizer=f=800:width_type=o:width=1.5:g=-5," + + "acompressor=threshold=-28dB:ratio=4:attack=10:release=100:makeup=4," + + "aphaser=type=t:decay=0.3:delay=2.5:speed=0.6," + + "volume=1.1," + + "aresample=async=1:first_pts=0" + ) + + # 720p 竖屏,符合 YouTube 推荐:4–6 Mbps、2s 关键帧、AAC 128k + _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"] ffmpeg_command = [ "ffmpeg", "-y", "-loglevel", "info", "-nostdin", "-re", "-stats", "-stats_period", "1", - "-rw_timeout", "30000000", + "-rw_timeout", "50000000", "-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", - "-reconnect_delay_max", "5", + "-reconnect_delay_max", str(RECONNECT_DELAY_MAX), "-fflags", "+genpts+discardcorrupt+nobuffer+flush_packets", "-flags", "low_delay", "-err_detect", "ignore_err", "-max_delay", "80000", "-thread_queue_size", "2048", - "-headers", douyin_headers, "-i", real_url, - # 720p "-vf", "fps=30,scale=720:1280:force_original_aspect_ratio=decrease:flags=lanczos,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black", - "-c:v", "libx264", - "-preset", "fast", - # "-tune", "zerolatency", - "-profile:v", "high", - # 720p - # "-minrate", "3200k","-b:v", "3200k", "-maxrate", "3200k", "-bufsize", "6400k", # bufsize = 2× bitrate,保持真 CBR - "-b:v", "2600k","-maxrate", "3000k","-bufsize", "5200k", - "-vsync", "cfr", - "-g", "60", "-keyint_min", "60", - "-r", "30", - "-bf", "0", - "-sc_threshold", "0", - # "-nal-hrd", "cbr", # 改2:强制 CBR - # 720p - # "-x264-params", "nal-hrd=cbr:force-cfr=1:scenecut=0:filler=1", # 改3:简化 params,锁死 CBR - "-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0", + "-c:v", codec_v, + *video_args, + *_video_mid, "-pix_fmt", "yuv420p", - "-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2", # 改4:1080p可音频上 128k(YouTube 推荐) - "-af", "aresample=async=1:first_pts=0", - + "-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2", + "-af", _af_chain, "-flags", "+global_header", "-flvflags", "no_duration_filesize", "-f", "flv", youtube_rtmp ] - - - - # "arnndn=m=./arnndn-models/cb.rnnn:mix=0.85," # 人声增强 -# 720p-低CPU + 背景音乐处理 + 防ContentID - # ffmpeg_command = [ - # "ffmpeg", "-y", "-loglevel", "info", "-nostdin", "-re", - # "-stats", "-stats_period", "1", - # "-rw_timeout", "30000000", - # "-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", - # "-reconnect_delay_max", "5", - # "-fflags", "+genpts+discardcorrupt+nobuffer+flush_packets", - # "-flags", "low_delay", - # "-err_detect", "ignore_err", - # "-max_delay", "80000", - # "-thread_queue_size", "2048", - - # "-headers", douyin_headers, - # "-i", real_url, - - # # 视频处理 720p - # "-vf", - # "fps=25,scale=720:1280:force_original_aspect_ratio=decrease:flags=bicubic," - # "pad=720:1280:(ow-iw)/2:(oh-ih)/2:black", - - # "-c:v", "libx264", - # "-preset", "veryfast", # 降低CPU - # "-profile:v", "high", - # "-b:v", "2600k", "-maxrate", "3000k", "-bufsize", "5200k", - # "-vsync", "cfr", - # "-g", "50", "-keyint_min", "50", # 与fps=25匹配 - # "-r", "25", - # "-bf", "0", - # "-sc_threshold", "0", - # "-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0", - # "-pix_fmt", "yuv420p", - - # # 音频处理(轻量 + 背景音乐弱化 + 防Content ID) - # "-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2", - # "-af", - # "afftdn=nf=-28:tn=1," # 轻 FFT 降噪,背景弱化 - # "highpass=f=120,lowpass=f=4800," # 切低频鼓 & 高频镲 - # "equalizer=f=250:width_type=o:width=2:g=-8," # 衰减低中频 - # "equalizer=f=800:width_type=o:width=1.5:g=-5," # 衰减中频 - # "acompressor=threshold=-30dB:ratio=4:attack=10:release=100:makeup=4," # 压动态 - # "asetrate=48000*1.02,aresample=48000," # 音高微升 - # "afreqshift=shift=15," # 小幅频率偏移 - # "volume=1.1," # 音量补偿 - # "aresample=async=1:first_pts=0", # 音视频同步 - - # # 推流参数 - # "-flvflags", "no_duration_filesize", - # "-f", "flv", youtube_rtmp - # ] - - - - - - - # 1080p - # ffmpeg_command = [ - # "ffmpeg", "-y", "-loglevel", "info", "-nostdin", "-re", - # "-stats", "-stats_period", "1", - # "-rw_timeout", "30000000", - # "-reconnect", "1", "-reconnect_at_eof", "1", - # "-reconnect_streamed", "1", - # "-reconnect_delay_max", "5", - # "-fflags", "+genpts+discardcorrupt+nobuffer+flush_packets", - # "-flags", "low_delay", - # "-err_detect", "ignore_err", - # "-max_delay", "80000", - # "-thread_queue_size", "2048", - - # "-headers", douyin_headers, - # "-i", real_url, - - # # 视频:不动你原策略,只给编码喘口气 - # "-vf", "fps=25,scale=1080:1920:force_original_aspect_ratio=decrease:flags=bicubic," - # "pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black", - - # "-c:v", "libx264", - # "-preset", "superfast", - # "-tune", "zerolatency", - # "-profile:v", "high", - # "-b:v", "5200k", "-maxrate", "5800k", "-bufsize", "10400k", - # "-vsync", "cfr", - # "-g", "50", "-keyint_min", "50", - # "-r", "25", - # "-bf", "0", - # "-sc_threshold", "0", - # "-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0", - # "-pix_fmt", "yuv420p", - - # # 音频 - # "-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2", - - # "-af", - # "afftdn=nf=-18:tn=1," - # "highpass=f=120,lowpass=f=4600," - # "equalizer=f=250:width_type=o:width=2:g=-6," - # "equalizer=f=900:width_type=o:width=1.4:g=-4," - # "asetrate=48000*1.012,aresample=48000," - # "acompressor=threshold=-30dB:ratio=4:attack=10:release=120:makeup=4," - # "volume=1.10," - # "aresample=async=1:first_pts=0", - - # "-flvflags", "no_duration_filesize", - # "-f", "flv", youtube_rtmp - # ] - - -# 1080p - 极致优化版本(Ubuntu Server 专用,高质量 + YouTube直播推荐友好 + 强防Content ID) -# 针对Ubuntu server(通常CPU较强,无iOS硬件限制): -# - preset 升级到 medium 或 slow(如果CPU能承受,质量显著提升) -# - 比特率保持8500k-10000k峰值,符合YouTube 1080p直播高质量推荐 -# - 音频防Content ID:音高+5%、频率偏移、多段EQ衰减背景音乐、强压缩、相位扰动(使用aphaser正确参数)、轻噪门 -# - 移除无效参数,修复之前aphaser错误(aphaser支持in_gain/out_gain/delay/decay/speed/type,不支持feedback) -# - Ubuntu下推荐使用最新FFmpeg(apt install ffmpeg 或从源码编译支持libx264) - - # ffmpeg_command = [ - # "ffmpeg", "-y", "-loglevel", "info", "-nostdin", "-re", - # "-stats", "-stats_period", "1", - # "-rw_timeout", "30000000", - # "-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1", - # "-reconnect_delay_max", "5", - # "-fflags", "+genpts+discardcorrupt+nobuffer+flush_packets", - # "-flags", "low_delay", - # "-err_detect", "ignore_err", - # "-max_delay", "50000", - # "-thread_queue_size", "4096", - - # "-headers", douyin_headers, - # "-i", real_url, - - # # 视频处理:1080p 纵屏优化,黑边填充 - # "-vf", - # "fps=25,scale=1080:1920:force_original_aspect_ratio=decrease:flags=bicubic," - # "pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black", - - # "-c:v", "libx264", - # "-preset", "ultrafast", # Ubuntu server CPU通常能承受,质量比faster好很多;若掉帧可回退到faster或veryfast - # "-threads", "4", - # "-tune", "zerolatency", - # "-profile:v", "high", - # "-level", "4.2", # 支持1080p@25fps - # # "-b:v", "8500k", "-maxrate", "10000k", "-bufsize", "20000k", - # "-b:v", "4500k", "-maxrate", "5500k", "-bufsize", "9000k", - # "-vsync", "cfr", - # "-g", "50", "-keyint_min", "50", - # "-r", "25", - # "-bf", "0", - # "-sc_threshold", "0", - # "-x264-params", "force-cfr=1:scenecut=0:open_gop=0:sync-lookahead=0:rc-lookahead=0", - # "-pix_fmt", "yuv420p", - - # # 音频处理 - 防Content ID 强化版(多维度修改音频指纹) - # "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-ac", "2", - # "-af", - # "arnndn=m=./arnndn-models/cb.rnnn:mix=0.85," #神经网络 - # "afftdn=nf=-24:tn=1," # 中等降噪,保留人声清晰度 - # "highpass=f=100,lowpass=f=5200," # 切除低频鼓/贝斯 & 高频镲/噪音,聚焦人声区 - # "equalizer=f=180:width_type=o:width=2.2:g=-12," # 强衰减低频(背景音乐基础层) - # "equalizer=f=350:width_type=o:width=1.8:g=-9," # 衰减低中频(常见旋律区) - # "equalizer=f=750:width_type=o:width=1.6:g=-7," # 中频衰减,破坏音乐结构 - # "equalizer=f=2800:width_type=o:width=1.2:g=-5," # 高中频轻衰减,保持人声自然 - # "acompressor=threshold=-26dB:ratio=5.5:attack=7:release=90:makeup=6," # 强压缩,改变动态指纹 - # "asetrate=48000*1.05,atempo=1.0,aresample=48000," # 音高抬升5%(不改速度),有效规避Content ID - # "afreqshift=shift=22," # 频率整体偏移,进一步破坏匹配 - # "aphaser=type=t:decay=0.35:delay=3.0:speed=0.5," # 正确参数:轻微相位扰动(triangular类型),防检测 - # # "anlmdn=s=0.00012:p=0.0008:r=0.002," # 轻量非线性噪门,清理残余背景音乐 - # "volume=1.08," # 补偿音量衰减 - # "aresample=async=1:first_pts=0:min_hard_comp=0.100000:first_pts=0", # 强制音视频同步 - - # # 推流优化(FLV适合YouTube RTMP/RTMPS) - # "-flvflags", "no_duration_filesize", - # "-f", "flv", youtube_rtmp - # ] - - - - # ffmpeg_command = [ - # "ffmpeg","-y","-loglevel","info","-nostdin","-re", - # "-stats","-stats_period","1", - - # # 输入稳定 - # "-rw_timeout","30000000", - # "-reconnect","1","-reconnect_at_eof","1","-reconnect_streamed","1", - # "-reconnect_delay_max","5", - - # # 关键:删除低延迟杀手参数 - # "-fflags","+genpts+discardcorrupt", - # "-err_detect","ignore_err", - # "-max_delay","500000", - # "-thread_queue_size","512", - - # # 抖音源 - # "-headers", douyin_headers, - # "-i", real_url, - - # # 视频处理 - # "-vf","fps=25,scale=1080:1920:force_original_aspect_ratio=decrease,pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black", - - # # 编码 - # "-c:v","libx264", - # "-preset","veryfast", - # "-profile:v","high", - # "-level","4.2", - # "-b:v","4500k","-maxrate","4500k","-bufsize","9000k", - # "-g","50","-keyint_min","50", - # "-r","25", - # "-pix_fmt","yuv420p", - # "-bf","0", - # "-sc_threshold","0", - # "-x264-params","force-cfr=1:scenecut=0:open_gop=0", - - # # 音频(强烈建议简化) - # "-c:a","aac","-b:a","128k","-ar","44100","-ac","2", - # "-af","aresample=async=1,volume=1.05", - - # # 推流 - # "-flvflags","no_duration_filesize", - # "-f","flv", youtube_rtmp - # ] - - proc = None stderr_q = None reader_t = None