File size: 11,195 Bytes
40e0b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
"""Server-side HLS encoder — produces an annotated HLS stream per camera.

We spawn one ffmpeg subprocess per active camera and feed it raw BGR24
frames via stdin. ffmpeg muxes the output into MPEG-TS segments and a
rolling playlist on disk.

Key timing properties:

- ``feed()`` is non-blocking. Frames go into a bounded queue, and a
  dedicated writer thread drains it into ffmpeg's stdin. This means the
  render thread NEVER stalls on a slow encoder — important when the
  YOLO inference thread is hammering the GIL.
- ffmpeg is started with ``-use_wallclock_as_timestamps 1`` so frame
  PTS comes from arrival time rather than the assumed ``-framerate``.
  That makes the wall-clock duration of each emitted segment match the
  wall-clock arrival time of its frames, which keeps browser playback
  steady even when render rate fluctuates.

The point is embed simplicity: clients drop
``<video src=".../hls/playlist.m3u8">`` (or hls.js) into the page and
get smooth playback with YOLO bboxes already baked into the pixels —
no canvas overlay, no WebSocket coupling needed."""
from __future__ import annotations

import logging
import queue
import shutil
import subprocess
import threading
from pathlib import Path
from typing import Optional

import numpy as np

log = logging.getLogger(__name__)


