diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b35f9b05d..4f4771c8d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -314,6 +314,18 @@ jobs: sleep 2 done if [ "$ok" -ne 1 ]; then echo "sentinel skip never logged"; docker logs frigate-puid; exit 1; fi + # a replaced media volume re-sweeps despite the sentinel + docker stop frigate-puid + sudo rm -rf /tmp/frigate-media-puid + sudo mkdir /tmp/frigate-media-puid + docker start frigate-puid + up=0 + for i in $(seq 1 60); do + docker exec frigate-puid curl -fs http://127.0.0.1:5000/api/version && up=1 && break + sleep 5 + done + if [ "$up" -ne 1 ]; then echo "replaced media volume was not swept"; docker logs frigate-puid; exit 1; fi + docker exec frigate-puid stat -c %u:%g /media/frigate | grep -qx 1500:1500 docker rm -f frigate-puid - name: Assert read-only rootfs with --user works run: | diff --git a/docker/main/rootfs/usr/local/bin/fix-ownership b/docker/main/rootfs/usr/local/bin/fix-ownership index 3c76ea471a..2ab031ae28 100755 --- a/docker/main/rootfs/usr/local/bin/fix-ownership +++ b/docker/main/rootfs/usr/local/bin/fix-ownership @@ -70,16 +70,6 @@ if [[ -n "$mode" ]]; then sentinel_content="${sentinel_content}:${mode}" fi -# safe-sentinel reports only a root-owned regular file, so a forged or -# symlinked sentinel in the runtime-user-owned /config can't suppress the sweep -if [[ "$dry_run" -eq 0 && -n "$sentinel" ]]; then - if existing=$(/usr/local/bin/safe-sentinel read "$sentinel" 2>/dev/null) && \ - [[ "$existing" == "$sentinel_content" ]]; then - echo "[INFO] fix-ownership: ${target_uid}:${target_gid} (schema ${schema}) already applied, skipping" - exit 0 - fi -fi - # A sweep that could not chown everything must not be recorded as complete: # the sentinel would make every later boot skip it and the entries would stay # unreachable once services run unprivileged. @@ -102,6 +92,24 @@ mismatch_expr=( -a ! -path /config/.permissions_version ) +first_mismatched_root() { + find "$@" -maxdepth 0 "${mismatch_expr[@]}" -print -quit 2>/dev/null || true +} + +# safe-sentinel reports only a root-owned regular file, so a forged or +# symlinked sentinel in the runtime-user-owned /config can't suppress the sweep. +# A mismatched volume root means the volume was replaced or wiped since the +# sweep (Docker recreates a missing bind source as root), so it sweeps again, +# unless the sentinel records a filesystem that ignores chown. +if [[ "$dry_run" -eq 0 && -n "$sentinel" ]]; then + if existing=$(/usr/local/bin/safe-sentinel read "$sentinel" 2>/dev/null) && \ + { [[ "$existing" == "${sentinel_content}:unmanaged" ]] || \ + { [[ "$existing" == "$sentinel_content" ]] && [[ -z "$(first_mismatched_root "$@")" ]]; }; }; then + echo "[INFO] fix-ownership: ${target_uid}:${target_gid} (schema ${schema}) already applied, skipping" + exit 0 + fi +fi + exec 3>&1 for path in "$@"; do @@ -199,6 +207,13 @@ if [[ "$dry_run" -eq 0 && -d /config ]]; then fi if [[ "$dry_run" -eq 0 && -n "$sentinel" && "$swept_clean" -eq 1 ]]; then + # CIFS without the setuids option accepts chown and changes nothing, so + # the root can never match. Without this every boot would sweep again. + unmanaged_root=$(first_mismatched_root "$@") + if [[ -n "$unmanaged_root" ]]; then + echo "[WARN] fix-ownership: ${unmanaged_root} kept its owner after chown; its filesystem ignores ownership changes, so set the owner through its mount options" + sentinel_content="${sentinel_content}:unmanaged" + fi /usr/local/bin/safe-sentinel write "$sentinel" "$sentinel_content" || \ echo "[WARN] fix-ownership: could not write ${sentinel}; the sweep will run again on next boot" fi diff --git a/docs/docs/configuration/cameras.md b/docs/docs/configuration/cameras.md index 2b531b484e..6647ba58b2 100644 --- a/docs/docs/configuration/cameras.md +++ b/docs/docs/configuration/cameras.md @@ -83,12 +83,12 @@ A camera is enabled by default but can be disabled by using `enabled: False`. Ca Each role can only be assigned to one input per camera. The options for roles are as follows: -| Role | Description | -| ------------ | ------------------------------------------------------------------------------------------------------------ | -| `detect` | Main feed for object detection. [docs](object_detectors.md) | -| `record` | Saves segments of the video feed based on configuration settings. [docs](record.md) | +| Role | Description | +| ------------ | --------------------------------------------------------------------------------------------------------------- | +| `detect` | Main feed for object detection. [docs](object_detectors.md) | +| `record` | Saves segments of the video feed based on configuration settings. [docs](record.md) | | `record_sub` | Saves segments of a second, lower quality stream with its own retention. [docs](record.md#sub-stream-recording) | -| `audio` | Feed for audio based detection. [docs](audio_detectors.md) | +| `audio` | Feed for audio based detection. [docs](audio_detectors.md) | @@ -160,6 +160,8 @@ If you only define one stream in your `inputs` and do not assign a `detect` role If you plan to use Frigate for recording only, it is still recommended to define a `detect` role for a low resolution stream to minimize resource usage from the required stream decoding. +Setting the `detect` `width` and `height` explicitly is recommended. When they are unset, Frigate probes the detect stream at every startup, which can add several seconds per camera. Cameras added with the [Add Camera Wizard](#adding-a-camera-with-the-add-camera-wizard) have them set automatically. + ::: For camera model specific settings check the [camera specific](camera_specific.md) infos. diff --git a/docs/docs/configuration/non_root.md b/docs/docs/configuration/non_root.md index 0347900616..4fe88f8dec 100644 --- a/docs/docs/configuration/non_root.md +++ b/docs/docs/configuration/non_root.md @@ -86,6 +86,16 @@ Once the volumes are aligned, start Frigate normally. A file at `/config/.permis If something under your volumes can't be chowned, a read-only btrfs snapshot directory for example, the sweep warns and names the path and doesn't record the migration as finished. It retries on the next boot instead. Either move those paths outside `/media/frigate` or expect the scan to repeat. +### Custom database location + +The sweep only covers `/config` and `/media/frigate`. If `database.path` points somewhere else, such as a separate volume, align that directory yourself before upgrading, and again after running with `FRIGATE_RUN_AS_ROOT=true`: + +```bash +chown -R 1000:1000 /path/to/your/database/dir +``` + +Use your `PUID` and `PGID` if you've changed them. Until the directory and its files are writable, Frigate stops at startup with an error naming the path it can't write. + ### Network storage Recordings on a NAS behave differently, so check what you have before migrating: @@ -94,7 +104,7 @@ Recordings on a NAS behave differently, so check what you have before migrating: findmnt -T /path/to/your/storage -o TARGET,FSTYPE,OPTIONS ``` -**SMB and CIFS** don't store per-file ownership at all. It's synthesized from the mount options, so a per-file `chown` fails and isn't needed. Mount the share as the uid and gid Frigate runs as, and every file already looks correct to the sweep: +**SMB and CIFS** don't store per-file ownership at all. It's synthesized from the mount options, so a per-file `chown` has no effect and isn't needed. Mount the share as the uid and gid Frigate runs as, and every file already looks correct to the sweep: ``` //nas/frigate /media/frigate cifs credentials=/root/.smb,uid=1000,gid=1000,file_mode=0664,dir_mode=0775 0 0 diff --git a/frigate/api/app.py b/frigate/api/app.py index 8cb69762a4..f831d5d720 100644 --- a/frigate/api/app.py +++ b/frigate/api/app.py @@ -336,6 +336,8 @@ def config(request: Request): for cmd in camera_dict["ffmpeg_cmds"]: cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"])) + camera_dict["detect_resolution_source"] = camera.detect_resolution_source + # masking misses vendor-specific credentials in paths and args, and the # non-admin UI never reads them if not is_admin: diff --git a/frigate/api/media.py b/frigate/api/media.py index 69e12b74ca..12459b0b50 100644 --- a/frigate/api/media.py +++ b/frigate/api/media.py @@ -61,7 +61,11 @@ from frigate.util.file import ( get_event_thumbnail_bytes, load_event_snapshot_image, ) -from frigate.util.image import get_image_from_recording, get_image_quality_params +from frigate.util.image import ( + get_image_from_recording, + get_image_quality_params, + read_image, +) from frigate.util.object import create_empty_regions_grid from frigate.util.recording_coverage import ( build_spans, @@ -259,7 +263,7 @@ async def latest_frame( if preview_path: logger.debug(f"Using most recent preview frame for {camera_name}") - frame = cv2.imread(preview_path, cv2.IMREAD_UNCHANGED) + frame = read_image(preview_path, cv2.IMREAD_UNCHANGED) if frame is not None: is_offline = True diff --git a/frigate/app.py b/frigate/app.py index b4fedbe8d0..ea698e2150 100644 --- a/frigate/app.py +++ b/frigate/app.py @@ -4,6 +4,7 @@ import multiprocessing as mp import os import secrets import shutil +import sys from collections.abc import Callable from multiprocessing import Queue from multiprocessing.managers import DictProxy, SyncManager @@ -91,7 +92,7 @@ from frigate.timeline import TimelineProcessor from frigate.track.object_processing import TrackedObjectProcessor from frigate.util.builtin import empty_and_close_queue from frigate.util.image import UntrackedSharedMemory -from frigate.util.ownership import chown_to_runtime +from frigate.util.ownership import chown_to_runtime, find_unwritable_database_path from frigate.util.process import FrigateProcess from frigate.util.runtime_deps import RuntimeDependencyError from frigate.util.services import set_file_limit @@ -197,8 +198,32 @@ class FrigateApp: except PermissionError: logger.error("Unable to write to /config to save DB state") + def exit_if_unwritable(paths: tuple[str, ...]) -> None: + unwritable = find_unwritable_database_path(paths) + + if unwritable is None: + return + + logger.error( + "Frigate is running as uid %s, gid %s and can't write to %s. Make " + "sure it exists and is owned by that user, see " + "https://docs.frigate.video/configuration/non_root#custom-database-location", + os.getuid(), + os.getgid(), + unwritable, + ) + sys.exit(1) + + db_path = self.config.database.path + backup_path = db_path.replace("frigate.db", "backup.db") + db_files = (db_path, f"{db_path}-wal", f"{db_path}-shm", backup_path) + + # the ownership sweep covers /config and /media/frigate only, so a + # database kept elsewhere can still be owned by root after upgrading + exit_if_unwritable(db_files[:3]) + # Migrate DB schema - migrate_db = SqliteDatabase(self.config.database.path) + migrate_db = SqliteDatabase(db_path) # Run migrations del logging.getLogger("peewee_migrate").handlers[:] @@ -206,10 +231,8 @@ class FrigateApp: if len(router.diff) > 0: logger.info("Making backup of DB before migrations...") - shutil.copyfile( - self.config.database.path, - self.config.database.path.replace("frigate.db", "backup.db"), - ) + exit_if_unwritable((backup_path,)) + shutil.copyfile(db_path, backup_path) router.run() @@ -235,12 +258,7 @@ class FrigateApp: # a root frigate service creates these as root; wal and shm recreated # later in the run are realigned by the per-boot /config sweep - for db_file in ( - self.config.database.path, - f"{self.config.database.path}-wal", - f"{self.config.database.path}-shm", - self.config.database.path.replace("frigate.db", "backup.db"), - ): + for db_file in db_files: if os.path.exists(db_file): chown_to_runtime(db_file) diff --git a/frigate/camera/state.py b/frigate/camera/state.py index 0f9930de54..a30d536bb1 100644 --- a/frigate/camera/state.py +++ b/frigate/camera/state.py @@ -24,6 +24,7 @@ from frigate.util.image import ( draw_timestamp, is_better_thumbnail, is_label_printable, + write_image, ) logger = logging.getLogger(__name__) @@ -647,7 +648,7 @@ class CameraState: thumb = cv2.resize(img_frame, dsize=(width, 175), interpolation=cv2.INTER_AREA) thumb_path = os.path.join(THUMB_DIR, self.name) os.makedirs(thumb_path, exist_ok=True) - cv2.imwrite(os.path.join(thumb_path, f"{event_id}.webp"), thumb) + write_image(os.path.join(thumb_path, f"{event_id}.webp"), thumb) def shutdown(self) -> None: for obj in self.tracked_objects.values(): diff --git a/frigate/config/camera/camera.py b/frigate/config/camera/camera.py index 0ef6f3664a..1556f19210 100644 --- a/frigate/config/camera/camera.py +++ b/frigate/config/camera/camera.py @@ -1,5 +1,6 @@ import os from enum import Enum +from typing import Literal from pydantic import Field, PrivateAttr, model_validator @@ -208,6 +209,12 @@ class CameraConfig(FrigateBaseModel): _ffmpeg_cmds: list[dict[str, list[str]]] = PrivateAttr() + # "config" when set by the user, "probed" from the stream at startup, or + # "default" when the probe failed and the fallback size is in use + _detect_resolution_source: Literal["config", "probed", "default"] = PrivateAttr( + default="config" + ) + def __init__(self, **config): # Set zone colors if "zones" in config: @@ -249,6 +256,10 @@ class CameraConfig(FrigateBaseModel): def ffmpeg_cmds(self) -> list[dict[str, list[str]]]: return self._ffmpeg_cmds + @property + def detect_resolution_source(self) -> Literal["config", "probed", "default"]: + return self._detect_resolution_source + def get_formatted_name(self) -> str: """Return the friendly name if set, otherwise return a formatted version of the camera name.""" if self.friendly_name: diff --git a/frigate/config/config.py b/frigate/config/config.py index a435b571df..f534159bba 100644 --- a/frigate/config/config.py +++ b/frigate/config/config.py @@ -1213,6 +1213,11 @@ class FrigateConfig(FrigateBaseModel): if stream_info.get("height") else DEFAULT_DETECT_DIMENSIONS["height"] ) + camera_config._detect_resolution_source = ( + "probed" + if stream_info.get("width") and stream_info.get("height") + else "default" + ) # Warn if detect fps > 10 if camera_config.detect.fps > 10 and camera_config.type != "lpr": diff --git a/frigate/data_processing/real_time/custom_classification.py b/frigate/data_processing/real_time/custom_classification.py index 7b5ab74dbc..53eee0aab5 100644 --- a/frigate/data_processing/real_time/custom_classification.py +++ b/frigate/data_processing/real_time/custom_classification.py @@ -19,7 +19,7 @@ from frigate.log import suppress_stderr_during from frigate.util.builtin import EventsPerSecond, InferenceSpeed, load_labels from frigate.util.classification import resize_classification_image from frigate.util.file import trim_oldest_files -from frigate.util.image import calculate_region +from frigate.util.image import calculate_region, write_image from frigate.util.object import box_overlaps from ..types import DataProcessorMetrics @@ -748,5 +748,5 @@ def write_classification_attempt( file = os.path.join(folder, f"{event_id}-{timestamp}-{label}-{score}.webp") os.makedirs(folder, exist_ok=True) - cv2.imwrite(file, frame) + write_image(file, frame) trim_oldest_files(folder, max_files) diff --git a/frigate/data_processing/real_time/face.py b/frigate/data_processing/real_time/face.py index 9c508b590c..800451848a 100644 --- a/frigate/data_processing/real_time/face.py +++ b/frigate/data_processing/real_time/face.py @@ -28,7 +28,7 @@ from frigate.data_processing.common.face.recognizer import ( from frigate.types import TrackedObjectUpdateTypesEnum from frigate.util.builtin import EventsPerSecond, InferenceSpeed from frigate.util.file import trim_oldest_files -from frigate.util.image import area +from frigate.util.image import area, write_image from frigate.util.path import safe_join, sanitize_path_component from ..types import DataProcessorMetrics @@ -488,5 +488,5 @@ class FaceRealTimeProcessor(RealTimeProcessorApi): folder, f"{event_id}-{timestamp}-{sub_label}-{score}.webp" ) os.makedirs(folder, exist_ok=True) - cv2.imwrite(file, frame) + write_image(file, frame) trim_oldest_files(folder, self.config.face_recognition.save_attempts) diff --git a/frigate/output/preview.py b/frigate/output/preview.py index 4a1b99feb0..9ff20e2f95 100644 --- a/frigate/output/preview.py +++ b/frigate/output/preview.py @@ -22,7 +22,12 @@ from frigate.ffmpeg_presets import ( parse_preset_hardware_acceleration_encode, ) from frigate.models import Previews -from frigate.util.image import copy_yuv_to_position, get_blank_yuv_frame, get_yuv_crop +from frigate.util.image import ( + copy_yuv_to_position, + get_blank_yuv_frame, + get_yuv_crop, + write_image, +) from frigate.util.ownership import chown_to_runtime logger = logging.getLogger(__name__) @@ -373,7 +378,7 @@ class PreviewRecorder: ) cache_path = get_cache_image_name(self.camera_name, frame_time) - if not cv2.imwrite( + if not write_image( cache_path, small_frame, [ diff --git a/frigate/ptz/onvif.py b/frigate/ptz/onvif.py index 7930e51675..171312b745 100644 --- a/frigate/ptz/onvif.py +++ b/frigate/ptz/onvif.py @@ -351,12 +351,13 @@ class OnvifController: autotracking_config.enabled_in_config and autotracking_config.enabled ) - # setup relative move request when FOV relative movement is supported - if ( + fov_supported = ( fov_space_id is not None and configs.DefaultRelativePanTiltTranslationSpace is not None - ): - # one-off GetStatus to seed Translation field + ) + + # relative moves are seeded from the current position + if fov_supported: status = None try: status = await ptz.GetStatus({"ProfileToken": profile.token}) @@ -364,6 +365,15 @@ class OnvifController: except Exception as e: logger.warning(f"Unable to get status from camera {camera_name}: {e}") + if status is None or status.Position is None: + logger.warning( + "Disabling relative movement for %s: camera does not report its PTZ position", + camera_name, + ) + fov_supported = False + + # setup relative move request when FOV relative movement is supported + if fov_supported: rel_move_request = ptz.create_type("RelativeMove") rel_move_request.ProfileToken = profile.token logger.debug(f"{camera_name}: Relative move request: {rel_move_request}") @@ -373,15 +383,8 @@ class OnvifController: ]["URI"] if rel_move_request.Translation is None: - if status is not None: - # seed from current position - rel_move_request.Translation = status.Position - rel_move_request.Translation.PanTilt.space = fov_uri - else: - # fallback: construct Translation explicitly - rel_move_request.Translation = { - "PanTilt": {"x": 0, "y": 0, "space": fov_uri} - } + rel_move_request.Translation = status.Position + rel_move_request.Translation.PanTilt.space = fov_uri # configure zoom on relative move request if ( @@ -497,11 +500,7 @@ class OnvifController: except Exception as e: logger.debug(f"Focus not supported for {camera_name}: {e}") - # detect FOV relative movement support - if ( - fov_space_id is not None - and configs.DefaultRelativePanTiltTranslationSpace is not None - ): + if fov_supported: supported_features.append("pt-r-fov") cam["relative_fov_range"] = ( ptz_config.Spaces.RelativePanTiltTranslationSpace[fov_space_id] diff --git a/frigate/review/maintainer.py b/frigate/review/maintainer.py index 7796482678..b18c413d44 100644 --- a/frigate/review/maintainer.py +++ b/frigate/review/maintainer.py @@ -33,7 +33,11 @@ from frigate.models import ReviewSegment from frigate.review.severity import get_review_severity from frigate.review.types import SeverityEnum from frigate.track.object_processing import ManualEventState -from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop +from frigate.util.image import ( + SharedMemoryFrameManager, + calculate_16_9_crop, + write_image, +) logger = logging.getLogger(__name__) @@ -147,7 +151,7 @@ class PendingReviewSegment: self.thumb_time = datetime.datetime.now().timestamp() self.has_frame = True Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True) - if not cv2.imwrite( + if not write_image( self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60] ): logger.error("Failed to write review thumbnail to %s", self.frame_path) @@ -162,7 +166,7 @@ class PendingReviewSegment: if self._frame is not None: self.has_frame = True Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True) - if not cv2.imwrite( + if not write_image( self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60] ): logger.error("Failed to write review thumbnail to %s", self.frame_path) diff --git a/frigate/test/http_api/test_http_app.py b/frigate/test/http_api/test_http_app.py index 78a92c9339..a514a3682f 100644 --- a/frigate/test/http_api/test_http_app.py +++ b/frigate/test/http_api/test_http_app.py @@ -280,6 +280,7 @@ class TestHttpApp(BaseTestHttp): assert camera["ffmpeg"]["inputs"][0]["input_args"] == auth_header assert camera["ffmpeg"]["input_args"] == auth_header assert camera["ffmpeg_cmds"] + assert camera["detect_resolution_source"] == "config" assert config["go2rtc"]["streams"]["front_door"][0] == secret_path assert "webtorrent" in config["go2rtc"] diff --git a/frigate/test/test_config.py b/frigate/test/test_config.py index b45c89cd62..b8f1614c22 100644 --- a/frigate/test/test_config.py +++ b/frigate/test/test_config.py @@ -2483,5 +2483,45 @@ class TestFfmpegPath(unittest.TestCase): ) +class TestDetectResolutionSource(unittest.TestCase): + def setUp(self): + self.config = { + "mqtt": {"host": "mqtt"}, + "cameras": { + "back": { + "ffmpeg": { + "inputs": [ + {"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]} + ] + }, + } + }, + } + + def test_set_in_config(self): + self.config["cameras"]["back"]["detect"] = {"width": 1920, "height": 1080} + camera = FrigateConfig(**self.config).cameras["back"] + assert camera.detect_resolution_source == "config" + + def test_set_globally(self): + self.config["detect"] = {"width": 1920, "height": 1080} + camera = FrigateConfig(**self.config).cameras["back"] + assert camera.detect_resolution_source == "config" + + @patch( + "frigate.config.config.stream_info_retriever.get_stream_info", + return_value={"width": 2560, "height": 1440, "fourcc": "h264"}, + ) + def test_probed_from_stream(self, _): + camera = FrigateConfig(**self.config).cameras["back"] + assert camera.detect_resolution_source == "probed" + assert (camera.detect.width, camera.detect.height) == (2560, 1440) + + def test_probe_failed_uses_default(self): + camera = FrigateConfig(**self.config).cameras["back"] + assert camera.detect_resolution_source == "default" + assert (camera.detect.width, camera.detect.height) == (1280, 720) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/frigate/test/test_norfair_tracker_deregister.py b/frigate/test/test_norfair_tracker_deregister.py new file mode 100644 index 0000000000..c8c90967c2 --- /dev/null +++ b/frigate/test/test_norfair_tracker_deregister.py @@ -0,0 +1,69 @@ +"""Per-object tracker state is released when an object is deregistered.""" + +import unittest +from unittest.mock import MagicMock + +import numpy as np + +from frigate.camera import PTZMetrics +from frigate.config import FrigateConfig +from frigate.track.norfair_tracker import NorfairTracker + +CAMERA = "front" +BOX = (400, 200, 500, 500) + + +class TestNorfairTrackerDeregister(unittest.TestCase): + def setUp(self) -> None: + config = FrigateConfig( + **{ + "mqtt": {"enabled": False}, + "cameras": { + CAMERA: { + "ffmpeg": { + "inputs": [ + { + "path": "rtsp://10.0.0.1:554/video", + "roles": ["detect"], + } + ] + }, + "detect": {"width": 1280, "height": 720}, + } + }, + } + ) + camera_config = config.cameras[CAMERA] + self.tracker = NorfairTracker(camera_config, PTZMetrics()) + self.tracker.frame_manager = MagicMock() + self.tracker.frame_manager.get.return_value = np.zeros( + camera_config.frame_shape_yuv, dtype=np.uint8 + ) + self.frame_time = 1000.0 + + def run_frames(self, count: int, detections: list) -> None: + for _ in range(count): + self.frame_time += 0.2 + self.tracker.match_and_update("frame", self.frame_time, detections) + + def test_departed_object_leaves_no_state(self): + self.run_frames(100, [("car", 0.9, BOX, 30000, 0.33, (0, 0, 640, 640))]) + + (obj_id,) = self.tracker.tracked_objects + classifier = self.tracker.stationary_classifier + self.assertIn(obj_id, self.tracker.positions) + self.assertIn(obj_id, classifier.anchor_crops) + + self.run_frames(100, []) + + self.assertEqual(self.tracker.tracked_objects, {}) + self.assertEqual(self.tracker.positions, {}) + self.assertEqual(self.tracker.stationary_box_history, {}) + self.assertEqual(classifier.anchor_crops, {}) + self.assertEqual(classifier.anchor_boxes, {}) + self.assertEqual(classifier.changed_counts, {}) + self.assertEqual(classifier.shift_histories, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/frigate/test/test_ownership.py b/frigate/test/test_ownership.py index 529c6e2cab..0e605119a6 100644 --- a/frigate/test/test_ownership.py +++ b/frigate/test/test_ownership.py @@ -1,5 +1,7 @@ """Tests for runtime ownership helpers.""" +import os +import tempfile import unittest from unittest.mock import patch @@ -73,5 +75,53 @@ class TestChownToRuntime(unittest.TestCase): ownership.chown_to_runtime("/config/test") # must not raise +class TestFindUnwritableDatabasePath(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.db_dir = os.path.join(tmp.name, "db") + os.mkdir(self.db_dir) + # restore access so cleanup can remove the tree + self.addCleanup(os.chmod, self.db_dir, 0o755) + self.db_path = os.path.join(self.db_dir, "frigate.db") + self.db_files = ( + self.db_path, + f"{self.db_path}-wal", + f"{self.db_path}-shm", + os.path.join(self.db_dir, "backup.db"), + ) + + def test_writable_directory_without_database(self): + assert ownership.find_unwritable_database_path(self.db_files) is None + + def test_writable_directory_and_database(self): + open(self.db_path, "w").close() + assert ownership.find_unwritable_database_path(self.db_files) is None + + def test_missing_directory(self): + missing_dir = os.path.join(self.db_dir, "missing") + db_files = (os.path.join(missing_dir, "frigate.db"),) + assert ownership.find_unwritable_database_path(db_files) == missing_dir + + @unittest.skipIf(os.geteuid() == 0, "root bypasses permission checks") + def test_unwritable_directory(self): + os.chmod(self.db_dir, 0o555) + assert ownership.find_unwritable_database_path(self.db_files) == self.db_dir + + @unittest.skipIf(os.geteuid() == 0, "root bypasses permission checks") + def test_unwritable_database(self): + open(self.db_path, "w").close() + os.chmod(self.db_path, 0o444) + assert ownership.find_unwritable_database_path(self.db_files) == self.db_path + + @unittest.skipIf(os.geteuid() == 0, "root bypasses permission checks") + def test_unwritable_backup(self): + backup = self.db_files[3] + open(self.db_path, "w").close() + open(backup, "w").close() + os.chmod(backup, 0o444) + assert ownership.find_unwritable_database_path(self.db_files) == backup + + if __name__ == "__main__": unittest.main() diff --git a/frigate/test/test_ptz_onvif.py b/frigate/test/test_ptz_onvif.py index bb81d67d65..67f89c0475 100644 --- a/frigate/test/test_ptz_onvif.py +++ b/frigate/test/test_ptz_onvif.py @@ -165,6 +165,25 @@ class TestOnvifInitRequests(unittest.IsolatedAsyncioTestCase): self.assertTrue(await controller._init_onvif(CAMERA)) self.assertIsNone(controller.cams[CAMERA]["video_source_token"]) + async def test_fov_movement_requires_reported_position(self) -> None: + # cameras with StatusPosition="false" omit Position from GetStatus + for position in (MagicMock(), None): + with self.subTest(position=position): + controller = _make_controller(autotracking_enabled=False) + ptz = controller.cams[CAMERA]["onvif"].create_ptz_service.return_value + ptz_config = MagicMock() + ptz_config.Spaces.RelativePanTiltTranslationSpace = [ + {"URI": "http://www.onvif.org/TranslationSpaceFov"} + ] + ptz.GetConfigurationOptions = AsyncMock(return_value=ptz_config) + ptz.GetStatus = AsyncMock(return_value=MagicMock(Position=position)) + + self.assertTrue(await controller._init_onvif(CAMERA)) + self.assertEqual( + "pt-r-fov" in controller.cams[CAMERA]["features"], + position is not None, + ) + class TestManualRelativeMoveMetrics(unittest.IsolatedAsyncioTestCase): """A manual move from the UI (click to move, drag to zoom) sends move_relative diff --git a/frigate/test/test_util_image.py b/frigate/test/test_util_image.py index ebdb7b276a..fbc02c12a3 100644 --- a/frigate/test/test_util_image.py +++ b/frigate/test/test_util_image.py @@ -1,9 +1,12 @@ +import os +import sys +import tempfile import unittest import cv2 import numpy as np -from frigate.util.image import get_snapshot_bytes +from frigate.util.image import get_snapshot_bytes, read_image, write_image class TestSnapshotBytes(unittest.TestCase): @@ -34,3 +37,44 @@ class TestSnapshotBytes(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class TestImageFiles(unittest.TestCase): + def setUp(self) -> None: + self.dir = tempfile.TemporaryDirectory() + self.image = np.full((20, 30, 3), 128, np.uint8) + + def tearDown(self) -> None: + self.dir.cleanup() + + def test_round_trip(self): + path = os.path.join(self.dir.name, "frame.png") + + self.assertTrue(write_image(path, self.image)) + np.testing.assert_array_equal(read_image(path), self.image) + + def test_encodes_by_extension_with_params(self): + path = os.path.join(self.dir.name, "frame.webp") + + self.assertTrue(write_image(path, self.image, [cv2.IMWRITE_WEBP_QUALITY, 60])) + with open(path, "rb") as f: + self.assertEqual(f.read(12)[8:], b"WEBP") + + def test_failures_return_falsy(self): + missing_dir = os.path.join(self.dir.name, "missing", "frame.png") + empty = os.path.join(self.dir.name, "empty.png") + open(empty, "wb").close() + + self.assertFalse(write_image(missing_dir, self.image)) + self.assertIsNone(read_image(missing_dir)) + self.assertIsNone(read_image(empty)) + + def test_path_is_not_retained(self): + path = os.path.join(self.dir.name, "frame.webp") + before = sys.getrefcount(path) + + for _ in range(3): + write_image(path, self.image) + read_image(path) + + self.assertEqual(sys.getrefcount(path), before) diff --git a/frigate/track/norfair_tracker.py b/frigate/track/norfair_tracker.py index ec807ee93f..ac99ca2123 100644 --- a/frigate/track/norfair_tracker.py +++ b/frigate/track/norfair_tracker.py @@ -348,6 +348,9 @@ class NorfairTracker(ObjectTracker): del self.tracked_objects[id] del self.disappeared[id] + self.positions.pop(id, None) + self.stationary_box_history.pop(id, None) + self.stationary_classifier.forget(id) # only manually deregister objects from norfair's list if max_frames is defined if ( diff --git a/frigate/track/stationary_classifier.py b/frigate/track/stationary_classifier.py index 1e22ec6f6d..515307f880 100644 --- a/frigate/track/stationary_classifier.py +++ b/frigate/track/stationary_classifier.py @@ -116,6 +116,13 @@ class StationaryMotionClassifier: self.changed_counts[id] = 0 self.shift_histories[id] = [] + def forget(self, id: str) -> None: + """Drop all state for an object that is no longer tracked.""" + self.anchor_crops.pop(id, None) + self.anchor_boxes.pop(id, None) + self.changed_counts.pop(id, None) + self.shift_histories.pop(id, None) + def _extract_y_crop( self, yuv_frame: np.ndarray, box: tuple[int, int, int, int] ) -> np.ndarray: diff --git a/frigate/util/image.py b/frigate/util/image.py index 909a505b62..c75728a412 100644 --- a/frigate/util/image.py +++ b/frigate/util/image.py @@ -2,9 +2,11 @@ import datetime import logging +import os import subprocess as sp import threading from abc import ABC, abstractmethod +from collections.abc import Sequence from multiprocessing import resource_tracker as _mprt from multiprocessing import shared_memory as _mpshm from string import printable @@ -272,6 +274,38 @@ def get_image_quality_params(ext: str, quality: int | None) -> list[int]: return [] +def write_image(path: str, image: np.ndarray, params: Sequence[int] = ()) -> bool: + """Encode an image by the path's extension and write it to disk. + + OpenCV 4.11 keeps a reference to every path string passed to cv2.imwrite + or cv2.imread (opencv/opencv#28047), so recurring writes encode in memory. + """ + ok, encoded = cv2.imencode(os.path.splitext(path)[1], image, list(params)) + + if not ok: + return False + + try: + encoded.tofile(path) + except OSError: + return False + + return True + + +def read_image(path: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None: + """Read and decode an image without passing the path to OpenCV.""" + try: + data = np.fromfile(path, dtype=np.uint8) + except OSError: + return None + + if data.size == 0: + return None + + return cv2.imdecode(data, flags) + + def relative_box_to_absolute( frame_shape: tuple[int, ...], box: list[float] | tuple[float, ...] | None ) -> tuple[int, int, int, int] | None: diff --git a/frigate/util/ownership.py b/frigate/util/ownership.py index e1b9cc236c..c4fbe50ae2 100644 --- a/frigate/util/ownership.py +++ b/frigate/util/ownership.py @@ -45,3 +45,21 @@ def chown_to_runtime(path: str) -> None: os.chown(path, *ids) except OSError as err: logger.warning(f"Unable to set ownership of {path}: {err}") + + +def find_unwritable_database_path(db_files: tuple[str, ...]) -> str | None: + """Return the database directory or file the current user can't write, if any. + + db_files starts with the database itself. SQLite creates its -wal and -shm + files next to it, so the directory has to be writable too. + """ + db_dir = os.path.dirname(os.path.abspath(db_files[0])) + + if not os.access(db_dir, os.W_OK | os.X_OK): + return db_dir + + for path in db_files: + if os.path.exists(path) and not os.access(path, os.R_OK | os.W_OK): + return path + + return None diff --git a/web/e2e/fixtures/mock-data/config.ts b/web/e2e/fixtures/mock-data/config.ts index 6267aa908a..235ee8d37a 100644 --- a/web/e2e/fixtures/mock-data/config.ts +++ b/web/e2e/fixtures/mock-data/config.ts @@ -52,22 +52,25 @@ export function deepMerge>( export const BASE_CONFIG = { ...configSnapshot, version: "0.15.0-test", - // injected by the /config endpoint rather than the Pydantic model, so it - // is absent from the snapshot + // injected by the /config endpoint rather than the Pydantic model, so they + // are absent from the snapshot, as is each camera's detect_resolution_source plus: { enabled: false }, cameras: { ...configSnapshot.cameras, front_door: { ...configSnapshot.cameras.front_door, friendly_name: "Front Door", + detect_resolution_source: "config", }, backyard: { ...configSnapshot.cameras.backyard, friendly_name: "Backyard", + detect_resolution_source: "config", }, garage: { ...configSnapshot.cameras.garage, friendly_name: "Garage", + detect_resolution_source: "config", }, }, }; diff --git a/web/e2e/specs/system-health.spec.ts b/web/e2e/specs/system-health.spec.ts index bbdda90e11..04b3627083 100644 --- a/web/e2e/specs/system-health.spec.ts +++ b/web/e2e/specs/system-health.spec.ts @@ -57,6 +57,14 @@ const EVENT_NOTICE = { muted_at: null, }; +// a repeated device gets a '#2' suffix, which a raw URL would cut off as a fragment +const SUFFIXED_NOTICE = { + ...EVENT_NOTICE, + id: "detector_stuck:openvino:GPU#2", + scope: "openvino:GPU#2", + params: { detector: "openvino:GPU#2" }, +}; + test.describe("System — Health tab @medium", () => { test("Health is the default tab and lists notices by severity", async ({ frigateApp, @@ -95,19 +103,20 @@ test.describe("System — Health tab @medium", () => { for (const action of ["acknowledge", "mute"] as const) { test(`${action} posts and removes the row`, async ({ frigateApp }) => { + const path = `/api/notices/${encodeURIComponent(SUFFIXED_NOTICE.id)}/${action}`; await frigateApp.installDefaults({ config: RESTREAMED, stats: QUIET_STATS, - notices: [EVENT_NOTICE], + notices: [SUFFIXED_NOTICE], }); // the list shrinks after the POST so the refetch shows the row gone let hidden = false; await frigateApp.page.route("**/api/notices", (route) => - route.fulfill({ json: hidden ? [] : [EVENT_NOTICE] }), + route.fulfill({ json: hidden ? [] : [SUFFIXED_NOTICE] }), ); await frigateApp.page.route( - `**/api/notices/detector_stuck/${action}`, + (url) => url.pathname.endsWith(path), (route) => { hidden = true; return route.fulfill({ json: { success: true } }); @@ -117,11 +126,10 @@ test.describe("System — Health tab @medium", () => { await frigateApp.goto("/system#health"); const request = frigateApp.page.waitForRequest( (req) => - req.url().includes(`/api/notices/detector_stuck/${action}`) && - req.method() === "POST", + new URL(req.url()).pathname.endsWith(path) && req.method() === "POST", ); await frigateApp.page - .getByTestId("health-problem-notice:detector_stuck") + .getByTestId(`health-problem-notice:${SUFFIXED_NOTICE.id}`) .getByRole("button", { name: action === "mute" ? "Mute" : "Acknowledge", exact: true, @@ -264,8 +272,9 @@ test.describe("System — Health tab @medium", () => { url.searchParams.get("include_hidden") === "true", (route) => route.fulfill({ json: [MUTED_NOTICE] }), ); + const path = `/api/notices/${encodeURIComponent(MUTED_NOTICE.id)}/hidden`; await frigateApp.page.route( - "**/api/notices/model_download_failed:yolo/model.onnx/hidden", + (url) => url.pathname.endsWith(path), (route) => route.fulfill({ json: { success: true } }), ); await frigateApp.goto("/system#health"); @@ -276,11 +285,7 @@ test.describe("System — Health tab @medium", () => { const request = frigateApp.page.waitForRequest( (req) => - req - .url() - .endsWith( - "/api/notices/model_download_failed:yolo/model.onnx/hidden", - ) && req.method() === "DELETE", + new URL(req.url()).pathname.endsWith(path) && req.method() === "DELETE", ); await frigateApp.page .getByTestId( @@ -1067,6 +1072,76 @@ test.describe("System — Health notices sources @medium", () => { ).toHaveCount(0); }); + test("a camera on the fallback detect resolution is flagged", async ({ + frigateApp, + }) => { + await frigateApp.installDefaults({ + config: { cameras: { garage: { detect_resolution_source: "default" } } }, + stats: QUIET_STATS, + }); + await frigateApp.goto("/system#health"); + + const row = frigateApp.page.getByTestId( + "health-problem-config:detect:detect-resolution-not-probed:camera.garage", + ); + await expect(row).toBeVisible({ timeout: 15_000 }); + await expect(row).toHaveAttribute("data-severity", "warning"); + await expect( + frigateApp.page.getByTestId( + "health-problem-config:detect:detect-resolution-not-probed:camera.front_door", + ), + ).toHaveCount(0); + }); + + test("an unprobeable resolution is only flagged when Frigate must probe it", async ({ + frigateApp, + }) => { + const noSize = [ + { + return_code: 0, + stderr: "", + stdout: { + streams: [ + { codec_type: "video", codec_name: "h264" }, + { codec_type: "audio", codec_name: "aac" }, + ], + }, + }, + ]; + await frigateApp.installDefaults({ + config: { + cameras: { + backyard: { detect_resolution_source: "probed" }, + front_door: { detect_resolution_source: "default" }, + }, + }, + ffprobe: { backyard: noSize, front_door: noSize, garage: noSize }, + stats: QUIET_STATS, + }); + await frigateApp.goto("/system#health"); + + await frigateApp.page + .getByRole("button", { name: "Run stream checks" }) + .click(); + + await expect( + frigateApp.page.getByTestId( + "health-problem-stream:backyard:0:resolution-unknown", + ), + ).toBeVisible({ timeout: 15_000 }); + await expect( + frigateApp.page.getByTestId( + "health-problem-stream:garage:0:resolution-unknown", + ), + ).toHaveCount(0); + // the startup probe's own row already covers this camera + await expect( + frigateApp.page.getByTestId( + "health-problem-stream:front_door:0:resolution-unknown", + ), + ).toHaveCount(0); + }); + test("wizard-only Reolink advice stays off the tab", async ({ frigateApp, }) => { @@ -1281,10 +1356,14 @@ test.describe("System — Health notices sources @medium", () => { // the list gains the mute after the POST so the refetch hides the row let muted = false; - await frigateApp.page.route(`**/api/notices/${id}/mute`, (route) => { - muted = true; - return route.fulfill({ json: { success: true } }); - }); + const path = `/api/notices/${encodeURIComponent(id)}/mute`; + await frigateApp.page.route( + (url) => url.pathname.endsWith(path), + (route) => { + muted = true; + return route.fulfill({ json: { success: true } }); + }, + ); await frigateApp.page.route("**/api/notices/muted_checks", (route) => route.fulfill({ json: muted ? [{ id, muted_at: NOW }] : [] }), ); @@ -1297,8 +1376,7 @@ test.describe("System — Health notices sources @medium", () => { ); const request = frigateApp.page.waitForRequest( (req) => - req.url().includes(`/api/notices/${id}/mute`) && - req.method() === "POST", + new URL(req.url()).pathname.endsWith(path) && req.method() === "POST", ); await row.getByRole("button", { name: "Mute", exact: true }).click(); await request; diff --git a/web/public/locales/en/views/settings.json b/web/public/locales/en/views/settings.json index 4876977ff2..a95c761341 100644 --- a/web/public/locales/en/views/settings.json +++ b/web/public/locales/en/views/settings.json @@ -2028,6 +2028,7 @@ }, "detect": { "fpsGreaterThanFive": "Setting the detect FPS higher than 5 is not recommended. Higher values may cause performance issues and will not provide any benefit.", + "resolutionNotProbed": "Frigate could not probe the resolution of this camera's detect stream, so it is using a default of 1280x720, which may not match the camera. Set the detect width and height to match the stream.", "disabled": "Object detection is disabled. Snapshots, review items, and enrichments such as face recognition, license plate recognition, and Generative AI will not function.", "runtimeDisabled": "Object detection is enabled in your config, but it is currently turned off for this camera. Snapshots, review items, and enrichments such as face recognition, license plate recognition, and Generative AI will not function until it is turned back on from the camera's live view, or until the active profile stops disabling it.", "sceneWithoutModel": "No detection model is configured for this scene, so this camera falls back to the Default model. Add a model for this scene to give the camera its own.", diff --git a/web/src/components/config-form/section-configs/detect.ts b/web/src/components/config-form/section-configs/detect.ts index 5ec2a3c424..ff22e78f5f 100644 --- a/web/src/components/config-form/section-configs/detect.ts +++ b/web/src/components/config-form/section-configs/detect.ts @@ -18,6 +18,17 @@ const detect: SectionConfigOverrides = { condition: (ctx) => ctx.level === "camera" && ctx.formData?.enabled === false, }, + { + key: "detect-resolution-not-probed", + health: true, + messageKey: "configMessages.detect.resolutionNotProbed", + severity: "warning", + // profiles hide width and height + condition: (ctx) => + ctx.level === "camera" && + !ctx.profileName && + ctx.fullCameraConfig?.detect_resolution_source === "default", + }, ], fieldMessages: [ { diff --git a/web/src/hooks/use-health-problems.ts b/web/src/hooks/use-health-problems.ts index 70fd0a84e0..d7ac3a8247 100644 --- a/web/src/hooks/use-health-problems.ts +++ b/web/src/hooks/use-health-problems.ts @@ -58,7 +58,7 @@ export function useHealthProblems( const muteCheck = useCallback( async (id: string) => { - await axios.post(`notices/${id}/mute`); + await axios.post(`notices/${encodeURIComponent(id)}/mute`); mutateMutedChecks(); }, [mutateMutedChecks], @@ -66,7 +66,7 @@ export function useHealthProblems( const unmuteCheck = useCallback( async (id: string) => { - await axios.delete(`notices/${id}/hidden`); + await axios.delete(`notices/${encodeURIComponent(id)}/hidden`); mutateMutedChecks(); }, [mutateMutedChecks], diff --git a/web/src/hooks/use-notices.ts b/web/src/hooks/use-notices.ts index 44140566f6..0b38aff845 100644 --- a/web/src/hooks/use-notices.ts +++ b/web/src/hooks/use-notices.ts @@ -60,15 +60,17 @@ export function useNotices(showHidden: boolean) { ); const acknowledge = useCallback( - (id: string) => act(axios.post(`notices/${id}/acknowledge`)), + (id: string) => + act(axios.post(`notices/${encodeURIComponent(id)}/acknowledge`)), [act], ); const mute = useCallback( - (id: string) => act(axios.post(`notices/${id}/mute`)), + (id: string) => act(axios.post(`notices/${encodeURIComponent(id)}/mute`)), [act], ); const unhide = useCallback( - (id: string) => act(axios.delete(`notices/${id}/hidden`)), + (id: string) => + act(axios.delete(`notices/${encodeURIComponent(id)}/hidden`)), [act], ); diff --git a/web/src/types/frigateConfig.ts b/web/src/types/frigateConfig.ts index bc8017ed87..a916cc56bf 100644 --- a/web/src/types/frigateConfig.ts +++ b/web/src/types/frigateConfig.ts @@ -36,6 +36,8 @@ export interface FaceRecognitionConfig { export type SearchModel = "jinav1" | "jinav2" | (string & NonNullable); export type SearchModelSize = "small" | "large"; +export type DetectResolutionSource = "config" | "probed" | "default"; + export type LiveTranscodeQuality = { height: number; bitrate: number; @@ -116,6 +118,7 @@ export interface CameraConfig { cmd: string; roles: string[]; }[]; + detect_resolution_source?: DetectResolutionSource; live: { height: number; quality: number; diff --git a/web/src/utils/streamHealth.ts b/web/src/utils/streamHealth.ts index 6fe72d0a2b..e057075ec8 100644 --- a/web/src/utils/streamHealth.ts +++ b/web/src/utils/streamHealth.ts @@ -58,6 +58,10 @@ export function streamHealth( checked += 1; const link = `/settings?page=cameraFfmpeg&camera=${encodeURIComponent(name)}`; const copiesAudio = recordCopiesAudio(camera); + // a set resolution needs no probe, and a failed startup probe has its own row + const resolutionCovered = + camera.detect_resolution_source === "config" || + camera.detect_resolution_source === "default"; let flagged = false; if (check.error) { @@ -125,7 +129,8 @@ export function streamHealth( (issue): issue is StreamIssue & { type: "warning" | "error" } => issue.type !== "good" && !WIZARD_ONLY_RULES.has(issue.rule) && - (issue.rule !== "audio-codec-record" || copiesAudio), + (issue.rule !== "audio-codec-record" || copiesAudio) && + (issue.rule !== "resolution-unknown" || !resolutionCovered), ) .forEach((issue) => { flagged = true;