cctv-object-detection / app /services /ring_buffer.py
openscopelabs's picture
feat(scan): right-click scan-mode alerting + per-camera pose
d6b1333
Raw History Blame Contribute Delete
9.19 kB
"""Frame ring buffer for scan-mode alerting.
A scan session pushes one frame per inference tick (1-2 fps typical).
The buffer keeps the last N seconds in RAM so that when a rule fires we
have *pre-event* context to attach to the alert (analyst can see "what
was happening 10s before the spike?").
Two output paths:
- ``snapshot_jpeg(path)`` writes a single representative frame.
- ``encode_mp4(path, fps)`` drains the whole buffer into an MP4 clip.
Both are synchronous I/O — call them off the scan session's tick thread
if their cost matters (a 30 s clip at 1280×720 / 1 fps ≈ 60-150 KB and
encodes in well under a second on CPU). The scan session in this repo
schedules them in a small worker pool so a fire never blocks inference.
"""
from __future__ import annotations
import logging
import shutil
import subprocess
import threading
from collections import deque
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
log = logging.getLogger(__name__)
class FrameRingBuffer:
"""Bounded FIFO of (frame_bgr, capture_ts) keyed by wall seconds.
``capacity`` is computed as ``ceil(max_seconds * fps_hint)`` with a
minimum of 2. The buffer never blocks — when full it discards the
oldest entry (deque(maxlen=...) semantics).
Callers MUST pass frames they don't intend to mutate afterwards.
We do NOT copy on append — at the scan loop's 1-2 fps cadence the
cost would be ~3 MB × 2 Hz = 6 MB/s of avoidable churn. The scan
session in this repo resizes-and-copies once during capture and
hands ownership over."""
def __init__(self, max_seconds: float, fps_hint: float):
capacity = max(2, int(round(max_seconds * max(0.1, fps_hint))))
self._buf: deque[tuple[np.ndarray, float]] = deque(maxlen=capacity)
self._lock = threading.Lock()
self.max_seconds = float(max_seconds)
self.fps_hint = float(fps_hint)
@property
def capacity(self) -> int:
return self._buf.maxlen or 0
def __len__(self) -> int:
with self._lock:
return len(self._buf)
def append(self, frame: np.ndarray, capture_ts: float) -> None:
with self._lock:
self._buf.append((frame, capture_ts))
def clear(self) -> None:
with self._lock:
self._buf.clear()
def snapshot(self) -> list[tuple[np.ndarray, float]]:
"""Atomic shallow copy of the buffer contents (oldest → newest)."""
with self._lock:
return list(self._buf)
def latest(self) -> Optional[tuple[np.ndarray, float]]:
with self._lock:
return self._buf[-1] if self._buf else None
# ---------- exports ----------
def snapshot_jpeg(
self,
path: Path,
frame: Optional[np.ndarray] = None,
quality: int = 85,
) -> bool:
"""Encode either the supplied frame or the latest buffered one
to JPEG at ``path``. Returns True on success."""
if frame is None:
tail = self.latest()
if tail is None:
return False
frame = tail[0]
try:
path.parent.mkdir(parents=True, exist_ok=True)
ok, buf = cv2.imencode(
".jpg", frame,
[int(cv2.IMWRITE_JPEG_QUALITY), int(quality)],
)
if not ok:
return False
path.write_bytes(buf.tobytes())
return True
except Exception as e: # noqa: BLE001
log.warning("snapshot write failed at %s: %s", path, e)
return False
def encode_mp4(
self,
path: Path,
fps: Optional[float] = None,
) -> bool:
"""Encode the current buffer to an MP4 at ``path``.
``fps`` defaults to whatever cadence the buffer was filled at
(derived from the median frame-to-frame delta — robust to the
occasional inference hiccup).
Codec strategy: H.264 (libx264) via ffmpeg subprocess. We tried
``cv2.VideoWriter`` with the ``mp4v`` fourcc first — fewer moving
parts, no external dep — but the resulting MPEG-4 Part 2 stream
won't play in Chromium / Safari (browsers require H.264 in MP4).
ffmpeg already ships with the cakra container image for HLS
encode so the cost is zero; we just pipe BGR frames in via
rawvideo + ``-movflags +faststart`` so the artefact streams
immediately when the analyst opens it in the alert panel.
Falls back to the cv2 ``mp4v`` path if ffmpeg is unavailable —
keeps local dev on machines without ffmpeg installed functional
(clips just won't play in-browser there)."""
frames = self.snapshot()
if len(frames) < 2:
return False
if fps is None or fps <= 0:
fps = _derive_fps(frames) or self.fps_hint
# Floor fps for ffmpeg — fractional rates < 1.0 confuse the muxer
# and the analyst clip needs the timeline to advance regardless.
fps_int = max(1, int(round(fps)))
first_frame = frames[0][0]
height, width = first_frame.shape[:2]
path.parent.mkdir(parents=True, exist_ok=True)
ffmpeg = shutil.which("ffmpeg")
if ffmpeg is not None:
return _encode_ffmpeg(ffmpeg, path, frames, width, height, fps_int)
log.warning(
"ffmpeg not found on PATH — falling back to mp4v fourcc "
"(browser playback will likely fail)",
)
return _encode_cv2(path, frames, width, height, float(fps))
def _encode_ffmpeg(
ffmpeg_bin: str,
path: Path,
frames: list[tuple[np.ndarray, float]],
width: int,
height: int,
fps: int,
) -> bool:
"""Pipe raw BGR frames into ffmpeg → libx264 mp4."""
# ``-y`` overwrite without prompt
# ``-f rawvideo`` input is raw frames (no container)
# ``-pix_fmt bgr24`` OpenCV's native layout
# ``-s WxH -r fps`` explicit input geometry / cadence
# ``-c:v libx264 -crf 23`` good-quality CPU h.264
# ``-pix_fmt yuv420p`` widest player compatibility
# ``-movflags +faststart`` move moov atom to file head so the FE
# can stream the clip without download-then-play
cmd = [
ffmpeg_bin, "-y",
"-loglevel", "error",
"-f", "rawvideo",
"-pix_fmt", "bgr24",
"-s", f"{width}x{height}",
"-r", str(fps),
"-i", "-",
"-c:v", "libx264",
"-preset", "veryfast",
"-crf", "23",
"-pix_fmt", "yuv420p",
"-movflags", "+faststart",
str(path),
]
try:
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
log.warning("ffmpeg spawn failed for %s: %s", path, e)
return False
assert proc.stdin is not None
try:
for frame, _ts in frames:
if frame.shape[1] != width or frame.shape[0] != height:
frame = cv2.resize(frame, (width, height))
# Frames may not be contiguous after resize/slice; tobytes()
# handles that copy.
proc.stdin.write(frame.tobytes())
except BrokenPipeError:
log.warning("ffmpeg pipe broke mid-encode at %s", path)
finally:
try:
proc.stdin.close()
except Exception: # noqa: BLE001
pass
_stderr = proc.stderr.read() if proc.stderr else b""
rc = proc.wait()
if rc != 0:
log.warning(
"ffmpeg exit=%d for %s — stderr: %s",
rc, path, _stderr.decode("utf-8", errors="replace").strip(),
)
return False
try:
return path.stat().st_size > 0
except OSError:
return False
def _encode_cv2(
path: Path,
frames: list[tuple[np.ndarray, float]],
width: int,
height: int,
fps: float,
) -> bool:
"""Best-effort fallback when ffmpeg is missing. mp4v fourcc — not
web-playable on Chromium but writes a valid container that can be
transcoded later (ffmpeg -i ... out.mp4)."""
fourcc = cv2.VideoWriter_fourcc(*"mp4v") # noqa: F821 (cv2 dynamic attr)
writer = cv2.VideoWriter(str(path), fourcc, fps, (width, height))
if not writer.isOpened():
log.warning("VideoWriter failed to open at %s", path)
return False
try:
for frame, _ts in frames:
if frame.shape[1] != width or frame.shape[0] != height:
frame = cv2.resize(frame, (width, height))
writer.write(frame)
finally:
writer.release()
try:
return path.stat().st_size > 0
except OSError:
return False
def _derive_fps(frames: list[tuple[np.ndarray, float]]) -> Optional[float]:
"""Median of inter-frame deltas → effective playback fps."""
if len(frames) < 2:
return None
deltas = [
max(1e-3, frames[i + 1][1] - frames[i][1])
for i in range(len(frames) - 1)
]
if not deltas:
return None
deltas.sort()
mid = deltas[len(deltas) // 2]
if mid <= 0:
return None
return 1.0 / mid