diff --git a/frigate/api/config_util.py b/frigate/api/config_util.py index c69c242aed..84c6c899fa 100644 --- a/frigate/api/config_util.py +++ b/frigate/api/config_util.py @@ -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) diff --git a/frigate/api/fastapi_app.py b/frigate/api/fastapi_app.py index fbc4da7fed..6057ea128f 100644 --- a/frigate/api/fastapi_app.py +++ b/frigate/api/fastapi_app.py @@ -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 diff --git a/frigate/debug_replay.py b/frigate/debug_replay.py index f8e801c3f3..712477ddf2 100644 --- a/frigate/debug_replay.py +++ b/frigate/debug_replay.py @@ -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( diff --git a/frigate/jobs/debug_replay.py b/frigate/jobs/debug_replay.py index be0f9ac040..b743f462a0 100644 --- a/frigate/jobs/debug_replay.py +++ b/frigate/jobs/debug_replay.py @@ -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 diff --git a/frigate/jobs/export.py b/frigate/jobs/export.py index f93daf208f..6bbca19127 100644 --- a/frigate/jobs/export.py +++ b/frigate/jobs/export.py @@ -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 diff --git a/frigate/output/birdseye.py b/frigate/output/birdseye.py index fe46626afb..8684631605 100644 --- a/frigate/output/birdseye.py +++ b/frigate/output/birdseye.py @@ -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() diff --git a/frigate/test/test_birdseye.py b/frigate/test/test_birdseye.py index 12b685afae..711f1ef1ed 100644 --- a/frigate/test/test_birdseye.py +++ b/frigate/test/test_birdseye.py @@ -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.""" diff --git a/frigate/test/test_config_util.py b/frigate/test/test_config_util.py index 279f66fc06..807f58000c 100644 --- a/frigate/test/test_config_util.py +++ b/frigate/test/test_config_util.py @@ -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) diff --git a/frigate/test/test_debug_replay.py b/frigate/test/test_debug_replay.py index a91f759c44..1e6faf5c80 100644 --- a/frigate/test/test_debug_replay.py +++ b/frigate/test/test_debug_replay.py @@ -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() diff --git a/frigate/test/test_debug_replay_job.py b/frigate/test/test_debug_replay_job.py index 99bf4fbc04..e047139dfe 100644 --- a/frigate/test/test_debug_replay_job.py +++ b/frigate/test/test_debug_replay_job.py @@ -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"), diff --git a/frigate/test/test_export_progress.py b/frigate/test/test_export_progress.py index bdb6a2fd5b..811d7f01c6 100644 --- a/frigate/test/test_export_progress.py +++ b/frigate/test/test_export_progress.py @@ -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.""" diff --git a/web/src/utils/cameraUtil.ts b/web/src/utils/cameraUtil.ts index 2a0eaefb21..25089acfd4 100644 --- a/web/src/utils/cameraUtil.ts +++ b/web/src/utils/cameraUtil.ts @@ -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,