class HLSEncoder:
    """One ffmpeg subprocess that ingests BGR frames and emits HLS."""

    def __init__(
        self,
        camera_id: str,
        out_dir: Path,
        width: int,
        height: int,
        fps: int,
        segment_seconds: float = 1.0,
        list_size: int = 6,
        crf: int = 23,
        preset: str = "veryfast",
        encoder: str = "libx264",
    ):
        self.camera_id = camera_id
        self.out_dir = Path(out_dir)
        self.width = width
        self.height = height
        self.fps = fps
        self.segment_seconds = segment_seconds
        self.list_size = list_size
        self.crf = crf
        self.preset = preset
        self.encoder = self._resolve_encoder(encoder)

        self._proc: Optional[subprocess.Popen] = None
        self._stderr_thread: Optional[threading.Thread] = None
        self._running = False

        # Writer queue — render thread enqueues raw frame bytes here;
        # writer thread drains into ffmpeg stdin. Bound the size so the
        # render thread sees backpressure when ffmpeg falls behind, but
        # keep it large enough that GIL jitter from YOLO inference is
        # absorbed cleanly (~0.5-1.0s slack).
        self._write_queue: "queue.Queue[bytes]" = queue.Queue(maxsize=max(8, self.fps))
        self._writer_thread: Optional[threading.Thread] = None

    def _encoder_quality_flags(self) -> list[str]:
        """Codec-specific quality flags. libx264 takes ``-preset`` + CRF;
        h264_videotoolbox takes ``-q:v`` (1-100, higher = better) and
        ignores presets; h264_nvenc takes ``-preset`` + ``-cq``."""
        if self.encoder == "libx264":
            return [
                "-preset", self.preset,
                "-tune", "zerolatency",
                "-profile:v", "main",
                "-crf", str(self.crf),
            ]
        if self.encoder == "h264_videotoolbox":
            # Map CRF (18-28 typical) to videotoolbox q (60-90 sane range).
            q = max(40, min(95, 100 - self.crf * 2))
            return [
                "-q:v", str(q),
                "-realtime", "1",
                "-profile:v", "main",
            ]
        if self.encoder == "h264_nvenc":
            return [
                "-preset", "p4",  # closest to libx264 veryfast
                "-tune", "ll",    # low-latency
                "-rc", "vbr",
                "-cq", str(self.crf),
                "-profile:v", "main",
            ]
        return []

    @staticmethod
    def _resolve_encoder(name: str) -> str:
        """Map env name → ffmpeg codec id. Falls back to libx264 if the
        requested hardware encoder is not available in this ffmpeg build."""
        name = (name or "libx264").strip().lower()
        candidate = {
            "libx264": "libx264",
            "x264": "libx264",
            "videotoolbox": "h264_videotoolbox",
            "h264_videotoolbox": "h264_videotoolbox",
            "nvenc": "h264_nvenc",
            "h264_nvenc": "h264_nvenc",
        }.get(name, "libx264")
        try:
            res = subprocess.run(
                ["ffmpeg", "-hide_banner", "-encoders"],
                capture_output=True, text=True, timeout=5,
            )
            if candidate not in res.stdout:
                log.warning("encoder '%s' not in ffmpeg build, falling back to libx264",
                            candidate)
                return "libx264"
        except Exception:  # noqa: BLE001
            pass
        return candidate

    @property
    def playlist_path(self) -> Path:
        return self.out_dir / "playlist.m3u8"

    @property
    def is_running(self) -> bool:
        return self._running and self._proc is not None and self._proc.poll() is None

    def start(self) -> None:
        if self._proc is not None:
            return
        self.out_dir.mkdir(parents=True, exist_ok=True)
        for p in self.out_dir.glob("*"):
            try:
                p.unlink()
            except OSError:
                pass

        gop = max(1, int(self.fps * self.segment_seconds))
        cmd = [
            "ffmpeg",
            "-hide_banner", "-loglevel", "warning",
            # Input: rawvideo from stdin at a STRICT fps. No
            # wallclock_as_timestamps — the pacer thread upstream gives
            # us exactly ``fps`` frames per wallclock second, so PTS is
            # generated as ``frame_index / fps`` (evenly spaced).
            "-f", "rawvideo",
            "-pixel_format", "bgr24",
            "-video_size", f"{self.width}x{self.height}",
            "-framerate", str(self.fps),
            "-r", str(self.fps),  # belt-and-braces: assert input rate
            "-i", "-",
            "-c:v", self.encoder,
        ]
        cmd += self._encoder_quality_flags()
        cmd += [
            "-pix_fmt", "yuv420p",
            # Output: TRUE CFR at the configured fps. ffmpeg duplicates
            # or drops frames as needed to keep PTS evenly spaced, so
            # segments split on exact second boundaries every time.
            "-r", str(self.fps),
            "-fps_mode", "cfr",
            # GOP aligned to segment boundary → key-frame at every
            # segment start, no mid-segment IDR, browsers seek cleanly.
            "-g", str(gop),
            "-keyint_min", str(gop),
            "-sc_threshold", "0",
            "-f", "hls",
            "-hls_time", str(self.segment_seconds),
            "-hls_list_size", str(self.list_size),
            "-hls_flags", "delete_segments+omit_endlist+independent_segments",
            "-hls_segment_type", "mpegts",
            "-hls_segment_filename", str(self.out_dir / "seg_%05d.ts"),
            str(self.playlist_path),
        ]
        log.info("[hls-enc %s] spawning ffmpeg → %s", self.camera_id, self.out_dir)
        try:
            self._proc = subprocess.Popen(
                cmd,
                stdin=subprocess.PIPE,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.PIPE,
            )
        except FileNotFoundError:
            log.error("[hls-enc %s] ffmpeg binary not found in PATH", self.camera_id)
            self._proc = None
            return

        self._running = True
        self._stderr_thread = threading.Thread(
            target=self._drain_stderr, daemon=True,
            name=f"hls-stderr-{self.camera_id}",
        )
        self._stderr_thread.start()
        self._writer_thread = threading.Thread(
            target=self._writer_loop, daemon=True,
            name=f"hls-writer-{self.camera_id}",
        )
        self._writer_thread.start()

    def feed(self, frame: np.ndarray) -> None:
        """Hand a frame to the writer thread. Non-blocking.

        If ffmpeg is falling behind and the queue is full we drop the
        OLDEST frame and append the newest — latest-wins semantics for
        a live stream. Render thread never stalls."""
        if not self._running or self._proc is None or self._proc.stdin is None:
            return
        if frame.ndim != 3 or frame.shape[2] != 3:
            return
        if frame.shape[1] != self.width or frame.shape[0] != self.height:
            return
        data = frame.tobytes()
        try:
            self._write_queue.put_nowait(data)
            return
        except queue.Full:
            pass
        # Backpressure: drop the oldest waiting frame, append the new one.
        try:
            self._write_queue.get_nowait()
            self._write_queue.put_nowait(data)
        except (queue.Empty, queue.Full):
            pass

    def _writer_loop(self) -> None:
        """Drain the queue into ffmpeg stdin. The only place that
        actually blocks on the pipe — keeps the render thread free."""
        proc = self._proc
        if proc is None or proc.stdin is None:
            return
        while self._running:
            try:
                data = self._write_queue.get(timeout=0.5)
            except queue.Empty:
                continue
            try:
                proc.stdin.write(data)
            except (BrokenPipeError, ValueError, OSError) as e:
                self._running = False
                log.warning("[hls-enc %s] ffmpeg stdin closed: %s",
                            self.camera_id, e)
                break

    def stop(self) -> None:
        self._running = False
        proc = self._proc
        if proc is None:
            return
        # Wake the writer thread so it notices _running is False.
        try:
            self._write_queue.put_nowait(b"")
        except queue.Full:
            pass
        if self._writer_thread is not None:
            try:
                self._writer_thread.join(timeout=1)
            except Exception:
                pass
        try:
            if proc.stdin is not None:
                try:
                    proc.stdin.close()
                except OSError:
                    pass
            try:
                proc.wait(timeout=2)
            except subprocess.TimeoutExpired:
                proc.kill()
                proc.wait(timeout=2)
        finally:
            self._proc = None
            log.info("[hls-enc %s] stopped", self.camera_id)
            if self.out_dir.exists():
                shutil.rmtree(self.out_dir, ignore_errors=True)

    def _drain_stderr(self) -> None:
        """Read ffmpeg's stderr so the pipe doesn't fill up and block the
        subprocess. Surface warnings/errors at the WARNING level."""
        proc = self._proc
        if proc is None or proc.stderr is None:
            return
        for raw in iter(proc.stderr.readline, b""):
            try:
                line = raw.decode("utf-8", errors="replace").rstrip()
            except Exception:  # noqa: BLE001
                continue
            if line:
                log.warning("[hls-enc %s] ffmpeg: %s", self.camera_id, line)