This commit is contained in:
Your Name
2026-01-02 04:37:59 +00:00
parent 041a402a73
commit 2375331973
2 changed files with 100 additions and 106 deletions

View File

@@ -1 +1,30 @@
https://live.douyin.com/9638535297,主播: 异度世界 https://live.douyin.com/9638535297,主播: 异度世界
https://live.douyin.com/372551154040,主播: 向嘉_手打柠檬茶
https://live.douyin.com/203476627795,主播: 蜜桃姐姐(手打柠檬茶)
https://live.douyin.com/825627287092,主播: 杏绘茶档_(00后创业版_手打柠檬茶)
https://live.douyin.com/147650297461,主播: 娱乐摆摊记
https://live.douyin.com/806666144080,主播: 卢荟胶
https://live.douyin.com/589958309143,主播: 大萝卜
https://live.douyin.com/35932729226,主播: 内向小学生
https://live.douyin.com/456576000931,主播: 介休〖烩饕〗大块牛肉饭「摆摊」
https://live.douyin.com/782322393954,主播: 小葵(摆摊版)
https://live.douyin.com/208318182053,主播: 小碗(创业版)
https://live.douyin.com/646935372639,主播: 小雪摆摊记
https://live.douyin.com/956877163856,主播: 饭饱饱
https://live.douyin.com/881451071780,主播: YINING一柠手打柠檬茶
https://live.douyin.com/270513395244,主播: 小喻的摆摊日记
https://live.douyin.com/742474761291,主播: 阿诺椰子•
https://live.douyin.com/820845121901,主播: 地摊闺蜜_创意寿司_(马儿努力版)
https://live.douyin.com/980855021360,主播: 图爸摆摊卖枣糕(日照首家)教学员
https://live.douyin.com/46238285118,主播: 我叫小彤呀
https://live.douyin.com/497155982953,主播: 想吃糖葫芦
https://live.douyin.com/349973241990,主播: 元气满满饭团(摆摊不摆烂版)
https://live.douyin.com/814839174401,主播: 飞飞摆摊不摆烂
https://live.douyin.com/597618993066,主播: 婷婷的茶生活
https://live.douyin.com/16531926455,主播: 木黎黎
https://live.douyin.com/739670432305,主播: 干饭007
https://live.douyin.com/486789870173,主播: 凉皮西施—豆豆
https://live.douyin.com/15652099787,主播: 莹莹在摆摊
https://live.douyin.com/572442812068,主播: 小小
https://live.douyin.com/477961427964,主播: 小鱼
https://live.douyin.com/686507122231,主播: 上海少妇鲜果茶

177
main.py
View File

