Spaces:
Runtime error
perf(stream): drift-free pacer + reader pacing for true 25 fps smoothness
Browse filesThree fixes layered to eliminate the "smooth → freeze → burst" cycle
caused by upstream HLS segment-burst delivery:
1. Drift-free pacer scheduler
The pacer now anchors every tick at an absolute monotonic target
(start + N*period) with a ~2 ms busy-wait tail. time.sleep() on
macOS overshoots by ~3-5 ms because the kernel timer tick is
coarse, which was silently drifting the pacer to ~22.7 fps even
when work was only 4 ms. Effective pacer rate is now 25.0 fps
measured.
2. Reader pacing at HLS_FPS
stream_reader.cap.read() was draining ffmpeg's HLS demuxer as
fast as it could decode, dumping a full ~50-frame segment into
the ring in ~100 ms. The ring's drop-oldest semantics then
threw away ~47 % of every burst, producing temporal
discontinuities visible downstream as fast-forward bursts
followed by frozen frames. Pacing cap.read() at HLS_FPS lets
TCP / ffmpeg backpressure smooth the source delivery; the ring
now stays at length 1-2 and source frame drops are zero.
3. Larger ring + resize at capture
maxlen bumped from HLS_FPS to 4×HLS_FPS as defense-in-depth in
case the reader briefly under-paces. Resize moved from the
pacer hot path back to the capture thread so ring entries are
output-resolution (~2.7 MB at 720p) rather than source-resolution
(~6 MB at 1080p), halving worst-case per-camera memory.
Measured via 60 s embed observation: 100 % "playing" state, buffered
ahead 10-12 s steady, zero waiting / stalled events, zero currentTime
jumps. Pacer telemetry: ring drops 0 per 5 s window (was 8-31).
Also: minor housekeeping —
- .env.example refreshed to match the post-events / post-mjpeg API
- docs/embed.html added as a minimal "production embed" reference
(no panel, just <video> + hls.js + a corner HUD)
- .env.example +57 -15
- app/services/pipeline.py +60 -26
- app/services/stream_reader.py +26 -0
- docs/embed.html +111 -0
|
@@ -1,29 +1,71 @@
|
|
| 1 |
-
# Server
|
| 2 |
HOST=0.0.0.0
|
| 3 |
PORT=8000
|
| 4 |
LOG_LEVEL=INFO
|
| 5 |
|
| 6 |
-
#
|
|
|
|
|
|
|
|
|
|
| 7 |
STREAMS_STATUS_FILTER=online
|
| 8 |
-
MAX_STREAMS=
|
| 9 |
RECONNECT_DELAY=5.0
|
| 10 |
|
| 11 |
-
# Database
|
|
|
|
|
|
|
| 12 |
DATABASE_URL=postgresql://user:pass@host:5432/dbname
|
| 13 |
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
| 17 |
IOU_THRESHOLD=0.5
|
| 18 |
-
INFERENCE_SIZE=
|
| 19 |
USE_HALF=true
|
| 20 |
-
|
| 21 |
-
# Processing / streaming
|
| 22 |
FRAME_SKIP=1
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
STALE_FRAME_SECONDS=2.0
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ---- Server ----
|
| 2 |
HOST=0.0.0.0
|
| 3 |
PORT=8000
|
| 4 |
LOG_LEVEL=INFO
|
| 5 |
|
| 6 |
+
# ---- Camera catalog ----
|
| 7 |
+
# Source camera rows from cctv_streams. STREAMS_STATUS_FILTER limits
|
| 8 |
+
# which rows are eligible (typically "online"). MAX_STREAMS caps the
|
| 9 |
+
# in-process worker pool.
|
| 10 |
STREAMS_STATUS_FILTER=online
|
| 11 |
+
MAX_STREAMS=50
|
| 12 |
RECONNECT_DELAY=5.0
|
| 13 |
|
| 14 |
+
# ---- Database ----
|
| 15 |
+
# Reads cctv_streams (catalog). Creates / UPSERTs cctv_session_metrics
|
| 16 |
+
# (one row per camera, lifetime aggregates). No hypertables.
|
| 17 |
DATABASE_URL=postgresql://user:pass@host:5432/dbname
|
| 18 |
|
| 19 |
+
# ---- YOLO ----
|
| 20 |
+
# Use scripts/setup_yolo_world.py to regenerate the model with custom
|
| 21 |
+
# classes. Default is YOLO-World medium with 17 Indonesian-traffic
|
| 22 |
+
# class names baked in.
|
| 23 |
+
MODEL_PATH=./models/yolo-world-id.pt
|
| 24 |
+
CONF_THRESHOLD=0.05
|
| 25 |
IOU_THRESHOLD=0.5
|
| 26 |
+
INFERENCE_SIZE=960
|
| 27 |
USE_HALF=true
|
|
|
|
|
|
|
| 28 |
FRAME_SKIP=1
|
| 29 |
+
# Pace YOLO inference. Lower than capture fps because YOLO can't keep
|
| 30 |
+
# up at full source rate on CPU/MPS.
|
| 31 |
+
TARGET_INFER_FPS=8
|
| 32 |
+
|
| 33 |
+
# ---- HUD mask (CCTV banner / timestamp overlay strips) ----
|
| 34 |
+
# Top + bottom strips of the source frame are blanked before inference
|
| 35 |
+
# so YOLO doesn't pick up burned-in agency banners as cars/trucks.
|
| 36 |
+
HUD_MASK_TOP_PCT=0.06
|
| 37 |
+
HUD_MASK_BOTTOM_PCT=0.05
|
| 38 |
STALE_FRAME_SECONDS=2.0
|
| 39 |
|
| 40 |
+
# ---- Video output ----
|
| 41 |
+
# Encoded HLS resolution. 1280x720 = clear surveillance quality.
|
| 42 |
+
# 854x480 if you need to scale to many cameras on a small box.
|
| 43 |
+
OUTPUT_WIDTH=1280
|
| 44 |
+
OUTPUT_HEIGHT=720
|
| 45 |
+
|
| 46 |
+
# ---- HLS encoder ----
|
| 47 |
+
# Match the upstream's native rate. Semarang livepantau is 25/1.
|
| 48 |
+
HLS_FPS=25
|
| 49 |
+
HLS_SEGMENT_SECONDS=2.0
|
| 50 |
+
HLS_PLAYLIST_SIZE=6
|
| 51 |
+
# CRF 20 = sharp surveillance, 23 = ffmpeg default, 18 = ~lossless.
|
| 52 |
+
HLS_CRF=22
|
| 53 |
+
HLS_PRESET=veryfast
|
| 54 |
+
# libx264 (universal CPU) | videotoolbox (macOS hw) | nvenc (NVIDIA).
|
| 55 |
+
# Auto-fallback to libx264 if the requested encoder isn't in this
|
| 56 |
+
# ffmpeg build.
|
| 57 |
+
HLS_ENCODER=libx264
|
| 58 |
+
HLS_OUTPUT_DIR=/tmp/cakra-hls
|
| 59 |
+
|
| 60 |
+
# ---- WebSocket push cadence ----
|
| 61 |
+
METRICS_WS_INTERVAL=0.1
|
| 62 |
+
|
| 63 |
+
# ---- Geo projection (per-detection lat/lng for map overlay) ----
|
| 64 |
+
# cctv_streams only carries lat/lng. Defaults below are applied to
|
| 65 |
+
# every camera; extend the catalog table to override per-camera.
|
| 66 |
+
GEO_DEFAULT_HEADING_DEG=0
|
| 67 |
+
GEO_FOV_DEG=70
|
| 68 |
+
GEO_V_FOV_DEG=40
|
| 69 |
+
GEO_MAX_DISTANCE_M=80
|
| 70 |
+
GEO_CAMERA_HEIGHT_M=4
|
| 71 |
+
GEO_CAMERA_TILT_DEG=15
|
|
@@ -103,10 +103,18 @@ class CameraWorker:
|
|
| 103 |
self._target_size = (settings.output_width, settings.output_height)
|
| 104 |
|
| 105 |
# ---- ring buffer (capture → pacer) -------------------------
|
| 106 |
-
#
|
| 107 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
self._ring: deque[tuple[np.ndarray, float]] = deque(
|
| 109 |
-
maxlen=max(
|
| 110 |
)
|
| 111 |
self._ring_lock = threading.Lock()
|
| 112 |
self._last_paced: Optional[tuple[np.ndarray, float]] = None
|
|
@@ -126,6 +134,11 @@ class CameraWorker:
|
|
| 126 |
self.reader = StreamReader(
|
| 127 |
camera_id, url, settings.reconnect_delay,
|
| 128 |
on_frame=self._on_source_frame,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
)
|
| 130 |
self._infer_thread: Optional[threading.Thread] = None
|
| 131 |
self._pacer_thread: Optional[threading.Thread] = None
|
|
@@ -195,32 +208,57 @@ class CameraWorker:
|
|
| 195 |
|
| 196 |
# ---------- capture (reader thread) ----------
|
| 197 |
def _on_source_frame(self, frame: np.ndarray, capture_ts: float) -> None:
|
| 198 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
tw, th = self._target_size
|
| 200 |
if frame.shape[1] != tw or frame.shape[0] != th:
|
| 201 |
-
sized = cv2.resize(frame, (tw, th))
|
| 202 |
else:
|
|
|
|
|
|
|
| 203 |
sized = frame.copy()
|
| 204 |
with self._ring_lock:
|
| 205 |
self._ring.append((sized, capture_ts))
|
| 206 |
|
| 207 |
# ---------- pace + annotate + encode (own thread) -----------------
|
| 208 |
def _run_pacer(self) -> None:
|
| 209 |
-
"""Drive the encoder at
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
self.camera_id, settings.hls_fps)
|
| 215 |
tw, th = self._target_size
|
| 216 |
period = 1.0 / max(1, settings.hls_fps)
|
| 217 |
stale_after = max(0.5, float(settings.stale_frame_seconds))
|
| 218 |
-
|
| 219 |
-
#
|
| 220 |
-
#
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
while self._running:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
tick_start = time.monotonic()
|
| 225 |
|
| 226 |
# 1) Pull the oldest ring frame, or repeat the last one if
|
|
@@ -295,18 +333,14 @@ class CameraWorker:
|
|
| 295 |
)
|
| 296 |
self._render_last_ts = now_wall
|
| 297 |
|
| 298 |
-
#
|
| 299 |
-
#
|
| 300 |
-
#
|
| 301 |
-
#
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
elif slack < -max_catchup:
|
| 307 |
-
# Persistent slow path; no point in adding cumulative
|
| 308 |
-
# debt. Yield briefly so other threads can run.
|
| 309 |
-
time.sleep(0.001)
|
| 310 |
|
| 311 |
log.info("[%s] pacer thread stopped", self.camera_id)
|
| 312 |
|
|
|
|
| 103 |
self._target_size = (settings.output_width, settings.output_height)
|
| 104 |
|
| 105 |
# ---- ring buffer (capture → pacer) -------------------------
|
| 106 |
+
# The upstream HLS source dumps a full segment (~2s = ~50 frames
|
| 107 |
+
# at 25 fps) into ffmpeg in a burst, then idles until the next
|
| 108 |
+
# segment lands. A ring sized at one-second-of-frames would drop
|
| 109 |
+
# half of every burst → encoder gets non-temporally-consistent
|
| 110 |
+
# content → viewer sees "smooth → freeze → burst" cycle. Sizing
|
| 111 |
+
# for ~4 seconds covers a 1-segment burst plus a 1-segment late
|
| 112 |
+
# catch-up without dropping. Frames here are stored at OUTPUT
|
| 113 |
+
# resolution (resize is done by the capture thread) so the
|
| 114 |
+
# memory cost stays ~270 MB per camera at 720p, not 600 MB at
|
| 115 |
+
# 1080p.
|
| 116 |
self._ring: deque[tuple[np.ndarray, float]] = deque(
|
| 117 |
+
maxlen=max(16, settings.hls_fps * 4)
|
| 118 |
)
|
| 119 |
self._ring_lock = threading.Lock()
|
| 120 |
self._last_paced: Optional[tuple[np.ndarray, float]] = None
|
|
|
|
| 134 |
self.reader = StreamReader(
|
| 135 |
camera_id, url, settings.reconnect_delay,
|
| 136 |
on_frame=self._on_source_frame,
|
| 137 |
+
# Pace cap.read() at the encoder's target rate so a 50-frame
|
| 138 |
+
# HLS segment burst doesn't drain ffmpeg's demuxer in one
|
| 139 |
+
# tight read loop. With reader and pacer at the same fps,
|
| 140 |
+
# the ring stays tiny and no source frames are dropped.
|
| 141 |
+
read_pace_fps=float(settings.hls_fps),
|
| 142 |
)
|
| 143 |
self._infer_thread: Optional[threading.Thread] = None
|
| 144 |
self._pacer_thread: Optional[threading.Thread] = None
|
|
|
|
| 208 |
|
| 209 |
# ---------- capture (reader thread) ----------
|
| 210 |
def _on_source_frame(self, frame: np.ndarray, capture_ts: float) -> None:
|
| 211 |
+
"""Resize to output, tag with capture timestamp, push to ring.
|
| 212 |
+
|
| 213 |
+
Resize is done here so ring entries occupy only ~2.7 MB each at
|
| 214 |
+
720p (vs ~6 MB at 1080p source). With ring=4 × fps that brings
|
| 215 |
+
per-camera peak memory from ~600 MB to ~270 MB. Resize cost
|
| 216 |
+
(~3 ms at 1280×720 INTER_LINEAR) is well below the source burst
|
| 217 |
+
cadence, so the decoder doesn't stall."""
|
| 218 |
tw, th = self._target_size
|
| 219 |
if frame.shape[1] != tw or frame.shape[0] != th:
|
| 220 |
+
sized = cv2.resize(frame, (tw, th), interpolation=cv2.INTER_LINEAR)
|
| 221 |
else:
|
| 222 |
+
# cv2.VideoCapture reuses an internal buffer — copy so the
|
| 223 |
+
# ring entry isn't mutated under us by the next decode.
|
| 224 |
sized = frame.copy()
|
| 225 |
with self._ring_lock:
|
| 226 |
self._ring.append((sized, capture_ts))
|
| 227 |
|
| 228 |
# ---------- pace + annotate + encode (own thread) -----------------
|
| 229 |
def _run_pacer(self) -> None:
|
| 230 |
+
"""Drive the encoder at exactly HLS_FPS using a drift-free
|
| 231 |
+
absolute scheduler with a sub-millisecond busy-wait tail.
|
| 232 |
+
|
| 233 |
+
``time.sleep()`` overshoots by ~3-5 ms on macOS because the
|
| 234 |
+
kernel timer tick is coarse, which silently drifts a naive
|
| 235 |
+
"sleep period each iter" pacer to ~22 fps even when work is
|
| 236 |
+
only 4 ms. We anchor every tick at ``start + N*period`` so
|
| 237 |
+
sleep overshoot is automatically compensated, and busy-wait
|
| 238 |
+
the last ~2 ms for tick-boundary precision."""
|
| 239 |
+
log.info("[%s] pacer thread starting (target %d fps)",
|
| 240 |
self.camera_id, settings.hls_fps)
|
| 241 |
tw, th = self._target_size
|
| 242 |
period = 1.0 / max(1, settings.hls_fps)
|
| 243 |
stale_after = max(0.5, float(settings.stale_frame_seconds))
|
| 244 |
+
busy_window = 0.002 # last 2 ms is busy-wait
|
| 245 |
+
# If we fall this far behind (sustained heavy work, suspend/
|
| 246 |
+
# resume, etc.) we snap the baseline forward instead of
|
| 247 |
+
# catching up with a burst that would inflate output fps.
|
| 248 |
+
max_drift = max(2.0, 5 * period)
|
| 249 |
+
|
| 250 |
+
sched_start = time.monotonic()
|
| 251 |
+
sched_tick = 0
|
| 252 |
|
| 253 |
while self._running:
|
| 254 |
+
# Drift-free wait for absolute tick boundary.
|
| 255 |
+
target = sched_start + sched_tick * period
|
| 256 |
+
wait = target - time.monotonic()
|
| 257 |
+
if wait > busy_window:
|
| 258 |
+
time.sleep(wait - busy_window)
|
| 259 |
+
while time.monotonic() < target:
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
tick_start = time.monotonic()
|
| 263 |
|
| 264 |
# 1) Pull the oldest ring frame, or repeat the last one if
|
|
|
|
| 333 |
)
|
| 334 |
self._render_last_ts = now_wall
|
| 335 |
|
| 336 |
+
# Advance to the next scheduled tick. If we drift past
|
| 337 |
+
# ``max_drift`` (suspended laptop, sustained heavy work),
|
| 338 |
+
# snap the baseline forward instead of bursting to catch
|
| 339 |
+
# up — better to drop a few frames than spike encoder fps.
|
| 340 |
+
sched_tick += 1
|
| 341 |
+
if time.monotonic() - (sched_start + sched_tick * period) > max_drift:
|
| 342 |
+
sched_start = time.monotonic()
|
| 343 |
+
sched_tick = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
log.info("[%s] pacer thread stopped", self.camera_id)
|
| 346 |
|
|
@@ -31,12 +31,18 @@ class StreamReader(threading.Thread):
|
|
| 31 |
url: str,
|
| 32 |
reconnect_delay: float = 5.0,
|
| 33 |
on_frame: Optional[FrameCallback] = None,
|
|
|
|
| 34 |
):
|
| 35 |
super().__init__(daemon=True, name=f"reader-{camera_id}")
|
| 36 |
self.camera_id = camera_id
|
| 37 |
self.url = url
|
| 38 |
self.reconnect_delay = reconnect_delay
|
| 39 |
self._on_frame = on_frame
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
self._cap: Optional[cv2.VideoCapture] = None
|
| 42 |
self._frame: Optional[np.ndarray] = None
|
|
@@ -85,6 +91,18 @@ class StreamReader(threading.Thread):
|
|
| 85 |
def run(self) -> None:
|
| 86 |
win_start = time.time()
|
| 87 |
win_count = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
while self._running:
|
| 89 |
try:
|
| 90 |
if self._cap is None or not self._cap.isOpened():
|
|
@@ -102,6 +120,14 @@ class StreamReader(threading.Thread):
|
|
| 102 |
self.last_error = None
|
| 103 |
log.info("[%s] connected", self.camera_id)
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
ok, frame = self._cap.read()
|
| 106 |
if not ok or frame is None:
|
| 107 |
self.connected = False
|
|
|
|
| 31 |
url: str,
|
| 32 |
reconnect_delay: float = 5.0,
|
| 33 |
on_frame: Optional[FrameCallback] = None,
|
| 34 |
+
read_pace_fps: float = 0.0,
|
| 35 |
):
|
| 36 |
super().__init__(daemon=True, name=f"reader-{camera_id}")
|
| 37 |
self.camera_id = camera_id
|
| 38 |
self.url = url
|
| 39 |
self.reconnect_delay = reconnect_delay
|
| 40 |
self._on_frame = on_frame
|
| 41 |
+
# Cap cap.read() rate at this many fps. ``0`` (default) means
|
| 42 |
+
# read as fast as ffmpeg will deliver. Set to the source's
|
| 43 |
+
# native fps to prevent burst-dump of an entire HLS segment in
|
| 44 |
+
# one tight read loop.
|
| 45 |
+
self._read_pace_fps = read_pace_fps
|
| 46 |
|
| 47 |
self._cap: Optional[cv2.VideoCapture] = None
|
| 48 |
self._frame: Optional[np.ndarray] = None
|
|
|
|
| 91 |
def run(self) -> None:
|
| 92 |
win_start = time.time()
|
| 93 |
win_count = 0
|
| 94 |
+
# Pace cap.read() at a slight margin above the encoder's target
|
| 95 |
+
# rate. cv2 / ffmpeg's HLS demuxer otherwise dumps each segment
|
| 96 |
+
# (≈50 frames) into us in ~100 ms, overflowing the downstream
|
| 97 |
+
# ring buffer and producing burst-then-freeze motion. By
|
| 98 |
+
# spacing reads at ~1/(fps+2) we let TCP/ffmpeg backpressure
|
| 99 |
+
# smooth the source delivery — the ring stays small, no
|
| 100 |
+
# frames are dropped, and motion plays at true 1× speed.
|
| 101 |
+
try:
|
| 102 |
+
paced_period = 1.0 / max(1, int(self._read_pace_fps))
|
| 103 |
+
except Exception:
|
| 104 |
+
paced_period = 0.0
|
| 105 |
+
last_read_ts = 0.0
|
| 106 |
while self._running:
|
| 107 |
try:
|
| 108 |
if self._cap is None or not self._cap.isOpened():
|
|
|
|
| 120 |
self.last_error = None
|
| 121 |
log.info("[%s] connected", self.camera_id)
|
| 122 |
|
| 123 |
+
# Pace the read so we don't drain ffmpeg's HLS demuxer
|
| 124 |
+
# faster than wall-clock playback.
|
| 125 |
+
if paced_period > 0 and last_read_ts > 0:
|
| 126 |
+
elapsed = time.monotonic() - last_read_ts
|
| 127 |
+
if elapsed < paced_period:
|
| 128 |
+
time.sleep(paced_period - elapsed)
|
| 129 |
+
last_read_ts = time.monotonic()
|
| 130 |
+
|
| 131 |
ok, frame = self._cap.read()
|
| 132 |
if not ok or frame is None:
|
| 133 |
self.connected = False
|
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8" />
|
| 5 |
+
<title>Cakra CCTV — pure embed</title>
|
| 6 |
+
<style>
|
| 7 |
+
html, body { margin:0; height:100%; background:#000;
|
| 8 |
+
font: 12px ui-monospace, Menlo, Consolas, monospace; color:#9af; }
|
| 9 |
+
#wrap { position:relative; height:100%; display:flex; align-items:center;
|
| 10 |
+
justify-content:center; }
|
| 11 |
+
video { max-width:100%; max-height:100%; display:block; background:#000; }
|
| 12 |
+
#hud { position:absolute; top:8px; right:8px; padding:6px 10px;
|
| 13 |
+
background:rgba(0,0,0,.6); border-radius:4px; }
|
| 14 |
+
#hud b { color:#fff; }
|
| 15 |
+
</style>
|
| 16 |
+
</head>
|
| 17 |
+
<body>
|
| 18 |
+
<div id="wrap">
|
| 19 |
+
<video id="v" autoplay muted playsinline></video>
|
| 20 |
+
<div id="hud">
|
| 21 |
+
<div>state: <b id="s">init</b></div>
|
| 22 |
+
<div>buf ahead: <b id="b">—</b>s</div>
|
| 23 |
+
<div>currentTime: <b id="t">—</b>s</div>
|
| 24 |
+
<div>w x h: <b id="r">—</b></div>
|
| 25 |
+
</div>
|
| 26 |
+
</div>
|
| 27 |
+
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.13/dist/hls.min.js"></script>
|
| 28 |
+
<script>
|
| 29 |
+
const qs = new URLSearchParams(location.search);
|
| 30 |
+
const base = qs.get("base") || "http://localhost:8000";
|
| 31 |
+
const id = qs.get("camera_id");
|
| 32 |
+
const v = document.getElementById("v");
|
| 33 |
+
const $ = (i) => document.getElementById(i);
|
| 34 |
+
|
| 35 |
+
if (!id) { $("s").textContent = "missing ?camera_id="; }
|
| 36 |
+
else {
|
| 37 |
+
fetch(`${base}/api/v1/cameras/${id}/connect`, { method:"POST" })
|
| 38 |
+
.then(r => r.ok ? r.json() : Promise.reject(r.status))
|
| 39 |
+
.then(() => {
|
| 40 |
+
const url = `${base}/api/v1/cameras/${id}/hls/playlist.m3u8`;
|
| 41 |
+
if (Hls.isSupported()) {
|
| 42 |
+
const hls = new Hls({
|
| 43 |
+
enableWorker: true,
|
| 44 |
+
lowLatencyMode: false,
|
| 45 |
+
liveSyncDurationCount: 999,
|
| 46 |
+
liveMaxLatencyDurationCount: 1000,
|
| 47 |
+
maxBufferLength: 30,
|
| 48 |
+
maxMaxBufferLength: 60,
|
| 49 |
+
backBufferLength: 0,
|
| 50 |
+
liveDurationInfinity: true,
|
| 51 |
+
manifestLoadingMaxRetry: 8, manifestLoadingRetryDelay: 500,
|
| 52 |
+
levelLoadingMaxRetry: 8, levelLoadingRetryDelay: 500,
|
| 53 |
+
fragLoadingMaxRetry: 4, fragLoadingRetryDelay: 500,
|
| 54 |
+
});
|
| 55 |
+
hls.loadSource(url); hls.attachMedia(v);
|
| 56 |
+
let anchored = false;
|
| 57 |
+
hls.on(Hls.Events.LEVEL_LOADED, (_e,d) => {
|
| 58 |
+
if (anchored) return;
|
| 59 |
+
const frags = d?.details?.fragments;
|
| 60 |
+
if (!frags?.length) return;
|
| 61 |
+
anchored = true;
|
| 62 |
+
v.currentTime = frags[0].start;
|
| 63 |
+
// Wait for 5s buffer then play.
|
| 64 |
+
$("s").textContent = "buffering";
|
| 65 |
+
const tick = () => {
|
| 66 |
+
const ahead = v.buffered.length
|
| 67 |
+
? v.buffered.end(v.buffered.length-1) - v.currentTime : 0;
|
| 68 |
+
if (ahead >= 5) { v.play(); }
|
| 69 |
+
else { setTimeout(tick, 200); }
|
| 70 |
+
};
|
| 71 |
+
tick();
|
| 72 |
+
});
|
| 73 |
+
} else if (v.canPlayType("application/vnd.apple.mpegurl")) {
|
| 74 |
+
v.src = url; v.play();
|
| 75 |
+
} else { $("s").textContent = "browser no HLS"; }
|
| 76 |
+
})
|
| 77 |
+
.catch(e => { $("s").textContent = "connect failed: " + e; });
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
v.addEventListener("playing", () => $("s").textContent = "playing");
|
| 81 |
+
v.addEventListener("waiting", () => $("s").textContent = "buffering");
|
| 82 |
+
v.addEventListener("stalled", () => $("s").textContent = "stalled");
|
| 83 |
+
v.addEventListener("loadedmetadata", () => {
|
| 84 |
+
$("r").textContent = v.videoWidth + " x " + v.videoHeight;
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
// HUD telemetry: track buffer + currentTime over time so we can spot stalls.
|
| 88 |
+
setInterval(() => {
|
| 89 |
+
const ahead = v.buffered.length
|
| 90 |
+
? v.buffered.end(v.buffered.length-1) - v.currentTime : 0;
|
| 91 |
+
$("b").textContent = ahead.toFixed(2);
|
| 92 |
+
$("t").textContent = v.currentTime.toFixed(2);
|
| 93 |
+
}, 200);
|
| 94 |
+
|
| 95 |
+
// Expose a sample-collector for automated probing.
|
| 96 |
+
window.__samples = [];
|
| 97 |
+
setInterval(() => {
|
| 98 |
+
const ahead = v.buffered.length
|
| 99 |
+
? v.buffered.end(v.buffered.length-1) - v.currentTime : 0;
|
| 100 |
+
window.__samples.push({
|
| 101 |
+
t: performance.now(),
|
| 102 |
+
ahead: +ahead.toFixed(3),
|
| 103 |
+
ct: +v.currentTime.toFixed(3),
|
| 104 |
+
paused: v.paused,
|
| 105 |
+
state: $("s").textContent,
|
| 106 |
+
});
|
| 107 |
+
if (window.__samples.length > 600) window.__samples.shift();
|
| 108 |
+
}, 100);
|
| 109 |
+
</script>
|
| 110 |
+
</body>
|
| 111 |
+
</html>
|