File size: 9,185 Bytes
d6b1333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""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