This commit is contained in:
邓智航
2026-03-07 17:00:57 +08:00
parent e5c843334e
commit 5e2616471f
2 changed files with 51 additions and 18 deletions

View File

@@ -18,6 +18,7 @@ class Alert:
self.encode_thread = None
self.upload_thread = None
self.stop_event = threading.Event()
self.abort_event = threading.Event() # 新增:用于超时强制中断
self.dropped_frames = 0
def start(self, width=1920, height=1080, fps=30):
@@ -54,15 +55,19 @@ class Alert:
self.stream.width = width
self.stream.height = height
self.stream.pix_fmt = "yuv420p"
# 使用更快的编码预设
# self.stream.options = {"preset": "ultrafast", "crf": "23"}
self.stream.options = {"preset": "ultrafast", "tune": "zerolatency", "crf": "23"}
print("AV container and stream initialized")
# 启动编码线程
def _encode() -> None:
try:
print("Encode thread starting")
# 修改循环条件:增加 abort_event 检查
while not self.stop_event.is_set() or not self.frame_queue.empty():
if self.abort_event.is_set():
print("Encode thread aborted by timeout (dropping remaining frames)")
break
try:
frame = self.frame_queue.get(timeout=0.1)
if frame is None:
@@ -100,13 +105,10 @@ class Alert:
self.frame_queue.put(None)
self.stop_event.set()
# 等待编码线程完成
# 等待编码线程完成(不设超时,确保所有帧都编码完成)
if self.encode_thread:
self.encode_thread.join(timeout=30)
if self.encode_thread.is_alive():
print("Warning: Encode thread still running after timeout")
else:
print(f"Encode thread completed with {self.frame_count} frames")
self.encode_thread.join()
print(f"Encode thread completed with {self.frame_count} frames")
# 完成编码flush所有待处理的数据
try: