cctv-object-detection / app /services /hls_encoder.py
openscopelabs's picture
feat: real-time CCTV YOLO analytics with bbox-baked HLS
40e0b51
Raw History Blame Contribute Delete
11.2 kB
"""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)