@@ -1164,11 +1164,9 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
push_at = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') push_at = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
if port_info['is_live'] is False: if port_info['is_live'] is False:
print(f"\r{record_name} 等待直播... ") print(f"\r{record_name} 等待直播... ")
# 直接退出线程eric # 直接退出线程eric
# return # continue # 继续循环
# 继续循环 return # 线程彻底退出
continue
if start_pushed: if start_pushed:
if over_show_push: if over_show_push:
@@ -1622,17 +1620,15 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
error_window.append(1) error_window.append(1)
else: else:
# ====================== 抖音 → HDMI 终极无人值守版365×24h 永不卡死) ====================== # ====================== 抖音 → SRS → ffplay HDMI 终极低CPU清晰版 ======================
import queue import queue
import unicodedata import unicodedata
import traceback import traceback
# import os
# import datetime
# import time # import time
# import datetime
# import subprocess # import subprocess
# import threading # import threading
# import re # import re
# import signal
class StreamEnded(Exception): class StreamEnded(Exception):
pass pass
@@ -1671,27 +1667,15 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
proc.kill() proc.kill()
print(f"[INFO] 已强制终止 {name}") print(f"[INFO] 已强制终止 {name}")
def clear_fifo(fifo_path):
"""最彻底的FIFO清理方式"""
if os.path.exists(fifo_path):
try:
os.remove(fifo_path)
except:
pass
try:
os.mkfifo(fifo_path)
print(f"[INFO] FIFO 已彻底重建: {fifo_path}")
except Exception as e:
print(f"[FATAL] 创建 FIFO 失败: {e}")
raise
# ====================== 配置参数 ====================== # ====================== 配置参数 ======================
FIFO_PATH = "/tmp/douyin_hdmi.fifo" SRS_RTMP_URL = "rtmp://127.0.0.1/live/douyin"
SRS_PLAY_URL = "http://127.0.0.1:8080/live/douyin.flv"
MAX_RETRY_DELAY = 120 MAX_RETRY_DELAY = 120
INITIAL_RETRY_DELAY = 3 INITIAL_RETRY_DELAY = 3
NO_FRAME_TIMEOUT = 180 # 长时间无帧才判定下播,防止误判 NO_FRAME_TIMEOUT = 180
STALE_OUTPUT_SECONDS = 180 # FFmpeg僵死检测时间加长 STALE_OUTPUT_SECONDS = 180
MPV_RESTART_INTERVAL = 3600 * 6 # 每6小时强制重启一次mpv防内存泄漏 FFPLAY_RESTART_INTERVAL = 3600 * 6
END_KEYWORDS = [ END_KEYWORDS = [
"connection reset by peer", "failed to write trailer", "invalid data found", "connection reset by peer", "failed to write trailer", "invalid data found",
@@ -1703,90 +1687,83 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
timestamp_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) timestamp_str = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
_clean_title = sanitize_title(title_in_name) _clean_title = sanitize_title(title_in_name)
stream_title = sanitize_title(f"{anchor_name}{('_' + _clean_title) if _clean_title else ''}_{timestamp_str}") stream_title = sanitize_title(f"{anchor_name}{('_' + _clean_title) if _clean_title else ''}_{timestamp_str}")
print(f"[INFO] {rec_info} 启动终极无人值守HDMI转播: {stream_title}") print(f"[INFO] {rec_info} 启动 SRS → ffplay HDMI 转播低CPU原画版: {stream_title}")
# ====================== 最稳 mpv 参数(全年实测无黑屏) ====================== douyin_headers = (
mpv_cmd = [ "User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15\r\n"
"mpv", FIFO_PATH, "Referer: https://live.douyin.com/\r\n"
"--vo=drm", "Origin: https://live.douyin.com\r\n"
"--drm-device=/dev/dri/card0", )
"--drm-connector=0.HDMI-A-1", # 大多数板子有效;若黑屏改成 "HDMI-A-1"
"--hwdec=v4l2m2m-copy",
"--profile=low-latency",
"--cache=no", # 坚决关闭缓存
"--demuxer-lavf-format=flv",
"--demuxer-lavf-o=fflags=+nobuffer+genpts",
"--framedrop=no",
"--video-sync=display-resample",
"--video-rotate=270",
"--vd-lavc-fast",
"--video-unscaled=no",
"--fullscreen",
"--quiet",
"--loop-file=no",
"--no-input-default-bindings",
"--idle=no", # 防止mpv退出
]
# ====================== FFmpeg 推流到 SRS直抄原画低CPU ======================
ffmpeg_command = [ ffmpeg_command = [
"ffmpeg", "-y", "-loglevel", "info", "-nostdin", "ffmpeg", "-y", "-loglevel", "info", "-nostdin",
"-headers", douyin_headers,
"-rw_timeout", "30000000",
"-reconnect", "1", "-reconnect_at_eof", "1", "-reconnect_streamed", "1",
"-reconnect_delay_max", "7",
"-fflags", "+genpts+discardcorrupt+igndts",
"-err_detect", "ignore_err",
"-i", real_url, "-i", real_url,
"-fflags", "+genpts+discardcorrupt", "-c:v", "copy", # 直抄视频CPU极低画质取决于源抖音通常给原画
"-flags", "low_delay", "-c:a", "copy", # 直抄音频
"-c:v", "libx264", "-preset", "ultrafast", "-f", "flv", SRS_RTMP_URL
"-profile:v", "high", "-b:v", "2600k", "-maxrate", "3000k",
"-bufsize", "6000k", "-g", "60", "-r", "30",
"-vsync", "cfr", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
"-af", "aresample=async=1",
"-f", "flv", "-flvflags", "+no_duration_filesize",
FIFO_PATH
] ]
# ====================== 主循环(终极自愈 ====================== # ====================== ffplay 最佳参数低CPU + 零漂移 + 全屏 ======================
proc = None ffplay_cmd = [
mpv_proc = None "ffplay",
"-fflags", "nobuffer+genpts",
"-flags", "low_delay",
"-framedrop",
"-sync", "ext", # 零漂移
"-vf", "transpose=2", # 旋转
"-autoexit",
"-fs", # 全屏
"-loglevel", "quiet",
"-i", SRS_PLAY_URL
]
ffmpeg_proc = None
ffplay_proc = None
stderr_q = queue.Queue()
reader_t = None
retry_delay = INITIAL_RETRY_DELAY retry_delay = INITIAL_RETRY_DELAY
last_mpv_restart = time.time() # 用于定时强制重启 last_ffplay_restart = time.time()
try: try:
while True: while True:
current_time = time.time() current_time = time.time()
# ========== 定时强制重启 mpv防内存泄漏/驱动僵死) ========== if ffplay_proc and (current_time - last_ffplay_restart > FFPLAY_RESTART_INTERVAL):
if mpv_proc and (current_time - last_mpv_restart > MPV_RESTART_INTERVAL): print("[SCHEDULE] 6小时预防性重启 ffplay")
print("[SCHEDULE] 到达6小时定时重启 mpv预防性维护") cleanup_proc(ffplay_proc, "ffplay")
cleanup_proc(mpv_proc, "mpv") ffplay_proc = None
mpv_proc = None
# ========== 重启/启动 mpv ========== if ffplay_proc is None or ffplay_proc.poll() is not None:
if mpv_proc is None or mpv_proc.poll() is not None: if ffplay_proc is not None:
if mpv_proc is not None: print("[WARN] ffplay 退出,重启中...")
print("[WARN] mpv 意外退出,正在重启...")
clear_fifo(FIFO_PATH) # 每次重启mpv必清FIFO print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 ffplay 播放 SRS 原画流")
ffplay_proc = subprocess.Popen(
print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 mpv") ffplay_cmd,
mpv_proc = subprocess.Popen(
mpv_cmd,
stdin=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True text=True
) )
time.sleep(2) # 给足启动时间 time.sleep(2)
last_mpv_restart = time.time() last_ffplay_restart = time.time()
# ========== 重连等待 ==========
if retry_delay > INITIAL_RETRY_DELAY: if retry_delay > INITIAL_RETRY_DELAY:
print(f"[WARN] 等待 {retry_delay}s 后重连...") print(f"[WARN] 等待 {retry_delay}s 后重连抖音源...")
time.sleep(retry_delay) time.sleep(retry_delay)
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY) retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
cleanup_proc(proc, "FFmpeg") cleanup_proc(ffmpeg_proc, "FFmpeg")
print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 FFmpeg 拉流") print(f"[INFO][{datetime.datetime.now():%H:%M:%S}] 启动 FFmpeg 直抄推流到 SRS")
proc = subprocess.Popen( ffmpeg_proc = subprocess.Popen(
ffmpeg_command, ffmpeg_command,
stdin=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
@@ -1795,10 +1772,10 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
bufsize=1, bufsize=1,
universal_newlines=True universal_newlines=True
) )
proc.last_out_ts = time.time() ffmpeg_proc.last_out_ts = time.time()
stderr_q = queue.Queue() stderr_q = queue.Queue()
reader_t = threading.Thread(target=_stderr_reader_thread, args=(proc, stderr_q)) reader_t = threading.Thread(target=_stderr_reader_thread, args=(ffmpeg_proc, stderr_q))
reader_t.daemon = True reader_t.daemon = True
reader_t.start() reader_t.start()
@@ -1808,8 +1785,7 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
try: try:
line = stderr_q.get(timeout=1.5) line = stderr_q.get(timeout=1.5)
except queue.Empty: except queue.Empty:
# FFmpeg僵死检测 if time.time() - ffmpeg_proc.last_out_ts > STALE_OUTPUT_SECONDS:
if time.time() - proc.last_out_ts > STALE_OUTPUT_SECONDS:
print("[WARN] FFmpeg 僵死,重启") print("[WARN] FFmpeg 僵死,重启")
break break
continue continue
@@ -1821,44 +1797,33 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
if not line: if not line:
continue continue
proc.last_out_ts = time.time() ffmpeg_proc.last_out_ts = time.time()
print(f"[FFmpeg] {line}") print(f"[FFmpeg] {line}")
line_lower = line.lower() line_lower = line.lower()
# mpv缓冲堆积 → 立即重启mpv+清FIFO
if "1000 buffers queued" in line_lower:
print("[CRITICAL] mpv 缓冲堆积,强制重启 mpv + 清空 FIFO")
cleanup_proc(mpv_proc, "mpv")
mpv_proc = None
clear_fifo(FIFO_PATH)
break
# 下播关键字
if any(kw in line_lower for kw in END_KEYWORDS): if any(kw in line_lower for kw in END_KEYWORDS):
print("[INFO] 检测到下播关键字,停止转播")
raise StreamEnded() raise StreamEnded()
# 新帧重置
if re.search(r'frame=\s*\d+', line_lower): if re.search(r'frame=\s*\d+', line_lower):
last_frame_time = time.time() last_frame_time = time.time()
retry_delay = INITIAL_RETRY_DELAY retry_delay = INITIAL_RETRY_DELAY
# 长时间无帧 → 下播
if time.time() - last_frame_time > NO_FRAME_TIMEOUT: if time.time() - last_frame_time > NO_FRAME_TIMEOUT:
print(f"[INFO] {NO_FRAME_TIMEOUT}s 无新帧,判定下播") print(f"[INFO] {NO_FRAME_TIMEOUT}s 无新帧,判定下播")
raise StreamEnded() raise StreamEnded()
except StreamEnded: except StreamEnded:
print(f"[INFO] 主播已下播停止HDMI转播 → {record_name}") print(f"[INFO] 主播已下播,停止 SRS → ffplay HDMI 转播 → {record_name}")
except KeyboardInterrupt: except KeyboardInterrupt:
print("[INFO] 用户手动中断") print("[INFO] 用户手动中断")
except Exception as e: except Exception as e:
print(f"[FATAL] 未知异常: {e}") print(f"[FATAL] 未知异常: {e}")
traceback.print_exc() traceback.print_exc()
time.sleep(10) # 异常后稍等再重试 time.sleep(10)
finally: finally:
cleanup_proc(proc, "FFmpeg") cleanup_proc(ffmpeg_proc, "FFmpeg")
cleanup_proc(mpv_proc, "mpv") cleanup_proc(ffplay_proc, "ffplay")
# 清理全局状态
try: try:
recording.discard(record_name) recording.discard(record_name)
recording_time_list.pop(record_name, None) recording_time_list.pop(record_name, None)
@@ -1869,7 +1834,7 @@ def start_record(url_data: tuple, count_variable: int = -1) -> None:
clear_record_info(record_name, record_url) clear_record_info(record_name, record_url)
except: except:
pass pass
color_obj.print_colored(f"[{record_name}] HDMI转播已安全停止并清理\n", color_obj.GREEN) color_obj.print_colored(f"[{record_name}] SRS → ffplay HDMI 转播已彻底停止并清理完毕\n", color_obj.GREEN)
count_time = time.time() count_time = time.time()