This commit is contained in:
eric
2025-09-13 21:15:31 +08:00
parent ee4423e90f
commit 8db5196a35

34
live.py
View File

@@ -33,9 +33,6 @@ class AdaptiveHLS2YouTube:
threading.Thread(target=self._abr_thread, daemon=True).start() threading.Thread(target=self._abr_thread, daemon=True).start()
def _pull_thread(self, real_url): def _pull_thread(self, real_url):
max_retry = 3 # 最大重试次数
retry_count = 0
while not self.stop_flag.is_set():
cmd = [ cmd = [
"ffmpeg", "ffmpeg",
"-rw_timeout", "50000000", "-rw_timeout", "50000000",
@@ -52,41 +49,20 @@ class AdaptiveHLS2YouTube:
"-f", "mpegts", "-f", "mpegts",
"-" "-"
] ]
proc = None
try: try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
print("[拉流] FFmpeg 启动成功") print("[拉流] FFmpeg 启动成功")
retry_count = 0 # 成功拉流重置重试计数
while not self.stop_flag.is_set(): while not self.stop_flag.is_set():
data = proc.stdout.read(188*2000) # 大块读取 data = proc.stdout.read(188*2000) # 大块读取,减少空跑
if not data: if not data:
time.sleep(0.05) time.sleep(0.05)
continue continue
try: try:
self.buffer_queue.put_nowait(data) self.buffer_queue.put_nowait(data) # 非阻塞写入队列
except queue.Full: except queue.Full:
continue continue # 队列满直接丢掉,保证不卡
except Exception as e: except Exception as e:
print(f"拉流异常: {e}") print(f"拉流异常: {e}")
finally:
try:
if proc and proc.poll() is None:
proc.kill()
except:
pass
# 轮训逻辑:直播未开播时重试
retry_count += 1
if retry_count >= max_retry:
print(f"[拉流] 连续 {max_retry} 次没有拉到流,停止推流")
self.stop_all()
break
else:
print(f"[拉流] 等待 10 秒后重试 ({retry_count}/{max_retry})...")
for _ in range(6): # 每分钟 6 次,10 秒/次
if self.stop_flag.is_set():
break
time.sleep(10)
def _push_thread(self, youtube_key, room_name): def _push_thread(self, youtube_key, room_name):
min_buffer = max(1, self.delay_sec // self.segment_time) min_buffer = max(1, self.delay_sec // self.segment_time)
@@ -135,7 +111,7 @@ class AdaptiveHLS2YouTube:
proc.stdin.write(data) proc.stdin.write(data)
proc.stdin.flush() proc.stdin.flush()
except (BrokenPipeError, OSError): except (BrokenPipeError, OSError):
break break # 管道断开,退出推流循环
except queue.Empty: except queue.Empty:
continue continue
except Exception as e: except Exception as e:
@@ -153,7 +129,7 @@ class AdaptiveHLS2YouTube:
if new_bitrate != self.current_bitrate: if new_bitrate != self.current_bitrate:
print(f"[ABR] 调整码率: {self.current_bitrate}k -> {new_bitrate}k") print(f"[ABR] 调整码率: {self.current_bitrate}k -> {new_bitrate}k")
self.current_bitrate = new_bitrate self.current_bitrate = new_bitrate
time.sleep(max(self.check_interval, 10)) time.sleep(max(self.check_interval, 10)) # 降低 ABR 更新频率,避免频繁干扰
def stop_all(self): def stop_all(self):
print("停止所有推流...") print("停止所有推流...")