diff --git a/docs/docs/troubleshooting/cpu.md b/docs/docs/troubleshooting/cpu.md index 50a38a61a7..241dd0ebe5 100644 --- a/docs/docs/troubleshooting/cpu.md +++ b/docs/docs/troubleshooting/cpu.md @@ -112,3 +112,20 @@ This metric scales with how many detections per second Frigate runs and how expe - **Tune stationary object behavior.** Objects that never settle into a stationary state are re-detected continuously. Raising `detect -> stationary -> interval` reduces how often detection runs on objects that are already parked. See [stationary objects](../configuration/stationary_objects). Adding [more detector instances](#multiple-detector-instances) spreads this work across more CPU cores, but does not reduce the total CPU used. + +## Tracked object processing could not keep up {#tracked-object-processing-behind} + +After detection, Frigate hands each camera's frames to a single tracked object processor in the main Frigate process. It handles zones, loitering, snapshots, and event and MQTT updates for all cameras. When the processor falls more than about a second behind, Frigate drops new frames instead of waiting for it. Frigate raises this notice in the UI's Notices pane when it drops at least 5% of a camera's frames for more than a minute. + +This is different from "Detection could not keep up", which means the [object detector](#2-detector-selection-and-configuration) is too slow. Dropped frames mean the system itself is short on CPU or stalling. + +The notice stays until you acknowledge or mute it, and is raised again only after drops stop and later start again. `/api/stats` reports each camera's current `dropped_pct`. + +Detection, tracking, and recording continue while frames are dropped. Zone [inertia](../configuration/zones.md#zone-inertia) and [loitering time](../configuration/zones.md#zone-loitering) count fewer frames, so a fast object can miss a small zone and loitering triggers late. Snapshots are picked from fewer frames, and events, MQTT messages, and notifications are delayed until the processor catches up. + +To reduce dropped frames: + +- Check CPU use and any CPU limits on the container or VM (`cpus`, `cpuset`, or the cores assigned to a VM or LXC container). A rising `nr_throttled` in `/sys/fs/cgroup/cpu.stat` means a limit is throttling Frigate. +- Use a detect fps of 5, and no more than 10. See [choosing a detect frame rate](../frigate/camera_setup.md#choosing-a-detect-frame-rate). +- Lower the detect resolution. The snapshot saved when an object ends is encoded from the full detect frame. +- Keep `/media/frigate` on local storage, since the processor writes snapshots and thumbnails itself. diff --git a/frigate/camera/__init__.py b/frigate/camera/__init__.py index a060f72c25..85dcf96e10 100644 --- a/frigate/camera/__init__.py +++ b/frigate/camera/__init__.py @@ -11,6 +11,7 @@ class CameraMetrics: detection_frame: ValueProxy[float] process_fps: ValueProxy[float] skipped_fps: ValueProxy[float] + dropped_fps: ValueProxy[float] read_start: ValueProxy[float] audio_rms: ValueProxy[float] audio_dBFS: ValueProxy[float] @@ -29,6 +30,7 @@ class CameraMetrics: self.detection_frame = manager.Value("d", 0) self.process_fps = manager.Value("d", 0) self.skipped_fps = manager.Value("d", 0) + self.dropped_fps = manager.Value("d", 0) self.read_start = manager.Value("d", 0) self.audio_rms = manager.Value("d", 0) self.audio_dBFS = manager.Value("d", 0) diff --git a/frigate/notices/types.py b/frigate/notices/types.py index c410c8f34f..2179d1bb59 100644 --- a/frigate/notices/types.py +++ b/frigate/notices/types.py @@ -73,14 +73,11 @@ _KINDS = ( "detect_high_cpu", NoticeSeverity.warning, "camera", link="/system#cameras" ), NoticeKind("shm_too_low", NoticeSeverity.warning, "system", link="/system#storage"), - # every camera process raises it when the shared queue backs up, so repeats - # wait for the next flush instead of writing once per camera NoticeKind( "object_processing_behind", NoticeSeverity.warning, "system", link="/system#cameras", - batch_repeats=True, ), # one row per user per burst; the login log lines carry the address NoticeKind( diff --git a/frigate/stats/emitter.py b/frigate/stats/emitter.py index b140ab0f6f..c38e16041e 100644 --- a/frigate/stats/emitter.py +++ b/frigate/stats/emitter.py @@ -10,7 +10,7 @@ from typing import Any from frigate.comms.inter_process import InterProcessRequestor from frigate.config import FrigateConfig -from frigate.const import FREQUENCY_STATS_POINTS +from frigate.const import FREQUENCY_STATS_POINTS, REPLAY_CAMERA_PREFIX from frigate.notices import flush_notices, raise_notice, resolve_kind, resolve_notice from frigate.stats.hardware import HardwareStats from frigate.stats.prometheus import update_metrics @@ -29,6 +29,10 @@ VERSION_REFRESH_S = 24 * 60 * 60 # a camera skipping at least this percent of its frames is falling behind SKIPPED_DETECTIONS_PCT = 5 +# a camera dropping at least this percent of its frames because the tracked +# object processor is behind +DROPPED_FRAMES_PCT = 5 + # lifetime CPU averages at or above these are high; they match # CameraFfmpegThreshold.error and CameraDetectThreshold.error in the UI FFMPEG_HIGH_CPU_PCT = 20 @@ -102,6 +106,7 @@ class StatsEmitter(threading.Thread): self.hardware_stats = HardwareStats(config) self.stats_history: list[dict[str, Any]] = [] self.skipped_detections = EpisodeTracker(SKIPPED_DETECTIONS_PCT) + self.dropped_frames = EpisodeTracker(DROPPED_FRAMES_PCT) self.ffmpeg_cpu = EpisodeTracker(FFMPEG_HIGH_CPU_PCT) self.detect_cpu = EpisodeTracker(DETECT_HIGH_CPU_PCT) @@ -269,6 +274,17 @@ class StatsEmitter(threading.Thread): params={"pct": skipped[camera]}, ) + # all cameras share one processor, so the episode spans every camera. + # a replay camera's own drops are ignored since it can outpace real time + dropped = [ + camera_stats["dropped_pct"] + for camera, camera_stats in cameras.items() + if not camera.startswith(REPLAY_CAMERA_PREFIX) + ] + + if self.dropped_frames.update({"all": max(dropped, default=0.0)}, now): + raise_notice("object_processing_behind") + # high ffmpeg and detect CPU for tracker, kind, pid_key in ( (self.ffmpeg_cpu, "ffmpeg_high_cpu", "ffmpeg_pid"), diff --git a/frigate/stats/util.py b/frigate/stats/util.py index d610e2b25d..61bbd1565a 100644 --- a/frigate/stats/util.py +++ b/frigate/stats/util.py @@ -232,16 +232,16 @@ def embeddings_stats( return stats -def skipped_percent(skipped_fps: float, camera_fps: float, enabled: bool) -> float: - """Percent of a camera's frames dropped before detection. +def frame_percent(fps: float, camera_fps: float, enabled: bool) -> float: + """Share of a camera's frames, in percent, that a rate such as skipped_fps represents. - camera_fps counts the dropped frames too. A disabled camera keeps its last - readings, so it reports zero. + camera_fps counts every frame read from the camera. A disabled camera keeps + its last readings, so it reports zero. """ if not enabled or camera_fps <= 0: return 0.0 - return round(skipped_fps / camera_fps * 100, 1) + return round(fps / camera_fps * 100, 1) def get_go2rtc_pid(cpu_usages: dict[str, dict[str, Any]]) -> int | None: @@ -262,7 +262,8 @@ def stats_snapshot( camera_metrics = stats_tracking["camera_metrics"] stats: dict[str, Any] = {} - total_camera_fps = total_process_fps = total_skipped_fps = total_detection_fps = 0 + total_camera_fps = total_process_fps = total_skipped_fps = total_dropped_fps = 0 + total_detection_fps = 0 stats["cameras"] = {} for name, camera_stats in list(camera_metrics.items()): @@ -273,6 +274,7 @@ def stats_snapshot( total_camera_fps += camera_stats.camera_fps.value total_process_fps += camera_stats.process_fps.value total_skipped_fps += camera_stats.skipped_fps.value + total_dropped_fps += camera_stats.dropped_fps.value total_detection_fps += camera_stats.detection_fps.value pid = camera_stats.process_pid.value if camera_stats.process_pid.value else None ffmpeg_pid = camera_stats.ffmpeg_pid.value if camera_stats.ffmpeg_pid else None @@ -311,11 +313,17 @@ def stats_snapshot( "camera_fps": round(camera_stats.camera_fps.value, 2), "process_fps": round(camera_stats.process_fps.value, 2), "skipped_fps": round(camera_stats.skipped_fps.value, 2), - "skipped_pct": skipped_percent( + "skipped_pct": frame_percent( camera_stats.skipped_fps.value, current_fps, config.cameras[name].enabled, ), + "dropped_fps": round(camera_stats.dropped_fps.value, 2), + "dropped_pct": frame_percent( + camera_stats.dropped_fps.value, + current_fps, + config.cameras[name].enabled, + ), "detection_fps": round(camera_stats.detection_fps.value, 2), "detection_enabled": camera_config.detect.enabled, "pid": pid, @@ -330,6 +338,7 @@ def stats_snapshot( stats["camera_fps"] = round(total_camera_fps, 2) stats["process_fps"] = round(total_process_fps, 2) stats["skipped_fps"] = round(total_skipped_fps, 2) + stats["dropped_fps"] = round(total_dropped_fps, 2) stats["detection_fps"] = round(total_detection_fps, 2) stats["embeddings"] = embeddings_stats( diff --git a/frigate/test/test_dropped_frames_notice.py b/frigate/test/test_dropped_frames_notice.py deleted file mode 100644 index cd2d706c66..0000000000 --- a/frigate/test/test_dropped_frames_notice.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Tests for the notice raised when object processing drops camera frames.""" - -import threading -import unittest -from unittest.mock import patch - -from frigate.const import REPLAY_CAMERA_PREFIX -from frigate.notices.types import NOTICE_KINDS -from frigate.video.detect import ( - DROPPED_FRAMES_NOTICE_COUNT, - DROPPED_FRAMES_NOTICE_INTERVAL_S, - DROPPED_FRAMES_WINDOW_S, - DroppedFrameTracker, -) - - -class TestDroppedFrameTracker(unittest.TestCase): - def setUp(self): - raise_patch = patch("frigate.video.detect.raise_notice") - self.raise_notice = raise_patch.start() - self.addCleanup(raise_patch.stop) - - def _drop(self, tracker: DroppedFrameTracker, count: int, start: float) -> None: - for i in range(count): - tracker.dropped(start + i * 0.2) - - # the notice is sent on a background thread - if tracker._sender is not None: - tracker._sender.join(timeout=5) - - def test_kind_is_registered(self): - self.assertIn("object_processing_behind", NOTICE_KINDS) - - def test_a_few_drops_raise_nothing(self): - tracker = DroppedFrameTracker("front_door") - - self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT - 1, 0.0) - - self.raise_notice.assert_not_called() - - def test_enough_drops_raise_the_notice(self): - tracker = DroppedFrameTracker("front_door") - - self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT, 0.0) - - self.raise_notice.assert_called_once_with("object_processing_behind") - - def test_drops_outside_the_window_do_not_add_up(self): - tracker = DroppedFrameTracker("front_door") - - for i in range(DROPPED_FRAMES_NOTICE_COUNT): - tracker.dropped(i * (DROPPED_FRAMES_WINDOW_S + 1.0)) - - self.raise_notice.assert_not_called() - - def test_repeats_wait_for_the_interval(self): - tracker = DroppedFrameTracker("front_door") - - self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT, 0.0) - self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT * 2, 5.0) - self.assertEqual(self.raise_notice.call_count, 1) - - self._drop( - tracker, DROPPED_FRAMES_NOTICE_COUNT, DROPPED_FRAMES_NOTICE_INTERVAL_S - ) - self.assertEqual(self.raise_notice.call_count, 2) - - def test_a_pending_send_does_not_block_or_start_another(self): - sending = threading.Event() - release = threading.Event() - - def wait_for_reply(*_) -> None: - sending.set() - release.wait(5) - - self.raise_notice.side_effect = wait_for_reply - tracker = DroppedFrameTracker("front_door") - - # the first notice gets no reply while the second burst arrives - for i in range(DROPPED_FRAMES_NOTICE_COUNT): - tracker.dropped(i * 0.2) - - self.assertTrue(sending.wait(5)) - - for i in range(DROPPED_FRAMES_NOTICE_COUNT): - tracker.dropped(DROPPED_FRAMES_NOTICE_INTERVAL_S + i * 0.2) - - self.assertEqual(self.raise_notice.call_count, 1) - - release.set() - assert tracker._sender is not None - tracker._sender.join(timeout=5) - - def test_replay_camera_never_raises(self): - tracker = DroppedFrameTracker(f"{REPLAY_CAMERA_PREFIX}front_door") - - self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT * 2, 0.0) - - self.raise_notice.assert_not_called() - - -if __name__ == "__main__": - unittest.main() diff --git a/frigate/test/test_skipped_detections.py b/frigate/test/test_skipped_detections.py index 10637b56a2..9bab19e929 100644 --- a/frigate/test/test_skipped_detections.py +++ b/frigate/test/test_skipped_detections.py @@ -1,26 +1,29 @@ -"""Tests for the per-camera episode notices: skipped detections and high CPU.""" +"""Tests for the episode notices: skipped detections, dropped frames, and high CPU.""" import unittest from unittest.mock import call, patch +from frigate.const import REPLAY_CAMERA_PREFIX +from frigate.notices.types import NOTICE_KINDS from frigate.stats import emitter from frigate.stats.emitter import ( + DROPPED_FRAMES_PCT, SKIPPED_DETECTIONS_PCT, EpisodeTracker, cpu_average, ) -from frigate.stats.util import skipped_percent +from frigate.stats.util import frame_percent -class TestSkippedPercent(unittest.TestCase): +class TestFramePercent(unittest.TestCase): def test_share_of_all_frames(self): - self.assertEqual(skipped_percent(0.5, 5.0, True), 10.0) + self.assertEqual(frame_percent(0.5, 5.0, True), 10.0) def test_offline_camera_reports_zero(self): - self.assertEqual(skipped_percent(2.0, 0.0, True), 0.0) + self.assertEqual(frame_percent(2.0, 0.0, True), 0.0) def test_disabled_camera_reports_zero(self): - self.assertEqual(skipped_percent(2.0, 5.0, False), 0.0) + self.assertEqual(frame_percent(2.0, 5.0, False), 0.0) class TestEpisodeTracker(unittest.TestCase): @@ -116,6 +119,7 @@ class TestEmitterNotices(unittest.TestCase): def _emitter(self) -> emitter.StatsEmitter: stats_emitter = emitter.StatsEmitter.__new__(emitter.StatsEmitter) stats_emitter.skipped_detections = EpisodeTracker(SKIPPED_DETECTIONS_PCT) + stats_emitter.dropped_frames = EpisodeTracker(DROPPED_FRAMES_PCT) stats_emitter.ffmpeg_cpu = EpisodeTracker(emitter.FFMPEG_HIGH_CPU_PCT) stats_emitter.detect_cpu = EpisodeTracker(emitter.DETECT_HIGH_CPU_PCT) stats_emitter._shm_checked = False @@ -123,13 +127,29 @@ class TestEmitterNotices(unittest.TestCase): return stats_emitter def _stats( - self, uptime: int, pct: float, ffmpeg_cpu: str = "5.0", detect_cpu: str = "5.0" + self, + uptime: int, + pct: float, + ffmpeg_cpu: str = "5.0", + detect_cpu: str = "5.0", + dropped: dict[str, float] | None = None, ) -> dict: + cameras = { + "front_door": { + "skipped_pct": pct, + "dropped_pct": 0.0, + "ffmpeg_pid": 10, + "pid": 11, + } + } + + for camera, dropped_pct in (dropped or {}).items(): + cameras.setdefault(camera, {"skipped_pct": 0.0}) + cameras[camera]["dropped_pct"] = dropped_pct + return { "service": {"uptime": uptime, "storage": {"/dev/shm": {}}}, - "cameras": { - "front_door": {"skipped_pct": pct, "ffmpeg_pid": 10, "pid": 11} - }, + "cameras": cameras, "cpu_usages": { "10": {"cpu_average": ffmpeg_cpu}, "11": {"cpu_average": detect_cpu}, @@ -191,6 +211,96 @@ class TestEmitterNotices(unittest.TestCase): self.raise_notice.assert_not_called() + def test_dropped_frames_raise_one_system_notice(self): + stats_emitter = self._emitter() + dropped = {"front_door": 12.0, "driveway": 8.0} + + for uptime, now in ((300, 0.0), (360, 60.0)): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped=dropped), now + ) + + self.raise_notice.assert_called_once_with("object_processing_behind") + + def test_staggered_cameras_raise_one_notice(self): + stats_emitter = self._emitter() + + for uptime, now, dropped in ( + (300, 0.0, {"front_door": 12.0}), + (330, 30.0, {"front_door": 12.0, "driveway": 8.0}), + (360, 60.0, {"front_door": 12.0, "driveway": 8.0}), + (390, 90.0, {"front_door": 12.0, "driveway": 8.0}), + ): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped=dropped), now + ) + + self.raise_notice.assert_called_once_with("object_processing_behind") + + def test_drops_passing_between_cameras_raise_the_notice(self): + stats_emitter = self._emitter() + + for uptime, now, dropped in ( + (300, 0.0, {"front_door": 12.0, "driveway": 0.0}), + (330, 30.0, {"front_door": 0.0, "driveway": 8.0}), + (360, 60.0, {"front_door": 0.0, "driveway": 8.0}), + ): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped=dropped), now + ) + + self.raise_notice.assert_called_once_with("object_processing_behind") + + def test_drops_return_after_recovery_raise_again(self): + stats_emitter = self._emitter() + + for uptime, now, pct in ( + (300, 0.0, 12.0), + (360, 60.0, 12.0), + (390, 90.0, 0.0), + (420, 120.0, 12.0), + (480, 180.0, 12.0), + ): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped={"front_door": pct}), now + ) + + self.assertEqual(self.raise_notice.call_count, 2) + + def test_dropped_frames_during_startup_raise_nothing(self): + stats_emitter = self._emitter() + + for uptime, now in ((30, 0.0), (90, 60.0)): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped={"front_door": 50.0}), now + ) + + self.raise_notice.assert_not_called() + + def test_brief_dropped_frames_raise_nothing(self): + stats_emitter = self._emitter() + + for uptime, now, pct in ((300, 0.0, 12.0), (330, 30.0, 0.0), (360, 60.0, 12.0)): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped={"front_door": pct}), now + ) + + self.raise_notice.assert_not_called() + + def test_replay_camera_dropped_frames_raise_nothing(self): + stats_emitter = self._emitter() + dropped = {f"{REPLAY_CAMERA_PREFIX}front_door": 50.0} + + for uptime, now in ((300, 0.0), (360, 60.0)): + stats_emitter._update_notices( + self._stats(uptime, 0.0, dropped=dropped), now + ) + + self.raise_notice.assert_not_called() + + def test_dropped_frames_kind_is_registered(self): + self.assertIn("object_processing_behind", NOTICE_KINDS) + def test_every_tick_flushes_held_repeats(self): self._emitter()._update_notices(self._stats(30, 0.0), 0.0) diff --git a/frigate/video/detect.py b/frigate/video/detect.py index a9c17d33cb..05c1fb391b 100644 --- a/frigate/video/detect.py +++ b/frigate/video/detect.py @@ -3,9 +3,7 @@ import logging import queue import random -import threading import time -from collections import deque from datetime import UTC, datetime, timedelta from multiprocessing import Queue from multiprocessing.synchronize import Event as MpEvent @@ -23,12 +21,10 @@ from frigate.config.camera.updater import ( ) from frigate.const import ( PROCESS_PRIORITY_HIGH, - REPLAY_CAMERA_PREFIX, REQUEST_REGION_GRID, ) from frigate.motion import MotionDetector from frigate.motion.improved_motion import ImprovedMotionDetector -from frigate.notices import raise_notice from frigate.object_detection.base import RemoteObjectDetector from frigate.ptz.autotrack import ptz_moving_at_frame_time from frigate.track import ObjectTracker @@ -57,61 +53,6 @@ from frigate.util.time import get_tomorrow_at_time logger = logging.getLogger(__name__) -# this many frames dropped within the window because the shared detected frames -# queue was full means tracked object processing is falling behind -DROPPED_FRAMES_NOTICE_COUNT = 5 -DROPPED_FRAMES_WINDOW_S = 30 - -DROPPED_FRAMES_NOTICE_INTERVAL_S = 60 - - -class DroppedFrameTracker: - """Raises a notice when a camera drops frames because object processing is behind.""" - - def __init__(self, camera: str) -> None: - # a debug replay can feed frames faster than real time - self._enabled = not camera.startswith(REPLAY_CAMERA_PREFIX) - self._drops: deque[float] = deque() - self._last_notice: float | None = None - - # raising a notice waits on the main process, which answers every - # process's requests one at a time, so it runs off the frame loop - self._sender: threading.Thread | None = None - - def dropped(self, now: float) -> None: - """Record a dropped frame and raise the notice if enough were dropped. - - Args: - now: Monotonic time of the drop in seconds - """ - if not self._enabled: - return - - self._drops.append(now) - - while now - self._drops[0] > DROPPED_FRAMES_WINDOW_S: - self._drops.popleft() - - if ( - len(self._drops) < DROPPED_FRAMES_NOTICE_COUNT - or ( - self._last_notice is not None - and now - self._last_notice < DROPPED_FRAMES_NOTICE_INTERVAL_S - ) - or (self._sender is not None and self._sender.is_alive()) - ): - return - - self._drops.clear() - self._last_notice = now - self._sender = threading.Thread( - target=raise_notice, - args=("object_processing_behind",), - name="dropped_frames_notice", - daemon=True, - ) - self._sender.start() - class CameraTracker(FrigateProcess): def __init__( @@ -274,7 +215,9 @@ def process_frames( fps_tracker = EventsPerSecond() fps_tracker.start() - dropped_frames = DroppedFrameTracker(camera_config.name) + dropped_eps = EventsPerSecond() + dropped_eps.start() + dropped_fps = 0.0 startup_scan = True stationary_frame_counter = 0 @@ -298,6 +241,13 @@ def process_frames( while not stop_event.is_set(): updated_configs = config_subscriber.check_for_updates() + # each write is a round trip to the metrics manager, so skip unchanged rates + current_dropped_fps = dropped_eps.eps() + + if current_dropped_fps != dropped_fps: + dropped_fps = current_dropped_fps + camera_metrics.dropped_fps.value = dropped_fps + if "enabled" in updated_configs: prev_enabled = camera_enabled camera_enabled = camera_config.enabled @@ -613,14 +563,9 @@ def process_frames( f"debug/frames/{camera_config.name}-{'{:.6f}'.format(frame_time)}.jpg", bgr_frame, ) - # add to the queue if not full - if detected_objects_queue.full(): - dropped_frames.dropped(time.monotonic()) - continue - else: - fps_tracker.update() - camera_metrics.process_fps.value = fps_tracker.eps() - detected_objects_queue.put( + # a full queue means the tracked object processor is behind + try: + detected_objects_queue.put_nowait( ( camera_config.name, frame_name, @@ -630,7 +575,13 @@ def process_frames( regions, ) ) - camera_metrics.detection_fps.value = object_detector.fps.eps() + except queue.Full: + dropped_eps.update() + continue + + fps_tracker.update() + camera_metrics.process_fps.value = fps_tracker.eps() + camera_metrics.detection_fps.value = object_detector.fps.eps() motion_detector.stop() requestor.stop()