's'
This commit is contained in:
135
main.py
135
main.py
@@ -1529,7 +1529,9 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
error_window.append(1)
|
||||
|
||||
else:
|
||||
# ====================== 抖音→YouTube 2025 终极永不死版(已修复所有已知致命问题) ======================
|
||||
|
||||
|
||||
# ====================== 抖音→YouTube 2025(重构:单层重试 + 统一清理) ======================
|
||||
import queue, unicodedata, platform, traceback
|
||||
|
||||
class StreamEnded(Exception):
|
||||
@@ -1546,12 +1548,19 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
try:
|
||||
while True:
|
||||
line = proc.stderr.readline()
|
||||
if not line: break
|
||||
if not line:
|
||||
break
|
||||
q.put(line)
|
||||
except Exception as e:
|
||||
q.put(f"__ERR__READER__:{e}")
|
||||
try:
|
||||
q.put(f"__ERR__READER__:{e}")
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
q.put(None)
|
||||
try:
|
||||
q.put(None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def cleanup_proc(proc):
|
||||
try:
|
||||
@@ -1561,29 +1570,24 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
proc.wait(timeout=5)
|
||||
except Exception:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
try:
|
||||
proc.kill()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ========== 参数配置 ==========
|
||||
# YT_STREAM_KEY = "ue78-1c3e-mr9g-14mz-9r4z" # 没有ypp的美食
|
||||
|
||||
|
||||
YT_STREAM_KEY = "qxvb-r47b-r5ju-6ud3-6k7z" # vlog频道
|
||||
# ========== 参数配置(保留你原始配置) ==========
|
||||
YT_STREAM_KEY = "qxvb-r47b-r5ju-6ud3-6k7z"
|
||||
youtube_rtmp = f"rtmp://a.rtmp.youtube.com/live2/{YT_STREAM_KEY}"
|
||||
|
||||
# 内网SRS服务器
|
||||
# YT_STREAM_KEY = "douyin" # vlog频道
|
||||
# youtube_rtmp = f"rtmp://192.168.31.184/live/{YT_STREAM_KEY}"
|
||||
|
||||
MAX_RETRY_DELAY = 90
|
||||
INITIAL_RETRY_DELAY = 3
|
||||
NO_FRAME_TIMEOUT = 120 # 120秒无新帧才判真下播(完美契合YouTube 25~30秒容忍)
|
||||
NO_FRAME_TIMEOUT = 120
|
||||
START_CHECK_AFTER = 25.0
|
||||
STALE_OUTPUT_SECONDS = 40 # 40秒无任何日志才重启(更宽容)
|
||||
STALE_OUTPUT_SECONDS = 40
|
||||
STDERR_QUEUE_TIMEOUT = 1.0
|
||||
|
||||
# 2025年12月实测最准的下播关键词(一个都不能少!)
|
||||
END_KEYWORDS = [
|
||||
"connection reset by peer",
|
||||
"failed to write trailer",
|
||||
@@ -1599,13 +1603,12 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
"connection timed out",
|
||||
]
|
||||
|
||||
# 标题清洗
|
||||
timestamp_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
|
||||
_clean_title_in_name = sanitize_title(title_in_name)
|
||||
stream_title = sanitize_title(f"{anchor_name}{('_' + _clean_title_in_name) if _clean_title_in_name else ''}_{timestamp_str}")
|
||||
print(f"[INFO] {rec_info} 开始推流到 YouTube: {stream_title}")
|
||||
|
||||
# NVENC 检测
|
||||
# NVENC 检测(原样保留)
|
||||
codec_v, preset_v, tune_param = "libx264", "veryfast", ["-tune", "zerolatency"]
|
||||
try:
|
||||
if platform.system().lower() in ["windows", "linux"]:
|
||||
@@ -1618,14 +1621,13 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
except Exception as e:
|
||||
print(f"[WARN] NVENC 检测失败,回退软件编码: {e}")
|
||||
|
||||
# 伪装 headers
|
||||
# headers & ffmpeg command(保持原来参数)
|
||||
douyin_headers = (
|
||||
"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
|
||||
"Referer: https://live.douyin.com/\r\n"
|
||||
"Origin: https://live.douyin.com\r\n"
|
||||
)
|
||||
|
||||
# FFmpeg 命令(关键!bufsize=1)
|
||||
ffmpeg_command = [
|
||||
"ffmpeg", "-loglevel", "info",
|
||||
"-rw_timeout", "15000000",
|
||||
@@ -1646,8 +1648,10 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
"-f", "flv", youtube_rtmp
|
||||
]
|
||||
|
||||
# ---- 单层重试循环(清晰可控) ----
|
||||
proc = None
|
||||
stderr_q = queue.Queue()
|
||||
stderr_q = None
|
||||
reader_t = None
|
||||
retry_delay = INITIAL_RETRY_DELAY
|
||||
|
||||
try:
|
||||
@@ -1657,7 +1661,15 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
print(f"[WARN] 防风控等待 {retry_delay}s 后重新连接抖音源...")
|
||||
time.sleep(retry_delay)
|
||||
|
||||
cleanup_proc(proc)
|
||||
# 每次重连前先清理上一次的进程/线程
|
||||
try:
|
||||
cleanup_proc(proc)
|
||||
except Exception:
|
||||
pass
|
||||
if stderr_q:
|
||||
# 垃圾化旧队列以便 GC
|
||||
stderr_q = None
|
||||
stderr_q = queue.Queue()
|
||||
|
||||
print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 YouTube 推流 → {stream_title}")
|
||||
proc = subprocess.Popen(
|
||||
@@ -1666,33 +1678,37 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
bufsize=1, # 关键!必须是 1
|
||||
bufsize=1,
|
||||
universal_newlines=True
|
||||
)
|
||||
proc.last_out_ts = time.time() # 给 proc 加个属性记录最后输出时间
|
||||
proc.last_out_ts = time.time()
|
||||
|
||||
# 启动 stderr reader
|
||||
reader_t = threading.Thread(target=_stderr_reader_thread, args=(proc, stderr_q))
|
||||
reader_t.daemon = True
|
||||
reader_t.start()
|
||||
|
||||
start_time = last_frame_time = time.time()
|
||||
|
||||
# ---- 监控循环(单一职责:处理 stderr 日志并决定是否结束/重连) ----
|
||||
while True:
|
||||
try:
|
||||
try:
|
||||
line = stderr_q.get(timeout=STDERR_QUEUE_TIMEOUT)
|
||||
except queue.Empty:
|
||||
# 超时检查僵死
|
||||
if time.time() - proc.last_out_ts > STALE_OUTPUT_SECONDS:
|
||||
# 超时检查:如果太久没有任何日志,判为僵死,重启 proc(跳出内层,进行重试)
|
||||
if time.time() - getattr(proc, "last_out_ts", time.time()) > STALE_OUTPUT_SECONDS:
|
||||
print("[WARN] 长时间无任何日志,强制重启进程")
|
||||
cleanup_proc(proc)
|
||||
break
|
||||
continue
|
||||
|
||||
if line is None: # reader 结束
|
||||
if line is None:
|
||||
# reader 线程结束;如果 proc 已退出,跳出去重试
|
||||
if proc.poll() is not None:
|
||||
break
|
||||
continue
|
||||
else:
|
||||
continue
|
||||
|
||||
line = line.strip()
|
||||
if line.startswith("__ERR__READER__"):
|
||||
@@ -1700,22 +1716,21 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
continue
|
||||
|
||||
if line:
|
||||
proc.last_out_ts = time.time() # 任意日志都更新时间
|
||||
proc.last_out_ts = time.time()
|
||||
print(f"[FFmpeg] {line}")
|
||||
|
||||
line_lower = line.lower()
|
||||
|
||||
# 真下播精准检测
|
||||
# 检测到明确下播关键字 -> 认为主播真下播,立即退出(不再重试)
|
||||
if any(kw in line_lower for kw in END_KEYWORDS):
|
||||
print("[ERROR] 检测到主播真下播或被明确拒绝,停止推流")
|
||||
cleanup_proc(proc)
|
||||
raise StreamEnded()
|
||||
|
||||
# 帧检测(只更新 last_frame_time)
|
||||
# 帧检测:更新 frame 时间戳
|
||||
if re.search(r'frame=\s*\d+', line_lower) or "fps=" in line_lower:
|
||||
last_frame_time = time.time()
|
||||
|
||||
# 120秒无新帧 = 真下播(完美契合 YouTube 25~30秒容忍)
|
||||
# 超时无新帧 => 认为下播
|
||||
if time.time() - start_time > START_CHECK_AFTER:
|
||||
if time.time() - last_frame_time > NO_FRAME_TIMEOUT:
|
||||
print(f"[WARN] 连续 {NO_FRAME_TIMEOUT}s 无新帧,判定主播已下播")
|
||||
@@ -1723,43 +1738,71 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
|
||||
raise StreamEnded()
|
||||
|
||||
except StreamEnded:
|
||||
# 真实下播,抛到外层处理(最终会退出函数)
|
||||
raise
|
||||
except Exception as e:
|
||||
# 内层非致命异常:打印、回退重试间隔,退出监控循环以在外层重试
|
||||
print(f"[ERROR] 内层异常: {e}")
|
||||
traceback.print_exc()
|
||||
cleanup_proc(proc)
|
||||
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
|
||||
break
|
||||
break # 跳出监控循环 -> 外层 while 会继续并重试
|
||||
|
||||
# 如果监控循环走到这里并不是因为 StreamEnded(例如 break),则重试连接(loop continue)
|
||||
# 将在 while True 的下一次循环中进行等待并重连
|
||||
continue
|
||||
|
||||
except StreamEnded:
|
||||
# 真实的主播下播,停止并彻底退出本录制线程
|
||||
print(f"[INFO] 主播已下播,停止 YouTube 转推 → {record_name}")
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
# 外层致命异常:打印并退出循环(会在 finally 里做统一清理)
|
||||
print(f"[ERROR] 外层异常: {e}")
|
||||
traceback.print_exc()
|
||||
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
|
||||
# 等待并尝试重连(除非你希望直接退出,这里保留重试策略)
|
||||
continue
|
||||
finally:
|
||||
cleanup_proc(proc)
|
||||
|
||||
# ============ 彻底清理 ============
|
||||
# ============ 正常或 StreamEnded 后的统一清理(在这里 break 到这里) ============
|
||||
cleanup_proc(proc)
|
||||
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
global monitoring
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
# 以下清理放在 try/except 里以防止清理过程出错导致漏逻辑
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
global monitoring
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
color_obj.print_colored(f"[{record_name}] YouTube 推流已彻底停止并清理完毕\n", color_obj.GREEN)
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
# 最外层异常也要统一清理(保证不会留下僵尸状态)
|
||||
print(f"[FATAL] YouTube 推流最外层异常: {e}")
|
||||
traceback.print_exc()
|
||||
cleanup_proc(proc)
|
||||
try:
|
||||
cleanup_proc(proc)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
recording.discard(record_name)
|
||||
recording_time_list.pop(record_name, None)
|
||||
if record_url in running_list:
|
||||
running_list.remove(record_url)
|
||||
# global monitoring
|
||||
monitoring = max(0, monitoring - 1)
|
||||
clear_record_info(record_name, record_url)
|
||||
except Exception:
|
||||
pass
|
||||
color_obj.print_colored(f"[{record_name}] YouTube 推流异常退出但已清理\n", color_obj.RED)
|
||||
return
|
||||
|
||||
count_time = time.time()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user