"""Threaded RTSP/HLS/HTTP frame reader with auto-reconnect.""" from __future__ import annotations import logging import os import threading import time from typing import Callable, Optional import cv2 import numpy as np log = logging.getLogger(__name__) FrameCallback = Callable[[np.ndarray, float], None] class StreamReader(threading.Thread): """One thread per camera. Continuously decodes frames and keeps only the latest one in a buffer of size 1, so a slow consumer never falls behind the wall clock. Consumers can either pull via ``read()`` (latest-wins) or register an ``on_frame`` callback to receive every decoded frame at native source fps. The callback runs INLINE on the reader thread — keep it bounded (push to a queue, don't do CV work there).""" def __init__( self, camera_id: str, url: str, reconnect_delay: float = 5.0, on_frame: Optional[FrameCallback] = None, read_pace_fps: float = 0.0, ): super().__init__(daemon=True, name=f"reader-{camera_id}") self.camera_id = camera_id self.url = url self.reconnect_delay = reconnect_delay self._on_frame = on_frame # Cap cap.read() rate at this many fps. ``0`` (default) means # read as fast as ffmpeg will deliver. Set to the source's # native fps to prevent burst-dump of an entire HLS segment in # one tight read loop. self._read_pace_fps = read_pace_fps self._cap: Optional[cv2.VideoCapture] = None self._frame: Optional[np.ndarray] = None self._lock = threading.Lock() self._running = True self.connected = False self.last_read_ts = 0.0 self.read_count = 0 self.fps = 0.0 self.last_error: Optional[str] = None # (width, height) of the most recently decoded frame, or None # until the first frame arrives. self.frame_size: Optional[tuple[int, int]] = None @staticmethod def configure_ffmpeg_env(open_timeout_us: int = 5_000_000) -> None: # Pacing flags: let FFmpeg deliver frames at the source's wall-clock # rate. Without this (i.e. with nobuffer/low_delay/max_delay=0), # HLS segments get burst-decoded — 30-60 frames dumped in ~100ms, # then a 2-4s gap. The "buffer size 1" pattern then discards the # intermediate frames, leaving viewers with freeze → teleport → # freeze. Paced delivery costs ~2-3s init latency but gives smooth # WebRTC/MJPEG playback. os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = ( f"rtsp_transport;tcp|stimeout;{open_timeout_us}|" f"reconnect;1|reconnect_streamed;1|reconnect_delay_max;5|" f"probesize;500000|analyzeduration;0" ) def _open(self) -> cv2.VideoCapture: cap = cv2.VideoCapture(self.url, cv2.CAP_FFMPEG) try: cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) except Exception: pass return cap def _release(self) -> None: try: if self._cap is not None: self._cap.release() finally: self._cap = None def run(self) -> None: win_start = time.time() win_count = 0 # Pace cap.read() at a slight margin above the encoder's target # rate. cv2 / ffmpeg's HLS demuxer otherwise dumps each segment # (≈50 frames) into us in ~100 ms, overflowing the downstream # ring buffer and producing burst-then-freeze motion. By # spacing reads at ~1/(fps+2) we let TCP/ffmpeg backpressure # smooth the source delivery — the ring stays small, no # frames are dropped, and motion plays at true 1× speed. try: paced_period = 1.0 / max(1, int(self._read_pace_fps)) except Exception: paced_period = 0.0 last_read_ts = 0.0 while self._running: try: if self._cap is None or not self._cap.isOpened(): log.info("[%s] opening stream", self.camera_id) self._cap = self._open() if not self._cap.isOpened(): self.connected = False self.last_error = "open_failed" log.warning("[%s] open failed; retry in %.1fs", self.camera_id, self.reconnect_delay) self._release() time.sleep(self.reconnect_delay) continue self.connected = True self.last_error = None log.info("[%s] connected", self.camera_id) # Pace the read so we don't drain ffmpeg's HLS demuxer # faster than wall-clock playback. if paced_period > 0 and last_read_ts > 0: elapsed = time.monotonic() - last_read_ts if elapsed < paced_period: time.sleep(paced_period - elapsed) last_read_ts = time.monotonic() ok, frame = self._cap.read() if not ok or frame is None: self.connected = False self.last_error = "read_failed" log.warning("[%s] read failed; reconnecting", self.camera_id) self._release() time.sleep(self.reconnect_delay) continue capture_ts = time.time() with self._lock: self._frame = frame self.last_read_ts = capture_ts self.read_count += 1 self.frame_size = (frame.shape[1], frame.shape[0]) # Hand a frame view (not a copy) straight to the encoder # pipeline at SOURCE fps with its capture timestamp. # The callback is expected to do at most a queue push — # heavy CV work would stall the decoder. if self._on_frame is not None: try: self._on_frame(frame, capture_ts) except Exception as e: # noqa: BLE001 log.exception("[%s] on_frame error: %s", self.camera_id, e) win_count += 1 now = time.time() if now - win_start >= 1.0: self.fps = win_count / (now - win_start) win_count = 0 win_start = now except Exception as e: # noqa: BLE001 self.connected = False self.last_error = str(e) log.exception("[%s] reader error: %s", self.camera_id, e) self._release() time.sleep(self.reconnect_delay) def read(self) -> Optional[np.ndarray]: with self._lock: return None if self._frame is None else self._frame.copy() def read_with_ts(self) -> tuple[Optional[np.ndarray], float]: """Return (frame_copy, capture_timestamp) atomically. Use this when you need to correlate a frame with downstream state (e.g. tagging detections with the exact capture time so annotations can be aligned later).""" with self._lock: if self._frame is None: return None, 0.0 return self._frame.copy(), self.last_read_ts def stop(self) -> None: self._running = False self._release()