Compare commits

..
Author SHA1 Message Date
Josh Hawkins 8934b19484 fix birdseye runtime toggles, debug replay teardown, and stale export config
- Keep the Birdseye restream flag from startup so enabling restream at runtime no longer writes a buffer that was never created and crashes the output loop
- Clear a runtime-disabled camera's Birdseye state once instead of re-arming it and forcing a render on every frame
- Advance the Birdseye output time after an idle heartbeat so it sends at the configured rate
- Keep the published replay camera in each config swapped in by a settings save, and send its remove on stop, so a save during a replay no longer leaves the replay camera running after stop
- Read the live config in the debug replay auto-stop watchdog
- Skip publishing the replay camera when the session was stopped during startup
- Rename a camera named with the reserved _replay_ prefix in the camera wizard and clone dialog, since debug replay deletes that camera's data
- Update the export job manager's config on every call so exports follow config saves
2026-11-23 16:14:20 -06:00
14 changed files with 251 additions and 78 deletions
+3
View File
@@ -41,6 +41,9 @@ def swap_runtime_config(app: FastAPI, config: FrigateConfig) -> None:
"""
app.frigate_config = config
if app.replay_manager is not None:
app.replay_manager.update_config(config)
if app.config_holder is not None:
app.config_holder.set(config)
+1 -1
View File
@@ -88,7 +88,7 @@ def create_fastapi_app(
logger.info("FastAPI started")
asyncio.create_task(
debug_replay_auto_stop_watchdog(
replay_manager, frigate_config, config_publisher
replay_manager, lambda: app.frigate_config, config_publisher
)
)
yield
+31 -14
View File
@@ -11,10 +11,11 @@ import os
import shutil
import threading
import time
from collections.abc import Callable
from ruamel.yaml import YAML
from frigate.config import FrigateConfig
from frigate.config import CameraConfig, FrigateConfig
from frigate.config.camera.updater import (
CameraConfigUpdateEnum,
CameraConfigUpdatePublisher,
@@ -61,6 +62,7 @@ class DebugReplayManager:
self.start_ts: float | None = None
self.end_ts: float | None = None
self.session_started_at: float | None = None
self._published_camera: CameraConfig | None = None
self._job_state_publisher = JobStatePublisher()
@property
@@ -109,6 +111,13 @@ class DebugReplayManager:
self.start_ts = None
self.end_ts = None
self.session_started_at = None
self._published_camera = None
def update_config(self, config: FrigateConfig) -> None:
"""Carry the published replay camera into a newly swapped-in config."""
with self._lock:
if self._published_camera is not None and self.replay_camera_name:
config.cameras[self.replay_camera_name] = self._published_camera
def publish_camera(
self,
@@ -117,10 +126,11 @@ class DebugReplayManager:
clip_path: str,
frigate_config: FrigateConfig,
config_publisher: CameraConfigUpdatePublisher,
) -> None:
) -> bool:
"""Build the in-memory replay camera config and publish the add event.
Called by the job runner during the starting_camera phase.
Called by the job runner during the starting_camera phase. Returns
False without publishing if the session was stopped meanwhile.
"""
source_config = frigate_config.cameras[source_camera]
camera_dict = self._build_camera_config_dict(
@@ -140,12 +150,21 @@ class DebugReplayManager:
new_config = FrigateConfig.parse_object(config_data)
except Exception as e:
raise RuntimeError(f"Failed to validate replay camera config: {e}") from e
frigate_config.cameras[replay_name] = new_config.cameras[replay_name]
config_publisher.publish_update(
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
new_config.cameras[replay_name],
)
camera_config = new_config.cameras[replay_name]
with self._lock:
if self.replay_camera_name != replay_name:
return False
frigate_config.cameras[replay_name] = camera_config
self._published_camera = camera_config
config_publisher.publish_update(
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
camera_config,
)
return True
def stop(
self,
@@ -167,12 +186,10 @@ class DebugReplayManager:
replay_name = self.replay_camera_name
source_camera = self.source_camera
# Only publish remove if the camera was actually added to the live
# config (i.e. the runner reached the starting_camera phase).
if replay_name is not None and replay_name in frigate_config.cameras:
if replay_name is not None and self._published_camera is not None:
config_publisher.publish_update(
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
frigate_config.cameras[replay_name],
self._published_camera,
)
frigate_config.cameras.pop(replay_name, None)
@@ -362,7 +379,7 @@ def cleanup_replay_cameras() -> None:
async def debug_replay_auto_stop_watchdog(
manager: DebugReplayManager,
frigate_config: FrigateConfig,
get_config: Callable[[], FrigateConfig],
config_publisher: CameraConfigUpdatePublisher,
) -> None:
"""Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS.
@@ -384,7 +401,7 @@ async def debug_replay_auto_stop_watchdog(
replay_name = manager.replay_camera_name
await asyncio.to_thread(
manager.stop,
frigate_config=frigate_config,
frigate_config=get_config(),
config_publisher=config_publisher,
)
logger.info(
+5 -2
View File
@@ -376,13 +376,16 @@ class DebugReplayJobRunner(threading.Thread):
self._finalize_cancelled(clip_path)
return
self.replay_manager.publish_camera(
if not self.replay_manager.publish_camera(
source_camera=self.job.source_camera,
replay_name=replay_name,
clip_path=clip_path,
frigate_config=self.frigate_config,
config_publisher=self.config_publisher,
)
):
self._finalize_cancelled(clip_path)
return
self.replay_manager.mark_session_ready(clip_path)
self.job.status = JobStatusTypesEnum.success
+3
View File
@@ -487,6 +487,9 @@ def get_export_job_manager(config: FrigateConfig) -> ExportJobManager:
with _job_manager_lock:
if _job_manager is None:
_job_manager = ExportJobManager(config, _get_max_concurrent(config))
# callers pass the live config, which a save replaces
_job_manager.config = config
_job_manager.ensure_started()
return _job_manager
+14 -10
View File
@@ -789,16 +789,16 @@ class BirdsEyeFrameManager:
force_update = True
else:
return False, False
else:
# update the last active frame for the camera
camera_state["current_frame"] = frame.copy()
camera_state["current_frame_time"] = frame_time
modes = camera_config.birdseye.modes
# update the last active frame for the camera
camera_state["current_frame"] = frame.copy()
camera_state["current_frame_time"] = frame_time
modes = camera_config.birdseye.modes
if self.camera_threshold_active(modes, activity):
camera_state["last_active_frame"] = frame_time
if self.camera_threshold_active(modes, activity):
camera_state["last_active_frame"] = frame_time
camera_state["live_active"] = self.camera_live_active(modes, activity)
camera_state["live_active"] = self.camera_live_active(modes, activity)
# monotonic so a backward wall clock step can't freeze the output
now = time.monotonic()
@@ -865,7 +865,10 @@ class Birdseye:
(1.0 / self.idle_fps) if self.idle_fps > 0 else None
)
if config.birdseye.restream:
# restream changes need a restart, so the buffer exists only if it did at init
self.restream = config.birdseye.restream
if self.restream:
self.birdseye_buffer: Any = self.frame_manager.create(
"birdseye",
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
@@ -877,7 +880,7 @@ class Birdseye:
def __send_new_frame(self) -> None:
frame_bytes = self.birdseye_manager.frame.tobytes()
if self.config.birdseye.restream:
if self.restream:
self.birdseye_buffer[:] = frame_bytes
try:
@@ -954,6 +957,7 @@ class Birdseye:
>= self._idle_interval
):
self.__send_new_frame()
self.birdseye_manager.last_output_time = now
def stop(self) -> None:
self.review_subscriber.stop()
+69 -1
View File
@@ -2,7 +2,9 @@
import multiprocessing as mp
import unittest
from unittest.mock import Mock
from unittest.mock import Mock, patch
import numpy as np
from frigate.config import (
BirdseyeModeEnum,
@@ -607,6 +609,72 @@ class TestBirdseyeModePayload(unittest.TestCase):
assert birdseye_modes_from_mqtt_payload(payload) is None
class TestBirdseyeRuntimeToggles(unittest.TestCase):
"""Runtime config changes must not crash or overdrive Birdseye."""
def setUp(self):
config = {
"mqtt": {"enabled": False},
"birdseye": {"enabled": True, "modes": ["continuous"]},
"cameras": {
"front": {
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
}
},
}
self.config = FrigateConfig(**config)
self.manager = BirdsEyeFrameManager(self.config, mp.Event())
self.frame = np.zeros((1620, 1920), np.uint8)
self.activity = BirdseyeActivity(
has_object=True, has_motion=True, severity=None
)
def test_disabled_camera_forces_one_update_only(self):
self.manager.update("front", self.activity, 1000.0, self.frame)
self.config.cameras["front"].birdseye.enabled = False
changed, _ = self.manager.update("front", self.activity, 1000.2, self.frame)
assert changed
changed, _ = self.manager.update("front", self.activity, 1000.4, self.frame)
assert not changed
def test_enabling_restream_at_runtime_does_not_write_missing_buffer(self):
birdseye = Birdseye.__new__(Birdseye)
birdseye.restream = False
birdseye.config = self.config
birdseye.birdseye_manager = self.manager
birdseye.input = Mock()
self.config.birdseye.restream = True
birdseye._Birdseye__send_new_frame()
birdseye.input.put_nowait.assert_called_once()
def test_idle_heartbeat_waits_a_full_interval_between_sends(self):
birdseye = Birdseye.__new__(Birdseye)
birdseye.review_severity = {}
birdseye.birdseye_manager = Mock()
birdseye.birdseye_manager.update.return_value = (False, False)
birdseye.birdseye_manager.camera_layout = []
birdseye.birdseye_manager.last_output_time = 0.0
birdseye._idle_interval = 0.2
with (
patch.object(Birdseye, "_Birdseye__send_new_frame") as send,
patch("frigate.output.birdseye.time.monotonic", side_effect=[10.0, 10.1]),
):
birdseye.write_data("front", [], [], 1.0, Mock())
birdseye.write_data("front", [], [], 1.1, Mock())
assert send.call_count == 1
class TestBirdseyeReviewSeverity(unittest.TestCase):
"""Test that review updates drive the per-camera severity map."""
-38
View File
@@ -264,41 +264,3 @@ class TestCameraFileCleanup(unittest.TestCase):
]
self.assertEqual(remaining, other)
def test_delete_removes_recordings_and_keeps_colliding_dirs(self):
own = [
"recordings/2026-11-22/10/front/00.00.mp4",
"recordings/2026-11-22/10/front@sub/00.00.mp4",
"recordings/2026-11-23/03/front/10.00.mp4",
"clips/thumbs/front/a.webp",
"clips/previews/front/1.mp4",
"clips/lpr/front/a/1.jpg",
"clips/triggers/front/t.webp",
]
other = [
"recordings/2026-11-22/10/front_door/00.00.mp4",
"recordings/front/keep.mp4",
"clips/front/dataset/a.jpg",
"clips/thumbs/front_door/b.webp",
]
with tempfile.TemporaryDirectory() as root:
for name in own + other:
path = os.path.join(root, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
open(path, "w").close()
clips = os.path.join(root, "clips")
with patch.multiple(
camera_cleanup,
CLIPS_DIR=clips,
RECORD_DIR=os.path.join(root, "recordings"),
THUMB_DIR=os.path.join(clips, "thumbs"),
):
camera_cleanup.cleanup_camera_files("front")
remaining = [
n for n in own + other if os.path.exists(os.path.join(root, n))
]
self.assertEqual(remaining, other)
+1
View File
@@ -24,6 +24,7 @@ class TestSwapRuntimeConfig(unittest.TestCase):
self.assertIs(app.frigate_config, config)
app.genai_manager.update_config.assert_called_once_with(config)
app.replay_manager.update_config.assert_called_once_with(config)
app.profile_manager.update_config.assert_called_once_with(config)
self.assertIs(app.stats_emitter.config, config)
app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config)
+100
View File
@@ -101,6 +101,7 @@ class TestDebugReplayManagerStop(unittest.TestCase):
manager.mark_session_ready("/tmp/replay/_replay_front.mp4")
camera_config = MagicMock()
manager._published_camera = camera_config
frigate_config = MagicMock()
frigate_config.cameras = {"_replay_front": camera_config}
publisher = MagicMock()
@@ -169,6 +170,7 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
source_config = MagicMock()
new_camera_config = MagicMock()
@@ -246,5 +248,103 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
publisher.publish_update.assert_not_called()
class TestDebugReplayManagerLifecycle(unittest.TestCase):
def setUp(self) -> None:
patcher = patch("frigate.debug_replay.JobStatePublisher")
patcher.start()
self.addCleanup(patcher.stop)
def _publish(self, manager, frigate_config, publisher) -> bool:
from frigate.debug_replay import DebugReplayManager
parsed = MagicMock()
parsed.cameras = {"_replay_front": MagicMock(name="replay_camera")}
with (
patch.object(
DebugReplayManager,
"_build_camera_config_dict",
return_value={"enabled": True},
),
patch("frigate.debug_replay.find_config_file", return_value="/cfg.yml"),
patch("frigate.debug_replay.YAML") as yaml_cls,
patch(
"frigate.debug_replay.FrigateConfig.parse_object",
return_value=parsed,
),
patch("builtins.open", unittest.mock.mock_open(read_data="cameras:\n")),
):
yaml_cls.return_value.load.return_value = {"cameras": {}}
return manager.publish_camera(
source_camera="front",
replay_name="_replay_front",
clip_path="/tmp/clip.mp4",
frigate_config=frigate_config,
config_publisher=publisher,
)
def _config(self, name: str) -> MagicMock:
config = MagicMock(name=name)
config.cameras = {"front": MagicMock()}
return config
def _stop(self, manager, frigate_config, publisher) -> None:
with (
patch.object(manager, "_cleanup_db"),
patch.object(manager, "_cleanup_files"),
patch("frigate.debug_replay.cancel_debug_replay_job", return_value=False),
):
manager.stop(frigate_config=frigate_config, config_publisher=publisher)
def test_publish_after_stop_is_skipped(self) -> None:
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
config = self._config("live")
publisher = MagicMock()
self._stop(manager, config, publisher)
self.assertFalse(self._publish(manager, config, publisher))
self.assertNotIn("_replay_front", config.cameras)
publisher.publish_update.assert_not_called()
def test_config_swap_keeps_replay_camera_and_stop_removes_it(self) -> None:
from frigate.config.camera.updater import CameraConfigUpdateEnum
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
boot = self._config("boot")
publisher = MagicMock()
self.assertTrue(self._publish(manager, boot, publisher))
swapped = self._config("swapped")
manager.update_config(swapped)
self.assertIn("_replay_front", swapped.cameras)
self._stop(manager, swapped, publisher)
topic = publisher.publish_update.call_args.args[0]
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
self.assertNotIn("_replay_front", swapped.cameras)
def test_stop_with_stale_config_still_publishes_remove(self) -> None:
from frigate.config.camera.updater import CameraConfigUpdateEnum
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
live = self._config("live")
publisher = MagicMock()
self.assertTrue(self._publish(manager, live, publisher))
self._stop(manager, self._config("stale"), publisher)
topic = publisher.publish_update.call_args.args[0]
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -302,7 +302,7 @@ class TestRunnerHappyPath(unittest.TestCase):
patch.object(
self.manager,
"publish_camera",
side_effect=lambda *a, **kw: captured.append("published"),
side_effect=lambda *a, **kw: captured.append("published") or True,
),
patch("os.path.exists", return_value=True),
patch("os.makedirs"),
+18
View File
@@ -221,6 +221,24 @@ class TestFfmpegProgressParsing(unittest.TestCase):
assert any(abs(p - (30 / 90 * 100)) < 0.01 for p in encoding_percents)
class TestExportJobManagerConfig(unittest.TestCase):
def test_manager_follows_the_config_passed_by_callers(self) -> None:
import frigate.jobs.export as export_jobs
boot = MagicMock(name="boot")
swapped = MagicMock(name="swapped")
with (
patch.object(export_jobs, "_job_manager", None),
patch.object(export_jobs.ExportJobManager, "ensure_started"),
patch.object(export_jobs, "_get_max_concurrent", return_value=1),
):
export_jobs.get_export_job_manager(boot)
manager = export_jobs.get_export_job_manager(swapped)
self.assertIs(manager.config, swapped)
class TestBroadcastAggregation(unittest.TestCase):
"""Verify ExportJobManager broadcast payload shape and throttling."""
+3 -10
View File
@@ -1,12 +1,11 @@
"""Utilities for cleaning up camera data from database and filesystem."""
import glob
import logging
import os
import re
import shutil
from frigate.const import CLIPS_DIR, RECORD_DIR, SUB_CACHE_TAG, THUMB_DIR
from frigate.const import CLIPS_DIR, RECORD_DIR, THUMB_DIR
from frigate.models import (
Event,
Export,
@@ -113,18 +112,12 @@ def cleanup_camera_files(
export_paths: Optional list of export file paths to remove
"""
dirs_to_clean = [
os.path.join(RECORD_DIR, camera_name),
os.path.join(CLIPS_DIR, camera_name),
os.path.join(THUMB_DIR, camera_name),
os.path.join(CLIPS_DIR, "previews", camera_name),
os.path.join(CLIPS_DIR, "lpr", camera_name),
os.path.join(CLIPS_DIR, "triggers", camera_name),
]
# recordings live at RECORD_DIR/<date>/<hour>/<camera>
for name in (camera_name, f"{camera_name}{SUB_CACHE_TAG}"):
dirs_to_clean.extend(
glob.glob(os.path.join(glob.escape(RECORD_DIR), "*", "*", name))
)
for dir_path in dirs_to_clean:
if os.path.exists(dir_path):
try:
+2 -1
View File
@@ -16,7 +16,8 @@ export function processCameraName(userInput: string): {
} {
const normalizedInput = userInput.replace(/\s+/g, "_").toLowerCase();
if (isValidId(normalizedInput)) {
// debug replay owns this prefix and deletes data for cameras that use it
if (isValidId(normalizedInput) && !isReplayCamera(normalizedInput)) {
return {
finalCameraName: normalizedInput,
friendlyName: userInput.includes(" ") ? userInput : undefined,