Files
zenai-apc-ngoro/batch_video_recorder.py
2026-10-21 10:01:25 +07:00

479 lines
15 KiB
Python

"""
RAM-disk batch video recorder for live counter.
Writes frames to /dev/shm while a batch is open; finalize renames for upload.
Designed so the detection loop never blocks on encode or writer join:
- put() is non-blocking (drop only when queue is full)
- max_fps <= 0 means record every frame (no throttle)
- encode runs in a separate process on CPU (ffmpeg libx264 ultrafast / OpenCV fallback)
- finalize() may join the writer; callers should run it off the detect thread
- after encode, restamp container FPS to written/wall so duration ≈ wall time
"""
from __future__ import annotations
import multiprocessing as mp
import os
import queue
import subprocess
import threading
import time
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
SENTINEL = None
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "ffmpeg")
# libx264 ultrafast keeps up at 640x480 without blocking NPU detect
RECORD_ENCODER = os.getenv("BATCH_RECORD_ENCODER", "libx264").strip() or "libx264"
RECORD_PRESET = os.getenv("BATCH_RECORD_PRESET", "ultrafast").strip() or "ultrafast"
RECORD_CRF = os.getenv("BATCH_RECORD_CRF", "28").strip() or "28"
def _ffmpeg_writer_proc(
q: mp.Queue,
out_path: str,
fps: float,
width: int,
height: int,
encoder: str,
preset: str,
crf: str,
):
"""CPU encode via ffmpeg stdin — H.264 for browser + speed."""
path = Path(out_path)
path.parent.mkdir(parents=True, exist_ok=True)
fps = max(float(fps), 1.0)
cmd = [
FFMPEG_BIN,
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"rawvideo",
"-pix_fmt",
"bgr24",
"-s",
f"{width}x{height}",
"-r",
f"{fps:.6f}",
"-i",
"pipe:0",
"-an",
"-c:v",
encoder,
]
if encoder.startswith("libx264"):
cmd.extend(["-preset", preset, "-tune", "zerolatency", "-crf", crf])
# No +faststart here (needs second pass; breaks some pipe→file flows).
# Finalize restamp applies +faststart.
cmd.extend(["-pix_fmt", "yuv420p", str(path)])
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
assert proc.stdin is not None
frames = 0
err_tail = b""
try:
while True:
item = q.get()
if item is SENTINEL:
break
frame = item
if frame is None:
continue
fh, fw = frame.shape[:2]
if fw != width or fh != height:
if fw > width or fh > height:
frame = cv2.resize(
frame, (width, height), interpolation=cv2.INTER_AREA
)
else:
canvas = np.zeros((height, width, 3), dtype=frame.dtype)
canvas[:fh, :fw] = frame
frame = canvas
if not frame.flags["C_CONTIGUOUS"]:
frame = np.ascontiguousarray(frame)
try:
proc.stdin.write(frame.tobytes())
frames += 1
except BrokenPipeError:
break
except Exception as exc:
print(f"[BatchVideoRecorder] ffmpeg writer error: {exc}", flush=True)
finally:
try:
proc.stdin.close()
except Exception:
pass
try:
err_tail = proc.stderr.read() if proc.stderr else b""
except Exception:
err_tail = b""
try:
proc.wait(timeout=60)
except Exception:
proc.kill()
try:
proc.wait(timeout=5)
except Exception:
pass
ok = (
proc.returncode == 0
and Path(out_path).is_file()
and Path(out_path).stat().st_size > 1000
)
if not ok:
msg = (err_tail or b"").decode("utf-8", errors="replace")[-400:]
print(
f"[BatchVideoRecorder] ffmpeg failed rc={proc.returncode} "
f"frames={frames}: {msg}",
flush=True,
)
else:
print(
f"[BatchVideoRecorder] ffmpeg ok frames={frames} "
f"size={Path(out_path).stat().st_size}",
flush=True,
)
def _opencv_writer_proc(
q: mp.Queue,
out_path: str,
fps: float,
width: int,
height: int,
):
"""Fallback OpenCV writer (prefer avc1, then mp4v)."""
path = Path(out_path)
path.parent.mkdir(parents=True, exist_ok=True)
writer = None
try:
for fourcc in ("avc1", "H264", "mp4v"):
writer = cv2.VideoWriter(
str(path),
cv2.VideoWriter_fourcc(*fourcc),
max(fps, 1.0),
(width, height),
)
if writer.isOpened():
print(f"[BatchVideoRecorder] OpenCV fourcc={fourcc}", flush=True)
break
writer.release()
writer = None
if writer is None:
print("[BatchVideoRecorder] OpenCV VideoWriter failed to open", flush=True)
while True:
item = q.get()
if item is SENTINEL:
break
return
while True:
item = q.get()
if item is SENTINEL:
break
frame = item
if frame is None:
continue
fh, fw = frame.shape[:2]
if fw != width or fh != height:
if fw > width or fh > height:
frame = cv2.resize(
frame, (width, height), interpolation=cv2.INTER_AREA
)
else:
canvas = np.zeros((height, width, 3), dtype=frame.dtype)
canvas[:fh, :fw] = frame
frame = canvas
writer.write(frame)
except Exception as exc:
print(f"[BatchVideoRecorder] writer error: {exc}", flush=True)
finally:
if writer is not None:
writer.release()
def _writer_proc(
q: mp.Queue,
out_path: str,
fps: float,
width: int,
height: int,
use_ffmpeg: bool,
encoder: str,
preset: str,
crf: str,
):
if use_ffmpeg:
_ffmpeg_writer_proc(q, out_path, fps, width, height, encoder, preset, crf)
return
_opencv_writer_proc(q, out_path, fps, width, height)
def _restamp_fps(src: Path, dst: Path, measured_fps: float) -> bool:
"""Rewrite container timestamps so duration = n_frames / measured_fps."""
if measured_fps <= 0.1:
return False
try:
tmp = dst.with_suffix(".restamp.mp4")
cmd = [
FFMPEG_BIN,
"-y",
"-r",
f"{measured_fps:.6f}",
"-i",
str(src),
"-c",
"copy",
"-movflags",
"+faststart",
str(tmp),
]
subprocess.run(
cmd,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=600,
)
if not tmp.is_file() or tmp.stat().st_size < 1000:
tmp.unlink(missing_ok=True)
return False
tmp.replace(dst)
return True
except Exception as exc:
print(f"[BatchVideoRecorder] restamp failed: {exc}")
try:
dst.with_suffix(".restamp.mp4").unlink(missing_ok=True)
except Exception:
pass
return False
def _ffmpeg_available() -> bool:
try:
subprocess.run(
[FFMPEG_BIN, "-version"],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5,
)
return True
except Exception:
return False
class BatchVideoRecorder:
"""Non-blocking frame sink that records the active batch to SHM."""
def __init__(
self,
shm_dir: str,
enabled: bool = True,
max_fps: float = 0.0,
queue_size: int = 480,
):
self.shm_dir = Path(shm_dir)
self.enabled = enabled
# <=0 means passthrough every frame (no FPS throttle)
self.max_fps = float(max_fps) if max_fps and max_fps > 0 else 0.0
self.queue_size = max(4, int(queue_size))
self.shm_dir.mkdir(parents=True, exist_ok=True)
self._q: Optional[mp.Queue] = None
self._proc: Optional[mp.Process] = None
self._w = self._h = 0
self._fps = 15.0
self._active = False
self._batch_id: Optional[str] = None
self._partial: Optional[Path] = None
self._last_put_mono = 0.0
self._dropped = 0
self._written = 0
self._t0 = 0.0
self._measured_fps = 0.0
self._lock = threading.Lock()
self._use_ffmpeg = _ffmpeg_available() and RECORD_ENCODER.lower() != "opencv"
@property
def active(self) -> bool:
return self._active
@property
def stats(self) -> dict:
return {
"active": self._active,
"batch_id": self._batch_id,
"written": self._written,
"dropped": self._dropped,
"size": f"{self._w}x{self._h}",
"fps": self._fps,
"max_fps": self.max_fps,
"measured_fps": self._measured_fps,
"encoder": RECORD_ENCODER if self._use_ffmpeg else "opencv",
}
def start(self, batch_id: str, width: int, height: int, fps: float):
if not self.enabled:
return
with self._lock:
self._stop_discard_locked()
self._batch_id = batch_id
self._w = max(1, int(width))
self._h = max(1, int(height))
src_fps = float(fps) if fps and fps > 1 else 15.0
# Writer stamp uses camera fps; finalize restamps to measured.
if self.max_fps > 0:
self._fps = min(src_fps, self.max_fps)
else:
self._fps = src_fps
self._partial = self.shm_dir / f"batch_{batch_id}.partial.mp4"
if self._partial.exists():
self._partial.unlink(missing_ok=True)
legacy = self.shm_dir / "batch_TMP.mp4"
legacy.unlink(missing_ok=True)
self._q = mp.Queue(maxsize=self.queue_size)
self._proc = mp.Process(
target=_writer_proc,
args=(
self._q,
str(self._partial),
self._fps,
self._w,
self._h,
self._use_ffmpeg,
RECORD_ENCODER,
RECORD_PRESET,
RECORD_CRF,
),
daemon=True,
)
self._proc.start()
self._active = True
self._last_put_mono = 0.0
self._dropped = 0
self._written = 0
self._measured_fps = 0.0
self._t0 = time.monotonic()
print(
f"[BatchVideoRecorder] start {batch_id} "
f"{self._w}x{self._h}@{self._fps:.1f} "
f"queue={self.queue_size} encoder="
f"{RECORD_ENCODER if self._use_ffmpeg else 'opencv'}",
flush=True,
)
def put(self, frame: np.ndarray):
if not self._active or self._q is None:
return
if self.max_fps > 0:
now = time.monotonic()
min_dt = 1.0 / self.max_fps
if self._last_put_mono and (now - self._last_put_mono) < min_dt:
self._dropped += 1
return
self._last_put_mono = now
try:
self._q.put_nowait(frame.copy())
self._written += 1
except queue.Full:
self._dropped += 1
try:
self._q.get_nowait()
except queue.Empty:
pass
try:
self._q.put_nowait(frame.copy())
self._written += 1
except queue.Full:
pass
def finalize(self) -> Optional[Path]:
"""Close writer, restamp FPS to match wall time, return final path."""
with self._lock:
if not self._active and self._proc is None:
return None
batch_id = self._batch_id
q, proc = self._q, self._proc
partial = self._partial
written = self._written
dropped = self._dropped
t0 = self._t0
self._active = False
self._q = None
self._proc = None
self._batch_id = None
self._partial = None
if q is not None:
try:
q.put(SENTINEL, timeout=2)
except Exception:
pass
if proc is not None:
# Longer join — draining a full queue at end of batch can take a bit.
proc.join(timeout=120)
if proc.is_alive():
proc.terminate()
proc.join(timeout=2)
if not batch_id or partial is None:
return None
if not partial.is_file() or partial.stat().st_size < 1000:
partial.unlink(missing_ok=True)
return None
wall = max(0.001, time.monotonic() - t0) if t0 else 0.0
measured = (written / wall) if wall > 0 and written > 0 else 0.0
self._measured_fps = measured
total_attempted = written + dropped
drop_pct = (100.0 * dropped / total_attempted) if total_attempted else 0.0
print(
f"[BatchVideoRecorder] finalize {batch_id}: "
f"written={written} dropped={dropped} ({drop_pct:.1f}%) "
f"wall={wall:.1f}s measured_fps={measured:.2f}",
flush=True,
)
out = self.shm_dir / f"batch_{batch_id}.mp4"
if measured >= 1.0 and _restamp_fps(partial, out, measured):
partial.unlink(missing_ok=True)
else:
partial.replace(out)
return out
def stop_discard(self):
"""Abort recording and delete partial."""
with self._lock:
self._stop_discard_locked()
def _stop_discard_locked(self):
partial = self._partial
if self._active or self._proc is not None:
q, proc = self._q, self._proc
self._active = False
self._q = None
self._proc = None
self._batch_id = None
self._partial = None
if q is not None:
try:
q.put(SENTINEL, timeout=1)
except Exception:
pass
if proc is not None:
proc.join(timeout=5)
if proc.is_alive():
proc.terminate()
proc.join(timeout=2)
if partial is not None:
partial.unlink(missing_ok=True)
(self.shm_dir / "batch_TMP.mp4").unlink(missing_ok=True)