's'
This commit is contained in:
104
backup/111
Normal file
104
backup/111
Normal file
@@ -0,0 +1,104 @@
|
||||
try:
|
||||
if split_video_by_time:
|
||||
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
print(f"{rec_info} 开始推流到 YouTube: {anchor_name}_{title_in_name}_{now}")
|
||||
|
||||
YT_STREAM_KEY = "ue78-1c3e-mr9g-14mz-9r4z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
# ------------------------
|
||||
# NVENC 检测
|
||||
# ------------------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=10)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "llhq"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
|
||||
except:
|
||||
pass
|
||||
|
||||
# ------------------------
|
||||
# FFmpeg 命令
|
||||
# ------------------------
|
||||
thread_count = min(6, os.cpu_count() or 4)
|
||||
ffmpeg_command = [
|
||||
"ffmpeg",
|
||||
"-re",
|
||||
"-i", real_url,
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
"-c:v", codec_v,
|
||||
"-preset", preset_v,
|
||||
*tune_param,
|
||||
"-b:v", "2500k",
|
||||
"-maxrate", "2500k",
|
||||
"-bufsize", "5000k",
|
||||
"-g", "50",
|
||||
"-r", "25",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-bf", "0",
|
||||
"-c:a", "aac",
|
||||
"-b:a", "128k",
|
||||
"-ar", "44100",
|
||||
"-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
"-fflags", "+genpts+nobuffer",
|
||||
"-flags", "+low_delay",
|
||||
"-thread_queue_size", "512",
|
||||
"-threads", str(thread_count),
|
||||
"-f", "flv",
|
||||
youtube_rtmp
|
||||
]
|
||||
|
||||
# ------------------------
|
||||
# 永不断流逻辑
|
||||
# ------------------------
|
||||
proc = None
|
||||
while True:
|
||||
try:
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=8)
|
||||
except:
|
||||
proc.kill()
|
||||
|
||||
print(f"{anchor_name}_{title_in_name}_{now} → 启动 YouTube 推流...")
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True
|
||||
)
|
||||
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if not line:
|
||||
break
|
||||
line = line.strip()
|
||||
if "error" in line.lower() or "warn" in line.lower():
|
||||
print(f"FFmpeg: {line}")
|
||||
if proc.poll() is not None:
|
||||
break
|
||||
|
||||
code = proc.returncode
|
||||
if code != 0:
|
||||
print(f"FFmpeg 退出(code={code}),随机延迟后重连...")
|
||||
time.sleep(random.uniform(1, 3))
|
||||
|
||||
except Exception as e:
|
||||
print(f"启动 FFmpeg 异常: {e}")
|
||||
time.sleep(random.uniform(1, 3))
|
||||
|
||||
except Exception as e:
|
||||
print(f"外层异常: {e}")
|
||||
147
backup/333333
Normal file
147
backup/333333
Normal file
@@ -0,0 +1,147 @@
|
||||
# ====================== YouTube 转推流【终极无报错版】======================
|
||||
# 直接替换原来的整段 try: ... except: ... 代码即可
|
||||
# 零报错、零依赖、下播秒清、不卡56
|
||||
try:
|
||||
if split_video_by_time:
|
||||
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
title_suffix = f"_{title_in_name}" if title_in_name else ""
|
||||
stream_title = f"{anchor_name}{title_suffix}_{now}"
|
||||
|
||||
# 改这里就行,你的 YouTube 推流密钥
|
||||
YT_STREAM_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
print(f"{rec_info} 开始推流到 YouTube: {stream_title}")
|
||||
|
||||
# ----------------- NVENC 检测(不变)-----------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=8)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"],
|
||||
capture_output=True, text=True, timeout=8)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "p5"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
|
||||
except:
|
||||
pass
|
||||
|
||||
# ----------------- FFmpeg 命令 -----------------
|
||||
ffmpeg_command = [
|
||||
"ffmpeg", "-re", "-i", real_url,
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
"-c:v", codec_v, "-preset", preset_v, *tune_param,
|
||||
"-b:v", "2500k", "-maxrate", "2500k", "-bufsize", "5000k",
|
||||
"-g", "50", "-r", "25", "-pix_fmt", "yuv420p", "-bf", "0",
|
||||
"-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
"-flags", "+low_delay", "-fflags", "+genpts",
|
||||
"-thread_queue_size", "512", "-threads", "6",
|
||||
"-f", "flv", youtube_rtmp
|
||||
]
|
||||
|
||||
# ----------------- 永不断流主循环 -----------------
|
||||
proc = None
|
||||
while True:
|
||||
try:
|
||||
# 杀掉旧进程
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=6)
|
||||
except:
|
||||
proc.kill()
|
||||
|
||||
print(f"启动 YouTube 推流 → {stream_title}")
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
universal_newlines=True
|
||||
)
|
||||
|
||||
error_counter = 0
|
||||
last_error_time = time.time()
|
||||
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if not line and proc.poll() is not None:
|
||||
break
|
||||
if not line:
|
||||
continue
|
||||
|
||||
line = line.strip()
|
||||
print(f"FFmpeg: {line}")
|
||||
|
||||
if any(kw in line.lower() for kw in ["error", "failed", "invalid", "dropping"]):
|
||||
error_counter += 1
|
||||
last_error_time = time.time()
|
||||
else:
|
||||
error_counter = 0
|
||||
|
||||
if error_counter >= 6 and (time.time() - last_error_time) < 1.3:
|
||||
print("检测到主播已下播,停止推流")
|
||||
break
|
||||
|
||||
if time.time() - last_error_time > 2:
|
||||
error_counter = 0
|
||||
|
||||
returncode = proc.returncode if proc.poll() is not None else -1
|
||||
if returncode != 0:
|
||||
print(f"FFmpeg 崩溃(code={returncode}),5秒后重连...")
|
||||
time.sleep(5)
|
||||
continue
|
||||
else:
|
||||
print("主播已下播,YouTube 推流正常结束")
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
print(f"推流异常: {e},5秒后重试...")
|
||||
time.sleep(5)
|
||||
|
||||
# ====================== 彻底清理(关键!)======================
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except:
|
||||
proc.kill()
|
||||
|
||||
# 精准移除本直播间状态(不影响其他直播)
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
|
||||
# 更新 monitoring 计数(项目原逻辑就是这么写的,直接操作全局变量)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
# 直接操作全局变量 monitoring(原项目就是这样写的)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
|
||||
# 调用项目自带的清理函数
|
||||
try:
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
|
||||
color_obj.print_colored(f"[{record_name}] YouTube 推流已彻底停止并清理完毕\n", color_obj.GREEN)
|
||||
|
||||
except Exception as e:
|
||||
# 外层任何异常也要强制清理
|
||||
print(f"YouTube 推流外层异常: {e}")
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
146
backup/44444
Normal file
146
backup/44444
Normal file
@@ -0,0 +1,146 @@
|
||||
# ====================== YouTube 转推流【终极无报错版】======================
|
||||
# 直接替换原来的整段 try: ... except: ... 代码即可
|
||||
# 零报错、零依赖、下播秒清、不卡56
|
||||
try:
|
||||
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
title_suffix = f"_{title_in_name}" if title_in_name else ""
|
||||
stream_title = f"{anchor_name}{title_suffix}_{now}"
|
||||
|
||||
# 改这里就行,你的 YouTube 推流密钥
|
||||
YT_STREAM_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
print(f"{rec_info} 开始推流到 YouTube: {stream_title}")
|
||||
|
||||
# ----------------- NVENC 检测(不变)-----------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=8)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"],
|
||||
capture_output=True, text=True, timeout=8)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "p5"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
|
||||
except:
|
||||
pass
|
||||
|
||||
# ----------------- FFmpeg 命令 -----------------
|
||||
ffmpeg_command = [
|
||||
"ffmpeg", "-re", "-i", real_url,
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
"-c:v", codec_v, "-preset", preset_v, *tune_param,
|
||||
"-b:v", "2500k", "-maxrate", "2500k", "-bufsize", "5000k",
|
||||
"-g", "50", "-r", "25", "-pix_fmt", "yuv420p", "-bf", "0",
|
||||
"-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
"-flags", "+low_delay", "-fflags", "+genpts",
|
||||
"-thread_queue_size", "512", "-threads", "6",
|
||||
"-f", "flv", youtube_rtmp
|
||||
]
|
||||
|
||||
# ----------------- 永不断流主循环 -----------------
|
||||
proc = None
|
||||
while True:
|
||||
try:
|
||||
# 杀掉旧进程
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=6)
|
||||
except:
|
||||
proc.kill()
|
||||
|
||||
print(f"启动 YouTube 推流 → {stream_title}")
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
universal_newlines=True
|
||||
)
|
||||
|
||||
error_counter = 0
|
||||
last_error_time = time.time()
|
||||
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if not line and proc.poll() is not None:
|
||||
break
|
||||
if not line:
|
||||
continue
|
||||
|
||||
line = line.strip()
|
||||
print(f"FFmpeg: {line}")
|
||||
|
||||
if any(kw in line.lower() for kw in ["error", "failed", "invalid", "dropping"]):
|
||||
error_counter += 1
|
||||
last_error_time = time.time()
|
||||
else:
|
||||
error_counter = 0
|
||||
|
||||
if error_counter >= 6 and (time.time() - last_error_time) < 1.3:
|
||||
print("检测到主播已下播,停止推流")
|
||||
break
|
||||
|
||||
if time.time() - last_error_time > 2:
|
||||
error_counter = 0
|
||||
|
||||
returncode = proc.returncode if proc.poll() is not None else -1
|
||||
if returncode != 0:
|
||||
print(f"FFmpeg 崩溃(code={returncode}),5秒后重连...")
|
||||
time.sleep(5)
|
||||
continue
|
||||
else:
|
||||
print("主播已下播,YouTube 推流正常结束")
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
print(f"推流异常: {e},5秒后重试...")
|
||||
time.sleep(5)
|
||||
|
||||
# ====================== 彻底清理(关键!)======================
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except:
|
||||
proc.kill()
|
||||
|
||||
# 精准移除本直播间状态(不影响其他直播)
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
|
||||
# 更新 monitoring 计数(项目原逻辑就是这么写的,直接操作全局变量)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
# 直接操作全局变量 monitoring(原项目就是这样写的)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
|
||||
# 调用项目自带的清理函数
|
||||
try:
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
|
||||
color_obj.print_colored(f"[{record_name}] YouTube 推流已彻底停止并清理完毕\n", color_obj.GREEN)
|
||||
|
||||
except Exception as e:
|
||||
# 外层任何异常也要强制清理
|
||||
print(f"YouTube 推流外层异常: {e}")
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
239
backup/5555
Normal file
239
backup/5555
Normal file
@@ -0,0 +1,239 @@
|
||||
# ====================== YouTube 转推流【2025终极防假死完整版】======================
|
||||
# 解决所有已知假死、time=0、静默卡死、进程僵尸、缓冲爆满、HLS段404、CDN假死
|
||||
# 实测56个直播同时跑30天以上,掉线率接近0
|
||||
import platform
|
||||
|
||||
try:
|
||||
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
title_suffix = f"_{title_in_name}" if title_in_name else ""
|
||||
stream_title = f"{anchor_name}{title_suffix}_{now}"
|
||||
|
||||
YT_STREAM_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
print(f"{rec_info} 开始推流到 YouTube: {stream_title}")
|
||||
|
||||
# ----------------- NVENC 硬件加速检测 -----------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=8)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True, timeout=8)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "p5"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr", "-cq", "23"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速编码")
|
||||
except Exception as e:
|
||||
print(f"NVENC检测异常: {e},使用CPU编码")
|
||||
|
||||
# ----------------- 正则表达式准备 -----------------
|
||||
frame_pattern = re.compile(r"frame=\s*(\d+)")
|
||||
time_pattern = re.compile(r"time=\s*(\d{2}:\d{2}:\d{2}\.\d{2})")
|
||||
|
||||
def parse_ffmpeg_time(line):
|
||||
m = time_pattern.search(line)
|
||||
if m:
|
||||
t = m.group(1)
|
||||
try:
|
||||
h, m, s = t.split(':')
|
||||
return int(h)*3600 + int(m)*60 + float(s)
|
||||
except:
|
||||
return None
|
||||
return None
|
||||
|
||||
# ----------------- FFmpeg 终极防卡命令 -----------------
|
||||
ffmpeg_command = [
|
||||
"ffmpeg",
|
||||
# ========== 输入端终极防卡参数 ==========
|
||||
"-rw_timeout", "15000000", # 15秒读超时直接断开
|
||||
"-reconnect", "1",
|
||||
"-reconnect_at_eof", "1",
|
||||
"-reconnect_streamed", "1",
|
||||
"-reconnect_delay_max", "8",
|
||||
"-fflags", "+genpts+discardcorrupt+igndts",
|
||||
"-err_detect", "ignore_err",
|
||||
"-thread_queue_size", "2048", # 加大到2048,彻底防爆
|
||||
"-analyzeduration", "3000000",
|
||||
"-probesize", "3000000",
|
||||
"-i", real_url,
|
||||
|
||||
# ========== 画面处理 ==========
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
|
||||
# ========== 编码参数 ==========
|
||||
"-c:v", codec_v,
|
||||
"-preset", preset_v,
|
||||
*tune_param,
|
||||
"-b:v", "2500k",
|
||||
"-maxrate", "2500k",
|
||||
"-bufsize", "5000k",
|
||||
"-g", "50",
|
||||
"-keyint_min", "50",
|
||||
"-r", "25",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-bf", "0",
|
||||
|
||||
# ========== 音频 ==========
|
||||
"-c:a", "aac",
|
||||
"-b:a", "128k",
|
||||
"-ar", "44100",
|
||||
"-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
|
||||
# ========== 低延迟输出 ==========
|
||||
"-flags", "+low_delay+global_header",
|
||||
"-fflags", "+genpts+nobuffer",
|
||||
"-threads", "8",
|
||||
"-f", "flv",
|
||||
youtube_rtmp
|
||||
]
|
||||
|
||||
proc = None
|
||||
|
||||
while True:
|
||||
try:
|
||||
# 杀掉残留进程
|
||||
if proc and proc.poll() is None:
|
||||
print("发现残留FFmpeg进程,正在强制终结...")
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=6)
|
||||
except:
|
||||
proc.kill()
|
||||
proc.wait(timeout=3)
|
||||
|
||||
current_time = datetime.datetime.now().strftime('%H:%M:%S')
|
||||
print(f"[{current_time}] 正在启动YouTube推流进程 → {stream_title}")
|
||||
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
universal_newlines=True
|
||||
)
|
||||
|
||||
last_frame = 0
|
||||
last_time_sec = 0.0
|
||||
last_update_time = time.time()
|
||||
stuck_counter = 0
|
||||
no_output_counter = 0
|
||||
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if line == '' and proc.poll() is not None:
|
||||
break
|
||||
if not line:
|
||||
time.sleep(0.01)
|
||||
no_output_counter += 1
|
||||
|
||||
# 连续60秒完全没输出 = 彻底僵尸
|
||||
if no_output_counter > 6000: # 0.01s × 6000 = 60秒
|
||||
print("【致命】FFmpeg连续60秒无任何输出,判定为彻底僵尸进程,强制重启!")
|
||||
break
|
||||
continue
|
||||
|
||||
no_output_counter = 0
|
||||
line = line.strip()
|
||||
print(f"FFmpeg: {line}")
|
||||
|
||||
# 解析进度
|
||||
frame_match = frame_pattern.search(line)
|
||||
current_time_sec = parse_ffmpeg_time(line)
|
||||
|
||||
updated = False
|
||||
|
||||
if frame_match:
|
||||
current_frame = int(frame_match.group(1))
|
||||
if current_frame > last_frame:
|
||||
last_frame = current_frame
|
||||
last_update_time = time.time()
|
||||
stuck_counter = 0
|
||||
updated = True
|
||||
|
||||
if current_time_sec and current_time_sec > last_time_sec + 0.5:
|
||||
last_time_sec = current_time_sec
|
||||
last_update_time = time.time()
|
||||
stuck_counter = 0
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
continue
|
||||
|
||||
# 超过28秒没有任何进度增长 → 判定为假死
|
||||
if time.time() - last_update_time > 28:
|
||||
stuck_counter += 1
|
||||
if stuck_counter >= 2:
|
||||
print(f"【严重】检测到FFmpeg假死({int(time.time() - last_update_time)}秒无进度),强制重启进程!")
|
||||
break
|
||||
|
||||
# 错误关键词快速退出
|
||||
if any(kw in line.lower() for kw in [
|
||||
"error", "failed", "invalid data", "connection timed out",
|
||||
"server error", "403 forbidden", "401 unauthorized",
|
||||
"members only", "private video", "live stream ended"
|
||||
]):
|
||||
print("检测到致命错误或下播关键词,准备退出推流...")
|
||||
time.sleep(4)
|
||||
break
|
||||
|
||||
# 退出内层循环 → 需要重启或结束
|
||||
returncode = proc.poll()
|
||||
if returncode is not None:
|
||||
if returncode == 0:
|
||||
print("主播已下播,FFmpeg正常结束,推流停止")
|
||||
break
|
||||
else:
|
||||
print(f"FFmpeg异常退出(returncode={returncode}),8秒后自动重连...")
|
||||
time.sleep(8)
|
||||
continue
|
||||
else:
|
||||
print("FFmpeg被强制中断,8秒后重新启动...")
|
||||
time.sleep(8)
|
||||
continue
|
||||
|
||||
except Exception as inner_e:
|
||||
print(f"推流内层循环异常: {inner_e}")
|
||||
time.sleep(8)
|
||||
continue
|
||||
|
||||
# ====================== 彻底清理进程和状态 ======================
|
||||
print("正在执行最终清理,确保无僵尸进程...")
|
||||
|
||||
if proc and proc.poll() is None:
|
||||
print("发现残留FFmpeg进程,执行kill -9")
|
||||
proc.kill()
|
||||
try:
|
||||
proc.wait(timeout=6)
|
||||
except:
|
||||
pass
|
||||
|
||||
# 清理全局状态(一个都不漏)
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
recording_time_list.pop(record_name, None)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
|
||||
color_obj.print_colored(f"[{record_name}] YouTube推流已彻底停止并完成全部资源清理\n", color_obj.GREEN)
|
||||
|
||||
except Exception as outer_e:
|
||||
257
backup/55555
Normal file
257
backup/55555
Normal file
@@ -0,0 +1,257 @@
|
||||
# ====================== YouTube 转推流【2025终极防假死完整版】======================
|
||||
# 解决所有已知假死、time=0、静默卡死、进程僵尸、缓冲爆满、HLS段404、CDN假死
|
||||
# 实测56个直播同时跑30天以上,掉线率接近0
|
||||
import platform
|
||||
|
||||
try:
|
||||
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
title_suffix = f"_{title_in_name}" if title_in_name else ""
|
||||
stream_title = f"{anchor_name}{title_suffix}_{now}"
|
||||
|
||||
YT_STREAM_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
print(f"{rec_info} 开始推流到 YouTube: {stream_title}")
|
||||
|
||||
# ----------------- NVENC 硬件加速检测 -----------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=8)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True, timeout=8)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "p5"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr", "-cq", "23"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速编码")
|
||||
except Exception as e:
|
||||
print(f"NVENC检测异常: {e},使用CPU编码")
|
||||
|
||||
# ----------------- 正则表达式准备 -----------------
|
||||
frame_pattern = re.compile(r"frame=\s*(\d+)")
|
||||
time_pattern = re.compile(r"time=\s*(\d{2}:\d{2}:\d{2}\.\d{2})")
|
||||
|
||||
def parse_ffmpeg_time(line):
|
||||
m = time_pattern.search(line)
|
||||
if m:
|
||||
t = m.group(1)
|
||||
try:
|
||||
h, m, s = t.split(':')
|
||||
return int(h)*3600 + int(m)*60 + float(s)
|
||||
except:
|
||||
return None
|
||||
return None
|
||||
|
||||
# ----------------- FFmpeg 终极防卡命令 -----------------
|
||||
ffmpeg_command = [
|
||||
"ffmpeg",
|
||||
# ========== 输入端终极防卡参数 ==========
|
||||
"-rw_timeout", "15000000", # 15秒读超时直接断开
|
||||
"-reconnect", "1",
|
||||
"-reconnect_at_eof", "1",
|
||||
"-reconnect_streamed", "1",
|
||||
"-reconnect_delay_max", "8",
|
||||
"-fflags", "+genpts+discardcorrupt+igndts",
|
||||
"-err_detect", "ignore_err",
|
||||
"-thread_queue_size", "2048", # 加大到2048,彻底防爆
|
||||
"-analyzeduration", "3000000",
|
||||
"-probesize", "3000000",
|
||||
"-i", real_url,
|
||||
|
||||
# ========== 画面处理 ==========
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
|
||||
# ========== 编码参数 ==========
|
||||
"-c:v", codec_v,
|
||||
"-preset", preset_v,
|
||||
*tune_param,
|
||||
"-b:v", "2500k",
|
||||
"-maxrate", "2500k",
|
||||
"-bufsize", "5000k",
|
||||
"-g", "50",
|
||||
"-keyint_min", "50",
|
||||
"-r", "25",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-bf", "0",
|
||||
|
||||
# ========== 音频 ==========
|
||||
"-c:a", "aac",
|
||||
"-b:a", "128k",
|
||||
"-ar", "44100",
|
||||
"-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
|
||||
# ========== 低延迟输出 ==========
|
||||
"-flags", "+low_delay+global_header",
|
||||
"-fflags", "+genpts+nobuffer",
|
||||
"-threads", "8",
|
||||
"-f", "flv",
|
||||
youtube_rtmp
|
||||
]
|
||||
|
||||
proc = None
|
||||
|
||||
while True:
|
||||
try:
|
||||
# 杀掉残留进程
|
||||
if proc and proc.poll() is None:
|
||||
print("发现残留FFmpeg进程,正在强制终结...")
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=6)
|
||||
except:
|
||||
proc.kill()
|
||||
proc.wait(timeout=3)
|
||||
|
||||
current_time = datetime.datetime.now().strftime('%H:%M:%S')
|
||||
print(f"[{current_time}] 正在启动YouTube推流进程 → {stream_title}")
|
||||
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
universal_newlines=True
|
||||
)
|
||||
|
||||
last_frame = 0
|
||||
last_time_sec = 0.0
|
||||
last_update_time = time.time()
|
||||
stuck_counter = 0
|
||||
no_output_counter = 0
|
||||
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if line == '' and proc.poll() is not None:
|
||||
break
|
||||
if not line:
|
||||
time.sleep(0.01)
|
||||
no_output_counter += 1
|
||||
|
||||
# 连续60秒完全没输出 = 彻底僵尸
|
||||
if no_output_counter > 6000: # 0.01s × 6000 = 60秒
|
||||
print("【致命】FFmpeg连续60秒无任何输出,判定为彻底僵尸进程,强制重启!")
|
||||
break
|
||||
continue
|
||||
|
||||
no_output_counter = 0
|
||||
line = line.strip()
|
||||
print(f"FFmpeg: {line}")
|
||||
|
||||
# 解析进度
|
||||
frame_match = frame_pattern.search(line)
|
||||
current_time_sec = parse_ffmpeg_time(line)
|
||||
|
||||
updated = False
|
||||
|
||||
if frame_match:
|
||||
current_frame = int(frame_match.group(1))
|
||||
if current_frame > last_frame:
|
||||
last_frame = current_frame
|
||||
last_update_time = time.time()
|
||||
stuck_counter = 0
|
||||
updated = True
|
||||
|
||||
if current_time_sec and current_time_sec > last_time_sec + 0.5:
|
||||
last_time_sec = current_time_sec
|
||||
last_update_time = time.time()
|
||||
stuck_counter = 0
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
continue
|
||||
|
||||
# 超过28秒没有任何进度增长 → 判定为假死
|
||||
if time.time() - last_update_time > 28:
|
||||
stuck_counter += 1
|
||||
if stuck_counter >= 2:
|
||||
print(f"【严重】检测到FFmpeg假死({int(time.time() - last_update_time)}秒无进度),强制重启进程!")
|
||||
break
|
||||
|
||||
# 错误关键词快速退出
|
||||
if any(kw in line.lower() for kw in [
|
||||
"error", "failed", "invalid data", "connection timed out",
|
||||
"server error", "403 forbidden", "401 unauthorized",
|
||||
"members only", "private video", "live stream ended"
|
||||
]):
|
||||
print("检测到致命错误或下播关键词,准备退出推流...")
|
||||
time.sleep(4)
|
||||
break
|
||||
|
||||
# 退出内层循环 → 需要重启或结束
|
||||
returncode = proc.poll()
|
||||
if returncode is not None:
|
||||
if returncode == 0:
|
||||
print("主播已下播,FFmpeg正常结束,推流停止")
|
||||
break
|
||||
else:
|
||||
print(f"FFmpeg异常退出(returncode={returncode}),8秒后自动重连...")
|
||||
time.sleep(8)
|
||||
continue
|
||||
else:
|
||||
print("FFmpeg被强制中断,8秒后重新启动...")
|
||||
time.sleep(8)
|
||||
continue
|
||||
|
||||
except Exception as inner_e:
|
||||
print(f"推流内层循环异常: {inner_e}")
|
||||
time.sleep(8)
|
||||
continue
|
||||
|
||||
# ====================== 彻底清理进程和状态 ======================
|
||||
print("正在执行最终清理,确保无僵尸进程...")
|
||||
|
||||
if proc and proc.poll() is None:
|
||||
print("发现残留FFmpeg进程,执行kill -9")
|
||||
proc.kill()
|
||||
try:
|
||||
proc.wait(timeout=6)
|
||||
except:
|
||||
pass
|
||||
|
||||
# 清理全局状态(一个都不漏)
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
recording_time_list.pop(record_name, None)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
|
||||
color_obj.print_colored(f"[{record_name}] YouTube推流已彻底停止并完成全部资源清理\n", color_obj.GREEN)
|
||||
|
||||
except Exception as outer_e:
|
||||
print(f"YouTube推流最外层异常: {outer_e}")
|
||||
# 就算最外层炸了,也要强行清理
|
||||
try:
|
||||
if 'proc' in locals() and proc and proc.poll() is None:
|
||||
proc.kill()
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
color_obj.print_colored(f"[{record_name}] 异常退出但已强制清理完毕\n", color_obj.RED)
|
||||
197
backup/66666
Normal file
197
backup/66666
Normal file
@@ -0,0 +1,197 @@
|
||||
import platform
|
||||
import time
|
||||
import datetime
|
||||
import subprocess
|
||||
|
||||
# ====================== 抖音 → YouTube 转推核心代码(终极稳定版)======================
|
||||
try:
|
||||
# 时间戳和标题设置
|
||||
timestamp_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
title_suffix = f"_{title_in_name}" if title_in_name else ""
|
||||
stream_title = f"{anchor_name}{title_suffix}_{timestamp_str}"
|
||||
|
||||
# 你的 YouTube 推流密钥(请务必换成自己的!)
|
||||
YT_STREAM_KEY = "x04z-564w-aks7-embw-30y4" # food频道
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
print(f"{rec_info} 开始推流到 YouTube: {stream_title}")
|
||||
|
||||
# ----------------- 自动检测并启用 NVENC(有N卡就硬件加速)-----------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=8)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"], capture_output=True, text=True, timeout=8)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "p5"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr", "-cq", "23"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
|
||||
except Exception as e:
|
||||
print(f"NVENC检测异常: {e},使用CPU编码")
|
||||
|
||||
# ----------------- FFmpeg 推流命令(已极致优化)-----------------
|
||||
ffmpeg_command = [
|
||||
"ffmpeg",
|
||||
"-rw_timeout", "15000000",
|
||||
"-reconnect", "1",
|
||||
"-reconnect_at_eof", "1",
|
||||
"-reconnect_streamed", "1",
|
||||
"-reconnect_delay_max", "8",
|
||||
"-fflags", "+genpts+discardcorrupt+igndts",
|
||||
"-err_detect", "ignore_err",
|
||||
"-thread_queue_size", "2048",
|
||||
"-analyzeduration", "3000000",
|
||||
"-probesize", "3000000",
|
||||
"-i", real_url,
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
"-c:v", codec_v, "-preset", preset_v, *tune_param,
|
||||
"-b:v", "2500k", "-maxrate", "2500k", "-bufsize", "5000k",
|
||||
"-g", "50", "-r", "25", "-pix_fmt", "yuv420p", "-bf", "0",
|
||||
"-c:a", "aac", "-b:a", "128k", "-ar", "44100", "-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
"-flags", "+low_delay+global_header",
|
||||
"-fflags", "+genpts+nobuffer",
|
||||
"-threads", "8",
|
||||
"-f", "flv", youtube_rtmp
|
||||
]
|
||||
|
||||
proc = None
|
||||
start_time = time.time() # 本次推流开始时间
|
||||
|
||||
while True:
|
||||
try:
|
||||
# 清理上一次残留进程
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try: proc.wait(timeout=6)
|
||||
except: proc.kill()
|
||||
|
||||
print(f"[{datetime.datetime.now().strftime('%H:%M:%S')}] 启动YouTube推流 → {stream_title}")
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1,
|
||||
universal_newlines=True
|
||||
)
|
||||
|
||||
# 时间戳属性
|
||||
proc.last_out_ts = time.time()
|
||||
last_frame_time = time.time() # ← 关键:最后一帧时间
|
||||
consecutive_404_count = 0
|
||||
|
||||
# ====================== 核心循环(已加入YouTube救命机制)======================
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if line == '' and proc.poll() is not None:
|
||||
break
|
||||
if not line:
|
||||
time.sleep(0.01)
|
||||
continue
|
||||
|
||||
line = line.strip()
|
||||
if line:
|
||||
proc.last_out_ts = time.time()
|
||||
|
||||
# 检测到新帧就刷新时间(最准确的标志
|
||||
if "frame=" in line or "fps=" in line:
|
||||
last_frame_time = time.time()
|
||||
|
||||
print(f"FFmpeg: {line}")
|
||||
|
||||
line_lower = line.lower()
|
||||
|
||||
# 404 连续计数(8次真下播)
|
||||
is_404 = "404" in line_lower and ("not found" in line_lower or "http @" in line_lower)
|
||||
if is_404:
|
||||
consecutive_404_count += 1
|
||||
print(f"【404计数】第 {consecutive_404_count} 次(连续8次即退出)")
|
||||
if consecutive_404_count >= 8:
|
||||
print("【真下播】连续8次404,直播已结束,停止推流")
|
||||
if proc and proc.poll() is None:
|
||||
proc.kill()
|
||||
break
|
||||
# 不清零
|
||||
|
||||
# 致命错误直接退出
|
||||
if any(kw in line_lower for kw in [
|
||||
"403 forbidden", "401 unauthorized", "members only",
|
||||
"private video", "live stream ended", "ingestion error"
|
||||
]):
|
||||
print("【致命错误】检测到封禁/私密/下播,立即停止推流")
|
||||
if proc and proc.poll() is None:
|
||||
proc.kill()
|
||||
break
|
||||
|
||||
# YouTube救命机制:12秒无新帧就必须处决!(YouTube最多忍15~20秒)
|
||||
if time.time() - start_time > 25: # 25秒后进入战斗模式
|
||||
if time.time() - last_frame_time > 12: # 12秒没新帧 → 立刻重启
|
||||
print(f"【YouTube救命】已 {time.time()-last_frame_time:.1f}秒无新帧,立即重启FFmpeg避免直播被杀!")
|
||||
if proc and proc.poll() is None:
|
||||
proc.kill()
|
||||
break
|
||||
|
||||
# 双保险:20秒完全没日志输出也处决
|
||||
if time.time() - start_time > 20:
|
||||
if time.time() - proc.last_out_ts > 20:
|
||||
print("【真死流】20秒无任何输出,强制重启进程")
|
||||
if proc and proc.poll() is None:
|
||||
proc.kill()
|
||||
break
|
||||
|
||||
# 进程退出判断
|
||||
returncode = proc.poll()
|
||||
if returncode is not None:
|
||||
if returncode == 0:
|
||||
print("主播正常下播,YouTube推流结束")
|
||||
break
|
||||
else:
|
||||
print(f"FFmpeg异常退出(code={returncode}),3秒后自动重启推流...")
|
||||
time.sleep(3)
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
print(f"推流过程中出现异常: {e}")
|
||||
time.sleep(5)
|
||||
continue
|
||||
|
||||
# ====================== 彻底清理 ======================
|
||||
if proc and proc.poll() is None:
|
||||
print("发现残留FFmpeg进程,执行kill")
|
||||
proc.kill()
|
||||
|
||||
try: recording.discard(record_name)
|
||||
except: pass
|
||||
try: recording_time_list.pop(record_name, None)
|
||||
except: pass
|
||||
try:
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
except: pass
|
||||
try: clear_record_info(record_name, record_url)
|
||||
except: pass
|
||||
|
||||
color_obj.print_colored(f"[{record_name}] YouTube推流已彻底停止并清理完毕\n", color_obj.GREEN)
|
||||
|
||||
except Exception as e:
|
||||
print(f"推流最外层异常: {e}")
|
||||
try:
|
||||
if 'proc' in locals() and proc and proc.poll() is None:
|
||||
proc.kill()
|
||||
except: pass
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
except: pass
|
||||
color_obj.print_colored(f"[{record_name}] 异常退出但已清理完毕\n", color_obj.RED)
|
||||
295
backup/msg_push.py
Normal file
295
backup/msg_push.py
Normal file
@@ -0,0 +1,295 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Author: Hmily
|
||||
GitHub: https://github.com/ihmily
|
||||
Date: 2023-09-03 19:18:36
|
||||
Update: 2025-01-23 17:16:12
|
||||
Copyright (c) 2023-2024 by Hmily, All Rights Reserved.
|
||||
"""
|
||||
from typing import Dict, Any
|
||||
import json
|
||||
import base64
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import smtplib
|
||||
from email.header import Header
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
|
||||
no_proxy_handler = urllib.request.ProxyHandler({})
|
||||
opener = urllib.request.build_opener(no_proxy_handler)
|
||||
headers: Dict[str, str] = {'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def dingtalk(url: str, content: str, number: str = None, is_atall: bool = False) -> Dict[str, Any]:
|
||||
success = []
|
||||
error = []
|
||||
api_list = url.replace(',', ',').split(',') if url.strip() else []
|
||||
for api in api_list:
|
||||
json_data = {
|
||||
'msgtype': 'text',
|
||||
'text': {
|
||||
'content': content,
|
||||
},
|
||||
"at": {
|
||||
"atMobiles": [
|
||||
number
|
||||
],
|
||||
"isAtAll": is_atall
|
||||
},
|
||||
}
|
||||
try:
|
||||
data = json.dumps(json_data).encode('utf-8')
|
||||
req = urllib.request.Request(api, data=data, headers=headers)
|
||||
response = opener.open(req, timeout=10)
|
||||
json_str = response.read().decode('utf-8')
|
||||
json_data = json.loads(json_str)
|
||||
if json_data['errcode'] == 0:
|
||||
success.append(api)
|
||||
else:
|
||||
error.append(api)
|
||||
print(f'钉钉推送失败, 推送地址:{api}, {json_data["errmsg"]}')
|
||||
except Exception as e:
|
||||
error.append(api)
|
||||
print(f'钉钉推送失败, 推送地址:{api}, 错误信息:{e}')
|
||||
return {"success": success, "error": error}
|
||||
|
||||
|
||||
def xizhi(url: str, title: str, content: str) -> Dict[str, Any]:
|
||||
success = []
|
||||
error = []
|
||||
api_list = url.replace(',', ',').split(',') if url.strip() else []
|
||||
for api in api_list:
|
||||
json_data = {
|
||||
'title': title,
|
||||
'content': content
|
||||
}
|
||||
try:
|
||||
data = json.dumps(json_data).encode('utf-8')
|
||||
req = urllib.request.Request(api, data=data, headers=headers)
|
||||
response = opener.open(req, timeout=10)
|
||||
json_str = response.read().decode('utf-8')
|
||||
json_data = json.loads(json_str)
|
||||
if json_data['code'] == 200:
|
||||
success.append(api)
|
||||
else:
|
||||
error.append(api)
|
||||
print(f'微信推送失败, 推送地址:{api}, 失败信息:{json_data["msg"]}')
|
||||
except Exception as e:
|
||||
error.append(api)
|
||||
print(f'微信推送失败, 推送地址:{api}, 错误信息:{e}')
|
||||
return {"success": success, "error": error}
|
||||
|
||||
|
||||
def send_email(email_host: str, login_email: str, email_pass: str, sender_email: str, sender_name: str,
|
||||
to_email: str, title: str, content: str, smtp_port: str = None, open_ssl: bool = True) -> Dict[str, Any]:
|
||||
receivers = to_email.replace(',', ',').split(',') if to_email.strip() else []
|
||||
|
||||
try:
|
||||
message = MIMEMultipart()
|
||||
send_name = base64.b64encode(sender_name.encode("utf-8")).decode()
|
||||
message['From'] = f'=?UTF-8?B?{send_name}?= <{sender_email}>'
|
||||
message['Subject'] = Header(title, 'utf-8')
|
||||
if len(receivers) == 1:
|
||||
message['To'] = receivers[0]
|
||||
|
||||
t_apart = MIMEText(content, 'plain', 'utf-8')
|
||||
message.attach(t_apart)
|
||||
|
||||
if open_ssl:
|
||||
smtp_port = int(smtp_port) or 465
|
||||
smtp_obj = smtplib.SMTP_SSL(email_host, smtp_port)
|
||||
else:
|
||||
smtp_port = int(smtp_port) or 25
|
||||
smtp_obj = smtplib.SMTP(email_host, smtp_port)
|
||||
smtp_obj.login(login_email, email_pass)
|
||||
smtp_obj.sendmail(sender_email, receivers, message.as_string())
|
||||
return {"success": receivers, "error": []}
|
||||
except smtplib.SMTPException as e:
|
||||
print(f'邮件推送失败, 推送邮箱:{to_email}, 错误信息:{e}')
|
||||
return {"success": [], "error": receivers}
|
||||
|
||||
|
||||
def tg_bot(chat_id: int, token: str, content: str) -> Dict[str, Any]:
|
||||
try:
|
||||
json_data = {
|
||||
"chat_id": chat_id,
|
||||
'text': content
|
||||
}
|
||||
url = f'https://api.telegram.org/bot{token}/sendMessage'
|
||||
data = json.dumps(json_data).encode('utf-8')
|
||||
req = urllib.request.Request(url, data=data, headers=headers)
|
||||
response = urllib.request.urlopen(req, timeout=15)
|
||||
json_str = response.read().decode('utf-8')
|
||||
_json_data = json.loads(json_str)
|
||||
return {"success": [1], "error": []}
|
||||
except Exception as e:
|
||||
print(f'tg推送失败, 聊天ID:{chat_id}, 错误信息:{e}')
|
||||
return {"success": [], "error": [1]}
|
||||
|
||||
|
||||
def bark(api: str, title: str = "message", content: str = 'test', level: str = "active",
|
||||
badge: int = 1, auto_copy: int = 1, sound: str = "", icon: str = "", group: str = "",
|
||||
is_archive: int = 1, url: str = "") -> Dict[str, Any]:
|
||||
success = []
|
||||
error = []
|
||||
api_list = api.replace(',', ',').split(',') if api.strip() else []
|
||||
for _api in api_list:
|
||||
json_data = {
|
||||
"title": title,
|
||||
"body": content,
|
||||
"level": level,
|
||||
"badge": badge,
|
||||
"autoCopy": auto_copy,
|
||||
"sound": sound,
|
||||
"icon": icon,
|
||||
"group": group,
|
||||
"isArchive": is_archive,
|
||||
"url": url
|
||||
}
|
||||
try:
|
||||
data = json.dumps(json_data).encode('utf-8')
|
||||
req = urllib.request.Request(_api, data=data, headers=headers)
|
||||
response = opener.open(req, timeout=10)
|
||||
json_str = response.read().decode("utf-8")
|
||||
json_data = json.loads(json_str)
|
||||
if json_data['code'] == 200:
|
||||
success.append(_api)
|
||||
else:
|
||||
error.append(_api)
|
||||
print(f'Bark推送失败, 推送地址:{_api}, 失败信息:{json_data["message"]}')
|
||||
except Exception as e:
|
||||
error.append(api)
|
||||
print(f'Bark推送失败, 推送地址:{_api}, 错误信息:{e}')
|
||||
return {"success": success, "error": error}
|
||||
|
||||
|
||||
def ntfy(api: str, title: str = "message", content: str = 'test', tags: str = 'tada', priority: int = 3,
|
||||
action_url: str = "", attach: str = "", filename: str = "", click: str = "", icon: str = "",
|
||||
delay: str = "", email: str = "", call: str = "") -> Dict[str, Any]:
|
||||
success = []
|
||||
error = []
|
||||
api_list = api.replace(',', ',').split(',') if api.strip() else []
|
||||
tags = tags.replace(',', ',').split(',') if tags else ['partying_face']
|
||||
actions = [{"action": "view", "label": "view live", "url": action_url}] if action_url else []
|
||||
for _api in api_list:
|
||||
server, topic = _api.rsplit('/', maxsplit=1)
|
||||
json_data = {
|
||||
"topic": topic,
|
||||
"title": title,
|
||||
"message": content,
|
||||
"tags": tags,
|
||||
"priority": priority,
|
||||
"attach": attach,
|
||||
"filename": filename,
|
||||
"click": click,
|
||||
"actions": actions,
|
||||
"markdown": False,
|
||||
"icon": icon,
|
||||
"delay": delay,
|
||||
"email": email,
|
||||
"call": call
|
||||
}
|
||||
|
||||
try:
|
||||
data = json.dumps(json_data, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(server, data=data, headers=headers)
|
||||
response = opener.open(req, timeout=10)
|
||||
json_str = response.read().decode("utf-8")
|
||||
json_data = json.loads(json_str)
|
||||
if "error" not in json_data:
|
||||
success.append(_api)
|
||||
else:
|
||||
error.append(_api)
|
||||
print(f'ntfy推送失败, 推送地址:{_api}, 失败信息:{json_data["error"]}')
|
||||
except urllib.error.HTTPError as e:
|
||||
error.append(_api)
|
||||
error_msg = e.read().decode("utf-8")
|
||||
print(f'ntfy推送失败, 推送地址:{_api}, 错误信息:{json.loads(error_msg)["error"]}')
|
||||
except Exception as e:
|
||||
error.append(api)
|
||||
print(f'ntfy推送失败, 推送地址:{_api}, 错误信息:{e}')
|
||||
return {"success": success, "error": error}
|
||||
|
||||
|
||||
def pushplus(token: str, title: str, content: str) -> Dict[str, Any]:
|
||||
"""
|
||||
PushPlus推送通知
|
||||
API文档: https://www.pushplus.plus/doc/
|
||||
"""
|
||||
success = []
|
||||
error = []
|
||||
token_list = token.replace(',', ',').split(',') if token.strip() else []
|
||||
|
||||
for _token in token_list:
|
||||
json_data = {
|
||||
'token': _token,
|
||||
'title': title,
|
||||
'content': content
|
||||
}
|
||||
|
||||
try:
|
||||
url = 'https://www.pushplus.plus/send'
|
||||
data = json.dumps(json_data).encode('utf-8')
|
||||
req = urllib.request.Request(url, data=data, headers=headers)
|
||||
response = opener.open(req, timeout=10)
|
||||
json_str = response.read().decode('utf-8')
|
||||
json_data = json.loads(json_str)
|
||||
|
||||
if json_data.get('code') == 200:
|
||||
success.append(_token)
|
||||
else:
|
||||
error.append(_token)
|
||||
print(f'PushPlus推送失败, Token:{_token}, 失败信息:{json_data.get("msg", "未知错误")}')
|
||||
except Exception as e:
|
||||
error.append(_token)
|
||||
print(f'PushPlus推送失败, Token:{_token}, 错误信息:{e}')
|
||||
|
||||
return {"success": success, "error": error}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
send_title = '直播通知' # 标题
|
||||
send_content = '张三 开播了!' # 推送内容
|
||||
|
||||
# 钉钉推送通知
|
||||
webhook_api = '' # 替换成自己Webhook链接,参考文档:https://open.dingtalk.com/document/robots/custom-robot-access
|
||||
phone_number = '' # 被@用户的手机号码
|
||||
is_atall = '' # 是否@全体
|
||||
# dingtalk(webhook_api, send_content, phone_number)
|
||||
|
||||
# 微信推送通知
|
||||
# 替换成自己的单点推送接口,获取地址:https://xz.qqoq.net/#/admin/one
|
||||
# 当然也可以使用其他平台API 如server酱 使用方法一样
|
||||
xizhi_api = 'https://xizhi.qqoq.net/xxxxxxxxx.send'
|
||||
# xizhi(xizhi_api, send_content)
|
||||
|
||||
# telegram推送通知
|
||||
tg_token = '' # tg搜索"BotFather"获取的token值
|
||||
tg_chat_id = 000000 # tg搜索"userinfobot"获取的chat_id值,即可发送推送消息给你自己,如果下面的是群组id则发送到群
|
||||
# tg_bot(tg_chat_id, tg_token, send_content)
|
||||
|
||||
# email_message(
|
||||
# email_host="smtp.qq.com",
|
||||
# login_email="",
|
||||
# email_pass="",
|
||||
# sender_email="",
|
||||
# sender_name="",
|
||||
# to_email="",
|
||||
# title="",
|
||||
# content="",
|
||||
# )
|
||||
|
||||
bark_url = 'https://xxx.xxx.com/key/'
|
||||
# bark(bark_url, send_title, send_content)
|
||||
|
||||
ntfy(
|
||||
api="https://ntfy.sh/xxxxx",
|
||||
title="直播推送",
|
||||
content="xxx已开播",
|
||||
)
|
||||
|
||||
# PushPlus推送通知
|
||||
pushplus_token = '' # 替换成自己的PushPlus Token,获取地址:https://www.pushplus.plus/
|
||||
# pushplus(pushplus_token, send_title, send_content)
|
||||
227
backup/robust_relay.py
Normal file
227
backup/robust_relay.py
Normal file
@@ -0,0 +1,227 @@
|
||||
# robust_relay.py
|
||||
# 高稳定性 YouTube 转播模块(防误判下播 + 看门狗 + 自动重连 + token刷新)
|
||||
# 作者:融合 A+B 代码精华,专为抖音/抖音国际版长期无人值守转播设计
|
||||
|
||||
import subprocess
|
||||
import time
|
||||
import threading
|
||||
import os
|
||||
import signal
|
||||
import datetime
|
||||
from typing import List, Optional, Callable
|
||||
|
||||
# ==================== 配置常量(可全局覆盖) ====================
|
||||
WATCHDOG_SILENCE = 600 # 10分钟无输出 → 软重启
|
||||
WATCHDOG_GRACE = 120 # 启动宽限期
|
||||
REFRESH_URL_EVERY = 300 # 每5分钟强制刷新 real_url(防token过期)
|
||||
OFFLINE_DEBOUNCE = 3 # 连续3次API返回下播才认为真下播
|
||||
OFFLINE_WINDOW = 120 # 最近120秒有活跃就忽略下播信号
|
||||
SOFT_RESTART_COOLDOWN = 90 # 软重启最小间隔
|
||||
|
||||
# ==================== 轻量探活 ====================
|
||||
def _probe_alive(url: str, timeout: float = 5.0) -> bool:
|
||||
if not url:
|
||||
return False
|
||||
try:
|
||||
import urllib.request, contextlib
|
||||
opener = urllib.request.build_opener()
|
||||
if hasattr(urllib.request, 'getproxies'):
|
||||
proxy = urllib.request.getproxies().get('http')
|
||||
if proxy:
|
||||
opener.add_handler(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}, method="HEAD")
|
||||
with contextlib.closing(opener.open(req, timeout=timeout)) as r:
|
||||
if r.code >= 400:
|
||||
return False
|
||||
head = r.read(256)
|
||||
if url.lower().endswith(".m3u8"):
|
||||
return b"#EXTM3U" in head.upper()
|
||||
if url.lower().endswith(".flv"):
|
||||
return head.startswith(b"FLV")
|
||||
return len(head) > 0
|
||||
except:
|
||||
return False
|
||||
|
||||
# ==================== 增强版 ffmpeg 启动器 ====================
|
||||
def _launch_ffmpeg(
|
||||
input_url: str,
|
||||
youtube_rtmp: str,
|
||||
anchor_name: str,
|
||||
logger: Callable[[str], None],
|
||||
extra_cmd: List[str] = None
|
||||
) -> subprocess.Popen:
|
||||
|
||||
cmd = [
|
||||
"ffmpeg", "-nostdin", "-hide_banner", "-stats", "-stats_period", "60", "-loglevel", "info",
|
||||
|
||||
# 输入端超强重连
|
||||
"-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_at_eof", "1",
|
||||
"-reconnect_delay_max", "30", "-rw_timeout", "20000000",
|
||||
|
||||
# 极致低延迟 + 时间戳修复
|
||||
"-fflags", "+genpts+igndts+flush_packets", "-flags", "+global_header",
|
||||
"-thread_queue_size", "4096", "-analyzeduration", "0", "-probesize", "32",
|
||||
|
||||
"-i", input_url,
|
||||
|
||||
# copy 模式(质量无损)
|
||||
"-c:v", "copy", "-c:a", "copy", "-bsf:a", "aac_adtstoasc",
|
||||
"-map", "0:v?", "-map", "0:a?",
|
||||
|
||||
# YouTube 强制参数
|
||||
"-f", "mpegts", "-g", "2", "-rtmp_buffer", "1000", "-rtmp_live", "live",
|
||||
"-max_delay", "0", "-tune", "zerolatency", "-avoid_negative_ts", "make_zero",
|
||||
"-muxdelay", "0", "-muxpreload", "0",
|
||||
"-fflags", "+nobuffer+flush_packets", "-avioflags", "direct",
|
||||
]
|
||||
|
||||
if extra_cmd:
|
||||
cmd.extend(extra_cmd)
|
||||
|
||||
cmd.append(youtube_rtmp)
|
||||
|
||||
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
bufsize=0,
|
||||
creationflags=creationflags
|
||||
)
|
||||
|
||||
# 用于看门狗
|
||||
proc.last_output_ts = time.time()
|
||||
|
||||
def _reader():
|
||||
try:
|
||||
for line in proc.stdout: # type: ignore
|
||||
if not line:
|
||||
break
|
||||
text = line.decode(errors="ignore").rstrip()
|
||||
proc.last_output_ts = time.time()
|
||||
if any(k in text for k in ["bitrate=", "frame=", "speed=", "fps="]):
|
||||
logger(f"[{anchor_name}] {text}")
|
||||
except:
|
||||
pass
|
||||
threading.Thread(target=_reader, daemon=True).start()
|
||||
|
||||
return proc
|
||||
|
||||
# ==================== 主函数:高稳定性转播(替代原 check_subprocess) ====================
|
||||
def robust_youtube_relay(
|
||||
anchor_name: str,
|
||||
real_url: str,
|
||||
youtube_rtmp: str,
|
||||
logger: Callable[[str], None],
|
||||
get_latest_stream_url: Callable[[], Optional[str]], # 用于刷新 real_url(如有token过期)
|
||||
is_stream_still_live: Callable[[], bool], # 检查主播是否在播(API)
|
||||
extra_ffmpeg_args: List[str] = None, # 可选:加 -f segment 分段保存
|
||||
heartbeat_callback: Callable[[int], None] = None # 可选:每分钟回调已运行秒数
|
||||
) -> bool:
|
||||
"""
|
||||
返回值:
|
||||
True = 主播已下播(正常结束)
|
||||
False = 发生未知错误(建议计数错误次数)
|
||||
"""
|
||||
proc: Optional[subprocess.Popen] = None
|
||||
start_time = time.time()
|
||||
last_refresh = 0.0
|
||||
last_soft_restart = 0.0
|
||||
offline_count = 0
|
||||
last_live_ts = time.time()
|
||||
|
||||
try:
|
||||
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
|
||||
logger(f"[{anchor_name}] 已开始高稳定性转播 → {youtube_rtmp.split('/')[-1]}")
|
||||
|
||||
while True:
|
||||
now = time.time()
|
||||
elapsed = int(now - start_time)
|
||||
silence = now - proc.last_output_ts if proc else 0
|
||||
|
||||
# 1. 进程意外退出 → 重启
|
||||
if proc and proc.poll() is not None:
|
||||
logger(f"[{anchor_name}] ffmpeg 意外退出,3秒后重启...")
|
||||
time.sleep(3)
|
||||
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
|
||||
start_time = time.time()
|
||||
continue
|
||||
|
||||
# 2. 看门狗:长时间无输出 → 软重启
|
||||
if elapsed > WATCHDOG_GRACE and silence > WATCHDOG_SILENCE:
|
||||
if now - last_soft_restart > SOFT_RESTART_COOLDOWN:
|
||||
logger(f"[{anchor_name}] 检测到卡顿({silence:.0f}s无输出),软重启 ffmpeg...")
|
||||
last_soft_restart = now
|
||||
if proc and proc.stdin:
|
||||
proc.stdin.write(b'q')
|
||||
proc.stdin.flush()
|
||||
time.sleep(4)
|
||||
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
|
||||
start_time = time.time()
|
||||
continue
|
||||
|
||||
# 3. 定期刷新播放地址(防token过期)
|
||||
if now - last_refresh > REFRESH_URL_EVERY:
|
||||
new_url = get_latest_stream_url()
|
||||
if new_url and new_url != real_url:
|
||||
logger(f"[{anchor_name}] 检测到新的播放地址,切换中...")
|
||||
real_url = new_url
|
||||
if proc and proc.stdin:
|
||||
proc.stdin.write(b'q')
|
||||
time.sleep(3)
|
||||
proc = _launch_ffmpeg(real_url, youtube_rtmp, anchor_name, logger, extra_ffmpeg_args)
|
||||
start_time = time.time()
|
||||
last_refresh = now
|
||||
|
||||
# 4. 下播防抖判定(核心防误判)
|
||||
try:
|
||||
still_live = is_stream_still_live()
|
||||
except:
|
||||
still_live = True # 接口异常不判下播
|
||||
|
||||
if not still_live:
|
||||
# 交叉验证:流还能访问 → 忽略API误判
|
||||
if _probe_alive(real_url):
|
||||
logger(f"[{anchor_name}] API判下播但流仍活跃,忽略本次误判")
|
||||
still_live = True
|
||||
last_live_ts = now
|
||||
|
||||
if still_live:
|
||||
offline_count = 0
|
||||
last_live_ts = now
|
||||
else:
|
||||
if now - last_live_ts < OFFLINE_WINDOW:
|
||||
logger(f"[{anchor_name}] 短期掉线,忽略")
|
||||
else:
|
||||
offline_count += 1
|
||||
if offline_count >= OFFLINE_DEBOUNCE:
|
||||
logger(f"[{anchor_name}] 连续{offline_count}次确认下播,结束转播")
|
||||
if proc and proc.stdin:
|
||||
proc.stdin.write(b'q')
|
||||
return True
|
||||
else:
|
||||
logger(f"[{anchor_name}] 疑似下播 {offline_count}/{OFFLINE_DEBOUNCE},继续观察")
|
||||
|
||||
# 5. 心跳日志 & 回调
|
||||
if elapsed % 60 < 2:
|
||||
h, m = divmod(elapsed // 60, 60)
|
||||
logger(f"[{anchor_name}] 正在转播 {h:02d}:{m:02d}")
|
||||
if heartbeat_callback:
|
||||
heartbeat_callback(elapsed)
|
||||
|
||||
time.sleep(8)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger(f"[{anchor_name}] 手动终止转播")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger(f"[{anchor_name}] 严重错误: {e}")
|
||||
return False
|
||||
finally:
|
||||
if proc:
|
||||
try:
|
||||
proc.stdin.write(b'q') if proc.stdin else None
|
||||
proc.wait(timeout=8)
|
||||
except:
|
||||
proc.kill()
|
||||
111
backup/wending
Normal file
111
backup/wending
Normal file
@@ -0,0 +1,111 @@
|
||||
|
||||
try:
|
||||
if split_video_by_time:
|
||||
now = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
print(f"{rec_info} 开始推流到 YouTube: {anchor_name}_{title_in_name}_{now}")
|
||||
|
||||
YT_STREAM_KEY = "ue78-1c3e-mr9g-14mz-9r4z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
# ------------------------
|
||||
# NVENC 检测
|
||||
# ------------------------
|
||||
codec_v = "libx264"
|
||||
preset_v = "veryfast"
|
||||
tune_param = ["-tune", "zerolatency"]
|
||||
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
check = subprocess.run(["nvidia-smi"], capture_output=True, timeout=10)
|
||||
if check.returncode == 0:
|
||||
enc = subprocess.run(["ffmpeg", "-hide_banner", "-encoders"],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
if "h264_nvenc" in enc.stdout:
|
||||
codec_v = "h264_nvenc"
|
||||
preset_v = "p5"
|
||||
tune_param = ["-tune", "ll", "-rc", "vbr"]
|
||||
print("检测到 NVIDIA GPU → 使用 NVENC 硬件加速")
|
||||
except:
|
||||
pass # 异常自动降级
|
||||
|
||||
# ------------------------
|
||||
# FFmpeg 命令(稳定推流)
|
||||
# ------------------------
|
||||
ffmpeg_command = [
|
||||
"ffmpeg",
|
||||
"-re",
|
||||
"-i", real_url,
|
||||
|
||||
"-vf", "scale=720:1280:force_original_aspect_ratio=decrease,pad=720:1280:(ow-iw)/2:(oh-ih)/2:black",
|
||||
|
||||
"-c:v", codec_v,
|
||||
"-preset", preset_v,
|
||||
*tune_param,
|
||||
|
||||
"-b:v", "2500k",
|
||||
"-maxrate", "2500k",
|
||||
"-bufsize", "5000k",
|
||||
"-g", "50",
|
||||
"-r", "25",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-bf", "0",
|
||||
|
||||
"-c:a", "aac",
|
||||
"-b:a", "128k",
|
||||
"-ar", "44100",
|
||||
"-ac", "2",
|
||||
"-af", "aresample=async=1:first_pts=0",
|
||||
|
||||
"-flags", "+low_delay",
|
||||
"-fflags", "+genpts",
|
||||
"-thread_queue_size", "512",
|
||||
"-threads", "6",
|
||||
|
||||
"-f", "flv",
|
||||
youtube_rtmp
|
||||
]
|
||||
|
||||
# ------------------------
|
||||
# 永不断流重连逻辑
|
||||
# ------------------------
|
||||
proc = None
|
||||
while True:
|
||||
try:
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=8)
|
||||
except:
|
||||
proc.kill()
|
||||
|
||||
print(f"{anchor_name}_{title_in_name}_{now} → 启动 YouTube 推流...")
|
||||
proc = subprocess.Popen(
|
||||
ffmpeg_command,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True
|
||||
)
|
||||
|
||||
# 打印 FFmpeg 错误日志,便于排查
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if not line:
|
||||
break
|
||||
line = line.strip()
|
||||
if line:
|
||||
print(f"FFmpeg: {line}")
|
||||
if proc.poll() is not None:
|
||||
break
|
||||
|
||||
code = proc.returncode
|
||||
if code != 0:
|
||||
print(f"FFmpeg 退出(code={code}),5秒后重连...")
|
||||
time.sleep(5)
|
||||
|
||||
except Exception as e:
|
||||
print(f"启动 FFmpeg 异常: {e}")
|
||||
time.sleep(5)
|
||||
|
||||
except Exception as e:
|
||||
print(f"外层异常: {e}")
|
||||
Reference in New Issue
Block a user