Compare commits

...
69 Commits
Author SHA1 Message Date
Josh Hawkins f4d25ccbcc docs 2026-08-22 11:55:16 -05:00
Josh Hawkins 6d0733d18c read the exec override from an import time snapshot
environment_vars is exported into os.environ, and is_go2rtc_arbitrary_exec_allowed read os.environ live, so the config file could enable exec sources. Snapshot the variable at import, which runs before any config is loaded.
2026-08-22 11:55:16 -05:00
Josh Hawkins 027bafdb29 use the shared substitution namespace in go2rtc config
The generator rebuilt the namespace itself from os.environ and a hardcoded /run/secrets, so it never saw environment_vars or CREDENTIALS_DIRECTORY, and str.format made any stray brace fatal. It now installs the FRIGATE_ names from environment_vars and substitutes streams the same way every other field does.
2026-08-22 11:55:16 -05:00
Josh Hawkins 1355075fda add secrets.yaml and merge substitution sources by precedence
FRIGATE_ENV_VARS was built once at import from container env and /run/secrets, and the environment_vars validator overwrote it unconditionally, so the block beat the deployment and nothing could be re-read. Sources are now separate dicts merged lowest to highest (environment_vars, secrets.yaml, container env, credentials directory), re-read at the top of every parse, and a collision warns once naming the winner. An undefined {FRIGATE_*} raises a ValueError subclass so pydantic reports the field instead of a KeyError traceback.
2026-08-22 11:55:16 -05:00
Josh Hawkins 01bb9f3f37 fix clip download deadlock from unread ffmpeg stderr (#24032)
ffmpeg's stderr was piped but never read, so recording segments that generate more than 64 KB of ffmpeg warnings blocked ffmpeg mid-write, stranding the streaming thread and its anyio threadpool token for good. Enough of those and every sync endpoint stops responding until restart. The trigger is how noisy the segments are, not how long the clip is.

Send stderr to a temp file instead, and guarantee ffmpeg teardown and playlist cleanup on every exit path, including client disconnect.

Also fixes two bugs the deadlock hid: the failure branch was unreachable because returncode is None mid-loop, so the playlist file leaked and ffmpeg's logs were never reported. Playlist files now get a unique name so concurrent requests for one range cannot delete each other's input.

Extracts the terminate helper motion search already had into frigate/util/ffmpeg.py, now shared by both streaming call sites.
2026-08-22 11:40:42 -05:00
Josh Hawkins b91fb05314 fix the model lookup KeyError for cameras added at runtime (#24026) 2026-08-22 11:40:42 -05:00
Josh Hawkins 199bea081c Add import/export for camera group layouts and per-camera streaming settings (#24025)
* add import/export for camera group layouts and streaming settings

Camera group layouts and per-camera streaming settings are stored in the browser's IndexedDB, so they are tied to a single browser on a single device. Users with more than one device have to rebuild every group layout and re-pick every camera's stream settings by hand, and clearing browser data loses the work.

Add a Backup & Restore card to Settings > UI Settings that exports these settings to a JSON file and imports that file on another device. Import shows a confirmation dialog with per-section counts, switches for layouts, streaming settings, and UI preferences, and warnings about camera groups or cameras in the file that are not on this server.

Server-side storage is deliberately avoided. These are per-device presentation settings: a layout arranged for a desktop is wrong on a tablet, and continuous full-resolution streams that are free on a wired LAN are not on a phone. An explicit file moves settings only when the user chooses to move them.

Implementation notes:

- web/src/utils/uiSettingsTransfer.ts owns a registry of transferable IndexedDB keys. Each entry records whether the key is user-namespaced, matching which persistence hook wrote it, plus a zod schema for its value.
- Only registry-known keys are ever written, and only when their value passes that schema. The file format deliberately lets unknown keys survive parsing, so this filter is what prevents a hand-edited file from writing arbitrary storage keys or out-of-range values.
- Export falls back to the legacy un-namespaced key, because the username migration runs lazily on first mount of each owning hook.
- Streaming settings merge per group rather than replacing the whole map, so groups configured only on the receiving device survive.
- Import writes storage and then reloads, because useUserPersistence reads a key only on mount and StreamingSettingsProvider would otherwise write its stale in-memory state back over the import.
- playbackBandwidthEstimate, frigate-search-history, and live-layout are excluded: the first two are measurements and user data rather than preferences, and live-layout's default is derived from the device.

* merge imported streaming settings per camera instead of per group
2026-08-22 11:40:42 -05:00
Nicolas MowenandJosh Hawkins 07ba2357e6 Implement UI for managing multiple models (#24023)
* Implement hardware detection and UI management

* Cleanup Frigate+ detection

* Don't count model as changed

* Fixes for audio map error

* Add descriptions

* Enforce that all model must exist

* Fix hardware picking

* Docs fixes

* WebUI cleanup

* Cleanup handling of scenes

* UI refinement

* Cleanup recommended UI

* test fixews
2026-08-22 11:40:42 -05:00
Josh Hawkins 79ea68caa2 Base emergency cleanup on the streams a camera is currently recording (#24022)
* gate emergency cleanup bandwidth on the streams a camera currently records

* settle bandwidth samples per stream instead of per camera

* fix mypy
2026-08-22 11:40:42 -05:00
Nicolas MowenandJosh Hawkins 5c9c02002f Refactor detector and model management (#23995)
* Refactor detector and model management

* Fix model resolution field
2026-08-22 11:40:42 -05:00
Ersa Oktavian RamadanandJosh Hawkins 7b42d94bfe Add audio labelmap grouping (#24004)
Allow audio classes to be grouped under a shared configured label.

Keep audio overrides separate from object labels and retain only the highest-scoring grouped detection.

Refs #23967
2026-08-22 11:40:42 -05:00
Josh Hawkins 0f5ed8822d Show main and sub stream usage separately in Storage Metrics (#24015)
* backend

* frontend

* docs

* test

* report null instead of 0 for a stream with no cached bandwidth sample
2026-08-22 11:40:42 -05:00
Josh Hawkins af537b9479 Refactor MQTT (#24010)
* refactor mqtt so that Frigate owns the transport lifecycle instead of delegating it to paho

* release the shutdown barrier on worker crash and replay retained publishes the broker never acked

* collapse in-flight retained values by topic and release the shutdown barrier from a finally

* replay the outage buffer before the publish queue so newer values are not reverted
2026-08-22 11:40:42 -05:00
Josh Hawkins 2395a82639 Refactor birdseye activity modes as a list and add alerts/detections (#24012)
* backend

* tests

* frontend and i18n

* e2e test schema

* docs
2026-08-22 11:40:42 -05:00
Josh Hawkins e8c7f4b2ff Improve History's seek startup time and recordings query performance (#24011)
* serve a segment startup ladder so seeks begin playing sooner

nginx-vod was handed one 10s segment per recording file, so every playlist start had to download and decode a full segment before the first frame. Declare real keyframe data per clip and let nginx cut short leading segments from it.

- add vod_bootstrap_segment_durations 1000/2000/4000 so each playlist starts with 1s/2s/4s segments before settling at 10s
- emit real clip-relative keyFrameDurations (plus firstKeyFrameOffset when nonzero) from the recording keyframe index; rows without an index keep the whole-clip declaration, the only safe cut without keyframe knowledge
- drop the manifest's segment_duration field, which was always inert: nginx-vod parses only camelCase segmentDuration
- rebuild the player source at the seek target, quantized to a 10s grid, so the ladder applies to every seek and seek URLs stay repeatable for nginx's mapping and response caches
- route the seek model, in-range checks, and the stale-report guard through the source window rather than the chunk range
- bridge repositioning seeks (>2s from the last played timestamp) through the preview player and hold the release anchor one commit, so neither path paints a stale frame
- clear a pending loading timer before replacing it; an orphaned timer escaped onPlaying's clearTimeout and flashed loading mid-playback

* keep recordings queries on their indexes

Several recordings queries degraded into full scans or large sorts on big databases: the planner ignored index order, or the query shape gave it nothing tight to seek on. Reshape them into bounded seeks and add the composite index the per-stream lookups need.

- index recordings on (camera, stream_type, start_time DESC) and drop the (camera, stream_type) index it supersedes
- walk the recordings summary day by day with EXISTS probes and per-camera MIN/MAX seeks, skipping ahead over empty gaps instead of bucketing every row for the requested cameras
- run the summary endpoint on the event loop rather than the threadpool
- bound the unavailable-recordings query by start_time per camera and merge the results in Python
- bound the expire query's start_time so it seeks the retention window instead of scanning a camera's whole history
- enumerate deleted cameras with one index seek each rather than a camera NOT IN (...) scan
- compute bandwidth with segment_size filtered in a CASE projection; as a WHERE predicate it baited the planner into the (camera, segment_size) index plus a full sort of the camera's history
- fall back to a 1000-segment window when the recent 100 are all zero-size, so an ingest glitch doesn't report zero bandwidth
- limit the needs_refresh count instead of counting every segment
- cover sub-only and sparse calendar days, midnight-spanning day attribution, multi-camera gap merging, deleted-camera expiry, and zero-size segment runs

* fix mypy
2026-08-22 11:40:42 -05:00
Josh Hawkins f7afec3aa7 Enable PTZ control setup in the Add Camera Wizard (#23444)
* add ptz controls to camera via wizard when onvif has already been probed

* i18n

* add e2e test

* backend add and remove subscriber

* tweaks

* turn on switch by default if pan and/or tilt capability is available

* fix test
2026-08-22 11:40:42 -05:00
Josh Hawkins d67304a84d Add sub stream recording with adaptive quality playback (#24009)
* add sub stream recording with adaptive quality playback

Optionally record a second, lower bitrate stream alongside the main
recording stream via a `record_sub` input role and `record.sub` config block, with its own retention windows.
Recordings rows now carry the stream type plus the media details needed to serve both streams from one manifest: video codec, audio presence, audio codec and rate, and a record-time keyframe index.

Playback resolves coverage across both streams and merges them into a single VOD sequence, falling back to a discontinuity manifest with per-clip init segments when the media signatures differ. The player exposes a quality selector, and an auto governor picks the stream from stall time, bandwidth, codec support, and the save-data hint.

* fix tests and i18n
2026-08-22 11:40:42 -05:00
Josh Hawkins 8de6216c61 stop creating a config subscriber per capture thread (#24002) 2026-08-22 11:40:42 -05:00
Josh Hawkins 80e0bbeda6 Guard lookups when adding/deleting cameras at runtime (#23994)
* Guard object processor queue handlers against unknown cameras

* Skip embeddings post processing for removed cameras

* End review segments for removed cameras

* Drop queued autotracker moves for removed cameras

* Release tracked event thumbnails when skipping a removed camera

* Add locked accessors for camera states

* Read camera states through the processor accessors

* Guard output and recording paths against cameras not yet known

* Resolve camera state once in ONVIF, notification, and transcription paths
2026-08-22 11:40:42 -05:00
Ersa Oktavian RamadanandJosh Hawkins 4147d01374 Refactor Birdseye activity types as composable booleans (#23940)
* Add combined motion and object Birdseye mode

Add a motion_objects mode that keeps Birdseye active when motion is detected or a confirmed tracked object is present, including stationary objects.

Wire the mode through configuration, runtime commands, API schemas, documentation, and UI labels. Exclude false-positive trackers and add regression coverage for Birdseye activation and MQTT validation.

* Refactor Birdseye activity types as booleans

Replace combination-specific Birdseye modes with composable boolean activity types for motion, active objects, stationary objects, and continuous display.

Preserve legacy single-mode configuration and MQTT inputs, support canonical comma-separated MQTT combinations, and allow scalar YAML values to be replaced by nested settings through the config API.

* Preserve OpenVINO config translations

Regenerate the configuration translations with the OpenVINO detector schema available so the unrelated production detector labels remain intact.

* Preserve partial Birdseye mode overrides

Allow an empty activity selection with a canonical NONE MQTT state so partial camera and profile overrides can disable inherited flags without failing validation.

Add regression coverage for camera and profile inheritance, document the NONE contract, and keep the generated schema fixture scoped to Birdseye.

* Address Birdseye activity review feedback

Move scalar mode compatibility into the 0.18-1 config migration and reject empty activity selections instead of publishing a NONE state.

Pass activity signals through a frozen dataclass, preserve existing active-object tracker behavior, and require confirmed stationary objects. Revert the generic YAML mutation and cover migration, inheritance, MQTT, and activation regressions.

* Move Birdseye migration to 0.19

Use the 0.19-0 configuration revision for converting scalar Birdseye modes to composable activity flags, and update the migration regression coverage accordingly.

* Remove Birdseye migration test

Drop the dedicated config migration test as requested during review while retaining the 0.19-0 migration implementation.
2026-08-22 11:40:42 -05:00
Josh Hawkins a9d09f8a81 Fix birdseye layout overlap with mixed landscape/portrait cameras (#22917)
* fix birdseye layout calculation

replace the two pass layout with a single pass pixel space algorithm

* add test
2026-08-22 11:40:42 -05:00
Nicolas MowenandJosh Hawkins fe14d4ef09 Don't require object type for parameter in categorized names tool 2026-08-22 11:40:42 -05:00
079bd802f2 Dynamically resolve Intel NPU (#23761)
* Add support for newer Intel NPU busy time counter

* Resolve Intel NPU device dynamically

---------

Co-authored-by: Filious Louis <1417132+fjlouis@users.noreply.github.com>
2026-08-22 11:40:42 -05:00
DoFabienandJosh Hawkins 163d3b865e Improve recording timeline and VOD query performance (#23862)
* Improve recording timeline and VOD query performance

* Add recording query boundary tests
2026-08-22 11:40:42 -05:00
Nicolas MowenandJosh Hawkins ca6d327f74 GenAI Chat Prompt Refinements (#23864)
* Prompt refactoring and optimization

* Update spec
2026-08-22 11:40:42 -05:00
Nicolas MowenandJosh Hawkins 8700227704 Update to 0.19 2026-08-22 11:40:41 -05:00
Nicolas MowenandGitHub ad79e666eb API Consistency / Security Fixes (#24057)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* Make review user read status consistent with other APIs

* Validate URLs for web push endpoint

* Validate the role for a custom viewer, rate limit password changing

* Cleanup
2026-08-22 11:08:24 -05:00
Nicolas MowenandGitHub fc79aeab5e Fix review summary report analysis creation to be scoped for users with full camera access only (#24056)
* Fix review summary analysis

* Add ability to scope based on full camera access
2026-08-22 11:06:01 -05:00
b1cdf1f76b Translated using Weblate (Norwegian Bokmål)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Norwegian Bokmål)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Norwegian Bokmål)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Norwegian Bokmål)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Norwegian Bokmål)

Currently translated at 100.0% (50 of 50 strings)

Translated using Weblate (Norwegian Bokmål)

Currently translated at 100.0% (1295 of 1295 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: OverTheHillsAndFarAway <prosjektx@users.noreply.hosted.weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-camera/nb_NO/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/nb_NO/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/nb_NO/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/nb_NO/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/nb_NO/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/nb_NO/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-camera
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
fc319f4223 Translated using Weblate (Chinese (Simplified Han script))
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Chinese (Simplified Han script))

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Chinese (Simplified Han script))

Currently translated at 100.0% (108 of 108 strings)

Co-authored-by: GuoQing Liu <842607283@qq.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/zh_Hans/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/zh_Hans/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/zh_Hans/
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-replay
2026-08-21 14:34:47 -05:00
bf35e90bc8 Translated using Weblate (Chinese (Traditional Han script))
Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Chinese (Traditional Han script))

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Chinese (Traditional Han script))

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Chinese (Traditional Han script))

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Chinese (Traditional Han script))

Currently translated at 100.0% (129 of 129 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Ryan He <koungho@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/zh_Hant/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/zh_Hant/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/zh_Hant/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/zh_Hant/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/zh_Hant/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
07abbd2c0a Translated using Weblate (Khmer (Central))
Currently translated at 0.5% (1 of 185 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 98.7% (1279 of 1295 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 0.8% (2 of 239 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 100.0% (6 of 6 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 100.0% (2 of 2 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 100.0% (2 of 2 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 1.3% (1 of 74 strings)

Translated using Weblate (Khmer (Central))

Currently translated at 100.0% (10 of 10 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: SeyhaLite <sok123230@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/common/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-auth/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-filter/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-icons/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-input/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-recording/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/km/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-system/km/
Translation: Frigate NVR/common
Translation: Frigate NVR/components-auth
Translation: Frigate NVR/components-filter
Translation: Frigate NVR/components-icons
Translation: Frigate NVR/components-input
Translation: Frigate NVR/views-recording
Translation: Frigate NVR/views-settings
Translation: Frigate NVR/views-system
2026-08-21 14:34:47 -05:00
694d162071 Translated using Weblate (Korean)
Currently translated at 90.6% (117 of 129 strings)

Translated using Weblate (Korean)

Currently translated at 85.2% (426 of 500 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: ydavelee <ydavelee.work@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/ko/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/ko/
Translation: Frigate NVR/audio
Translation: Frigate NVR/objects
2026-08-21 14:34:47 -05:00
b1d9676638 Translated using Weblate (Persian)
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (141 of 141 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (185 of 185 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (86 of 86 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (86 of 86 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (74 of 74 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (239 of 239 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (500 of 500 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (45 of 45 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (62 of 62 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (54 of 54 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (23 of 23 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (25 of 25 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (141 of 141 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (185 of 185 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (100 of 100 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (86 of 86 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (145 of 145 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (129 of 129 strings)

Translated using Weblate (Persian)

Currently translated at 100.0% (239 of 239 strings)

Translated using Weblate (Persian)

Currently translated at 65.1% (71 of 109 strings)

Co-authored-by: Abdollah Ashjaa <abdollah.ashjaa@gmail.com>
Co-authored-by: Amir reza Irani ali poor <amir1376irani@yahoo.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: حمید ملک محمدی <hmmftg@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/common/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-filter/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-groups/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-validation/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-chat/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-classificationmodel/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-explore/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-exports/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-live/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-motionsearch/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/fa/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-system/fa/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/Config - Groups
Translation: Frigate NVR/Config - Validation
Translation: Frigate NVR/audio
Translation: Frigate NVR/common
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/components-filter
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-chat
Translation: Frigate NVR/views-classificationmodel
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-explore
Translation: Frigate NVR/views-exports
Translation: Frigate NVR/views-live
Translation: Frigate NVR/views-motionSearch
Translation: Frigate NVR/views-replay
Translation: Frigate NVR/views-settings
Translation: Frigate NVR/views-system
2026-08-21 14:34:47 -05:00
891a0df879 Translated using Weblate (Swedish)
Currently translated at 63.2% (506 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 62.2% (498 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 51.7% (670 of 1295 strings)

Translated using Weblate (Swedish)

Currently translated at 51.7% (670 of 1295 strings)

Translated using Weblate (Swedish)

Currently translated at 90.0% (54 of 60 strings)

Translated using Weblate (Swedish)

Currently translated at 100.0% (239 of 239 strings)

Translated using Weblate (Swedish)

Currently translated at 46.8% (375 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 95.7% (454 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 37.8% (303 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 69.8% (331 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 36.7% (294 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 67.9% (322 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Swedish)

Currently translated at 33.7% (270 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 62.2% (295 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 26.1% (209 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 48.7% (231 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 13.3% (107 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 26.1% (124 of 474 strings)

Translated using Weblate (Swedish)

Currently translated at 100.0% (26 of 26 strings)

Translated using Weblate (Swedish)

Currently translated at 100.0% (109 of 109 strings)

Translated using Weblate (Swedish)

Currently translated at 100.0% (501 of 501 strings)

Translated using Weblate (Swedish)

Currently translated at 99.8% (500 of 501 strings)

Translated using Weblate (Swedish)

Currently translated at 2.3% (19 of 800 strings)

Translated using Weblate (Swedish)

Currently translated at 5.6% (27 of 474 strings)

Co-authored-by: Fredrik B <fredrik@brannvall.nu>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Kristian Johansson <knmjohansson@gmail.com>
Co-authored-by: Mats Lojander <mats@lojander.com>
Co-authored-by: Samuel Åkesson <samuel.akesson@bolmso.se>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/common/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-player/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-facelibrary/sv/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/sv/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/audio
Translation: Frigate NVR/common
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/components-player
Translation: Frigate NVR/views-facelibrary
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
2d5845c770 Translated using Weblate (French)
Currently translated at 18.1% (145 of 800 strings)

Translated using Weblate (French)

Currently translated at 54.4% (258 of 474 strings)

Translated using Weblate (French)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (French)

Currently translated at 16.2% (130 of 800 strings)

Translated using Weblate (French)

Currently translated at 51.4% (244 of 474 strings)

Translated using Weblate (French)

Currently translated at 100.0% (26 of 26 strings)

Translated using Weblate (French)

Currently translated at 100.0% (109 of 109 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Jérémy MRPX <jeremy.marpaux@gmail.com>
Co-authored-by: Nathan Signouret <nathan.signouret@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/fr/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-player/fr/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/fr/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/fr/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/components-player
2026-08-21 14:34:47 -05:00
612a7cb871 Translated using Weblate (Spanish)
Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (141 of 141 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (145 of 145 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (109 of 109 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (129 of 129 strings)

Translated using Weblate (Spanish)

Currently translated at 100.0% (1295 of 1295 strings)

Co-authored-by: David Cambra <cambrafontan.david@gmail.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-classificationmodel/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-explore/es/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/es/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-classificationmodel
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-explore
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
101e5d0e98 Translated using Weblate (Nepali)
Currently translated at 4.8% (24 of 500 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Milan Thapa <hello@milanthapa.me>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/ne/
Translation: Frigate NVR/audio
2026-08-21 14:34:47 -05:00
bcff29c35b Translated using Weblate (Dutch)
Currently translated at 75.8% (47 of 62 strings)

Translated using Weblate (Dutch)

Currently translated at 97.0% (776 of 800 strings)

Translated using Weblate (Dutch)

Currently translated at 84.8% (402 of 474 strings)

Translated using Weblate (Dutch)

Currently translated at 86.8% (1125 of 1295 strings)

Translated using Weblate (Dutch)

Currently translated at 83.5% (396 of 474 strings)

Translated using Weblate (Dutch)

Currently translated at 96.7% (774 of 800 strings)

Translated using Weblate (Dutch)

Currently translated at 83.1% (394 of 474 strings)

Translated using Weblate (Dutch)

Currently translated at 100.0% (109 of 109 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Patrick <github@derr.eu>
Co-authored-by: Wim Timmer <wc.timmer@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/nl/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/nl/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/nl/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-motionsearch/nl/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/nl/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-motionSearch
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
467404b410 Translated using Weblate (Arabic)
Currently translated at 38.5% (193 of 501 strings)

Translated using Weblate (Arabic)

Currently translated at 38.5% (193 of 501 strings)

Co-authored-by: Ahmed Marzouq <ahmed.marzouq.co@gmail.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Modar Soos <modarsoos@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/ar/
Translation: Frigate NVR/audio
2026-08-21 14:34:47 -05:00
767597967e Translated using Weblate (Italian)
Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (185 of 185 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (74 of 74 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (100 of 100 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (145 of 145 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (239 of 239 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (141 of 141 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (185 of 185 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (145 of 145 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (109 of 109 strings)

Translated using Weblate (Italian)

Currently translated at 99.2% (140 of 141 strings)

Translated using Weblate (Italian)

Currently translated at 94.0% (174 of 185 strings)

Translated using Weblate (Italian)

Currently translated at 99.6% (1291 of 1295 strings)

Translated using Weblate (Italian)

Currently translated at 98.5% (66 of 67 strings)

Translated using Weblate (Italian)

Currently translated at 99.7% (798 of 800 strings)

Translated using Weblate (Italian)

Currently translated at 92.9% (131 of 141 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (129 of 129 strings)

Translated using Weblate (Italian)

Currently translated at 85.5% (684 of 800 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Italian)

Currently translated at 74.1% (593 of 800 strings)

Translated using Weblate (Italian)

Currently translated at 99.7% (473 of 474 strings)

Translated using Weblate (Italian)

Currently translated at 100.0% (109 of 109 strings)

Co-authored-by: Filippo-riccardo Franzin (filippo franzin) <filric01@gmail.com>
Co-authored-by: Gringo <ita.translations@tiscali.it>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Nton <arlatalpa@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/common/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-filter/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-classificationmodel/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-explore/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-live/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/it/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-system/it/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/common
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/components-filter
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-classificationmodel
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-explore
Translation: Frigate NVR/views-live
Translation: Frigate NVR/views-replay
Translation: Frigate NVR/views-settings
Translation: Frigate NVR/views-system
2026-08-21 14:34:47 -05:00
57b8206e86 Translated using Weblate (Malay)
Currently translated at 9.7% (49 of 501 strings)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Added translation using Weblate (Malay)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Nazri Masnan <nazrimasnan@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/ms/
Translation: Frigate NVR/audio
2026-08-21 14:34:47 -05:00
86b828f52e Translated using Weblate (Polish)
Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Polish)

Currently translated at 17.7% (142 of 800 strings)

Translated using Weblate (Polish)

Currently translated at 17.7% (142 of 800 strings)

Translated using Weblate (Polish)

Currently translated at 46.6% (221 of 474 strings)

Translated using Weblate (Polish)

Currently translated at 46.6% (221 of 474 strings)

Co-authored-by: Artur <wy66m6xm@anonaddy.me>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: J P <jpoloczek24@gmail.com>
Co-authored-by: Kamil Cybułka <kamil.cybulka@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/pl/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/pl/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/pl/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/views-events
2026-08-21 14:34:47 -05:00
4b39edf983 Translated using Weblate (Hungarian)
Currently translated at 51.3% (56 of 109 strings)

Translated using Weblate (Hungarian)

Currently translated at 100.0% (50 of 50 strings)

Translated using Weblate (Hungarian)

Currently translated at 91.2% (457 of 501 strings)

Translated using Weblate (Hungarian)

Currently translated at 100.0% (239 of 239 strings)

Co-authored-by: Dávid Attila Balog <davidattilabalog@gmail.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/hu/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/common/hu/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-camera/hu/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/hu/
Translation: Frigate NVR/audio
Translation: Frigate NVR/common
Translation: Frigate NVR/components-camera
Translation: Frigate NVR/components-dialog
2026-08-21 14:34:47 -05:00
06f5229567 Translated using Weblate (Catalan)
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Catalan)

Currently translated at 100.0% (108 of 108 strings)

Co-authored-by: Eduardo Pastor Fernández <123eduardoneko123@gmail.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/ca/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/ca/
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-replay
2026-08-21 14:34:47 -05:00
90a33f504c Translated using Weblate (Japanese)
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Japanese)

Currently translated at 100.0% (129 of 129 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: alpha <alphamob0@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/ja/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/ja/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/ja/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/ja/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/ja/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/ja/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/ja/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-replay
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
d0766aa3ee Translated using Weblate (Ukrainian)
Currently translated at 2.8% (23 of 800 strings)

Translated using Weblate (Ukrainian)

Currently translated at 6.9% (33 of 474 strings)

Translated using Weblate (Ukrainian)

Currently translated at 100.0% (26 of 26 strings)

Translated using Weblate (Ukrainian)

Currently translated at 99.0% (108 of 109 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Nikita Mikheiev <nikimihiki@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/uk/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-player/uk/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/uk/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/uk/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/components-player
2026-08-21 14:34:47 -05:00
76a5e00bd5 Translated using Weblate (Romanian)
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Romanian)

Currently translated at 100.0% (108 of 108 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: lukasig <lukasig@hotmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/ro/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/ro/
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-replay
2026-08-21 14:34:47 -05:00
b914f32cea Translated using Weblate (Russian)
Currently translated at 100.0% (45 of 45 strings)

Translated using Weblate (Russian)

Currently translated at 100.0% (62 of 62 strings)

Translated using Weblate (Russian)

Currently translated at 100.0% (54 of 54 strings)

Translated using Weblate (Russian)

Currently translated at 99.7% (798 of 800 strings)

Translated using Weblate (Russian)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (Russian)

Currently translated at 100.0% (185 of 185 strings)

Translated using Weblate (Russian)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (Russian)

Currently translated at 100.0% (86 of 86 strings)

Translated using Weblate (Russian)

Currently translated at 64.1% (43 of 67 strings)

Translated using Weblate (Russian)

Currently translated at 77.7% (84 of 108 strings)

Co-authored-by: Artem Vladimirov <artyomka71@mail.ru>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-chat/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-exports/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-motionsearch/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/ru/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-system/ru/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-chat
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-exports
Translation: Frigate NVR/views-motionSearch
Translation: Frigate NVR/views-replay
Translation: Frigate NVR/views-settings
Translation: Frigate NVR/views-system
2026-08-21 14:34:47 -05:00
48acba8dab Translated using Weblate (Estonian)
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (Estonian)

Currently translated at 100.0% (108 of 108 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Priit Jõerüüt <jrthwlate@users.noreply.hosted.weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/et/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/et/
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/views-replay
2026-08-21 14:34:47 -05:00
c605295483 Translated using Weblate (Danish)
Currently translated at 4.8% (3 of 62 strings)

Translated using Weblate (Danish)

Currently translated at 0.1% (1 of 800 strings)

Translated using Weblate (Danish)

Currently translated at 85.1% (120 of 141 strings)

Translated using Weblate (Danish)

Currently translated at 1.6% (21 of 1295 strings)

Translated using Weblate (Danish)

Currently translated at 26.8% (18 of 67 strings)

Translated using Weblate (Danish)

Currently translated at 68.6% (344 of 501 strings)

Co-authored-by: Anders Fosgerau <afosgerau@gmail.com>
Co-authored-by: Hosted Weblate <hosted@weblate.org>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/audio/da/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/da/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-classificationmodel/da/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/da/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-motionsearch/da/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/da/
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/audio
Translation: Frigate NVR/views-classificationmodel
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-motionSearch
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
ad35bf49f7 Translated using Weblate (German)
Currently translated at 100.0% (46 of 46 strings)

Translated using Weblate (German)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (German)

Currently translated at 100.0% (800 of 800 strings)

Translated using Weblate (German)

Currently translated at 100.0% (474 of 474 strings)

Translated using Weblate (German)

Currently translated at 100.0% (141 of 141 strings)

Translated using Weblate (German)

Currently translated at 100.0% (1295 of 1295 strings)

Translated using Weblate (German)

Currently translated at 100.0% (129 of 129 strings)

Translated using Weblate (German)

Currently translated at 100.0% (60 of 60 strings)

Translated using Weblate (German)

Currently translated at 100.0% (67 of 67 strings)

Translated using Weblate (German)

Currently translated at 100.0% (109 of 109 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Viktor Stier <viktor-stier@gmx.de>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-classificationmodel/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-events/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-facelibrary/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-replay/de/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/de/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-classificationmodel
Translation: Frigate NVR/views-events
Translation: Frigate NVR/views-facelibrary
Translation: Frigate NVR/views-replay
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
000bf4a03b Translated using Weblate (Portuguese (Brazil))
Currently translated at 47.2% (378 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 85.0% (403 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 46.8% (375 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 83.7% (397 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 46.5% (372 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 80.8% (383 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 46.3% (371 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 79.7% (378 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 44.3% (355 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 76.1% (361 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 44.2% (354 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 75.9% (360 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 43.2% (346 of 800 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 74.2% (352 of 474 strings)

Translated using Weblate (Portuguese (Brazil))

Currently translated at 100.0% (108 of 108 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: Klenner Martins Barros <klenne.al@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/pt_BR/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/pt_BR/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/pt_BR/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
2026-08-21 14:34:47 -05:00
d2982bd144 Added translation using Weblate (Tamil)
Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Added translation using Weblate (Tamil)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: தமிழ்நேரம் <tamilneram247@gmail.com>
2026-08-21 14:34:47 -05:00
2cd53ccdfe Translated using Weblate (Lithuanian)
Currently translated at 100.0% (23 of 23 strings)

Translated using Weblate (Lithuanian)

Currently translated at 0.7% (6 of 800 strings)

Translated using Weblate (Lithuanian)

Currently translated at 1.2% (6 of 474 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (141 of 141 strings)

Translated using Weblate (Lithuanian)

Currently translated at 42.4% (550 of 1295 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (6 of 6 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (100 of 100 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (60 of 60 strings)

Translated using Weblate (Lithuanian)

Currently translated at 58.1% (50 of 86 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (145 of 145 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (26 of 26 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (108 of 108 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (129 of 129 strings)

Translated using Weblate (Lithuanian)

Currently translated at 100.0% (239 of 239 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: MaBeniu <runnerm@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/common/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-player/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-validation/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/objects/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-classificationmodel/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-explore/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-exports/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-facelibrary/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-live/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-recording/lt/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/views-settings/lt/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/Config - Validation
Translation: Frigate NVR/common
Translation: Frigate NVR/components-dialog
Translation: Frigate NVR/components-player
Translation: Frigate NVR/objects
Translation: Frigate NVR/views-classificationmodel
Translation: Frigate NVR/views-explore
Translation: Frigate NVR/views-exports
Translation: Frigate NVR/views-facelibrary
Translation: Frigate NVR/views-live
Translation: Frigate NVR/views-recording
Translation: Frigate NVR/views-settings
2026-08-21 14:34:47 -05:00
2ba33e227c Translated using Weblate (Turkish)
Currently translated at 7.8% (63 of 800 strings)

Translated using Weblate (Turkish)

Currently translated at 14.9% (71 of 474 strings)

Translated using Weblate (Turkish)

Currently translated at 98.1% (106 of 108 strings)

Co-authored-by: Hosted Weblate <hosted@weblate.org>
Co-authored-by: furkan geldi <furkangeldi@gmail.com>
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/components-dialog/tr/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-cameras/tr/
Translate-URL: https://hosted.weblate.org/projects/frigate-nvr/config-global/tr/
Translation: Frigate NVR/Config - Cameras
Translation: Frigate NVR/Config - Global
Translation: Frigate NVR/components-dialog
2026-08-21 14:34:47 -05:00
Josh HawkinsandGitHub 036bae4ea9 Return a specific 404 when starting a debug replay with no recordings in range (#24024)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
2026-08-18 10:08:52 -05:00
dtigheandGitHub 8384a8c5b3 Fix Gemini tool calling on 3.6+ by using documented function response role (#24013)
Gemini 3.6 and newer reject role="function" on the function response
Content with 400 INVALID_ARGUMENT, breaking any chat query that triggers
a tool call. The tool call itself succeeds; only the hand-back to the
model fails, and because the error surfaces mid-stream the request still
returns HTTP 200, so it is easy to miss.

Google's function calling documentation specifies role="user" for
returning function results:

    contents.append(response.candidates[0].content)
    contents.append(types.Content(role="user", parts=[function_response_part]))

https://ai.google.dev/gemini-api/docs/generate-content/function-calling

Verified with my local setup.
2026-08-18 08:16:47 -06:00
Josh HawkinsandGitHub 77fc2ce174 Miscellaneous fixes (0.18 beta) (#24016)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* fix classification drawer closing instead of scrolling when list is long on mobile

* add qwen3.8 to genai docs

* add titles to more clearly separate model types
2026-08-18 07:01:22 -06:00
Josh HawkinsandGitHub 8425a76558 Miscellaneous fixes (0.18 beta) (#23993)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* subscribe to add in webpush

* add docs for detector cpu usage

* rebuild notification camera access when a camera is added at runtime

* document how frigate shows CPU usage metrics

* add faq about version key in config
2026-08-16 12:39:28 -06:00
Josh HawkinsandGitHub 11f8786459 sanitize user-supplied path components (#23990)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
sanitize_filename leaves ".." intact and collapses variants like "..:" and "..*" to "..", so filesystem paths built from face names, classification model/category names, image ids, and trigger data could escape their base directory. Route every such site through new frigate/util/path.py helpers (safe_join, sanitize_path_component, sanitize_contained_path), which reject traversal and verify containment.

Worst case was DELETE /classification/{name}, which rmtree'd /media/frigate and /config while returning 200.

Important to note that all affected endpoints already require admin permission, so this sould be considered hardening rather than fixing exploitable code.
2026-08-13 21:59:46 -05:00
Josh HawkinsandGitHub 812e5308a3 fix notification suspend state lost on page reload (#23989)
<camera>/notifications/suspended arrives as a string over the live connection but as a number in the camera_activity snapshot, and the truthiness guard dropped the numeric 0, so a camera with notifications off rendered as active after a reload. Normalize to a string and derive isSuspended instead of storing it.
2026-08-13 16:51:44 -06:00
Josh HawkinsandGitHub fd98977506 Categorize manual events as alerts when their label is an alert label (#23981)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* Categorize manual events as alerts when their label is an alert label

* tweak docs
2026-08-13 11:16:02 -06:00
LarosenandGitHub 6816050a46 fix(audio): correct sodeling typo to yodeling (#23946)
* fix(audio): correct sodeling typo to yodeling

Fixes a typo in audio-labelmap.txt where the yodeling class was
misspelled as "sodeling".

* fix(i18n): remove duplicate sodeling key in en audio.json

The en audio.json already contains a correct "yodeling" key. Remove
the duplicate/misspelled "sodeling" entry to avoid ambiguity.
2026-08-13 07:02:38 -05:00
Josh HawkinsandGitHub c70a0802b8 filter dedicated LPR plates before creating the event (#23977) 2026-08-13 05:44:31 -06:00
Josh HawkinsandGitHub aff9799451 Don't require a restart to enable GenAI descriptions (#23964)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* create GenAI post processors when a camera enables GenAI at runtime

* fix types
2026-08-12 08:55:34 -05:00
Josh HawkinsandGitHub c75611b4df Multi-export UI fixes (#23959)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* multi export fixes

* i18n

* new tests
2026-08-11 10:11:47 -06:00
Josh HawkinsandGitHub 0735a8ac75 Docs updates (#23947)
* misc docs updates

* add warning about proxies to 5000 for notifications
2026-08-10 15:54:41 -06:00
Josh HawkinsandGitHub 2599795ab0 add faq to notifications docs (#23939) 2026-08-08 11:12:13 -06:00
464 changed files with 31731 additions and 6249 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
default_target: local default_target: local
COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1) COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1)
VERSION = 0.18.0 VERSION = 0.19.0
IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate
GITHUB_REF_NAME ?= $(shell git rev-parse --abbrev-ref HEAD) GITHUB_REF_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
BOARDS= #Initialized empty BOARDS= #Initialized empty
+1 -1
View File
@@ -24,7 +24,7 @@ yell
sigh sigh
singing singing
choir choir
sodeling yodeling
chant chant
mantra mantra
child_singing child_singing
@@ -3,13 +3,12 @@
import json import json
import os import os
import sys import sys
from pathlib import Path
from typing import Any from typing import Any
from ruamel.yaml import YAML from ruamel.yaml import YAML
sys.path.insert(0, "/opt/frigate") sys.path.insert(0, "/opt/frigate")
from frigate.config.env import substitute_frigate_vars from frigate.config.env import apply_config_env_vars, substitute_frigate_vars
from frigate.const import ( from frigate.const import (
BIRDSEYE_PIPE, BIRDSEYE_PIPE,
LIBAVFORMAT_VERSION_MAJOR, LIBAVFORMAT_VERSION_MAJOR,
@@ -25,15 +24,6 @@ sys.path.remove("/opt/frigate")
yaml = YAML() yaml = YAML()
FRIGATE_ENV_VARS = {k: v for k, v in os.environ.items() if k.startswith("FRIGATE_")}
# read docker secret files as env vars too
if os.path.isdir("/run/secrets"):
for secret_file in os.listdir("/run/secrets"):
if secret_file.startswith("FRIGATE_"):
FRIGATE_ENV_VARS[secret_file] = (
Path(os.path.join("/run/secrets", secret_file)).read_text().strip()
)
config_file = find_config_file() config_file = find_config_file()
try: try:
@@ -47,6 +37,20 @@ try:
except FileNotFoundError: except FileNotFoundError:
config: dict[str, Any] = {} config: dict[str, Any] = {}
# No validator runs here, so install environment_vars ourselves. FRIGATE_
# names only: anything else lands in os.environ, where the exec gate reads
# GO2RTC_ALLOW_ARBITRARY_EXEC.
config_env_vars = config.get("environment_vars")
apply_config_env_vars(
{
key: value
for key, value in config_env_vars.items()
if str(key).startswith("FRIGATE_")
}
if isinstance(config_env_vars, dict)
else {}
)
go2rtc_config: dict[str, Any] = config.get("go2rtc", {}) go2rtc_config: dict[str, Any] = config.get("go2rtc", {})
# Need to enable CORS for go2rtc so the frigate integration / card work automatically # Need to enable CORS for go2rtc so the frigate integration / card work automatically
@@ -113,7 +117,7 @@ for name in list(go2rtc_config.get("streams", {})):
if isinstance(stream, str): if isinstance(stream, str):
try: try:
formatted_stream = stream.format(**FRIGATE_ENV_VARS) formatted_stream = substitute_frigate_vars(stream)
if is_restricted_go2rtc_source(formatted_stream): if is_restricted_go2rtc_source(formatted_stream):
print( print(
f"[ERROR] Stream '{name}' uses a restricted source (echo/expr/exec) which is disabled by default for security. " f"[ERROR] Stream '{name}' uses a restricted source (echo/expr/exec) which is disabled by default for security. "
@@ -122,7 +126,7 @@ for name in list(go2rtc_config.get("streams", {})):
del go2rtc_config["streams"][name] del go2rtc_config["streams"][name]
continue continue
go2rtc_config["streams"][name] = formatted_stream go2rtc_config["streams"][name] = formatted_stream
except KeyError as e: except ValueError as e:
print( print(
"[ERROR] Invalid substitution found, see https://docs.frigate.video/configuration/restream#advanced-restream-configurations for more info." "[ERROR] Invalid substitution found, see https://docs.frigate.video/configuration/restream#advanced-restream-configurations for more info."
) )
@@ -132,7 +136,7 @@ for name in list(go2rtc_config.get("streams", {})):
filtered_streams = [] filtered_streams = []
for i, stream_item in enumerate(stream): for i, stream_item in enumerate(stream):
try: try:
formatted_stream = stream_item.format(**FRIGATE_ENV_VARS) formatted_stream = substitute_frigate_vars(stream_item)
if is_restricted_go2rtc_source(formatted_stream): if is_restricted_go2rtc_source(formatted_stream):
print( print(
f"[ERROR] Stream '{name}' item {i + 1} uses a restricted source (echo/expr/exec) which is disabled by default for security. " f"[ERROR] Stream '{name}' item {i + 1} uses a restricted source (echo/expr/exec) which is disabled by default for security. "
@@ -141,7 +145,7 @@ for name in list(go2rtc_config.get("streams", {})):
continue continue
filtered_streams.append(formatted_stream) filtered_streams.append(formatted_stream)
except KeyError as e: except ValueError as e:
print( print(
"[ERROR] Invalid substitution found, see https://docs.frigate.video/configuration/restream#advanced-restream-configurations for more info." "[ERROR] Invalid substitution found, see https://docs.frigate.video/configuration/restream#advanced-restream-configurations for more info."
) )
@@ -75,6 +75,12 @@ http {
vod_align_segments_to_key_frames on; vod_align_segments_to_key_frames on;
vod_manifest_segment_durations_mode accurate; vod_manifest_segment_durations_mode accurate;
vod_ignore_edit_list on; vod_ignore_edit_list on;
# short leading segments at each playlist start; sources start at
# the seek target, so the ladder applies to every seek. Only
# effective when clips declare real keyFrameDurations
vod_bootstrap_segment_durations 1000;
vod_bootstrap_segment_durations 2000;
vod_bootstrap_segment_durations 4000;
vod_segment_duration 10000; vod_segment_duration 10000;
# MPEG-TS settings (not used when fMP4 is enabled, kept for reference) # MPEG-TS settings (not used when fMP4 is enabled, kept for reference)
File diff suppressed because it is too large Load Diff
+102 -53
View File
@@ -56,17 +56,6 @@ mqtt:
# 2 = exactly once # 2 = exactly once
qos: 0 qos: 0
# Optional: Detectors configuration. Defaults to a single CPU detector
detectors:
# Required: name of the detector
detector_name:
# Required: type of the detector
# Frigate provides many types, see https://docs.frigate.video/configuration/object_detectors for more details (default: shown below)
# Additional detector types can also be plugged in.
# Detectors may require additional configuration.
# Refer to the Detectors configuration page for more information.
type: cpu
# Optional: Database configuration # Optional: Database configuration
database: database:
# The path to store the SQLite DB (default: shown below) # The path to store the SQLite DB (default: shown below)
@@ -157,44 +146,56 @@ auth:
- front_door - front_door
- back_yard - back_yard
# Optional: model modifications # Optional: object detection models. Defaults to a single model on a CPU detector.
# NOTE: The default values are for the EdgeTPU detector. # NOTE: The default values are for the EdgeTPU detector.
# Other detectors will require the model config to be set. # Other detectors will require the model config to be set.
model: models:
# Required: path to the model. Frigate+ models use plus://<model_id> (default: automatic based on detector) # Optional: the camera environment this model is for (default: shown below)
path: /edgetpu_model.tflite # Cameras select a model by setting detect -> scene to a matching value, and
# Required: path to the labelmap (default: shown below) # a model with a scene of all is used by any camera that does not set one.
labelmap_path: /labelmap.txt # Valid values are all, indoor, outdoor, indoor_thermal, outdoor_thermal
# Required: Object detection model input width (default: shown below) - scene: all
width: 320 # Required: hardware this model runs on, as <detector> or <detector>:<device>
# Required: Object detection model input height (default: shown below) # See https://docs.frigate.video/configuration/object_detectors for the
height: 320 # detectors available and the devices each one accepts. All of a model's
# Required: Object detection model input colorspace # devices must use the same detector. Listing the same device more than once
# Valid values are rgb, bgr, or yuv. (default: shown below) # runs additional inference processes on it.
input_pixel_format: rgb devices:
# Required: Object detection model input tensor format - edgetpu:pci:0
# Valid values are nhwc, nchw, hwnc, or hwcn (default: shown below) # Required: path to the model. Frigate+ models use plus://<model_id> (default: automatic based on detector)
input_tensor: nhwc path: /edgetpu_model.tflite
# Optional: Data type of the model input tensor # Required: path to the labelmap (default: shown below)
# Valid values are float, float_denorm, or int (default: shown below) labelmap_path: /labelmap.txt
input_dtype: int # Required: Object detection model input width (default: shown below)
# Required: Object detection model architecture, used by detectors that support more width: 320
# than one model type (openvino, onnx, rknn, memryx, axengine, synaptics, and others) # Required: Object detection model input height (default: shown below)
# Valid values are ssd, yolox, yolonas, yolo-generic, rfdetr, dfine (default: shown below) height: 320
model_type: ssd # Required: Object detection model input colorspace
# Required: Label name modifications. These are merged into the standard labelmap. # Valid values are rgb, bgr, or yuv. (default: shown below)
labelmap: input_pixel_format: rgb
2: vehicle # Required: Object detection model input tensor format
# Optional: Map of object labels to their attribute labels (default: depends on model) # Valid values are nhwc, nchw, hwnc, or hwcn (default: shown below)
attributes_map: input_tensor: nhwc
person: # Optional: Data type of the model input tensor
- amazon # Valid values are float, float_denorm, or int (default: shown below)
- face input_dtype: int
car: # Required: Object detection model architecture, used by detectors that support more
- amazon # than one model type (openvino, onnx, rknn, memryx, axengine, synaptics, and others)
- fedex # Valid values are ssd, yolox, yolonas, yolo-generic, rfdetr, dfine (default: shown below)
- license_plate model_type: ssd
- ups # Required: Label name modifications. These are merged into the standard labelmap.
labelmap:
2: vehicle
# Optional: Map of object labels to their attribute labels (default: depends on model)
attributes_map:
person:
- amazon
- face
car:
- amazon
- fedex
- license_plate
- ups
# Optional: Audio Events Configuration # Optional: Audio Events Configuration
# NOTE: Can be overridden at the camera level # NOTE: Can be overridden at the camera level
@@ -217,6 +218,8 @@ audio:
- fire_alarm - fire_alarm
- speech - speech
- yell - yell
# Optional: Audio label name modifications. These are merged into the standard audio labelmap.
labelmap: {}
# Optional: Filters to configure detection. # Optional: Filters to configure detection.
filters: filters:
# Label that matches label in listen config. # Label that matches label in listen config.
@@ -251,11 +254,15 @@ birdseye:
# Optional: Encoding quality of the mpeg1 feed (default: shown below) # Optional: Encoding quality of the mpeg1 feed (default: shown below)
# 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources. # 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources.
quality: 8 quality: 8
# Optional: Mode of the view. Available options are: objects, motion, and continuous # Optional: Activity types that include cameras in Birdseye (default: shown below)
# objects - cameras are included if they have had a tracked object within the last 30 seconds # Multiple activity types can be listed at the same time.
# motion - cameras are included if motion was detected in the last 30 seconds # continuous: all cameras are included always
# continuous - all cameras are included always # motion: included if motion was detected within the inactivity threshold
mode: objects # all_objects: included if a tracked object was present within the inactivity threshold
# alerts: included while an alert review item is in progress
# detections: included while a detection review item is in progress
modes:
- all_objects
# Optional: Threshold for camera activity to stop showing camera (default: shown below) # Optional: Threshold for camera activity to stop showing camera (default: shown below)
inactivity_threshold: 30 inactivity_threshold: 30
# Optional: Configure the birdseye layout # Optional: Configure the birdseye layout
@@ -287,6 +294,8 @@ ffmpeg:
detect: -threads 2 -f rawvideo -pix_fmt yuv420p detect: -threads 2 -f rawvideo -pix_fmt yuv420p
# Optional: output args for record streams (default: shown below) # Optional: output args for record streams (default: shown below)
record: preset-record-generic record: preset-record-generic
# Optional: output args for sub stream record streams (default: the record output args above)
# record_sub: preset-record-generic
# Optional: Time in seconds to wait before ffmpeg retries connecting to the camera. (default: shown below) # Optional: Time in seconds to wait before ffmpeg retries connecting to the camera. (default: shown below)
# If set too low, frigate will retry a connection to the camera's stream too frequently, using up the limited streams some cameras can allow at once # If set too low, frigate will retry a connection to the camera's stream too frequently, using up the limited streams some cameras can allow at once
# If set too high, then if a ffmpeg crash or camera stream timeout occurs, you could potentially lose up to a maximum of retry_interval second(s) of footage # If set too high, then if a ffmpeg crash or camera stream timeout occurs, you could potentially lose up to a maximum of retry_interval second(s) of footage
@@ -306,6 +315,10 @@ detect:
width: 1280 width: 1280
# Optional: height of the frame for the input with the detect role (default: use native stream resolution) # Optional: height of the frame for the input with the detect role (default: use native stream resolution)
height: 720 height: 720
# Optional: the environment this camera looks at, which picks the model it runs on
# (default: the model with a scene of all)
# Valid values are all, indoor, outdoor, indoor_thermal, outdoor_thermal
scene: outdoor
# Optional: desired fps for your camera for the input with the detect role (default: shown below) # Optional: desired fps for your camera for the input with the detect role (default: shown below)
# NOTE: Recommended value of 5. Ideally, try and reduce your FPS on the camera. # NOTE: Recommended value of 5. Ideally, try and reduce your FPS on the camera.
fps: 5 fps: 5
@@ -637,6 +650,42 @@ record:
# For example, if the camera retain mode is "motion", the segments without motion are # For example, if the camera retain mode is "motion", the segments without motion are
# never stored, so setting the mode to "all" here won't bring them back. # never stored, so setting the mode to "all" here won't bring them back.
mode: motion mode: motion
# Optional: Sub stream recording settings
# Records a second, lower quality stream for quality selection during playback
# and extended low quality retention. Requires the record_sub role to be assigned
# to one of the camera's inputs.
sub:
# Optional: Enable sub stream recording (default: shown below)
# NOTE: Recording must also be enabled for sub stream recording to run.
enabled: False
# Optional: Continuous retention settings for sub stream recordings
continuous:
# Optional: Number of days to retain sub stream recordings regardless of tracked objects or motion (default: shown below)
days: 0
# Optional: Motion retention settings for sub stream recordings
motion:
# Optional: Number of days to retain sub stream recordings triggered by motion (default: shown below)
days: 0
# Optional: Retention settings for sub stream recordings of alerts
# NOTE: Pre and post capture windows are taken from the main alerts config above.
alerts:
# Required: Retention days (default: shown below)
days: 10
# Optional: Mode for retention. (default: shown below)
# all - save all sub stream recording segments for alerts regardless of activity
# motion - save all sub stream recording segments for alerts with any detected motion
# active_objects - save all sub stream recording segments for alerts with active/moving objects
mode: motion
# Optional: Retention settings for sub stream recordings of detections
# NOTE: Pre and post capture windows are taken from the main detections config above.
detections:
# Required: Retention days (default: shown below)
days: 10
# Optional: Mode for retention. (default: shown below)
# all - save all sub stream recording segments for detections regardless of activity
# motion - save all sub stream recording segments for detections with any detected motion
# active_objects - save all sub stream recording segments for detections with active/moving objects
mode: motion
# Optional: Configuration for the snapshots written to the clips directory for each tracked object # Optional: Configuration for the snapshots written to the clips directory for each tracked object
# Timestamp, bounding_box, crop and height settings are applied by default to API requests for snapshots. # Timestamp, bounding_box, crop and height settings are applied by default to API requests for snapshots.
@@ -888,7 +937,7 @@ cameras:
# Required: the path to the stream # Required: the path to the stream
# NOTE: path may include environment variables or docker secrets, which must begin with 'FRIGATE_' and be referenced in {} # NOTE: path may include environment variables or docker secrets, which must begin with 'FRIGATE_' and be referenced in {}
- path: rtsp://viewer:{FRIGATE_RTSP_PASSWORD}@10.0.10.10:554/cam/realmonitor?channel=1&subtype=2 - path: rtsp://viewer:{FRIGATE_RTSP_PASSWORD}@10.0.10.10:554/cam/realmonitor?channel=1&subtype=2
# Required: list of roles for this stream. valid values are: audio,detect,record # Required: list of roles for this stream. valid values are: audio,detect,record,record_sub
# NOTICE: In addition to assigning the audio, detect, and record roles # NOTICE: In addition to assigning the audio, detect, and record roles
# they must also be enabled in the camera config. # they must also be enabled in the camera config.
roles: roles:
+46 -33
View File
@@ -63,15 +63,9 @@ go2rtc:
### `environment_vars` ### `environment_vars`
This section can be used to set environment variables for those unable to modify the environment of the container, like within Home Assistant OS. Docker users should set environment variables in their `docker run` command (`-e FRIGATE_MQTT_PASSWORD=secret`) or `docker-compose.yml` file (`environment:` section) instead. Note that values set here are stored in plain text in your config file, so if the goal is to keep credentials out of your configuration, use Docker environment variables or Docker secrets instead. This section sets environment variables in the Frigate process for those unable to modify the environment of the container, like within Home Assistant OS. It's meant for process settings such as `LIBVA_DRIVER_NAME` or the TensorFlow thread counts below. Docker users should set environment variables in their `docker run` command (`-e LIBVA_DRIVER_NAME=i965`) or `docker-compose.yml` file (`environment:` section) instead. Values set here are stored in plain text in your config file, so credentials belong in `secrets.yaml`, Docker environment variables, or Docker secrets instead.
Variables prefixed with `FRIGATE_` can be referenced in config fields that support environment variable substitution (such as MQTT host and credentials, camera stream URLs, and ONVIF host and credentials) using the `{FRIGATE_VARIABLE_NAME}` syntax. Names prefixed with `FRIGATE_` set here also take part in `{FRIGATE_VARIABLE_NAME}` substitution (see [below](#substitution-sources-and-precedence)), but `secrets.yaml` is the better home for them.
:::note
The `go2rtc` section is an exception. go2rtc runs as a separate process, so its stream definitions can only be substituted with variables that exist in the container's environment (set via Docker `-e`, the `environment:` section of `docker-compose.yml`, or Docker secrets). Variables defined in the `environment_vars` block above are not available to go2rtc streams. Home Assistant app users, who cannot set container environment variables, must instead put credentials directly in their go2rtc stream URLs.
:::
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
@@ -80,23 +74,17 @@ Navigate to <NavPath path="Settings > System > Environment variables" /> to add
| Field | Description | | Field | Description |
| ----------------- | --------------------------------------------------------- | | ----------------- | --------------------------------------------------------- |
| **Variable name** | The environment variable name (e.g., `FRIGATE_MQTT_USER`) | | **Variable name** | The environment variable name (e.g., `LIBVA_DRIVER_NAME`) |
| **Value** | The value for the variable | | **Value** | The value for the variable |
Variables defined here can be referenced elsewhere in your configuration using the `{FRIGATE_VARIABLE_NAME}` syntax. Names prefixed with `FRIGATE_` can also be referenced elsewhere in your configuration using the `{FRIGATE_VARIABLE_NAME}` syntax.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
environment_vars: environment_vars:
FRIGATE_MQTT_USER: my_mqtt_user LIBVA_DRIVER_NAME: i965
FRIGATE_MQTT_PASSWORD: my_mqtt_password
mqtt:
host: "{FRIGATE_MQTT_HOST}"
user: "{FRIGATE_MQTT_USER}"
password: "{FRIGATE_MQTT_PASSWORD}"
``` ```
</TabItem> </TabItem>
@@ -130,6 +118,29 @@ environment_vars:
</TabItem> </TabItem>
</ConfigTabs> </ConfigTabs>
### `secrets.yaml`
A `secrets.yaml` file in your config directory is an additional source of `FRIGATE_` variables, for installs that can't set container environment variables or mount Docker secrets. It's a flat map of names to values, and it is never read or written by the Frigate UI:
```yaml
FRIGATE_CAM_USER: viewer
FRIGATE_CAM_PASS: "p@ss w0rd"
FRIGATE_MQTT_HOST: mqtt.internal.example
```
Names must start with `FRIGATE_`, and nesting is not supported. `secrets.yaml` feeds `{FRIGATE_VARIABLE_NAME}` substitution, so the handful of variables Frigate reads straight from the process environment, such as `FRIGATE_JWT_SECRET`, still need a container environment variable or a Docker secret.
### Substitution sources and precedence
The same `{FRIGATE_VARIABLE_NAME}` placeholder resolves from four sources, listed strongest first. When a name is defined in more than one, the highest wins and a warning is logged:
1. Docker secrets or the directory named by `CREDENTIALS_DIRECTORY` (defaults to `/run/secrets`)
2. Container environment variables
3. `secrets.yaml`
4. The `environment_vars` block above
Referencing a name that no source defines is a config validation error naming the field.
### `database` ### `database`
Tracked object and recording information is managed in a sqlite database at `/config/frigate.db`. If that database is deleted, recordings will be orphaned and will need to be cleaned up manually. They also won't show up in the Media Browser within Home Assistant. Tracked object and recording information is managed in a sqlite database at `/config/frigate.db`. If that database is deleted, recordings will be orphaned and will need to be cleaned up manually. They also won't show up in the Media Browser within Home Assistant.
@@ -177,7 +188,7 @@ Custom models may also require different input tensor formats. The colorspace co
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and open the **Custom Model** tab to configure the model path, dimensions, and input format. Navigate to <NavPath path="Settings > System > Detection models" /> and, on the model you want to change, open the **Custom Model** tab to configure the model path, dimensions, and input format.
| Field | Description | | Field | Description |
| --------------------------------------------- | ------------------------------------ | | --------------------------------------------- | ------------------------------------ |
@@ -192,12 +203,14 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and open
```yaml ```yaml
# Optional: model config # Optional: model config
model: models:
path: /path/to/model - devices:
width: 320 - openvino:GPU
height: 320 path: /path/to/model
input_tensor: "nhwc" width: 320
input_pixel_format: "bgr" height: 320
input_tensor: "nhwc"
input_pixel_format: "bgr"
``` ```
</TabItem> </TabItem>
@@ -214,15 +227,15 @@ If the labelmap is customized then the labels used for alerts will need to be ad
The labelmap can be customized to your needs. A common reason to do this is to combine multiple object types that are easily confused when you don't need to be as granular such as car/truck. By default, truck is renamed to car because they are often confused. You cannot add new object types, but you can change the names of existing objects in the model. The labelmap can be customized to your needs. A common reason to do this is to combine multiple object types that are easily confused when you don't need to be as granular such as car/truck. By default, truck is renamed to car because they are often confused. You cannot add new object types, but you can change the names of existing objects in the model.
```yaml ```yaml
model: models:
labelmap: - labelmap:
2: vehicle 2: vehicle
3: vehicle 3: vehicle
5: vehicle 5: vehicle
7: vehicle 7: vehicle
15: animal 15: animal
16: animal 16: animal
17: animal 17: animal
``` ```
Note that if you rename objects in the labelmap, you will also need to update your `objects -> track` list as well. Note that if you rename objects in the labelmap, you will also need to update your `objects -> track` list as well.
@@ -114,6 +114,30 @@ audio:
</TabItem> </TabItem>
</ConfigTabs> </ConfigTabs>
#### Grouping Audio Labels
Related audio classes can be grouped under one label by mapping their numeric
class IDs to the same name. Add the grouped name to `listen` and use it for any
corresponding filter:
```yaml
audio:
listen:
- dogs
labelmap:
69: dogs # dog
70: dogs # bark
75: dogs # whimper_dog
filters:
dogs:
threshold: 0.8
```
Class IDs are zero-based indices in
[`audio-labelmap.txt`](https://github.com/blakeblackshear/frigate/blob/dev/audio-labelmap.txt),
so each ID is one less than the displayed file line number.
Audio label mappings are separate from the object detector's `model.labelmap`.
### Common Audio Labels ### Common Audio Labels
The labelmap includes hundreds of sound types. The labels below are the ones most users may find practical, grouped by what they're typically used for. Use the exact label string from the left column in your `listen` config, or search for the label in the Frigate UI directly. The labelmap includes hundreds of sound types. The labels below are the ones most users may find practical, grouped by what they're typically used for. Use the exact label string from the left column in your `listen` config, or search for the label in the Frigate UI directly.
+23 -16
View File
@@ -18,13 +18,17 @@ Each camera tile in Birdseye is composed from the frames of the stream assigned
## Birdseye Behavior ## Birdseye Behavior
### Birdseye Modes ### Birdseye Activity Types
Birdseye offers different modes to customize which cameras show under which circumstances. Birdseye offers independent activity types that control when cameras are shown. Multiple activity types can be listed together.
- **continuous:** All cameras are always included - **continuous:** The camera is always included
- **motion:** Cameras that have detected motion within the last 30 seconds are included - **motion:** The camera is included when motion was detected within the last 30 seconds
- **objects:** Cameras that have tracked an active object within the last 30 seconds are included - **all_objects:** The camera is included when a tracked object is present, active or stationary
- **alerts:** The camera is included while an alert review item is in progress
- **detections:** The camera is included while a detection review item is in progress
`alerts` and `detections` follow the review item's own lifetime, so the camera is removed as soon as the review item ends. Which objects qualify for each is set in [review configuration](./review.md).
### Custom Birdseye Icon ### Custom Birdseye Icon
@@ -39,27 +43,29 @@ To include a camera in Birdseye view only for specific circumstances, or exclude
**Global settings:** Navigate to <NavPath path="Settings > System > Birdseye" /> to configure the default Birdseye behavior for all cameras. **Global settings:** Navigate to <NavPath path="Settings > System > Birdseye" /> to configure the default Birdseye behavior for all cameras.
**Per-camera overrides:** Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> to override the mode or disable Birdseye for a specific camera. **Per-camera overrides:** Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> to override the activity types or disable Birdseye for a specific camera.
| Field | Description | | Field | Description |
| ------------------- | ------------------------------------------------------------- | | ---------------------- | ---------------------------------------------------------- |
| **Enable Birdseye** | Whether this camera appears in Birdseye view | | **Enable Birdseye** | Whether this camera appears in Birdseye view |
| **Tracking mode** | When to show the camera: `continuous`, `motion`, or `objects` | | **Activity types** | Conditions that determine when to show the camera |
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml {8-10,12-14} ```yaml {10-12,15-16}
# Include all cameras by default in Birdseye view # Include all cameras by default in Birdseye view
birdseye: birdseye:
enabled: True enabled: True
mode: continuous modes:
- continuous
cameras: cameras:
front: front:
# Only include the "front" camera in Birdseye view when objects are detected # Only include the "front" camera in Birdseye view when an alert is in progress
birdseye: birdseye:
mode: objects modes:
- alerts
back: back:
# Exclude the "back" camera from Birdseye view # Exclude the "back" camera from Birdseye view
birdseye: birdseye:
@@ -71,7 +77,7 @@ cameras:
### Birdseye Inactivity ### Birdseye Inactivity
By default birdseye shows all cameras that have had the configured activity in the last 30 seconds. This threshold can be configured. By default birdseye shows all cameras that have had the configured activity in the last 30 seconds. This threshold can be configured, and applies to the `motion` and `all_objects` activity types only.
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
@@ -140,7 +146,8 @@ Navigate to <NavPath path="Settings > System > Birdseye" /> and in the **Camera
# Include all cameras by default in Birdseye view # Include all cameras by default in Birdseye view
birdseye: birdseye:
enabled: True enabled: True
mode: continuous modes:
- continuous
cameras: cameras:
front: front:
+25
View File
@@ -50,6 +50,31 @@ Connect each stream to get a live preview, an estimated bandwidth figure, and a
Other features, including [hardware acceleration](hardware_acceleration_video.md), [two way talk](/configuration/live#two-way-talk), and audio transcoding, is configured after the camera has been added. For camera model specific quirks, see the [camera specific](camera_specific.md) docs. Other features, including [hardware acceleration](hardware_acceleration_video.md), [two way talk](/configuration/live#two-way-talk), and audio transcoding, is configured after the camera has been added. For camera model specific quirks, see the [camera specific](camera_specific.md) docs.
## Deleting a camera
Click **Delete Camera** in <NavPath path="Settings > Global configuration > Camera management" />, choose the camera, and confirm. Deleting a camera requires the `admin` role and cannot be undone.
:::warning
Deleting a camera permanently removes its recordings, tracked objects, and configuration. If you only want to stop processing a camera, set its state to **Off** or **Disabled** in <NavPath path="Settings > Global configuration > Camera management" /> instead. See [camera state](/configuration/live#camera-state).
:::
Deleting a camera removes:
- The camera's section of your config file, along with its entries in any [role](authentication.md#user-roles) camera list. A custom role left with no cameras is removed as well.
- Every database record for the camera: tracked objects, review items, recordings, previews, timeline entries, the saved region grid, and [triggers](semantic_search.md#triggers).
- Every media file for the camera: recordings, snapshots, thumbnails, and preview clips.
[Exports](/usage/exports) are kept by default, so saved footage survives the deletion of the camera it came from. Turn on **Also delete exports for this camera** in the confirmation step to remove those too.
The camera's processes are stopped and the change takes effect immediately, so no restart is required. If the resulting config cannot be parsed, Frigate restores the previous config and reports an error instead of leaving Frigate in a broken state.
Two things are not cleaned up for you:
- **go2rtc streams.** Frigate makes a best effort to stop a running [go2rtc](go2rtc.md) stream named after the camera, but stream entries in your config file remain and are recreated on the next restart. Remove them in <NavPath path="Settings > System > go2rtc streams" /> or in your config file.
- **Camera groups.** A deleted camera stays listed in any [camera group](#setting-up-camera-groups) that referenced it. The group skips the missing camera, so this is harmless, but you can edit the group to drop the stale entry.
## Setting Up Camera Inputs ## Setting Up Camera Inputs
Several inputs can be configured for each camera and the role of each input can be mixed and matched based on your needs. This allows you to use a lower resolution stream for object detection, but create recordings from a higher resolution stream, or vice versa. Several inputs can be configured for each camera and the role of each input can be mixed and matched based on your needs. This allows you to use a lower resolution stream for object detection, but create recordings from a higher resolution stream, or vice versa.
+17 -22
View File
@@ -100,7 +100,7 @@ VS Code supports JSON schemas for automatically validating configuration files.
## Environment Variable Substitution ## Environment Variable Substitution
Frigate supports the use of environment variables starting with `FRIGATE_` **only** where specifically indicated in the [reference config](./advanced/reference.md). For example, the following values can be replaced at runtime by using environment variables: Frigate supports the use of environment variables starting with `FRIGATE_` **only** where specifically indicated in the [reference config](./advanced/reference.md). See [substitution sources and precedence](./advanced/system.md#substitution-sources-and-precedence) for where those values can come from, including `secrets.yaml`. For example, the following values can be replaced at runtime by using environment variables:
```yaml ```yaml
mqtt: mqtt:
@@ -154,7 +154,7 @@ Here are some common starter configuration examples. These can be configured thr
1. Navigate to <NavPath path="Settings > System > MQTT" /> and configure the MQTT connection to your Home Assistant Mosquitto broker 1. Navigate to <NavPath path="Settings > System > MQTT" /> and configure the MQTT connection to your Home Assistant Mosquitto broker
2. Navigate to <NavPath path="Settings > Global configuration > FFmpeg" /> and set **Hardware acceleration arguments** to `Raspberry Pi (H.264)` 2. Navigate to <NavPath path="Settings > Global configuration > FFmpeg" /> and set **Hardware acceleration arguments** to `Raspberry Pi (H.264)`
3. Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a detector with **Type** `EdgeTPU` and **Device** `usb` 3. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (USB)** from the **Hardware** dropdown
4. Navigate to <NavPath path="Settings > Global configuration > Recording" /> and set **Enable recording** to on, **Motion retention > Retention days** to `7`, **Alert retention > Event retention > Retention days** to `30`, **Alert retention > Event retention > Retention mode** to `motion`, **Detection retention > Event retention > Retention days** to `30`, **Detection retention > Event retention > Retention mode** to `motion` 4. Navigate to <NavPath path="Settings > Global configuration > Recording" /> and set **Enable recording** to on, **Motion retention > Retention days** to `7`, **Alert retention > Event retention > Retention days** to `30`, **Alert retention > Event retention > Retention mode** to `motion`, **Detection retention > Event retention > Retention days** to `30`, **Detection retention > Event retention > Retention mode** to `motion`
5. Navigate to <NavPath path="Settings > Global configuration > Snapshots" /> and set **Enable snapshots** to on, **Snapshot retention > Default retention** to `30` 5. Navigate to <NavPath path="Settings > Global configuration > Snapshots" /> and set **Enable snapshots** to on, **Snapshot retention > Default retention** to `30`
6. Navigate to <NavPath path="Settings > Global configuration > Camera management" /> and add your camera with the appropriate RTSP stream URL 6. Navigate to <NavPath path="Settings > Global configuration > Camera management" /> and add your camera with the appropriate RTSP stream URL
@@ -172,10 +172,9 @@ mqtt:
ffmpeg: ffmpeg:
hwaccel_args: preset-rpi-64-h264 hwaccel_args: preset-rpi-64-h264
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
record: record:
enabled: True enabled: True
@@ -233,7 +232,7 @@ cameras:
1. Navigate to <NavPath path="Settings > System > MQTT" /> and set **Enable MQTT** to off 1. Navigate to <NavPath path="Settings > System > MQTT" /> and set **Enable MQTT** to off
2. Navigate to <NavPath path="Settings > Global configuration > FFmpeg" /> and set **Hardware acceleration arguments** to `VAAPI (Intel/AMD GPU)` 2. Navigate to <NavPath path="Settings > Global configuration > FFmpeg" /> and set **Hardware acceleration arguments** to `VAAPI (Intel/AMD GPU)`
3. Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a detector with **Type** `EdgeTPU` and **Device** `usb` 3. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (USB)** from the **Hardware** dropdown
4. Navigate to <NavPath path="Settings > Global configuration > Recording" /> and set **Enable recording** to on, **Motion retention > Retention days** to `7`, **Alert retention > Event retention > Retention days** to `30`, **Alert retention > Event retention > Retention mode** to `motion`, **Detection retention > Event retention > Retention days** to `30`, **Detection retention > Event retention > Retention mode** to `motion` 4. Navigate to <NavPath path="Settings > Global configuration > Recording" /> and set **Enable recording** to on, **Motion retention > Retention days** to `7`, **Alert retention > Event retention > Retention days** to `30`, **Alert retention > Event retention > Retention mode** to `motion`, **Detection retention > Event retention > Retention days** to `30`, **Detection retention > Event retention > Retention mode** to `motion`
5. Navigate to <NavPath path="Settings > Global configuration > Snapshots" /> and set **Enable snapshots** to on, **Snapshot retention > Default retention** to `30` 5. Navigate to <NavPath path="Settings > Global configuration > Snapshots" /> and set **Enable snapshots** to on, **Snapshot retention > Default retention** to `30`
6. Navigate to <NavPath path="Settings > Global configuration > Camera management" /> and add your camera with the appropriate RTSP stream URL 6. Navigate to <NavPath path="Settings > Global configuration > Camera management" /> and add your camera with the appropriate RTSP stream URL
@@ -249,10 +248,9 @@ mqtt:
ffmpeg: ffmpeg:
hwaccel_args: preset-vaapi hwaccel_args: preset-vaapi
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
record: record:
enabled: True enabled: True
@@ -310,8 +308,8 @@ cameras:
1. Navigate to <NavPath path="Settings > System > MQTT" /> and configure the connection to your MQTT broker 1. Navigate to <NavPath path="Settings > System > MQTT" /> and configure the connection to your MQTT broker
2. Navigate to <NavPath path="Settings > Global configuration > FFmpeg" /> and set **Hardware acceleration arguments** to `VAAPI (Intel/AMD GPU)` 2. Navigate to <NavPath path="Settings > Global configuration > FFmpeg" /> and set **Hardware acceleration arguments** to `VAAPI (Intel/AMD GPU)`
3. Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a detector with **Type** `openvino` and **Device** `AUTO` 3. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Intel GPU** from the **Hardware** dropdown
4. On the same page, in the **Custom Model** tab, configure the OpenVINO model path and settings 4. On the same model, open the **Custom Model** tab and configure the OpenVINO model path and settings
5. Navigate to <NavPath path="Settings > Global configuration > Recording" /> and set **Enable recording** to on, **Motion retention > Retention days** to `7`, **Alert retention > Event retention > Retention days** to `30`, **Alert retention > Event retention > Retention mode** to `motion`, **Detection retention > Event retention > Retention days** to `30`, **Detection retention > Event retention > Retention mode** to `motion` 5. Navigate to <NavPath path="Settings > Global configuration > Recording" /> and set **Enable recording** to on, **Motion retention > Retention days** to `7`, **Alert retention > Event retention > Retention days** to `30`, **Alert retention > Event retention > Retention mode** to `motion`, **Detection retention > Event retention > Retention days** to `30`, **Detection retention > Event retention > Retention mode** to `motion`
6. Navigate to <NavPath path="Settings > Global configuration > Snapshots" /> and set **Enable snapshots** to on, **Snapshot retention > Default retention** to `30` 6. Navigate to <NavPath path="Settings > Global configuration > Snapshots" /> and set **Enable snapshots** to on, **Snapshot retention > Default retention** to `30`
7. Navigate to <NavPath path="Settings > Global configuration > Camera management" /> and add your camera with the appropriate RTSP stream URL 7. Navigate to <NavPath path="Settings > Global configuration > Camera management" /> and add your camera with the appropriate RTSP stream URL
@@ -329,15 +327,12 @@ mqtt:
ffmpeg: ffmpeg:
hwaccel_args: preset-vaapi hwaccel_args: preset-vaapi
detectors: models:
ov: - devices:
type: openvino - openvino:AUTO
device: AUTO width: 300
height: 300
model: input_tensor: nhwc
width: 300
height: 300
input_tensor: nhwc
input_pixel_format: bgr input_pixel_format: bgr
path: /openvino-model/ssdlite_mobilenet_v2.xml path: /openvino-model/ssdlite_mobilenet_v2.xml
labelmap_path: /openvino-model/coco_91cl_bkgr.txt labelmap_path: /openvino-model/coco_91cl_bkgr.txt
@@ -106,3 +106,5 @@ Output arguments are passed to FFmpeg after your camera source and control how r
| preset-record-mjpeg | Record - MJPEG Cameras | Record an MJPEG stream | Restreaming the MJPEG stream is recommended instead | | preset-record-mjpeg | Record - MJPEG Cameras | Record an MJPEG stream | Restreaming the MJPEG stream is recommended instead |
| preset-record-jpeg | Record - JPEG Cameras | Record a live JPEG | Restreaming the live JPEG is recommended instead | | preset-record-jpeg | Record - JPEG Cameras | Record a live JPEG | Restreaming the live JPEG is recommended instead |
| preset-record-ubiquiti | Record - Ubiquiti Cameras | Record a Ubiquiti stream with audio | Handles Ubiquiti's non-standard audio format | | preset-record-ubiquiti | Record - Ubiquiti Cameras | Record a Ubiquiti stream with audio | Handles Ubiquiti's non-standard audio format |
These presets apply to the `record` output args. If [sub stream recording](/configuration/record#sub-stream-recording) is enabled, the same args are used for the `record_sub` role unless `output_args.record_sub` is set, which accepts the same presets and manual args.
+9 -5
View File
@@ -59,13 +59,17 @@ Running Generative AI models on CPU is not recommended, as high inference times
### Recommended Local Models ### Recommended Local Models
#### Vision models
You must use a vision-capable model with Frigate. The following models are recommended for local deployment of the `descriptions` and `chat` roles: You must use a vision-capable model with Frigate. The following models are recommended for local deployment of the `descriptions` and `chat` roles:
| Model | Notes | | Model | Notes |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `qwen3-vl` | Strong visual and situational understanding, enhanced ability to identify smaller objects and interactions with object. | | `qwen3-vl` | Strong visual and situational understanding, enhanced ability to identify smaller objects and interactions with object. |
| `qwen3.6` | Strong situational understanding, but missing DeepStack from qwen3-vl leading to worse performance for identifying objects in people's hand and other small details. | | `qwen3.6`/`qwen3.8` | Strong situational understanding, but missing DeepStack from qwen3-vl leading to worse performance for identifying objects in people's hand and other small details. |
| `gemma4` | Strong situational understanding, sometimes resorts to more vague terms like 'interacts' instead of assigning a specific action. | | `gemma4` | Strong situational understanding, sometimes resorts to more vague terms like 'interacts' instead of assigning a specific action. |
#### Embedding models
The `embeddings` role needs a different kind of model. Text queries are matched against the stored image embeddings, so the model must be trained to place images and text into the same vector space. A chat or description model will still return vectors when asked, but those vectors are not trained for retrieval and text searches will return poor matches with no error to indicate why. The `embeddings` role needs a different kind of model. Text queries are matched against the stored image embeddings, so the model must be trained to place images and text into the same vector space. A chat or description model will still return vectors when asked, but those vectors are not trained for retrieval and text searches will return poor matches with no error to indicate why.
+68 -2
View File
@@ -6,6 +6,7 @@ title: Notifications
import ConfigTabs from "@site/src/components/ConfigTabs"; import ConfigTabs from "@site/src/components/ConfigTabs";
import TabItem from "@theme/TabItem"; import TabItem from "@theme/TabItem";
import NavPath from "@site/src/components/NavPath"; import NavPath from "@site/src/components/NavPath";
import FaqItem from "@site/src/components/FaqItem";
# Notifications # Notifications
@@ -21,7 +22,7 @@ Push notifications require internet access from the Frigate server to the browse
In order to use notifications the following requirements must be met: In order to use notifications the following requirements must be met:
- Frigate must be accessed via a secure `https` connection ([see the authorization docs](/configuration/authentication)). - Frigate must be accessed via a secure `https` connection while signed in as a Frigate user ([see the authorization docs](/configuration/authentication)).
- A supported browser must be used. Currently Chrome, Firefox, and Safari are known to be supported. - A supported browser must be used. Currently Chrome, Firefox, and Safari are known to be supported.
- In order for notifications to be usable externally, Frigate must be accessible externally. - In order for notifications to be usable externally, Frigate must be accessible externally.
- For iOS devices, some users have also indicated that the Notifications switch needs to be enabled in iOS Settings --> Apps --> Safari --> Advanced --> Features. - For iOS devices, some users have also indicated that the Notifications switch needs to be enabled in iOS Settings --> Apps --> Safari --> Advanced --> Features.
@@ -85,7 +86,13 @@ cameras:
### Registration ### Registration
Once notifications are enabled, press the `Register for Notifications` button on all devices that you would like to receive notifications on. This will register the background worker. After this Frigate must be restarted and then notifications will begin to be sent. Once notifications are enabled, press the `Register This Device` button on all devices that you would like to receive notifications on. This will register the background worker. After this Frigate must be restarted and then notifications will begin to be sent.
:::warning
Each registration is attached to the Frigate user account you are signed in as, so you must register over a secure connection to the authenticated port (`8971`). Reverse proxies and tunnels should point at port `8971`.
:::
## Supported Notifications ## Supported Notifications
@@ -104,3 +111,62 @@ Different platforms handle notifications differently, some settings changes may
### Android ### Android
Most Android phones have battery optimization settings. To get reliable Notification delivery the browser (Chrome, Firefox) should have battery optimizations disabled. If Frigate is running as a PWA then the Frigate app should have battery optimizations disabled as well. Most Android phones have battery optimization settings. To get reliable Notification delivery the browser (Chrome, Firefox) should have battery optimizations disabled. If Frigate is running as a PWA then the Frigate app should have battery optimizations disabled as well.
## Notifications FAQ
<FaqItem id="how-do-i-debug-notifications-issues" question="How do I debug notifications issues?">
Push notifications involve Frigate, your browser, and your browser vendor's push service, so it helps to work from the server outward.
1. Enable debug logs for the push client by adding `frigate.comms.webpush: debug` to your `logger` configuration. Restart Frigate after this change.
```yaml
logger:
default: info
logs:
# highlight-next-line
frigate.comms.webpush: debug
```
These logs show exactly where a notification stopped, including:
- `Email must be provided for push notifications to be sent` means the global `email` field is empty and nothing will ever be sent.
- `Sending test notification` and `Sending push notification for <camera>, review ID <id>` mean Frigate handed the message off to the push service.
- `Skipping notification for <camera> - in global cooldown period` (or `camera-specific cooldown period`) means your [cooldown](#configuration) values suppressed it.
- `Notifications for <camera> are currently suspended` means notifications were suspended from <NavPath path="Settings > Notifications" /> or MQTT.
- `Notification endpoint expired for <user>, received 410` means that device's subscription is no longer valid and it must be re-registered.
- `Failed to send notification to <user> :: <status>` means the push service rejected the message. A `401` or `403` usually points at a VAPID or `email` problem, and a `5xx` is a problem on the push service's end.
- If you see no messages at all when an alert occurs, the notification was never queued. Confirm an actual **alert** was created (notifications are not sent for detections), and that notifications are enabled both globally and for that camera.
2. Verify the basics that most reports come down to:
- Frigate must be reached over `https` with a certificate your device trusts. Browsers silently refuse to register a service worker otherwise, and a self-signed certificate that is not installed as trusted on the device will fail.
- On iOS, notifications only work when Frigate has been installed to the Home Screen via **Share > Add to Home Screen** and opened from that icon. Safari and Chrome tabs cannot receive web push on iOS.
- Each device must be registered individually, and Frigate must be restarted after registering before anything can be sent, including test notifications.
- The Frigate server needs outbound internet access to the browser vendor's push service. See [Network Requirements](/frigate/network_requirements#push-notifications).
3. Test from the UI. Use the `Send a test notification` button in <NavPath path="Settings > Notifications" />. If the log shows `Sending test notification` but nothing arrives on the device, the problem is between the push service and your device rather than in Frigate.
4. Check the browser side on the device that is not receiving notifications:
- Confirm the site's notification permission is set to **Allow** in your browser or OS settings, and that a focus/do not disturb mode is not hiding them.
- In desktop browsers, open Developer Tools > Application > Service Workers and confirm `notifications-worker.js` is registered and activated. Unregistering it and registering the device again will rebuild a broken subscription.
- Check the browser console and your reverse proxy logs for failures loading `/notifications-worker.js` or errors on `/api/notifications/register`.
</FaqItem>
<FaqItem id="why-did-notifications-stop-arriving-after-working-for-a-while" question="Why did notifications stop arriving after working for a while?">
Push subscriptions are issued by the browser vendor and can be revoked, most often after a browser update, after clearing site data, or when a device has been offline for an extended period. When this happens the device still appears registered in Frigate, but the push service rejects the message. The debug logs will show `Notification endpoint expired` with a `404` or `410` status.
Unregister and re-register the affected device from <NavPath path="Settings > Notifications" />, then restart Frigate.
</FaqItem>
<FaqItem id="why-am-i-not-getting-notifications-for-one-specific-camera" question="Why am I not getting notifications for one specific camera?">
Work through these in order:
- Notifications are only sent for **alerts**. If the camera is producing detections instead, adjust the camera's `review > alerts > labels` so the objects you care about are classified as alerts.
- Confirm notifications are enabled for that camera in <NavPath path="Settings > Camera configuration > Notifications" />.
- Check the camera's `cooldown` value, and remember that the global cooldown applies across all cameras. A busy camera can consume the global cooldown and suppress a quieter one.
- If [authentication](/configuration/authentication) is enabled with roles, users only receive notifications for the cameras their role grants access to.
</FaqItem>
+112 -65
View File
@@ -68,12 +68,66 @@ Frigate supports multiple different detectors that work on different types of ha
:::note :::note
Multiple detectors can not be mixed for object detection (ex: OpenVINO and Coral EdgeTPU can not be used for object detection at the same time). A single model can not be spread across different detector types (ex: OpenVINO and Coral EdgeTPU can not run the same model at the same time). Configuring more than one model, each on its own detector type, is supported.
This does not affect using hardware for accelerating other tasks such as [semantic search](./semantic_search.md) This does not affect using hardware for accelerating other tasks such as [semantic search](./semantic_search.md)
::: :::
### Configuring models and hardware
Object detection is configured with a `models` list. Each entry describes one model and the hardware it runs on:
```yaml
models:
- devices:
- openvino:GPU
path: /config/model_cache/yolov9-s.onnx
model_type: yolo-generic
width: 320
height: 320
```
Each entry in `devices` is a detector type, optionally followed by a colon and a device for that detector, such as `edgetpu:pci:0`, `openvino:NPU`, or `tensorrt:0`. The per-detector sections below document the device values each one accepts. Listing several devices runs the model on all of them, and listing the **same** device more than once runs additional inference processes against it, which can improve throughput on hardware that keeps up with more than one stream:
```yaml
models:
- devices:
- openvino:GPU
- openvino:GPU
```
Coral EdgeTPU and MemryX accelerators can only be opened by one process, so those devices can not be repeated.
### Running more than one model
Cameras can be split across models by scene, which is useful when indoor and outdoor cameras benefit from differently trained models. Each model declares the `scene` it is for, and each camera picks one with `detect -> scene`:
```yaml
models:
- scene: outdoor
path: plus://your-outdoor-model
devices:
- edgetpu:pci:0
- scene: indoor
path: /config/model_cache/indoor.onnx
model_type: yolo-generic
devices:
- openvino:GPU
cameras:
driveway:
detect:
scene: outdoor
...
hallway:
detect:
scene: indoor
...
```
Available scenes are `all`, `indoor`, `outdoor`, `indoor_thermal`, and `outdoor_thermal`. A model with a scene of `all` is used by every camera that does not set one, and `all` is the default when a model does not declare a scene. Changing a camera's scene requires a restart.
### Choosing a model size ### Choosing a model size
Along with picking a detector for your hardware, you will choose a model's **input resolution** (such as `320x320` or `640x640`) and, for model families like YOLOv9, a **variant size** (`tiny`, `small`, etc.). Both affect the balance between accuracy and the inference time your hardware can sustain. Along with picking a detector for your hardware, you will choose a model's **input resolution** (such as `320x320` or `640x640`) and, for model families like YOLOv9, a **variant size** (`tiny`, `small`, etc.). Both affect the balance between accuracy and the inference time your hardware can sustain.
@@ -92,11 +146,11 @@ The best detection accuracy comes from a model trained on images that look like
# Officially Supported Detectors # Officially Supported Detectors
Frigate provides a number of builtin detector types. By default, Frigate will use a single CPU detector. Other detectors may require additional configuration as described below. When using multiple detectors they will run in dedicated processes, but pull from a common queue of detection requests from across all cameras. Frigate provides a number of builtin detector types. By default, Frigate will use a single CPU detector. Other detectors may require additional configuration as described below. Each of a model's devices runs in a dedicated process, and they pull from a common queue of detection requests from the cameras assigned to that model.
## Edge TPU Detector ## Edge TPU Detector
The Edge TPU detector type runs TensorFlow Lite models utilizing the Google Coral delegate for hardware acceleration. To configure an Edge TPU detector, set the `"type"` attribute to `"edgetpu"`. The Edge TPU detector type runs TensorFlow Lite models utilizing the Google Coral delegate for hardware acceleration. To use it, prefix a model's device with `edgetpu`.
The Edge TPU device can be specified using the `"device"` attribute according to the [Documentation for the TensorFlow Lite Python API](https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api). If not set, the delegate will use the first device it finds. The Edge TPU device can be specified using the `"device"` attribute according to the [Documentation for the TensorFlow Lite Python API](https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api). If not set, the delegate will use the first device it finds.
@@ -111,16 +165,15 @@ See [common Edge TPU troubleshooting steps](/troubleshooting/edgetpu) if the Edg
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and select **EdgeTPU** from the detector type dropdown and click **Add**, then set device to `usb`. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (USB)** from the **Hardware** dropdown.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
``` ```
</TabItem> </TabItem>
@@ -131,19 +184,16 @@ detectors:
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and select **EdgeTPU** from the detector type dropdown and click **Add** to add multiple detectors, specifying `usb:0` and `usb:1` as the device for each. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (USB)** from the **Hardware** dropdown and check each Coral the model should run on.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral1: - devices:
type: edgetpu - edgetpu:usb:0
device: usb:0 - edgetpu:usb:1
coral2:
type: edgetpu
device: usb:1
``` ```
</TabItem> </TabItem>
@@ -156,16 +206,15 @@ _warning: may have [compatibility issues](https://github.com/blakeblackshear/fri
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and select **EdgeTPU** from the detector type dropdown and click **Add**, then leave the device field empty. Navigate to <NavPath path="Settings > System > Detection models" /> and select the **Coral EdgeTPU** entry from the **Hardware** dropdown.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral: - devices:
type: edgetpu - 'edgetpu:'
device: ""
``` ```
</TabItem> </TabItem>
@@ -176,16 +225,15 @@ detectors:
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and select **EdgeTPU** from the detector type dropdown and click **Add**, then set device to `pci`. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (PCIe)** from the **Hardware** dropdown.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:pci
device: pci
``` ```
</TabItem> </TabItem>
@@ -196,19 +244,16 @@ detectors:
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and select **EdgeTPU** from the detector type dropdown and click **Add** to add multiple detectors, specifying `pci:0` and `pci:1` as the device for each. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (PCIe)** from the **Hardware** dropdown and check each Coral the model should run on.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral1: - devices:
type: edgetpu - edgetpu:pci:0
device: pci:0 - edgetpu:pci:1
coral2:
type: edgetpu
device: pci:1
``` ```
</TabItem> </TabItem>
@@ -219,19 +264,16 @@ detectors:
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and select **EdgeTPU** from the detector type dropdown and click **Add** to add multiple detectors with different device types (e.g., `usb` and `pci`). Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (USB)** from the **Hardware** dropdown. USB and PCIe Corals are listed as separate hardware, so mixing the two on one model has to be done in YAML.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral_usb: - devices:
type: edgetpu - edgetpu:usb
device: usb - edgetpu:pci
coral_pci:
type: edgetpu
device: pci
``` ```
</TabItem> </TabItem>
@@ -273,7 +315,7 @@ Hailo8 supports all models in the Hailo Model Zoo that include HailoRT post-proc
## OpenVINO Detector ## OpenVINO Detector
The OpenVINO detector type runs an OpenVINO IR model on AMD and Intel CPUs, Intel GPUs and Intel NPUs. To configure an OpenVINO detector, set the `"type"` attribute to `"openvino"`. The OpenVINO detector type runs an OpenVINO IR model on AMD and Intel CPUs, Intel GPUs and Intel NPUs. To use it, prefix a model's device with `openvino`.
The OpenVINO device to be used is specified using the `"device"` attribute according to the naming conventions in the [Device Documentation](https://docs.openvino.ai/2025/openvino-workflow/running-inference/inference-devices-and-modes.html). The most common devices are `CPU`, `GPU`, or `NPU`. The OpenVINO device to be used is specified using the `"device"` attribute according to the naming conventions in the [Device Documentation](https://docs.openvino.ai/2025/openvino-workflow/running-inference/inference-devices-and-modes.html). The most common devices are `CPU`, `GPU`, or `NPU`.
@@ -286,13 +328,10 @@ OpenVINO is supported on 6th Gen Intel platforms (Skylake) and newer. It will al
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be: When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be:
```yaml ```yaml
detectors: models:
ov_0: - devices:
type: openvino - openvino:GPU # or NPU
device: GPU # or NPU - openvino:GPU # or NPU
ov_1:
type: openvino
device: GPU # or NPU
``` ```
::: :::
@@ -313,6 +352,12 @@ Intel NPUs cannot be used under Home Assistant OS, which does not include the NP
## Apple Silicon detector ## Apple Silicon detector
:::warning
The network-based detectors (Deepstack and the Apple Silicon client) are being reworked. Their extra options no longer have a place in the config, so only the endpoint carried in the device string is honored right now: Deepstack ignores `api_key` and `api_timeout`, and the Apple Silicon client ignores `request_timeout_ms` and `linger_ms`. Anything else is dropped when your config is migrated.
:::
The NPU in Apple Silicon can't be accessed from within a container, so the [Apple Silicon detector client](https://github.com/frigate-nvr/apple-silicon-detector) must first be setup. It is recommended to use the Frigate docker image with `-standard-arm64` suffix, for example `ghcr.io/blakeblackshear/frigate:stable-standard-arm64`. The NPU in Apple Silicon can't be accessed from within a container, so the [Apple Silicon detector client](https://github.com/frigate-nvr/apple-silicon-detector) must first be setup. It is recommended to use the Frigate docker image with `-standard-arm64` suffix, for example `ghcr.io/blakeblackshear/frigate:stable-standard-arm64`.
### Setup {#setup-apple-silicon} ### Setup {#setup-apple-silicon}
@@ -453,11 +498,10 @@ If the correct build is used for your GPU then the GPU will be detected and used
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be: When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be:
```yaml ```yaml
detectors: models:
onnx_0: - devices:
type: onnx - onnx
onnx_1: - onnx
type: onnx
``` ```
::: :::
@@ -470,7 +514,7 @@ detectors:
## CPU Detector (not recommended) ## CPU Detector (not recommended)
The CPU detector type runs a TensorFlow Lite model utilizing the CPU without hardware acceleration. It is recommended to use a hardware accelerated detector type instead for better performance. To configure a CPU based detector, set the `"type"` attribute to `"cpu"`. The CPU detector type runs a TensorFlow Lite model utilizing the CPU without hardware acceleration. It is recommended to use a hardware accelerated detector type instead for better performance. To use it, set a model's device to `cpu`.
:::danger :::danger
@@ -480,7 +524,7 @@ The CPU detector is not recommended for general use. If you do not have GPU or E
The number of threads used by the interpreter can be specified using the `"num_threads"` attribute, and defaults to `3.` The number of threads used by the interpreter can be specified using the `"num_threads"` attribute, and defaults to `3.`
A TensorFlow Lite model is provided in the container at `/cpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with `model.path`. A TensorFlow Lite model is provided in the container at `/cpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with the model's `path`.
### Configuration {#configuration-cpu} ### Configuration {#configuration-cpu}
@@ -490,6 +534,12 @@ When using CPU detectors, you can add one CPU detector per camera. Adding more d
## Deepstack / CodeProject.AI Server Detector ## Deepstack / CodeProject.AI Server Detector
:::warning
The network-based detectors (Deepstack and the Apple Silicon client) are being reworked. Their extra options no longer have a place in the config, so only the endpoint carried in the device string is honored right now: Deepstack ignores `api_key` and `api_timeout`, and the Apple Silicon client ignores `request_timeout_ms` and `linger_ms`. Anything else is dropped when your config is migrated.
:::
The Deepstack / CodeProject.AI Server detector for Frigate allows you to integrate Deepstack and CodeProject.AI object detection capabilities into Frigate. CodeProject.AI and DeepStack are open-source AI platforms that can be run on various devices such as the Raspberry Pi, Nvidia Jetson, and other compatible hardware. It is important to note that the integration is performed over the network, so the inference times may not be as fast as native Frigate detectors, but it still provides an efficient and reliable solution for object detection and tracking. The Deepstack / CodeProject.AI Server detector for Frigate allows you to integrate Deepstack and CodeProject.AI object detection capabilities into Frigate. CodeProject.AI and DeepStack are open-source AI platforms that can be run on various devices such as the Raspberry Pi, Nvidia Jetson, and other compatible hardware. It is important to note that the integration is performed over the network, so the inference times may not be as fast as native Frigate detectors, but it still provides an efficient and reliable solution for object detection and tracking.
### Setup {#setup-deepstack} ### Setup {#setup-deepstack}
@@ -552,7 +602,7 @@ For detailed instructions on compiling models, refer to the [MemryX Compiler](ht
3. Depending on the model, the compiler may also generate a cropped post-processing network. If present, it will be named with the suffix `_post.onnx`. 3. Depending on the model, the compiler may also generate a cropped post-processing network. If present, it will be named with the suffix `_post.onnx`.
4. Bind-mount the `.zip` file into the container and specify its path using `model.path` in your config. 4. Bind-mount the `.zip` file into the container and specify its path using the model's `path` in your config.
5. Update `labelmap_path` to match your custom model's labels. 5. Update `labelmap_path` to match your custom model's labels.
@@ -682,13 +732,10 @@ If no custom model is provided, the RKNN detector downloads a default model from
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming NPU resources are available. An example configuration would be: When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming NPU resources are available. An example configuration would be:
```yaml ```yaml
detectors: models:
rknn_0: - devices:
type: rknn - rknn:0
num_cores: 0 - rknn:0
rknn_1:
type: rknn
num_cores: 0
``` ```
::: :::
+157
View File
@@ -275,6 +275,163 @@ record:
This configuration will retain recording segments that overlap with alerts and detections for 10 days. Because multiple tracked objects can reference the same recording segments, this avoids storing duplicate footage for overlapping tracked objects and reduces overall storage needs. This configuration will retain recording segments that overlap with alerts and detections for 10 days. Because multiple tracked objects can reference the same recording segments, this avoids storing duplicate footage for overlapping tracked objects and reduces overall storage needs.
## Sub Stream Recording
In addition to the main recording stream, Frigate can record a second, lower quality stream for each camera. This serves two purposes:
- **Quality selection during playback**: A quality selector (`Auto`, `Original`, or `Low`) appears in History view for cameras with sub stream recording enabled. `Original` and `Low` play only that stream's recordings. Time ranges where the selected stream has no footage are skipped during playback, and the selector notes when the selected stream has no recordings at all in the viewed time range. With `Auto` (the default), playback prefers the original quality and automatically falls back to the low quality stream when the connection cannot keep up, or for time ranges where the original recordings have expired. The selector shows each stream's video codec and audio details beneath the options; footage recorded by older Frigate versions shows no details.
- **Extended retention**: Sub stream recordings have their own retention settings, fully independent of the main recordings. By giving the low quality recordings a longer retention period, you can keep weeks or months of low quality history using a fraction of the storage, and that history remains playable after the main recordings expire. Playback falls back to the low quality recordings automatically, and the timeline shows a muted treatment for time ranges where only low quality footage remains.
### Configuring sub stream recording
Sub stream recording uses the `record_sub` input role. This role can be assigned to the same input as `detect`, so in the common case where detect already uses the camera's sub stream, no additional camera connection is needed. Like the main recording stream, sub stream segments are copied directly from the camera stream without re-encoding, so the recording quality is determined by the source stream.
The following examples keep 7 days of full quality continuous recordings and 60 days of low quality continuous recordings:
<ConfigTabs>
<TabItem value="ui">
Navigate to <NavPath path="Settings > Camera configuration > Streams (FFmpeg)" /> and select the camera.
- In **Camera inputs**, enable the **Record (Sub Stream)** role on the stream you want to record at low quality, commonly the same stream that has the **Detect** role. Only one stream may have this role, and it cannot be assigned to the same stream as the **Record** role.
Navigate to <NavPath path="Settings > Camera configuration > Recording" /> and select the camera.
- Set **Enable recording** to on
- Set **Continuous retention > Retention days** to `7`
- Set **Sub stream recording > Enable sub stream recording** to on
- Set **Sub stream recording > Sub stream continuous retention > Retention days** to `60`
The camera setup wizard also offers the **Record (Sub Stream)** role when assigning stream roles for a newly added camera.
</TabItem>
<TabItem value="yaml">
```yaml
cameras:
front_door:
ffmpeg:
inputs:
- path: rtsp://camera/main
roles:
- record
- path: rtsp://camera/sub
roles:
- detect
- record_sub
record:
enabled: true
continuous:
days: 7
sub:
enabled: true
continuous:
days: 60
```
If your camera does not provide a suitable sub stream (or the sub stream is already used at a resolution you don't want to record), you can use a go2rtc transcode as the source for `record_sub` instead:
```yaml
go2rtc:
streams:
front_door: rtsp://camera/main
front_door_lq: ffmpeg:front_door#video=h264#width=854#hardware
cameras:
front_door:
ffmpeg:
inputs:
- path: rtsp://127.0.0.1:8554/front_door
input_args: preset-rtsp-restream
roles:
- detect
- record
- path: rtsp://127.0.0.1:8554/front_door_lq
input_args: preset-rtsp-restream
roles:
- record_sub
record:
enabled: true
continuous:
days: 7
sub:
enabled: true
continuous:
days: 60
```
</TabItem>
</ConfigTabs>
The `record.sub` config supports the same retention structure as the main recording config: `continuous`, `motion`, `alerts`, and `detections` each with their own `days` (and `mode` for alerts and detections). The pre-capture and post-capture windows for alerts and detections are taken from the main `record.alerts` and `record.detections` config. Extending `sub.alerts.days` or `sub.detections.days` beyond the main values also keeps those review items visible in the review timeline for the longer window, with playback falling back to the low quality stream once the main recordings expire.
:::note
Recording must be enabled (`record.enabled`) for sub stream recording to run, and Frigate will fail to start if `record.sub.enabled` is set without a `record_sub` role assigned to one of the camera's inputs.
:::
### How Auto picks a quality
`Auto` measures throughput on every segment download and compares it against the original stream's bitrate (computed from the recorded footage itself). Playback drops to the low quality stream when any of these happen:
- A freeze lasts 4 seconds (10 seconds when it starts within 2 seconds of a seek, since the seek target is rarely buffered), or freezes total 7 seconds within the last minute.
- 3 downloads in a row measure below the original bitrate plus 10%, dropping quality before a stall ever becomes visible.
- No first frame appears within 10 seconds, or loading fails outright.
Playback returns to full quality only when measured throughput exceeds the original bitrate by 50%, checked continuously while playing the low quality stream and again at each new hour. The asymmetric thresholds (1.1x to drop, 1.5x to return) keep a borderline connection from switching back and forth.
The most recent measurement is remembered on the device: a connection last measured below the original bitrate (or below 3 Mbps when the bitrate is not yet known) starts playback on the low quality stream so a first frame appears immediately, then upgrades within a few segments if the speed allows.
The quality selector shows which stream Auto is currently playing and why. A browser with Data Saver enabled stays on the low quality stream, a browser that cannot decode the original stream's codec (for example H.265 without HEVC support) plays the low quality stream for that camera, and pinning `Original` or `Low` bypasses Auto entirely.
### Sub stream output args
By default the sub stream is recorded with the same [output args](/configuration/ffmpeg_presets#output-args-presets) as the main recording stream, so it inherits any customization made to `ffmpeg.output_args.record`. Setting `ffmpeg.output_args.record_sub` gives the sub stream its own args instead. Like all `ffmpeg` config, this can be set globally or per camera.
The most common reason to set this is a pair of streams whose audio differs. Many cameras send AAC on the main stream but PCM on the sub stream, and PCM cannot be copied into an mp4 recording. Copying the main stream's audio avoids re-encoding audio that is already AAC, while the sub stream still needs to be transcoded:
```yaml
ffmpeg:
output_args:
# main stream audio is already AAC, so copy it
record: preset-record-generic-audio-copy
# sub stream audio is PCM, so transcode it to AAC
record_sub: preset-record-generic-audio-aac
```
Other reasons to set this are recording a sub stream whose codec needs a different preset than the main stream, such as `preset-record-mjpeg`, or forcing a matching audio sample rate across the two streams with manual args ending in `-c:a aac -ar 16000`.
:::warning
Avoid removing audio from only one of the two streams (for example with `-an`). When one stream has audio and the other does not, playback of time ranges that combine both qualities is silent, so stripping audio from the sub stream also silences the merged timeline.
:::
### Which stream do features use?
As a general rule, features that read recordings prefer the main stream and fall back to the sub stream for time ranges where the main recordings have expired. Analytics features use only the main stream.
| Feature | Stream used |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Recording playback (History and Review) | Both (main preferred with sub fallback by default), or exactly one stream when a quality is selected manually |
| Tracking details and Explore clip playback | Main, falling back to sub where the main recordings have expired |
| Exports and clip downloads | Main; sub is used when no main recordings remain in the range (streams are never mixed in one file) |
| Frames grabbed from a recording in History (download snapshot, submit frame to Frigate+) | Main preferred, sub fallback |
| Audio extraction (e.g., transcription) | Main preferred, sub fallback |
| Motion search | Main only |
| Review timeline motion data | Main only |
| Storage usage statistics | Both streams counted, and listed separately per camera |
This table covers only features that read recordings from disk. Tracked object snapshots and thumbnails (the images shown in Explore and sent with notifications, and the images submitted to Frigate+ from a tracked object) are captured live from the `detect` stream as the object is tracked, never from recordings, so sub stream recording does not affect them.
### Trade-offs
- Recording a second stream increases overall storage use. The increase is typically small relative to the main recordings, since the low quality stream is much smaller.
- The go2rtc transcode approach continuously encodes the low quality stream, which uses CPU or GPU resources. This cost only applies to the transcode path; recording the camera's native sub stream does not re-encode. See the [go2rtc hardware acceleration documentation](https://github.com/AlexxIT/go2rtc?tab=readme-ov-file#source-ffmpeg) for accelerating the transcode.
- Many camera sub streams do not include audio. If the source stream has no audio, the low quality recordings will not have audio.
- **Matching video codecs and audio settings between the two streams gives the smoothest playback.** When playback combines both qualities on one timeline (the default `Auto` behavior: for example original quality during events with low quality in between, or low quality history after the original recordings expire) and the streams use different video codecs or audio settings, for example H.265 on the main stream and H.264 on the sub stream, or 16 kHz audio on one and 8 kHz on the other, playback still works: Frigate inserts a decoder reset at each quality transition, which can cause a barely-perceptible pause there. Configuring both streams in the camera's firmware to use the same video codec, audio codec, and sample rate makes transitions fully seamless, and a mismatched audio sample rate can also be corrected with [sub stream output args](#sub-stream-output-args). If one stream has audio and the other does not, combined time ranges play **without audio**; selecting a single quality with the playback selector always keeps that stream's audio.
## Can I have "continuous" recordings, but only at certain times? ## Can I have "continuous" recordings, but only at certain times?
Using Frigate UI, Home Assistant, or MQTT, cameras can be automated to only record in certain situations or at certain times. Using Frigate UI, Home Assistant, or MQTT, cameras can be automated to only record in certain situations or at certain times.
+1 -1
View File
@@ -221,7 +221,7 @@ For security reasons, the `echo:`, `expr:`, and `exec:` stream sources are disab
If you attempt to use these sources in your configuration, the streams will be removed and an error message will be printed in the logs. If you attempt to use these sources in your configuration, the streams will be removed and an error message will be printed in the logs.
To enable these sources, you must set the environment variable `GO2RTC_ALLOW_ARBITRARY_EXEC=true`. This can be done in your Docker Compose file or container environment: To enable these sources, you must set the environment variable `GO2RTC_ALLOW_ARBITRARY_EXEC=true`. This can be done in your Docker Compose file or container environment, or for Home Assistant App users with the `go2rtc_allow_arbitrary_exec` option in the App's configuration. The `environment_vars` section of the Frigate config can't enable it:
```yaml ```yaml
environment: environment:
+25
View File
@@ -121,6 +121,31 @@ cameras:
</TabItem> </TabItem>
</ConfigTabs> </ConfigTabs>
## Categorizing manual events
Events created with the [create manual event API](../integrations/api/create-event-events-camera-name-label-create-post.api.mdx) are categorized with the same label lists, using the label from the request path:
1. If alerts are enabled and the label is listed in `review -> alerts -> labels`, the review item is an alert.
2. Otherwise, if detections are enabled and the label is listed in `review -> detections -> labels`, the review item is a detection.
3. If the label is in neither list, the review item is an alert, or no review item is created if alerts are disabled.
This means manual events are alerts unless you explicitly list their label as a detection label. For example, to have PIR sensors create detections instead of alerts, post to `/api/events/front_door/pir_sensor/create` with the following config:
```yaml {5-7}
cameras:
front_door:
review:
detections:
labels:
- pir_sensor
```
:::note
Required zones do not apply to manual events, since they are created through the API rather than by the object tracker. Setting `review -> alerts -> labels` to an empty list also does not stop manual events from becoming alerts, as a label in neither list still falls back to an alert.
:::
## Restricting review items to specific zones ## Restricting review items to specific zones
By default a review item will be created if any `review -> alerts -> labels` and `review -> detections -> labels` are detected anywhere in the camera frame. You will likely want to configure review items to only be created when the object enters an area of interest, [see the zone docs for more information](./zones.md#restricting-alerts-and-detections-to-specific-zones) By default a review item will be created if any `review -> alerts -> labels` and `review -> detections -> labels` are detected anywhere in the camera frame. You will likely want to configure review items to only be created when the object enters an area of interest, [see the zone docs for more information](./zones.md#restricting-alerts-and-detections-to-specific-zones)
+2
View File
@@ -612,6 +612,8 @@ Home Assistant OS users can install via the App repository.
5. Start the App 5. Start the App
6. Use the _Open Web UI_ button to access the Frigate UI, then click in the _cog icon_ > _Configuration editor_ and configure Frigate to your liking 6. Use the _Open Web UI_ button to access the Frigate UI, then click in the _cog icon_ > _Configuration editor_ and configure Frigate to your liking
App users who can't set container environment variables can put `FRIGATE_` values in a `secrets.yaml` in the config directory instead. See [`secrets.yaml`](../configuration/advanced/system.md#secretsyaml).
There are several variants of the App available: There are several variants of the App available:
| App Variant | Description | | App Variant | Description |
+16 -21
View File
@@ -204,8 +204,8 @@ You need to refer to **Configure hardware acceleration** above to enable the con
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
1. Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a detector with **Type** `OpenVINO` and **Device** `GPU` 1. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Intel GPU** from the **Hardware** dropdown
2. On the same page, in the **Custom Model** tab, configure the model settings for OpenVINO: 2. On the same model, open the **Custom Model** tab and configure the model settings for OpenVINO:
| Field | Value | | Field | Value |
| ---------------------------------------- | ------------------------------------------ | | ---------------------------------------- | ------------------------------------------ |
@@ -222,15 +222,12 @@ You need to refer to **Configure hardware acceleration** above to enable the con
```yaml {3-6,9-15,20-21} ```yaml {3-6,9-15,20-21}
mqtt: ... mqtt: ...
detectors: # <---- add detectors models: # <---- add models
ov: - devices:
type: openvino # <---- use openvino detector - openvino:GPU # <---- use the openvino detector on the GPU
device: GPU # We will use the default MobileNet_v2 model from OpenVINO.
width: 300
# We will use the default MobileNet_v2 model from OpenVINO. height: 300
model:
width: 300
height: 300
input_tensor: nhwc input_tensor: nhwc
input_pixel_format: bgr input_pixel_format: bgr
path: /openvino-model/ssdlite_mobilenet_v2.xml path: /openvino-model/ssdlite_mobilenet_v2.xml
@@ -273,7 +270,7 @@ services:
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a detector with **Type** `EdgeTPU` and **Device** `usb`. Navigate to <NavPath path="Settings > System > Detection models" /> and select **Coral EdgeTPU (USB)** from the **Hardware** dropdown.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
@@ -281,10 +278,9 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a
```yaml {3-6,11-12} ```yaml {3-6,11-12}
mqtt: ... mqtt: ...
detectors: # <---- add detectors models: # <---- add models
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
cameras: cameras:
name_of_your_camera: name_of_your_camera:
@@ -321,10 +317,9 @@ If you are using YAML to configure Frigate instead of the UI, your configuration
mqtt: mqtt:
enabled: False enabled: False
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
cameras: cameras:
name_of_your_camera: name_of_your_camera:
@@ -357,7 +352,7 @@ In order to review activity in the Frigate UI, recordings need to be enabled.
```yaml {16-17} ```yaml {16-17}
mqtt: ... mqtt: ...
detectors: ... models: ...
cameras: cameras:
name_of_your_camera: name_of_your_camera:
+26 -15
View File
@@ -292,7 +292,9 @@ Topic with the currently active profile name. Published value is the profile nam
### `frigate/notifications/set` ### `frigate/notifications/set`
Topic to turn notifications on and off. Expected values are `ON` and `OFF`. Topic to turn notifications on and off for all cameras. Expected values are `ON` and `OFF`.
Only available when notifications are enabled in the config. Not persisted across Frigate restarts.
### `frigate/notifications/state` ### `frigate/notifications/state`
@@ -308,6 +310,8 @@ Publishes the current health status of each role that is enabled (`audio`, `dete
- `offline`: Stream is offline and is being restarted - `offline`: Stream is offline and is being restarted
- `disabled`: Camera is currently turned off (either at runtime via the `enabled/set` topic, or persistently via the configuration file). See [Camera state](/configuration/live#camera-state) for the distinction. - `disabled`: Camera is currently turned off (either at runtime via the `enabled/set` topic, or persistently via the configuration file). See [Camera state](/configuration/live#camera-state) for the distinction.
These reflect the state of Frigate's process for that role, not the camera's reachability, so an unreachable camera alternates between `offline` and `online` as the watchdog restarts ffmpeg. Wait for the status to hold steady (for example with Home Assistant's `for:`) rather than acting on a single message.
### `frigate/<camera_name>/<object_name>` ### `frigate/<camera_name>/<object_name>`
Publishes the count of objects for the camera for use as a sensor in Home Assistant. Publishes the count of objects for the camera for use as a sensor in Home Assistant.
@@ -549,35 +553,42 @@ must be enabled in the configuration.
Topic with current state of Birdseye for a camera. Published values are `ON` and `OFF`. Topic with current state of Birdseye for a camera. Published values are `ON` and `OFF`.
### `frigate/<camera_name>/birdseye_mode/set` ### `frigate/<camera_name>/birdseye_modes/set`
Topic to set Birdseye mode for a camera. Birdseye offers different modes to customize under which circumstances the camera is shown. Topic to set the Birdseye activity types for a camera. Send one uppercase activity type or combine multiple types with commas, for example `MOTION,ALERTS`.
_Note: Changing the value from `CONTINUOUS` -> `MOTION | OBJECTS` will take up to 30 seconds for _Note: Changing the value from `CONTINUOUS` to non-continuous activity types will take up to 30 seconds for
the camera to be removed from the view._ the camera to be removed from the view._
| Command | Description | | Command | Description |
| ------------ | ----------------------------------------------------------------- | | ------------- | ---------------------------------------------------------------- |
| `CONTINUOUS` | Always included | | `CONTINUOUS` | Always included |
| `MOTION` | Show when detected motion within the last 30 seconds are included | | `MOTION` | Shown if motion was detected within the last 30 seconds |
| `OBJECTS` | Shown if an active object tracked within the last 30 seconds | | `ALL_OBJECTS` | Shown if a tracked object was present within the last 30 seconds |
| `ALERTS` | Shown while an alert review item is in progress |
| `DETECTIONS` | Shown while a detection review item is in progress |
| `NONE` | Never included |
### `frigate/<camera_name>/birdseye_mode/state` ### `frigate/<camera_name>/birdseye_modes/state`
Topic with current state of the Birdseye mode for a camera. Published values are `CONTINUOUS`, `MOTION`, `OBJECTS`. Topic with the current Birdseye activity types for a camera. Multiple enabled types are published as a comma-separated value in the order `CONTINUOUS`, `MOTION`, `ALL_OBJECTS`, `ALERTS`, `DETECTIONS`. `NONE` is published when no activity types are enabled.
### `frigate/<camera_name>/notifications/set` ### `frigate/<camera_name>/notifications/set`
Topic to turn notifications on and off. Expected values are `ON` and `OFF`. Topic to turn notifications for a camera on and off. Expected values are `ON` and `OFF`.
`ON` is ignored unless notifications are enabled in the config for the camera. This is not persisted across Frigate restarts. It is the same control the UI labels **Suspend until restart**.
### `frigate/<camera_name>/notifications/state` ### `frigate/<camera_name>/notifications/state`
Topic with current state of notifications. Published values are `ON` and `OFF`. Topic with current state of notifications. Published values are `ON` and `OFF`. This is the authoritative topic for whether a camera will notify.
### `frigate/<camera_name>/notifications/suspend` ### `frigate/<camera_name>/notifications/suspend`
Topic to suspend notifications for a certain number of minutes. Expected value is an integer. Topic to suspend notifications for a certain number of minutes. Expected value is an integer. Separate from `notifications/set`: it does not change `notifications/state`, and is ignored while notifications are off.
### `frigate/<camera_name>/notifications/suspended` ### `frigate/<camera_name>/notifications/suspended`
Topic with timestamp that notifications are suspended until. Published value is a UNIX timestamp, or 0 if notifications are not suspended. Topic with timestamp that notifications are suspended until. Published value is a UNIX timestamp, or 0 if there is no timed suspension.
`0` does not mean notifications are enabled: `notifications/set` `OFF` clears the timed suspension, so this publishes `0` while `notifications/state` is `OFF`.
+11 -11
View File
@@ -59,13 +59,12 @@ You can view all of your submitted images at [https://plus.frigate.video](https:
Once you have [requested your first model](../plus/first_model.md) and gotten your own model ID, it can be used with a special model path. No other information needs to be configured for Frigate+ models because it fetches the remaining config from Frigate+ automatically. Once you have [requested your first model](../plus/first_model.md) and gotten your own model ID, it can be used with a special model path. No other information needs to be configured for Frigate+ models because it fetches the remaining config from Frigate+ automatically.
You can either choose the new model from the <NavPath path="Settings > System > Detectors and model" /> pane in the Frigate UI (the **Frigate+ Model** tab), or manually set the model at the root level in your config: You can either choose the new model from the <NavPath path="Settings > System > Detection models" /> pane in the Frigate UI (on the **Frigate+** tab of the model you want to change), or set it on that model in your config:
```yaml ```yaml
detectors: ... models:
- devices: ...
model: path: plus://<your_model_id>
path: plus://<your_model_id>
``` ```
:::note :::note
@@ -79,10 +78,11 @@ Models are downloaded into the `/config/model_cache` folder and only downloaded
If needed, you can override the labelmap for Frigate+ models. This is not recommended as renaming labels will break the Submit to Frigate+ feature if the labels are not available in Frigate+. If needed, you can override the labelmap for Frigate+ models. This is not recommended as renaming labels will break the Submit to Frigate+ feature if the labels are not available in Frigate+.
```yaml ```yaml
model: models:
path: plus://<your_model_id> - devices: ...
labelmap: path: plus://<your_model_id>
3: animal labelmap:
4: animal 3: animal
5: animal 4: animal
5: animal
``` ```
+4 -5
View File
@@ -30,16 +30,15 @@ Models available in Frigate+ can be used with a special model path. No other inf
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
Navigate to <NavPath path="Settings > System > Detectors and model" />. In the **Detection Model** section, choose the **Frigate+** tab. Select your new Frigate+ model from the **Available Frigate+ models** dropdown, then click **Save**. Restart Frigate to apply the change. Navigate to <NavPath path="Settings > System > Detection models" />. On the model you want to change, choose the **Frigate+** tab and select your new Frigate+ model from the **Available Frigate+ models** dropdown, then click **Save**. Restart Frigate to apply the change.
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: ... models:
- devices: ...
model: path: plus://<your_model_id>
path: plus://<your_model_id>
``` ```
:::tip :::tip
+1 -1
View File
@@ -131,7 +131,7 @@ The process was killed by the CPU for executing an unsupported instruction. Ther
<FaqItem id="onnx-invalidprotobuf" question="ONNX Runtime InvalidProtobuf / failed to load model"> <FaqItem id="onnx-invalidprotobuf" question="ONNX Runtime InvalidProtobuf / failed to load model">
ONNX Runtime could not parse the model file. The file exists but its contents are not a valid ONNX model, usually a corrupted or interrupted download in `model_cache`, or the wrong file pointed at by `model.path`. Delete the cached model file so Frigate re-downloads it, and confirm `model.path` points at an actual `.onnx` model. See [ONNX detector configuration](/configuration/object_detectors#onnx). ONNX Runtime could not parse the model file. The file exists but its contents are not a valid ONNX model, usually a corrupted or interrupted download in `model_cache`, or the wrong file pointed at by a model's `path`. Delete the cached model file so Frigate re-downloads it, and confirm the model's `path` points at an actual `.onnx` model. See [ONNX detector configuration](/configuration/object_detectors#onnx).
</FaqItem> </FaqItem>
+41 -1
View File
@@ -3,7 +3,31 @@ id: cpu
title: High CPU Usage title: High CPU Usage
--- ---
High CPU usage can impact Frigate's performance and responsiveness. This guide outlines the most effective configuration changes to help reduce CPU consumption and optimize resource usage. High CPU usage can impact Frigate's performance and responsiveness. This guide explains how to interpret the CPU values Frigate reports and outlines the most effective configuration changes to help reduce CPU consumption and optimize resource usage.
## Understanding Frigate's Reported CPU Usage
Frigate's CPU percentages often look much higher than what the host reports. Usually both numbers are correct and are simply measured against different denominators, so confirm you actually have a problem before tuning anything.
### Per-process values are relative to a single core
The values Frigate reports for FFmpeg, capture, detect, detector, and other processes follow the same convention as `top`: 100% means one CPU core is fully saturated, not that the whole system is saturated. A multithreaded process such as FFmpeg can legitimately report well over 100%.
Host and hypervisor tools instead report a percentage of the machine's total capacity across all cores. This includes `docker stats`, the `htop` summary, the Proxmox summary graph, the Unraid dashboard, Synology Resource Monitor, and Home Assistant's system monitor sensors. To reconcile the two:
```
host percentage ≈ (sum of Frigate's process percentages) / (number of cores)
```
On a 4 core system, an FFmpeg process reporting 100% is consuming one quarter of the machine, so the host will show roughly 25 to 30% once the remaining Frigate processes are included. That same 100% on a 16 core system is about 6%. Frigate's own warning thresholds use the per-core convention as well, so an FFmpeg process is flagged at 20% of a single core, not 20% of the system.
### Instantaneous samples and averages measure different things
Frigate collects stats every 15 seconds, and the `cpu` value covers only the interval since the previous collection. The `cpu_average` value in the stats API and MQTT payload is the average across the entire life of the process, and it is what the high CPU usage warnings are based on. Host dashboards generally plot data averaged over a longer window, so a single Frigate sample can show a peak that a host graph never displays. A process that has just started, such as FFmpeg after a camera reconnect, reports 0 until it has been sampled twice.
### The system-wide value depends on what the container can see
The system CPU value is read from `/proc/stat`. Under Docker that file belongs to the host, so the value covers the entire machine including workloads unrelated to Frigate, and it will not match `docker stats` for the Frigate container. Under an LXC container, lxcfs virtualizes `/proc/stat` and the value reflects only the cores assigned to the container. In a virtual machine, the guest sees only its assigned vCPUs while the hypervisor divides by every physical thread on the node, so guest and host percentages will not agree even when both are accurate.
## 1. Hardware Acceleration for Video Decoding ## 1. Hardware Acceleration for Video Decoding
@@ -72,3 +96,19 @@ The model you use significantly impacts detector performance. Frigate provides d
- Larger models (640x640): Slower inference, can sometimes have higher accuracy on very large objects that take up a majority of the frame. - Larger models (640x640): Slower inference, can sometimes have higher accuracy on very large objects that take up a majority of the frame.
For more detail on picking the right size, see [Choosing a model size](../configuration/object_detectors.md#choosing-a-model-size). For more detail on picking the right size, see [Choosing a model size](../configuration/object_detectors.md#choosing-a-model-size).
## 3. Reducing Detector CPU Usage
**Priority: High**
The **Detector CPU Usage** metric measures the CPU spent converting frames into the tensor format the model expects and post-processing the model's output. It does not include inference, so this value can be high even when you've configured a GPU, NPU, or Coral for object detection.
This metric scales with how many detections per second Frigate runs and how expensive each one is to prepare. Tuning [motion detection](../configuration/motion_detection) is usually the first recommendation to reduce the number of detections. Additionally, you can:
- **Lower `detect -> fps`.** 5 is the recommended value for nearly all cameras. Running at 10 doubles the frames eligible for detection and is one of the largest contributors to this metric.
- **Use a 320x320 model.** A 640x640 model has 4 times as many pixels to transpose, convert, and copy on every inference.
- **Prefer a model that takes integer input.** Models configured with `input_dtype: float` require each frame to be converted to float32 and normalized on the CPU first. Models taking `int` input, such as the tflite models used by the Edge TPU, skip that step.
- **Do not match the detect resolution to the model resolution.** The detect stream should match your camera's aspect ratio, for example `1280x720`, not the model's input size. Frigate crops and scales regions of motion itself, so an oversized detect stream only adds work.
- **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.
+16 -2
View File
@@ -65,9 +65,17 @@ This is because Frigate does not run in host mode so localhost points to the Fri
### How do I know if my camera is offline ### How do I know if my camera is offline
A camera being offline can be detected via MQTT or /api/stats, the camera_fps for any offline camera will be 0. Frigate publishes a per-role health status to [`frigate/<camera_name>/status/<role>`](/integrations/mqtt#frigatecamera_namestatusrole), where `<role>` is each enabled role on the camera (`detect`, `record`, and `audio`). The published value is one of:
Also, Home Assistant will mark any offline camera as being unavailable when the camera is offline. - `online`: Frigate's process for that role is running normally
- `offline`: the process is down and Frigate is restarting it
- `disabled`: the camera is turned off, either at runtime or in the configuration file
These reflect the state of Frigate's process for that role, not the camera's reachability, so an unreachable camera alternates between `offline` and `online` as the watchdog restarts ffmpeg. Wait for the status to hold steady (for example with Home Assistant's `for:`) rather than acting on a single message.
Because the status is per role, a camera whose substream is fine but whose recording stream has dropped will report `online` for `detect` and `offline` for `record`. The status is republished whenever it changes.
You can also detect an offline camera through `/api/stats`, where `camera_fps` will be 0.
### How can I view the Frigate log files without using the Web UI? ### How can I view the Frigate log files without using the Web UI?
@@ -125,6 +133,12 @@ cameras:
height: 720 height: 720
``` ```
### What is the `version` key in my config file?
`version` records the config format that your config was last migrated to. On startup Frigate compares it against the format the running version expects, and if it is older it copies your config to `/config/backup_config.yaml`, rewrites it to the new format, and updates `version` as the final step. A config with no `version` key is assumed to predate 0.14 and is migrated from there.
Frigate manages this key for you, so do not set or edit it. Raising it makes Frigate skip migrations your config still needs, and lowering it re-runs migrations against config that has already been converted. Either can leave you with a config that no longer validates.
### Why does Frigate keep creating new tracked objects for my parked car? ### Why does Frigate keep creating new tracked objects for my parked car?
Stationary tracking is designed to _prevent_ this: a parked car should remain a single tracked object rather than generating new ones. If you're repeatedly getting new tracked objects for the same car, it's likely that Frigate is losing the object and re-detecting it as a new one. Stationary tracking is designed to _prevent_ this: a parked car should remain a single tracked object rather than generating new ones. If you're repeatedly getting new tracked objects for the same car, it's likely that Frigate is losing the object and re-detecting it as a new one.
+2 -2
View File
@@ -40,7 +40,7 @@ Deleting a group also clears any custom layout you saved for it.
## Rearranging a camera group layout ## Rearranging a camera group layout
On desktop and tablet, each camera group has its own freely-arrangeable grid. Enter **Edit Layout** mode from the layout button in the lower-right corner: camera tiles gain a drag handle and corner resize handles. Drag a tile to reposition it and drag a corner to resize it (the aspect ratio is preserved). Exit edit mode to save. The layout is stored in your browser per device, so each device can have its own arrangement. On desktop and tablet, each camera group has its own freely-arrangeable grid. Enter **Edit Layout** mode from the layout button in the lower-right corner: camera tiles gain a drag handle and corner resize handles. Drag a tile to reposition it and drag a corner to resize it (the aspect ratio is preserved). Exit edit mode to save. The layout is stored in your browser per device, so each device can have its own arrangement, and layouts can be exported to a file and imported on another device.
The default **All Cameras** dashboard is not manually arrangeable. It automatically sizes tiles based on each camera's aspect ratio (wide cameras span two columns, tall cameras span two rows). The default **All Cameras** dashboard is not manually arrangeable. It automatically sizes tiles based on each camera's aspect ratio (wide cameras span two columns, tall cameras span two rows).
@@ -68,7 +68,7 @@ For non-default groups, the context menu also exposes **Streaming Settings** for
- the **streaming method**: **No Streaming**, **Smart Streaming** (recommended), or **Continuous Streaming** (higher bandwidth), and - the **streaming method**: **No Streaming**, **Smart Streaming** (recommended), or **Continuous Streaming** (higher bandwidth), and
- **compatibility mode**, for devices that have trouble rendering the default player. - **compatibility mode**, for devices that have trouble rendering the default player.
These settings are saved per group and per device in your browser, not in your config file. These settings are saved per group and per device in your browser, not in your config file, and can be exported to a file and imported on another device.
## The single-camera view ## The single-camera view
+1 -2
View File
@@ -63,8 +63,7 @@ SYSTEM_NAV: dict[str, tuple[str, str]] = {
"environment_vars": ("System", "Environment variables"), "environment_vars": ("System", "Environment variables"),
"telemetry": ("System", "Telemetry"), "telemetry": ("System", "Telemetry"),
"birdseye": ("System", "Birdseye"), "birdseye": ("System", "Birdseye"),
"detectors": ("System", "Detectors and model"), "models": ("System", "Detection models"),
"model": ("System", "Detectors and model"),
} }
# All known top-level config section keys # All known top-level config section keys
+277 -8
View File
@@ -713,7 +713,7 @@ paths:
| `improve_contrast` | `ON`, `OFF` | | `improve_contrast` | `ON`, `OFF` |
| `ptz_autotracker` | `ON`, `OFF` | | `ptz_autotracker` | `ON`, `OFF` |
| `birdseye` | `ON`, `OFF` | | `birdseye` | `ON`, `OFF` |
| `birdseye_mode` | `CONTINUOUS`, `MOTION`, `OBJECTS` | | `birdseye_modes` | `CONTINUOUS`, `MOTION`, `ALL_OBJECTS`, `ALERTS`, `DETECTIONS`, `NONE`, or a comma-separated combination |
| `motion_contour_area` | integer | | `motion_contour_area` | integer |
| `motion_threshold` | integer | | `motion_threshold` | integer |
| `motion_mask` | `ON`, `OFF` | | `motion_mask` | `ON`, `OFF` |
@@ -803,7 +803,7 @@ paths:
| `improve_contrast` | `ON`, `OFF` | | `improve_contrast` | `ON`, `OFF` |
| `ptz_autotracker` | `ON`, `OFF` | | `ptz_autotracker` | `ON`, `OFF` |
| `birdseye` | `ON`, `OFF` | | `birdseye` | `ON`, `OFF` |
| `birdseye_mode` | `CONTINUOUS`, `MOTION`, `OBJECTS` | | `birdseye_modes` | `CONTINUOUS`, `MOTION`, `ALL_OBJECTS`, `ALERTS`, `DETECTIONS`, `NONE`, or a comma-separated combination |
| `motion_contour_area` | integer | | `motion_contour_area` | integer |
| `motion_threshold` | integer | | `motion_threshold` | integer |
| `motion_mask` | `ON`, `OFF` | | `motion_mask` | `ON`, `OFF` |
@@ -2308,15 +2308,15 @@ paths:
$ref: '#/components/schemas/HTTPValidationError' $ref: '#/components/schemas/HTTPValidationError'
security: security:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: any x-required-role: camera
description: '**Access:** Any authenticated user.' description: '**Access:** Authenticated user with access to the referenced camera.'
/review/summarize/start/{start_ts}/end/{end_ts}: /review/summarize/start/{start_ts}/end/{end_ts}:
post: post:
tags: tags:
- Review - Review
summary: Generate Review Summary summary: Generate Review Summary
description: |- description: |-
**Access:** Admin role required. **Access:** Authenticated user with access to all cameras.
Use GenAI to summarize review items over a period of time. Use GenAI to summarize review items over a period of time.
operationId: operationId:
@@ -2347,8 +2347,8 @@ paths:
schema: schema:
$ref: '#/components/schemas/HTTPValidationError' $ref: '#/components/schemas/HTTPValidationError'
security: security:
- frigateAdminAuth: [] - frigateUserAuth: []
x-required-role: admin x-required-role: all_cameras
/: /:
get: get:
tags: tags:
@@ -2946,6 +2946,44 @@ paths:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: any x-required-role: any
description: '**Access:** Any authenticated user.' description: '**Access:** Any authenticated user.'
/categorized_object_names:
get:
tags:
- App
summary: Get known object names by object type
description: |-
**Access:** Any authenticated user.
Returns the sub labels and attributes this install can attach,
grouped by object type. Unlike /sub_labels, which reflects what has already been
detected, this reads the config and model files, so it covers recognized face
names, named license plates, custom object classification categories, and the
detector attributes of tracked objects.
operationId: categorized_object_names_categorized_object_names_get
parameters:
- name: object_type
in: query
required: false
schema:
anyOf:
- type: string
- type: 'null'
title: Object Type
responses:
'200':
description: Successful Response
content:
application/json:
schema: {}
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateUserAuth: []
x-required-role: any
/audio_labels: /audio_labels:
get: get:
tags: tags:
@@ -3972,6 +4010,49 @@ paths:
security: security:
- frigateAdminAuth: [] - frigateAdminAuth: []
x-required-role: admin x-required-role: admin
/hardware/probe:
get:
tags:
- Hardware
summary: Probe Hardware
description: |-
**Access:** Admin role required.
Get the object detection hardware attached to this system.
Args:
refresh: Probe again instead of returning the cached result
Returns:
Every kind of detection hardware that was found
operationId: probe_hardware_hardware_probe_get
parameters:
- name: refresh
in: query
required: false
schema:
type: boolean
default: false
title: Refresh
responses:
'200':
description: Successful Response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/DetectionHardware'
title: Response Probe Hardware Hardware Probe Get
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
/events: /events:
get: get:
tags: tags:
@@ -5093,6 +5174,7 @@ paths:
NOTES: NOTES:
- Creating a manual event does not trigger an update to /events MQTT topic. - Creating a manual event does not trigger an update to /events MQTT topic.
- If a duration is set to null, the event will need to be ended manually by calling /events/{event_id}/end. - If a duration is set to null, the event will need to be ended manually by calling /events/{event_id}/end.
- The review item is an alert unless the label is listed in the camera's review -> detections -> labels config.
operationId: create_event_events__camera_name___label__create_post operationId: create_event_events__camera_name___label__create_post
parameters: parameters:
- name: camera_name - name: camera_name
@@ -5983,6 +6065,65 @@ paths:
security: security:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: camera x-required-role: camera
/vod/{camera_name}/{stream}/start/{start_ts}/end/{end_ts}:
get:
tags:
- Media
summary: Vod Ts Stream
description: |-
**Access:** Authenticated user with access to the referenced camera.
Returns an HLS playlist pinned to one stream type (main or sub) for the specified timestamp-range on the specified camera. Append /master.m3u8 or /index.m3u8 for HLS playback.
operationId:
vod_ts_stream_vod__camera_name___stream__start__start_ts__end__end_ts__get
parameters:
- name: camera_name
in: path
required: true
schema:
anyOf:
- type: string
- type: 'null'
title: Camera Name
- name: stream
in: path
required: true
schema:
$ref: '#/components/schemas/VodStreamPreference'
- name: start_ts
in: path
required: true
schema:
type: number
title: Start Ts
- name: end_ts
in: path
required: true
schema:
type: number
title: End Ts
- name: force_discontinuity
in: query
required: false
schema:
type: boolean
default: false
title: Force Discontinuity
responses:
'200':
description: Successful Response
content:
application/json:
schema: {}
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateUserAuth: []
x-required-role: camera
/events/{event_id}/snapshot.jpg: /events/{event_id}/snapshot.jpg:
get: get:
tags: tags:
@@ -6921,6 +7062,63 @@ paths:
security: security:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: camera x-required-role: camera
/{camera_name}/recordings/coverage:
get:
tags:
- Recordings
summary: Recordings Coverage
description: |-
**Access:** Authenticated user with access to the referenced camera.
Returns merged recording coverage spans plus codec compatibility.
codecs_compatible is false only when more than one known video codec
appears across the range's rows, the case where the merged vod route
degrades to a single-stream manifest.
operationId: recordings_coverage__camera_name__recordings_coverage_get
parameters:
- name: camera_name
in: path
required: true
schema:
anyOf:
- type: string
- type: 'null'
title: Camera Name
- name: after
in: query
required: true
schema:
type: number
title: After
- name: before
in: query
required: true
schema:
type: number
title: Before
- name: timelines
in: query
required: false
schema:
type: boolean
default: false
title: Timelines
responses:
'200':
description: Successful Response
content:
application/json:
schema: {}
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateUserAuth: []
x-required-role: camera
/{camera_name}/recordings: /{camera_name}/recordings:
get: get:
tags: tags:
@@ -7108,7 +7306,9 @@ paths:
schema: schema:
$ref: '#/components/schemas/DebugReplayStartResponse' $ref: '#/components/schemas/DebugReplayStartResponse'
'400': '400':
description: Invalid camera, time range, or no recordings description: Invalid camera or time range
'404':
description: No recordings in the requested time range
'409': '409':
description: A replay session is already active description: A replay session is already active
'422': '422':
@@ -7685,6 +7885,46 @@ components:
required: required:
- ids - ids
title: DeleteFaceImagesBody title: DeleteFaceImagesBody
DetectionHardware:
properties:
key:
type: string
title: Hardware key
description: Stable identifier for this kind of hardware.
detector:
type: string
title: Detector type
description: The detector that drives this hardware.
name:
type: string
title: Hardware name
description: Human readable name for this kind of hardware.
units:
items:
$ref: '#/components/schemas/HardwareUnit'
type: array
title: Units
description: Each physical piece of this hardware that was found.
count:
type: integer
title: Unit count
description: How many units were found.
unlimited:
type: boolean
title: Unlimited detectors
description: Whether this hardware can run more inference processes
than there are units.
type: object
required:
- key
- detector
- name
- units
- count
- unlimited
title: DetectionHardware
description: A kind of detection hardware, and every unit of it that was
found.
EventCreateResponse: EventCreateResponse:
properties: properties:
success: success:
@@ -8412,6 +8652,24 @@ components:
title: Detail title: Detail
type: object type: object
title: HTTPValidationError title: HTTPValidationError
HardwareUnit:
properties:
device:
type: string
title: Device string
description: The value to put in a model's devices list, for example
'edgetpu:pci:1'.
label:
type: string
title: Unit label
description: How to identify this unit among others of the same kind,
for example 'PCIe 1'.
type: object
required:
- device
- label
title: HardwareUnit
description: One physical piece of hardware.
Last24HoursReview: Last24HoursReview:
properties: properties:
reviewed_alert: reviewed_alert:
@@ -8902,6 +9160,17 @@ components:
- msg - msg
- type - type
title: ValidationError title: ValidationError
VodStreamPreference:
type: string
enum:
- main
- sub
title: VodStreamPreference
description: |-
Stream pin for the path-segment VOD route.
nginx-vod derives its mapping fetch URI from the playlist URL path
(query params are dropped), so the preference must be a path segment.
securitySchemes: securitySchemes:
frigateAdminAuth: frigateAdminAuth:
type: apiKey type: apiKey
+58 -29
View File
@@ -71,6 +71,7 @@ from frigate.util.config import (
find_config_file, find_config_file,
redact_credential, redact_credential,
) )
from frigate.util.object_names import get_categorized_object_names
from frigate.util.schema import get_config_schema from frigate.util.schema import get_config_schema
from frigate.util.services import ( from frigate.util.services import (
get_nvidia_driver_info, get_nvidia_driver_info,
@@ -291,10 +292,6 @@ def config(request: Request):
config: dict[str, dict[str, Any]] = config_obj.model_dump( config: dict[str, dict[str, Any]] = config_obj.model_dump(
mode="json", warnings="none", exclude_none=True mode="json", warnings="none", exclude_none=True
) )
config["detectors"] = {
name: detector.model_dump(mode="json", warnings="none", exclude_none=True)
for name, detector in config_obj.detectors.items()
}
# remove environment_vars for non-admin users # remove environment_vars for non-admin users
if request.headers.get("remote-role") != "admin": if request.headers.get("remote-role") != "admin":
@@ -375,31 +372,28 @@ def config(request: Request):
config["go2rtc"]["streams"][stream_name] = cleaned config["go2rtc"]["streams"][stream_name] = cleaned
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()} config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
config["model"]["colormap"] = config_obj.model.colormap
config["model"]["all_attributes"] = config_obj.model.all_attributes
config["model"]["non_logo_attributes"] = config_obj.model.non_logo_attributes
# Add model plus data if plus is enabled for index, model in enumerate(config_obj.models):
if config["plus"]["enabled"]: model_dict = config["models"][index]
model_path = config.get("model", {}).get("path") model_dict["colormap"] = model.colormap
if model_path: model_dict["all_attributes"] = model.all_attributes
model_json_path = FilePath(model_path).with_suffix(".json") model_dict["non_logo_attributes"] = model.non_logo_attributes
model_dict["labelmap"] = model.merged_labelmap
if not config["plus"]["enabled"]:
continue
# Add model plus data if plus is enabled
model_dict["plus"] = None
if model.path:
model_json_path = FilePath(model.path).with_suffix(".json")
try: try:
with open(model_json_path) as f: with open(model_json_path) as f:
model_plus_data = json.load(f) model_dict["plus"] = json.load(f)
config["model"]["plus"] = model_plus_data except (FileNotFoundError, json.JSONDecodeError):
except FileNotFoundError: pass
config["model"]["plus"] = None
except json.JSONDecodeError:
config["model"]["plus"] = None
else:
config["model"]["plus"] = None
# use merged labelamp
for detector_config in config["detectors"].values():
detector_config["model"]["labelmap"] = (
request.app.frigate_config.model.merged_labelmap
)
return JSONResponse(content=config) return JSONResponse(content=config)
@@ -1313,9 +1307,41 @@ def get_sub_labels(
return JSONResponse(content=sub_labels) return JSONResponse(content=sub_labels)
@router.get(
"/categorized_object_names",
dependencies=[Depends(allow_any_authenticated())],
summary="Get known object names by object type",
description="""Returns the sub labels and attributes this install can attach,
grouped by object type. Unlike /sub_labels, which reflects what has already been
detected, this reads the config and model files, so it covers recognized face
names, named license plates, custom object classification categories, and the
detector attributes of tracked objects.""",
)
def categorized_object_names(
request: Request,
object_type: str | None = None,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
):
return JSONResponse(
content=get_categorized_object_names(
request.app.frigate_config, allowed_cameras, object_type
)
)
@router.get("/audio_labels", dependencies=[Depends(allow_any_authenticated())]) @router.get("/audio_labels", dependencies=[Depends(allow_any_authenticated())])
def get_audio_labels(): def get_audio_labels(request: Request):
labels = load_labels("/audio-labelmap.txt", prefill=521) labels = load_labels("/audio-labelmap.txt", prefill=521)
# configured overrides group several audio classes under one label, and the
# detector merges them over the defaults at runtime. Offer them here too, or
# a grouped label could never be picked in the UI.
config: FrigateConfig = request.app.frigate_config
labels.update(config.audio.labelmap)
for camera in config.cameras.values():
labels.update(camera.audio.labelmap)
return JSONResponse(content=labels) return JSONResponse(content=labels)
@@ -1337,11 +1363,14 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
modelList = models["list"] modelList = models["list"]
config: FrigateConfig = request.app.frigate_config
primary_model = config.primary_model
# current model type # current model type
modelType = request.app.frigate_config.model.model_type modelType = primary_model.model_type
# current detectorType for comparing to supportedDetectors # current detectorType for comparing to supportedDetectors
detectorType = list(request.app.frigate_config.detectors.values())[0].type detectorType = config.devices_for_model(primary_model)[0].detector
validModels = [] validModels = []
+26 -3
View File
@@ -83,6 +83,7 @@ def require_admin_by_default():
"/nvinfo", "/nvinfo",
"/labels", "/labels",
"/sub_labels", "/sub_labels",
"/categorized_object_names",
"/plus/models", "/plus/models",
"/recognized_license_plates", "/recognized_license_plates",
"/timeline", "/timeline",
@@ -971,6 +972,7 @@ def delete_user(request: Request, username: str):
summary="Update user password", summary="Update user password",
description="Updates a user's password. Users can only change their own password unless they have admin role. Requires the current password to verify identity for non-admin users. Password must be at least 12 characters long. If user changes their own password, a new JWT cookie is automatically issued.", description="Updates a user's password. Users can only change their own password unless they have admin role. Requires the current password to verify identity for non-admin users. Password must be at least 12 characters long. If user changes their own password, a new JWT cookie is automatically issued.",
) )
@limiter.limit(limit_value=rateLimiter.get_limit)
async def update_password( async def update_password(
request: Request, request: Request,
username: str, username: str,
@@ -984,10 +986,11 @@ async def update_password(
current_username = current_user.get("username") current_username = current_user.get("username")
current_role = current_user.get("role") current_role = current_user.get("role")
# viewers can only change their own password # Only admins may target another account. This has to cover every non-admin
if current_role == "viewer" and current_username != username: # role rather than just viewer, since custom roles are arbitrary names
if current_role != "admin" and current_username != username:
raise HTTPException( raise HTTPException(
status_code=403, detail="Viewers can only update their own password" status_code=403, detail="Users can only update their own password"
) )
HASH_ITERATIONS = request.app.frigate_config.auth.hash_iterations HASH_ITERATIONS = request.app.frigate_config.auth.hash_iterations
@@ -1251,3 +1254,23 @@ async def get_allowed_cameras_for_filter(request: Request):
all_camera_names = set(request.app.frigate_config.cameras.keys()) all_camera_names = set(request.app.frigate_config.cameras.keys())
roles_dict = request.app.frigate_config.auth.roles roles_dict = request.app.frigate_config.auth.roles
return User.get_allowed_cameras(role, roles_dict, all_camera_names) return User.get_allowed_cameras(role, roles_dict, all_camera_names)
async def require_full_camera_access(
request: Request,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
):
"""Dependency for endpoints returning data that spans every camera.
Some responses cannot be meaningfully scoped to a subset of cameras, so
rather than filter them the endpoint is limited to callers who can already
see every camera. Admin and viewer always qualify; a custom role qualifies
only when its camera list covers all configured cameras.
"""
all_camera_names = set(request.app.frigate_config.cameras.keys())
if not all_camera_names.issubset(allowed_cameras):
raise HTTPException(
status_code=403,
detail="Access to all cameras is required for this endpoint",
)
+40 -3
View File
@@ -33,7 +33,7 @@ from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdateTopic, CameraConfigUpdateTopic,
) )
from frigate.config.env import substitute_frigate_vars from frigate.config.env import UnknownVariableError, substitute_frigate_vars
from frigate.models import User from frigate.models import User
from frigate.util.builtin import clean_camera_user_pass, get_record_segment_time from frigate.util.builtin import clean_camera_user_pass, get_record_segment_time
from frigate.util.camera_cleanup import cleanup_camera_db, cleanup_camera_files from frigate.util.camera_cleanup import cleanup_camera_db, cleanup_camera_files
@@ -166,7 +166,7 @@ def go2rtc_add_stream(request: Request, stream_name: str, src: str = ""):
if src: if src:
try: try:
resolved_src = substitute_frigate_vars(src) resolved_src = substitute_frigate_vars(src)
except KeyError: except UnknownVariableError:
resolved_src = src resolved_src = src
if is_restricted_go2rtc_source(resolved_src): if is_restricted_go2rtc_source(resolved_src):
@@ -651,6 +651,32 @@ async def _connect_onvif_camera(
raise first_error raise first_error
def _supports_continuous_pan_tilt(nodes) -> bool:
"""Whether any PTZ node advertises continuous pan/tilt velocity.
The web UI's directional controls issue ContinuousMove with a PanTilt
velocity, so continuous pan/tilt is what makes those controls usable. This
is intentionally narrower than ptz_supported, which is true for any device
exposing the ONVIF PTZ service - including zoom/focus-only varifocal lenses.
"""
for node in nodes or []:
spaces = getattr(node, "SupportedPTZSpaces", None) or (
node.get("SupportedPTZSpaces") if isinstance(node, dict) else None
)
if spaces is None:
continue
continuous = getattr(spaces, "ContinuousPanTiltVelocitySpace", None) or (
spaces.get("ContinuousPanTiltVelocitySpace")
if isinstance(spaces, dict)
else None
)
if continuous:
return True
return False
@router.get( @router.get(
"/onvif/probe", "/onvif/probe",
dependencies=[Depends(require_role(["admin"]))], dependencies=[Depends(require_role(["admin"]))],
@@ -808,6 +834,7 @@ async def onvif_probe(
# Check PTZ support and capabilities # Check PTZ support and capabilities
ptz_supported = False ptz_supported = False
pan_tilt_supported = False
presets_count = 0 presets_count = 0
autotrack_supported = False autotrack_supported = False
@@ -841,6 +868,15 @@ async def onvif_probe(
logger.debug(f"Failed to get presets: {e}") logger.debug(f"Failed to get presets: {e}")
presets_count = 0 presets_count = 0
# Check for real (continuous) pan/tilt, which the UI controls need
if ptz_supported:
try:
nodes = await ptz_service.GetNodes()
pan_tilt_supported = _supports_continuous_pan_tilt(nodes)
logger.debug(f"Continuous pan/tilt supported: {pan_tilt_supported}")
except Exception as e:
logger.debug(f"Failed to read PTZ nodes for pan/tilt support: {e}")
# Check for autotracking support - requires both FOV relative movement and MoveStatus # Check for autotracking support - requires both FOV relative movement and MoveStatus
if ptz_supported and first_profile_token and ptz_config_token: if ptz_supported and first_profile_token and ptz_config_token:
# First check for FOV relative movement support # First check for FOV relative movement support
@@ -960,6 +996,7 @@ async def onvif_probe(
"firmware_version": device_info["firmware_version"], "firmware_version": device_info["firmware_version"],
"profiles_count": profiles_count, "profiles_count": profiles_count,
"ptz_supported": ptz_supported, "ptz_supported": ptz_supported,
"pan_tilt_supported": pan_tilt_supported,
"presets_count": presets_count, "presets_count": presets_count,
"autotrack_supported": autotrack_supported, "autotrack_supported": autotrack_supported,
} }
@@ -1349,7 +1386,7 @@ def camera_set(
| `improve_contrast` | `ON`, `OFF` | | `improve_contrast` | `ON`, `OFF` |
| `ptz_autotracker` | `ON`, `OFF` | | `ptz_autotracker` | `ON`, `OFF` |
| `birdseye` | `ON`, `OFF` | | `birdseye` | `ON`, `OFF` |
| `birdseye_mode` | `CONTINUOUS`, `MOTION`, `OBJECTS` | | `birdseye_modes` | `CONTINUOUS`, `MOTION`, `ALL_OBJECTS`, `ALERTS`, `DETECTIONS`, `NONE`, or a comma-separated combination |
| `motion_contour_area` | integer | | `motion_contour_area` | integer |
| `motion_threshold` | integer | | `motion_threshold` | integer |
| `motion_mask` | `ON`, `OFF` | | `motion_mask` | `ON`, `OFF` |
+27 -4
View File
@@ -50,6 +50,7 @@ from frigate.jobs.vlm_watch import (
stop_vlm_watch_job, stop_vlm_watch_job,
) )
from frigate.models import Event from frigate.models import Event
from frigate.util.object_names import get_categorized_object_names
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -539,6 +540,11 @@ async def execute_tool(
if tool_name == "search_objects": if tool_name == "search_objects":
return await _execute_search_objects(request, arguments, allowed_cameras) return await _execute_search_objects(request, arguments, allowed_cameras)
if tool_name == "get_categorized_object_names":
return JSONResponse(
content=_execute_get_categorized_object_names(request, allowed_cameras)
)
if tool_name == "find_similar_objects": if tool_name == "find_similar_objects":
result = await _execute_find_similar_objects( result = await _execute_find_similar_objects(
request, arguments, allowed_cameras request, arguments, allowed_cameras
@@ -591,7 +597,7 @@ async def _execute_get_live_context(
try: try:
frame_processor = request.app.detected_frames_processor frame_processor = request.app.detected_frames_processor
camera_state = frame_processor.camera_states.get(camera) camera_state = frame_processor.get_camera_state(camera)
if camera_state is None: if camera_state is None:
return { return {
@@ -655,7 +661,7 @@ async def _get_live_frame_image_url(
return None return None
try: try:
frame_processor = request.app.detected_frames_processor frame_processor = request.app.detected_frames_processor
if camera not in frame_processor.camera_states: if frame_processor.get_camera_state(camera) is None:
return None return None
frame = frame_processor.get_current_frame(camera, {}) frame = frame_processor.get_current_frame(camera, {})
if frame is None: if frame is None:
@@ -717,6 +723,21 @@ async def _execute_set_camera_state(
return {"success": True, "camera": camera, "feature": feature, "value": value} return {"success": True, "camera": camera, "feature": feature, "value": value}
def _execute_get_categorized_object_names(
request: Request,
allowed_cameras: list[str],
) -> dict[str, Any]:
names = get_categorized_object_names(request.app.frigate_config, allowed_cameras)
if not names:
return {
"names": {},
"message": "No names configured; search by label or semantic_query.",
}
return {"names": names}
async def _execute_tool_internal( async def _execute_tool_internal(
tool_name: str, tool_name: str,
arguments: dict[str, Any], arguments: dict[str, Any],
@@ -741,6 +762,8 @@ async def _execute_tool_internal(
except (json.JSONDecodeError, AttributeError) as e: except (json.JSONDecodeError, AttributeError) as e:
logger.warning(f"Failed to extract tool result: {e}") logger.warning(f"Failed to extract tool result: {e}")
return {"error": "Failed to parse tool result"} return {"error": "Failed to parse tool result"}
elif tool_name == "get_categorized_object_names":
return _execute_get_categorized_object_names(request, allowed_cameras)
elif tool_name == "find_similar_objects": elif tool_name == "find_similar_objects":
return await _execute_find_similar_objects(request, arguments, allowed_cameras) return await _execute_find_similar_objects(request, arguments, allowed_cameras)
elif tool_name == "set_camera_state": elif tool_name == "set_camera_state":
@@ -773,8 +796,8 @@ async def _execute_tool_internal(
else: else:
logger.error( logger.error(
"Tool call failed: unknown tool %r. Expected one of: search_objects, find_similar_objects, " "Tool call failed: unknown tool %r. Expected one of: search_objects, find_similar_objects, "
"get_live_context, start_camera_watch, stop_camera_watch, get_profile_status, get_recap. " "get_categorized_object_names, get_live_context, start_camera_watch, stop_camera_watch, "
"Arguments received: %s", "get_profile_status, get_recap. Arguments received: %s",
tool_name, tool_name,
json.dumps(arguments), json.dumps(arguments),
) )
+132 -63
View File
@@ -11,7 +11,6 @@ from typing import Any
import cv2 import cv2
from fastapi import APIRouter, Depends, Request, UploadFile from fastapi import APIRouter, Depends, Request, UploadFile
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from pathvalidate import sanitize_filename
from peewee import DoesNotExist from peewee import DoesNotExist
from playhouse.shortcuts import model_to_dict from playhouse.shortcuts import model_to_dict
@@ -43,12 +42,21 @@ from frigate.util.classification import (
write_training_metadata, write_training_metadata,
) )
from frigate.util.file import get_event_snapshot from frigate.util.file import get_event_snapshot
from frigate.util.path import safe_join, sanitize_path_component
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
router = APIRouter(tags=[Tags.classification]) router = APIRouter(tags=[Tags.classification])
def invalid_name_response(value: str) -> JSONResponse:
"""Response for a name that cannot be used as a path component."""
return JSONResponse(
content={"success": False, "message": f"Invalid name: {value}"},
status_code=400,
)
@router.get( @router.get(
"/faces", "/faces",
response_model=FacesResponse, response_model=FacesResponse,
@@ -98,9 +106,7 @@ def reclassify_face(request: Request, body: dict = None):
) )
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
training_file = os.path.join( training_file = safe_join(FACE_DIR, "train", json.get("training_file", ""))
FACE_DIR, f"train/{sanitize_filename(json.get('training_file', ''))}"
)
if not training_file or not os.path.isfile(training_file): if not training_file or not os.path.isfile(training_file):
return JSONResponse( return JSONResponse(
@@ -150,8 +156,10 @@ def train_face(request: Request, name: str, body: dict = None):
) )
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
training_file_name = sanitize_filename(json.get("training_file", "")) training_file_name = json.get("training_file", "")
training_file = os.path.join(FACE_DIR, f"train/{training_file_name}") training_file = (
safe_join(FACE_DIR, "train", training_file_name) if training_file_name else None
)
event_id = json.get("event_id") event_id = json.get("event_id")
if not training_file_name and not event_id: if not training_file_name and not event_id:
@@ -165,7 +173,9 @@ def train_face(request: Request, name: str, body: dict = None):
status_code=400, status_code=400,
) )
if training_file_name and not os.path.isfile(training_file): if training_file_name and (
training_file is None or not os.path.isfile(training_file)
):
return JSONResponse( return JSONResponse(
content=( content=(
{ {
@@ -176,9 +186,13 @@ def train_face(request: Request, name: str, body: dict = None):
status_code=404, status_code=404,
) )
sanitized_name = sanitize_filename(name) sanitized_name = sanitize_path_component(name)
new_file_folder = safe_join(FACE_DIR, name)
if sanitized_name is None or new_file_folder is None:
return invalid_name_response(name)
new_name = f"{sanitized_name}-{datetime.datetime.now().timestamp()}.webp" new_name = f"{sanitized_name}-{datetime.datetime.now().timestamp()}.webp"
new_file_folder = os.path.join(FACE_DIR, f"{sanitized_name}")
os.makedirs(new_file_folder, exist_ok=True) os.makedirs(new_file_folder, exist_ok=True)
@@ -261,9 +275,12 @@ async def create_face(request: Request, name: str):
content={"message": "Face recognition is not enabled.", "success": False}, content={"message": "Face recognition is not enabled.", "success": False},
) )
os.makedirs( face_folder = safe_join(FACE_DIR, name.replace(" ", "_"))
os.path.join(FACE_DIR, sanitize_filename(name.replace(" ", "_"))), exist_ok=True
) if face_folder is None:
return invalid_name_response(name)
os.makedirs(face_folder, exist_ok=True)
return JSONResponse( return JSONResponse(
status_code=200, status_code=200,
content={"success": False, "message": "Successfully created face folder."}, content={"success": False, "message": "Successfully created face folder."},
@@ -287,6 +304,9 @@ def register_face(request: Request, name: str, file: UploadFile):
content={"message": "Face recognition is not enabled.", "success": False}, content={"message": "Face recognition is not enabled.", "success": False},
) )
if sanitize_path_component(name) is None:
return invalid_name_response(name)
context: EmbeddingsContext = request.app.embeddings context: EmbeddingsContext = request.app.embeddings
result = None if context is None else context.register_face(name, file.file.read()) result = None if context is None else context.register_face(name, file.file.read())
@@ -356,8 +376,8 @@ def reclassify_face_image(request: Request, name: str, body: dict = None):
) )
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
image_id = sanitize_filename(json.get("id", "")) image_id = sanitize_path_component(json.get("id", ""))
new_name = sanitize_filename(json.get("new_name", "")) new_name = sanitize_path_component(json.get("new_name", ""))
if not image_id or not new_name: if not image_id or not new_name:
return JSONResponse( return JSONResponse(
@@ -381,7 +401,12 @@ def reclassify_face_image(request: Request, name: str, body: dict = None):
status_code=400, status_code=400,
) )
source_folder = os.path.join(FACE_DIR, sanitize_filename(name)) source_folder = safe_join(FACE_DIR, name)
target_folder = safe_join(FACE_DIR, new_name)
if source_folder is None or target_folder is None:
return invalid_name_response(name)
source_file = os.path.join(source_folder, image_id) source_file = os.path.join(source_folder, image_id)
if not os.path.isfile(source_file): if not os.path.isfile(source_file):
@@ -396,7 +421,6 @@ def reclassify_face_image(request: Request, name: str, body: dict = None):
) )
target_filename = f"{new_name}-{datetime.datetime.now().timestamp()}.webp" target_filename = f"{new_name}-{datetime.datetime.now().timestamp()}.webp"
target_folder = os.path.join(FACE_DIR, new_name)
os.makedirs(target_folder, exist_ok=True) os.makedirs(target_folder, exist_ok=True)
shutil.move(source_file, os.path.join(target_folder, target_filename)) shutil.move(source_file, os.path.join(target_folder, target_filename))
@@ -430,8 +454,19 @@ def deregister_faces(request: Request, name: str, body: DeleteFaceImagesBody):
content={"message": "Face recognition is not enabled.", "success": False}, content={"message": "Face recognition is not enabled.", "success": False},
) )
sanitized_name = sanitize_path_component(name)
if sanitized_name is None:
return invalid_name_response(name)
sanitized_ids = [
component
for component in map(sanitize_path_component, body.ids)
if component is not None
]
context: EmbeddingsContext = request.app.embeddings context: EmbeddingsContext = request.app.embeddings
context.delete_face_ids(name, map(lambda file: sanitize_filename(file), body.ids)) context.delete_face_ids(sanitized_name, sanitized_ids)
return JSONResponse( return JSONResponse(
content=({"success": True, "message": "Successfully deleted faces."}), content=({"success": True, "message": "Successfully deleted faces."}),
status_code=200, status_code=200,
@@ -642,7 +677,11 @@ def transcribe_audio(request: Request, body: AudioTranscriptionBody):
def get_classification_dataset(name: str): def get_classification_dataset(name: str):
dataset_dict: dict[str, list[str]] = {} dataset_dict: dict[str, list[str]] = {}
dataset_dir = os.path.join(CLIPS_DIR, sanitize_filename(name), "dataset") sanitized_name = sanitize_path_component(name)
dataset_dir = safe_join(CLIPS_DIR, name, "dataset")
if sanitized_name is None or dataset_dir is None:
return invalid_name_response(name)
if not os.path.exists(dataset_dir): if not os.path.exists(dataset_dir):
return JSONResponse( return JSONResponse(
@@ -664,8 +703,8 @@ def get_classification_dataset(name: str):
dataset_dict[category_name].append(file) dataset_dict[category_name].append(file)
# Get training metadata # Get training metadata
metadata = read_training_metadata(sanitize_filename(name)) metadata = read_training_metadata(sanitized_name)
current_image_count = get_dataset_image_count(sanitize_filename(name)) current_image_count = get_dataset_image_count(sanitized_name)
if metadata is None: if metadata is None:
training_metadata = { training_metadata = {
@@ -729,8 +768,8 @@ def get_custom_attributes(
if object_type is not None and object_type not in model_objects: if object_type is not None and object_type not in model_objects:
continue continue
dataset_dir = os.path.join(CLIPS_DIR, sanitize_filename(model_key), "dataset") dataset_dir = safe_join(CLIPS_DIR, model_key, "dataset")
if not os.path.exists(dataset_dir): if dataset_dir is None or not os.path.exists(dataset_dir):
continue continue
attributes = [] attributes = []
@@ -760,7 +799,10 @@ def get_custom_attributes(
The name must exist in the classification models. Returns a success message or an error if the name is invalid.""", The name must exist in the classification models. Returns a success message or an error if the name is invalid.""",
) )
def get_classification_images(name: str): def get_classification_images(name: str):
train_dir = os.path.join(CLIPS_DIR, sanitize_filename(name), "train") train_dir = safe_join(CLIPS_DIR, name, "train")
if train_dir is None:
return invalid_name_response(name)
if not os.path.exists(train_dir): if not os.path.exists(train_dir):
return JSONResponse(status_code=200, content=[]) return JSONResponse(status_code=200, content=[])
@@ -831,15 +873,17 @@ def delete_classification_dataset_images(
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
list_of_ids = json.get("ids", "") list_of_ids = json.get("ids", "")
folder = os.path.join( sanitized_name = sanitize_path_component(name)
CLIPS_DIR, sanitize_filename(name), "dataset", sanitize_filename(category) folder = safe_join(CLIPS_DIR, name, "dataset", category)
)
if sanitized_name is None or folder is None:
return invalid_name_response(name)
deleted_count = 0 deleted_count = 0
for id in list_of_ids: for id in list_of_ids:
file_path = os.path.join(folder, sanitize_filename(id)) file_path = safe_join(folder, id)
if os.path.isfile(file_path): if file_path and os.path.isfile(file_path):
os.unlink(file_path) os.unlink(file_path)
deleted_count += 1 deleted_count += 1
@@ -850,7 +894,6 @@ def delete_classification_dataset_images(
# This ensures the dataset is marked as changed after deletion # This ensures the dataset is marked as changed after deletion
# (even if the total count happens to be the same after adding and deleting) # (even if the total count happens to be the same after adding and deleting)
if deleted_count > 0: if deleted_count > 0:
sanitized_name = sanitize_filename(name)
metadata = read_training_metadata(sanitized_name) metadata = read_training_metadata(sanitized_name)
if metadata: if metadata:
last_count = metadata.get("last_training_image_count", 0) last_count = metadata.get("last_training_image_count", 0)
@@ -888,8 +931,8 @@ def reclassify_classification_image(
) )
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
image_id = sanitize_filename(json.get("id", "")) image_id = sanitize_path_component(json.get("id", ""))
new_category = sanitize_filename(json.get("new_category", "")) new_category = sanitize_path_component(json.get("new_category", ""))
if not image_id or not new_category: if not image_id or not new_category:
return JSONResponse( return JSONResponse(
@@ -913,10 +956,13 @@ def reclassify_classification_image(
status_code=400, status_code=400,
) )
sanitized_name = sanitize_filename(name) sanitized_name = sanitize_path_component(name)
source_folder = os.path.join( source_folder = safe_join(CLIPS_DIR, name, "dataset", category)
CLIPS_DIR, sanitized_name, "dataset", sanitize_filename(category) target_folder = safe_join(CLIPS_DIR, name, "dataset", new_category)
)
if sanitized_name is None or source_folder is None or target_folder is None:
return invalid_name_response(name)
source_file = os.path.join(source_folder, image_id) source_file = os.path.join(source_folder, image_id)
if not os.path.isfile(source_file): if not os.path.isfile(source_file):
@@ -933,7 +979,6 @@ def reclassify_classification_image(
random_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) random_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
timestamp = datetime.datetime.now().timestamp() timestamp = datetime.datetime.now().timestamp()
new_name = f"{new_category}-{timestamp}-{random_id}.png" new_name = f"{new_category}-{timestamp}-{random_id}.png"
target_folder = os.path.join(CLIPS_DIR, sanitized_name, "dataset", new_category)
os.makedirs(target_folder, exist_ok=True) os.makedirs(target_folder, exist_ok=True)
@@ -983,7 +1028,7 @@ def rename_classification_category(
) )
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
new_category = sanitize_filename(json.get("new_category", "")) new_category = sanitize_path_component(json.get("new_category", ""))
if not new_category: if not new_category:
return JSONResponse( return JSONResponse(
@@ -996,12 +1041,12 @@ def rename_classification_category(
status_code=400, status_code=400,
) )
old_folder = os.path.join( sanitized_name = sanitize_path_component(name)
CLIPS_DIR, sanitize_filename(name), "dataset", sanitize_filename(old_category) old_folder = safe_join(CLIPS_DIR, name, "dataset", old_category)
) new_folder = safe_join(CLIPS_DIR, name, "dataset", new_category)
new_folder = os.path.join(
CLIPS_DIR, sanitize_filename(name), "dataset", new_category if sanitized_name is None or old_folder is None or new_folder is None:
) return invalid_name_response(name)
if not os.path.exists(old_folder): if not os.path.exists(old_folder):
return JSONResponse( return JSONResponse(
@@ -1030,7 +1075,6 @@ def rename_classification_category(
# Mark dataset as ready to train by resetting training metadata # Mark dataset as ready to train by resetting training metadata
# This ensures the dataset is marked as changed after renaming # This ensures the dataset is marked as changed after renaming
sanitized_name = sanitize_filename(name)
write_training_metadata(sanitized_name, 0) write_training_metadata(sanitized_name, 0)
return JSONResponse( return JSONResponse(
@@ -1078,13 +1122,20 @@ def categorize_classification_image(request: Request, name: str, body: dict = No
) )
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
category = sanitize_filename(json.get("category", "")) category = sanitize_path_component(json.get("category", ""))
training_file_name = sanitize_filename(json.get("training_file", "")) training_file_name = json.get("training_file", "")
training_file = os.path.join( training_file = (
CLIPS_DIR, sanitize_filename(name), "train", training_file_name safe_join(CLIPS_DIR, name, "train", training_file_name)
if training_file_name
else None
) )
if training_file_name and not os.path.isfile(training_file): if category is None:
return invalid_name_response(json.get("category", ""))
if training_file_name and (
training_file is None or not os.path.isfile(training_file)
):
return JSONResponse( return JSONResponse(
content=( content=(
{ {
@@ -1098,9 +1149,10 @@ def categorize_classification_image(request: Request, name: str, body: dict = No
random_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) random_id = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
timestamp = datetime.datetime.now().timestamp() timestamp = datetime.datetime.now().timestamp()
new_name = f"{category}-{timestamp}-{random_id}.png" new_name = f"{category}-{timestamp}-{random_id}.png"
new_file_folder = os.path.join( new_file_folder = safe_join(CLIPS_DIR, name, "dataset", category)
CLIPS_DIR, sanitize_filename(name), "dataset", category
) if new_file_folder is None:
return invalid_name_response(name)
os.makedirs(new_file_folder, exist_ok=True) os.makedirs(new_file_folder, exist_ok=True)
@@ -1138,9 +1190,10 @@ def create_classification_category(request: Request, name: str, category: str):
status_code=404, status_code=404,
) )
category_folder = os.path.join( category_folder = safe_join(CLIPS_DIR, name, "dataset", category)
CLIPS_DIR, sanitize_filename(name), "dataset", sanitize_filename(category)
) if category_folder is None:
return invalid_name_response(category)
os.makedirs(category_folder, exist_ok=True) os.makedirs(category_folder, exist_ok=True)
@@ -1179,12 +1232,15 @@ def delete_classification_train_images(request: Request, name: str, body: dict =
json: dict[str, Any] = body or {} json: dict[str, Any] = body or {}
list_of_ids = json.get("ids", "") list_of_ids = json.get("ids", "")
folder = os.path.join(CLIPS_DIR, sanitize_filename(name), "train") folder = safe_join(CLIPS_DIR, name, "train")
if folder is None:
return invalid_name_response(name)
for id in list_of_ids: for id in list_of_ids:
file_path = os.path.join(folder, sanitize_filename(id)) file_path = safe_join(folder, id)
if os.path.isfile(file_path): if file_path and os.path.isfile(file_path):
os.unlink(file_path) os.unlink(file_path)
return JSONResponse( return JSONResponse(
@@ -1201,7 +1257,11 @@ def delete_classification_train_images(request: Request, name: str, body: dict =
) )
async def generate_state_examples(request: Request, body: GenerateStateExamplesBody): async def generate_state_examples(request: Request, body: GenerateStateExamplesBody):
"""Generate examples for state classification.""" """Generate examples for state classification."""
model_name = sanitize_filename(body.model_name) model_name = sanitize_path_component(body.model_name)
if model_name is None:
return invalid_name_response(body.model_name)
cameras_normalized = { cameras_normalized = {
camera_name: tuple(crop) camera_name: tuple(crop)
for camera_name, crop in body.cameras.items() for camera_name, crop in body.cameras.items()
@@ -1224,7 +1284,11 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
) )
async def generate_object_examples(request: Request, body: GenerateObjectExamplesBody): async def generate_object_examples(request: Request, body: GenerateObjectExamplesBody):
"""Generate examples for object classification.""" """Generate examples for object classification."""
model_name = sanitize_filename(body.model_name) model_name = sanitize_path_component(body.model_name)
if model_name is None:
return invalid_name_response(body.model_name)
collect_object_classification_examples(model_name, body.label) collect_object_classification_examples(model_name, body.label)
return JSONResponse( return JSONResponse(
@@ -1243,10 +1307,16 @@ async def generate_object_examples(request: Request, body: GenerateObjectExample
Returns a success message.""", Returns a success message.""",
) )
def delete_classification_model(request: Request, name: str): def delete_classification_model(request: Request, name: str):
sanitized_name = sanitize_filename(name) # This endpoint intentionally accepts models that are not in the config, so
# there is no allow list to fall back on. Both paths below are recursive
# deletes, so an unusable name has to be rejected outright.
data_dir = safe_join(CLIPS_DIR, name)
model_dir = safe_join(MODEL_CACHE_DIR, name)
if data_dir is None or model_dir is None:
return invalid_name_response(name)
# Delete the classification model's data directory in clips # Delete the classification model's data directory in clips
data_dir = os.path.join(CLIPS_DIR, sanitized_name)
if os.path.exists(data_dir): if os.path.exists(data_dir):
try: try:
shutil.rmtree(data_dir) shutil.rmtree(data_dir)
@@ -1255,7 +1325,6 @@ def delete_classification_model(request: Request, name: str):
logger.debug(f"Failed to delete data directory for {name}: {e}") logger.debug(f"Failed to delete data directory for {name}: {e}")
# Delete the classification model's files in model_cache # Delete the classification model's files in model_cache
model_dir = os.path.join(MODEL_CACHE_DIR, sanitized_name)
if os.path.exists(model_dir): if os.path.exists(model_dir):
try: try:
shutil.rmtree(model_dir) shutil.rmtree(model_dir)
+11 -1
View File
@@ -13,6 +13,7 @@ from frigate.api.auth import require_role
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.jobs.debug_replay import ( from frigate.jobs.debug_replay import (
ExportDebugReplaySource, ExportDebugReplaySource,
NoRecordingsError,
RecordingDebugReplaySource, RecordingDebugReplaySource,
start_debug_replay_job, start_debug_replay_job,
) )
@@ -74,7 +75,8 @@ class DebugReplayStopResponse(BaseModel):
response_model=DebugReplayStartResponse, response_model=DebugReplayStartResponse,
status_code=202, status_code=202,
responses={ responses={
400: {"description": "Invalid camera, time range, or no recordings"}, 400: {"description": "Invalid camera or time range"},
404: {"description": "No recordings in the requested time range"},
409: {"description": "A replay session is already active"}, 409: {"description": "A replay session is already active"},
}, },
dependencies=[Depends(require_role(["admin"]))], dependencies=[Depends(require_role(["admin"]))],
@@ -113,6 +115,14 @@ async def start_debug_replay(request: Request, body: DebugReplayStartBody):
}, },
status_code=409, status_code=409,
) )
except NoRecordingsError:
return JSONResponse(
content={
"success": False,
"message": "No recordings found in the selected time range",
},
status_code=404,
)
except ValueError: except ValueError:
logger.exception("Rejected debug replay start request") logger.exception("Rejected debug replay start request")
return JSONResponse( return JSONResponse(
+1
View File
@@ -8,6 +8,7 @@ class Tags(Enum):
chat = "Chat" chat = "Chat"
events = "Events" events = "Events"
export = "Export" export = "Export"
hardware = "Hardware"
classification = "Classification" classification = "Classification"
logs = "Logs" logs = "Logs"
media = "Media" media = "Media"
+44 -39
View File
@@ -16,7 +16,6 @@ import numpy as np
from fastapi import APIRouter, Request from fastapi import APIRouter, Request
from fastapi.params import Depends from fastapi.params import Depends
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from pathvalidate import sanitize_filename
from peewee import JOIN, DoesNotExist, fn, operator from peewee import JOIN, DoesNotExist, fn, operator
from playhouse.shortcuts import model_to_dict from playhouse.shortcuts import model_to_dict
@@ -56,11 +55,12 @@ from frigate.api.defs.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.comms.event_metadata_updater import EventMetadataTypeEnum from frigate.comms.event_metadata_updater import EventMetadataTypeEnum
from frigate.config.classification import ObjectClassificationType from frigate.config.classification import ObjectClassificationType
from frigate.const import CLIPS_DIR, TRIGGER_DIR from frigate.const import CLIPS_DIR
from frigate.embeddings import EmbeddingsContext from frigate.embeddings import EmbeddingsContext
from frigate.models import Event, ReviewSegment, Timeline, Trigger from frigate.models import Event, ReviewSegment, Timeline, Trigger
from frigate.track.object_processing import TrackedObject from frigate.track.object_processing import TrackedObject
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
from frigate.util.path import get_trigger_thumbnail_path, safe_join
from frigate.util.time import get_dst_transitions, get_tz_modifiers from frigate.util.time import get_dst_transitions, get_tz_modifiers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -1313,7 +1313,7 @@ async def set_sub_label(
if request.app.detected_frames_processor: if request.app.detected_frames_processor:
tracked_obj: TrackedObject = None tracked_obj: TrackedObject = None
for state in request.app.detected_frames_processor.camera_states.values(): for state in request.app.detected_frames_processor.get_camera_states():
tracked_obj = state.tracked_objects.get(event_id) tracked_obj = state.tracked_objects.get(event_id)
if tracked_obj is not None: if tracked_obj is not None:
@@ -1372,7 +1372,7 @@ async def set_plate(
if request.app.detected_frames_processor: if request.app.detected_frames_processor:
tracked_obj: TrackedObject = None tracked_obj: TrackedObject = None
for state in request.app.detected_frames_processor.camera_states.values(): for state in request.app.detected_frames_processor.get_camera_states():
tracked_obj = state.tracked_objects.get(event_id) tracked_obj = state.tracked_objects.get(event_id)
if tracked_obj is not None: if tracked_obj is not None:
@@ -1452,10 +1452,10 @@ async def set_attributes(
continue continue
# Get available labels from dataset directory # Get available labels from dataset directory
dataset_dir = os.path.join(CLIPS_DIR, sanitize_filename(model_key), "dataset") dataset_dir = safe_join(CLIPS_DIR, model_key, "dataset")
available_labels = set() available_labels = set()
if os.path.exists(dataset_dir): if dataset_dir and os.path.exists(dataset_dir):
for category_name in os.listdir(dataset_dir): for category_name in os.listdir(dataset_dir):
category_dir = os.path.join(dataset_dir, category_name) category_dir = os.path.join(dataset_dir, category_name)
if os.path.isdir(category_dir): if os.path.isdir(category_dir):
@@ -1748,6 +1748,7 @@ async def delete_events(request: Request, body: EventsDeleteBody):
NOTES: NOTES:
- Creating a manual event does not trigger an update to /events MQTT topic. - Creating a manual event does not trigger an update to /events MQTT topic.
- If a duration is set to null, the event will need to be ended manually by calling /events/{event_id}/end. - If a duration is set to null, the event will need to be ended manually by calling /events/{event_id}/end.
- The review item is an alert unless the label is listed in the camera's review -> detections -> labels config.
""", """,
) )
def create_event( def create_event(
@@ -1958,18 +1959,13 @@ def create_trigger_embedding(
if body.type == "thumbnail": if body.type == "thumbnail":
# Save image to the triggers directory # Save image to the triggers directory
try: try:
os.makedirs( webp_path = get_trigger_thumbnail_path(camera_name, body.data)
os.path.join(TRIGGER_DIR, sanitize_filename(camera_name)),
exist_ok=True, if webp_path is None:
) raise ValueError(f"Invalid trigger thumbnail path for {body.data}")
with open(
os.path.join( os.makedirs(os.path.dirname(webp_path), exist_ok=True)
TRIGGER_DIR, with open(webp_path, "wb") as f:
sanitize_filename(camera_name),
f"{sanitize_filename(body.data)}.webp",
),
"wb",
) as f:
f.write(thumbnail) f.write(thumbnail)
logger.debug( logger.debug(
f"Writing thumbnail for trigger with data {body.data} in {camera_name}." f"Writing thumbnail for trigger with data {body.data} in {camera_name}."
@@ -2041,10 +2037,16 @@ def update_trigger_embedding(
if body.type == "description": if body.type == "description":
embedding = context.generate_description_embedding(body.data) embedding = context.generate_description_embedding(body.data)
elif body.type == "thumbnail": elif body.type == "thumbnail":
webp_file = sanitize_filename(body.data) + ".webp" webp_path = get_trigger_thumbnail_path(camera_name, body.data)
webp_path = os.path.join(
TRIGGER_DIR, sanitize_filename(camera_name), webp_file if webp_path is None:
) return JSONResponse(
content={
"success": False,
"message": f"Invalid data for {body.type} trigger",
},
status_code=400,
)
try: try:
event: Event = Event.get(Event.id == body.data) event: Event = Event.get(Event.id == body.data)
@@ -2101,13 +2103,14 @@ def update_trigger_embedding(
# Update existing trigger # Update existing trigger
if trigger.data != body.data: # Delete old thumbnail only if data changes if trigger.data != body.data: # Delete old thumbnail only if data changes
try: try:
os.remove( old_path = get_trigger_thumbnail_path(camera_name, trigger.data)
os.path.join(
TRIGGER_DIR, if old_path is None:
sanitize_filename(camera_name), raise ValueError(
f"{trigger.data}.webp", f"Invalid trigger thumbnail path for {trigger.data}"
) )
)
os.remove(old_path)
logger.debug( logger.debug(
f"Deleted thumbnail for trigger with data {trigger.data} in {camera_name}." f"Deleted thumbnail for trigger with data {trigger.data} in {camera_name}."
) )
@@ -2141,12 +2144,13 @@ def update_trigger_embedding(
if body.type == "thumbnail": if body.type == "thumbnail":
# Save image to the triggers directory # Save image to the triggers directory
try: try:
camera_path = os.path.join(TRIGGER_DIR, sanitize_filename(camera_name)) thumbnail_path = get_trigger_thumbnail_path(camera_name, body.data)
os.makedirs(camera_path, exist_ok=True)
with open( if thumbnail_path is None:
os.path.join(camera_path, f"{sanitize_filename(body.data)}.webp"), raise ValueError(f"Invalid trigger thumbnail path for {body.data}")
"wb",
) as f: os.makedirs(os.path.dirname(thumbnail_path), exist_ok=True)
with open(thumbnail_path, "wb") as f:
f.write(thumbnail) f.write(thumbnail)
logger.debug( logger.debug(
f"Writing thumbnail for trigger with data {body.data} in {camera_name}." f"Writing thumbnail for trigger with data {body.data} in {camera_name}."
@@ -2217,11 +2221,12 @@ def delete_trigger_embedding(
) )
try: try:
os.remove( thumbnail_path = get_trigger_thumbnail_path(camera_name, trigger.data)
os.path.join(
TRIGGER_DIR, sanitize_filename(camera_name), f"{trigger.data}.webp" if thumbnail_path is None:
) raise ValueError(f"Invalid trigger thumbnail path for {trigger.data}")
)
os.remove(thumbnail_path)
logger.debug( logger.debug(
f"Deleted thumbnail for trigger with data {trigger.data} in {camera_name}." f"Deleted thumbnail for trigger with data {trigger.data} in {camera_name}."
) )
+6 -11
View File
@@ -13,7 +13,7 @@ from pathlib import Path
import psutil import psutil
from fastapi import APIRouter, Depends, Query, Request from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse from fastapi.responses import JSONResponse, StreamingResponse
from pathvalidate import sanitize_filename, sanitize_filepath from pathvalidate import sanitize_filename
from peewee import DoesNotExist from peewee import DoesNotExist
from playhouse.shortcuts import model_to_dict from playhouse.shortcuts import model_to_dict
@@ -72,6 +72,7 @@ from frigate.record.export import (
PlaybackSourceEnum, PlaybackSourceEnum,
validate_ffmpeg_args, validate_ffmpeg_args,
) )
from frigate.util.path import sanitize_contained_path
from frigate.util.time import is_current_hour from frigate.util.time import is_current_hour
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -129,18 +130,12 @@ def _validate_export_case(export_case_id: str | None) -> JSONResponse | None:
def _sanitize_existing_image( def _sanitize_existing_image(
image_path: str | None, image_path: str | None,
) -> tuple[str | None, JSONResponse | None]: ) -> tuple[str | None, JSONResponse | None]:
# sanitize_filepath normalizes "\" to "/" but leaves ".." intact, so a path if not image_path:
# like "clips\..\..\etc/passwd" passes the CLIPS_DIR prefix check yet still return None, None
# escapes the directory once resolved. A valid snapshot path never uses "..".
if image_path and ".." in image_path:
return None, JSONResponse(
content={"success": False, "message": "Invalid image path"},
status_code=400,
)
existing_image = sanitize_filepath(image_path) if image_path else None existing_image = sanitize_contained_path(image_path, CLIPS_DIR)
if existing_image and not existing_image.startswith(CLIPS_DIR): if existing_image is None:
return None, JSONResponse( return None, JSONResponse(
content={"success": False, "message": "Invalid image path"}, content={"success": False, "message": "Invalid image path"},
status_code=400, status_code=400,
+2
View File
@@ -21,6 +21,7 @@ from frigate.api import (
debug_replay, debug_replay,
event, event,
export, export,
hardware,
media, media,
motion_search, motion_search,
notification, notification,
@@ -145,6 +146,7 @@ def create_fastapi_app(
app.include_router(preview.router) app.include_router(preview.router)
app.include_router(notification.router) app.include_router(notification.router)
app.include_router(export.router) app.include_router(export.router)
app.include_router(hardware.router)
app.include_router(event.router) app.include_router(event.router)
app.include_router(media.router) app.include_router(media.router)
app.include_router(motion_search.router) app.include_router(motion_search.router)
+30
View File
@@ -0,0 +1,30 @@
"""Hardware discovery APIs."""
import logging
from fastapi import APIRouter, Depends
from frigate.api.auth import require_role
from frigate.api.defs.tags import Tags
from frigate.detectors.hardware import DetectionHardware, hardware_prober
logger = logging.getLogger(__name__)
router = APIRouter(tags=[Tags.hardware])
@router.get(
"/hardware/probe",
response_model=list[DetectionHardware],
dependencies=[Depends(require_role(["admin"]))],
)
def probe_hardware(refresh: bool = False) -> list[DetectionHardware]:
"""Get the object detection hardware attached to this system.
Args:
refresh: Probe again instead of returning the cached result
Returns:
Every kind of detection hardware that was found
"""
return hardware_prober.probe(refresh=refresh)
+317 -152
View File
@@ -6,10 +6,13 @@ import logging
import math import math
import os import os
import subprocess as sp import subprocess as sp
import tempfile
import time import time
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from enum import Enum
from pathlib import Path as FilePath from pathlib import Path as FilePath
from typing import Any from typing import IO, Any
from urllib.parse import unquote from urllib.parse import unquote
import cv2 import cv2
@@ -39,12 +42,14 @@ from frigate.config.camera.snapshots import SnapshotsConfig
from frigate.const import ( from frigate.const import (
CACHE_DIR, CACHE_DIR,
INSTALL_DIR, INSTALL_DIR,
MAX_SEGMENT_DURATION,
PREVIEW_FRAME_TYPE, PREVIEW_FRAME_TYPE,
STREAM_TYPE_MAIN,
STREAM_TYPE_SUB,
) )
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
from frigate.output.preview import get_most_recent_preview_frame from frigate.output.preview import get_most_recent_preview_frame
from frigate.track.object_processing import TrackedObjectProcessor from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.file import ( from frigate.util.file import (
get_event_snapshot_bytes, get_event_snapshot_bytes,
get_event_snapshot_path, get_event_snapshot_path,
@@ -52,12 +57,40 @@ from frigate.util.file import (
load_event_snapshot_image, 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
from frigate.util.media import get_keyframe_before
from frigate.util.object import create_empty_regions_grid from frigate.util.object import create_empty_regions_grid
from frigate.util.recording_coverage import (
build_spans,
null_audio_glitches,
plan_clip,
resolve_coverage,
stream_has_audio,
)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# must match the patched MAX_CLIPS in docker/main/build_nginx.sh; a
# normal hour needs ~360, one clip per recording file
NGINX_VOD_MAX_CLIPS = 1080
# tail of ffmpeg's stderr kept for the clip download failure log
CLIP_STDERR_LOG_BYTES = 8192
# how long a drained clip download waits for ffmpeg to exit on its own
CLIP_FFMPEG_EXIT_TIMEOUT = 10
class VodStreamPreference(str, Enum):
"""Stream pin for the path-segment VOD route.
nginx-vod derives its mapping fetch URI from the playlist URL path
(query params are dropped), so the preference must be a path segment.
"""
main = STREAM_TYPE_MAIN
sub = STREAM_TYPE_SUB
router = APIRouter(tags=[Tags.media]) router = APIRouter(tags=[Tags.media])
@@ -319,7 +352,7 @@ async def get_snapshot_from_recording(
& (frame_time <= Recordings.end_time) & (frame_time <= Recordings.end_time)
) )
.where(Recordings.camera == camera_name) .where(Recordings.camera == camera_name)
.order_by(Recordings.start_time.desc()) .order_by(Recordings.stream_type.asc(), Recordings.start_time.desc())
.limit(1) .limit(1)
.get() .get()
) )
@@ -338,7 +371,7 @@ async def get_snapshot_from_recording(
& (frame_time <= Recordings.end_time) & (frame_time <= Recordings.end_time)
) )
.where(Recordings.camera == camera_name) .where(Recordings.camera == camera_name)
.order_by(Recordings.start_time.desc()) .order_by(Recordings.stream_type.asc(), Recordings.start_time.desc())
.limit(1) .limit(1)
.get() .get()
) )
@@ -398,7 +431,7 @@ async def submit_recording_snapshot_to_plus(
(frame_time >= Recordings.start_time) & (frame_time <= Recordings.end_time) (frame_time >= Recordings.start_time) & (frame_time <= Recordings.end_time)
) )
.where(Recordings.camera == camera_name) .where(Recordings.camera == camera_name)
.order_by(Recordings.start_time.desc()) .order_by(Recordings.stream_type.asc(), Recordings.start_time.desc())
.limit(1) .limit(1)
) )
@@ -441,6 +474,53 @@ async def submit_recording_snapshot_to_plus(
) )
def _read_stderr_tail(stderr_file: IO[bytes]) -> str:
"""Read back the last CLIP_STDERR_LOG_BYTES of a captured stderr file."""
stderr_file.seek(0, os.SEEK_END)
stderr_file.seek(max(0, stderr_file.tell() - CLIP_STDERR_LOG_BYTES))
return stderr_file.read().decode("utf-8", "replace")
def _run_clip_download(ffmpeg_cmd: list[str], file_path: str) -> Iterator[bytes]:
"""Stream an ffmpeg concat remux to the client, always cleaning up after it."""
stderr_file = None
ffmpeg = None
try:
stderr_file = tempfile.TemporaryFile()
ffmpeg = sp.Popen(ffmpeg_cmd, stdout=sp.PIPE, stderr=stderr_file)
while True:
data = ffmpeg.stdout.read(8192)
if not data:
break
yield data
try:
# wait rather than signal, so the real exit code survives
ffmpeg.wait(timeout=CLIP_FFMPEG_EXIT_TIMEOUT)
except sp.TimeoutExpired:
pass
finally:
if ffmpeg is not None:
# read before terminating: a None here is our teardown, not a failure
exit_code = ffmpeg.poll()
terminate_ffmpeg_stream(ffmpeg)
if exit_code:
logger.error(
"Failed to generate clip, ffmpeg logs: %s",
_read_stderr_tail(stderr_file),
)
if stderr_file is not None:
stderr_file.close()
FilePath(file_path).unlink(missing_ok=True)
@router.get( @router.get(
"/{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4", "/{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4",
dependencies=[Depends(require_camera_access)], dependencies=[Depends(require_camera_access)],
@@ -452,40 +532,29 @@ async def recording_clip(
start_ts: float, start_ts: float,
end_ts: float, end_ts: float,
): ):
def run_download(ffmpeg_cmd: list[str], file_path: str): def get_clip_query(stream_type: str):
with sp.Popen( return (
ffmpeg_cmd, Recordings.select(
stderr=sp.PIPE, Recordings.path,
stdout=sp.PIPE, Recordings.start_time,
text=False, Recordings.end_time,
) as ffmpeg: )
while True: .where(
data = ffmpeg.stdout.read(8192) (Recordings.start_time.between(start_ts, end_ts))
if data is not None and len(data) > 0: | (Recordings.end_time.between(start_ts, end_ts))
yield data | ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time))
else: )
if ffmpeg.returncode and ffmpeg.returncode != 0: .where(Recordings.camera == camera_name)
logger.error( .where(Recordings.stream_type == stream_type)
f"Failed to generate clip, ffmpeg logs: {ffmpeg.stderr.read()}" .order_by(Recordings.start_time.asc())
) )
else:
FilePath(file_path).unlink(missing_ok=True)
break
recordings = ( # never mix streams in one concat; use main when available and
Recordings.select( # fall back to sub for expired-main history
Recordings.path, recordings = get_clip_query(STREAM_TYPE_MAIN)
Recordings.start_time,
Recordings.end_time, if recordings.count() == 0:
) recordings = get_clip_query(STREAM_TYPE_SUB)
.where(
(Recordings.start_time.between(start_ts, end_ts))
| (Recordings.end_time.between(start_ts, end_ts))
| ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time))
)
.where(Recordings.camera == camera_name)
.order_by(Recordings.start_time.asc())
)
if recordings.count() == 0: if recordings.count() == 0:
return JSONResponse( return JSONResponse(
@@ -496,7 +565,9 @@ async def recording_clip(
status_code=400, status_code=400,
) )
file_name = sanitize_filename(f"playlist_{camera_name}_{start_ts}-{end_ts}.txt") file_name = sanitize_filename(
f"playlist_{camera_name}_{start_ts}-{end_ts}_{os.urandom(4).hex()}.txt"
)
file_path = os.path.join(CACHE_DIR, file_name) file_path = os.path.join(CACHE_DIR, file_name)
with open(file_path, "w") as file: with open(file_path, "w") as file:
clip: Recordings clip: Recordings
@@ -544,22 +615,65 @@ async def recording_clip(
] ]
return StreamingResponse( return StreamingResponse(
run_download(ffmpeg_cmd, file_path), _run_clip_download(ffmpeg_cmd, file_path),
media_type="video/mp4", media_type="video/mp4",
) )
@router.get( def _build_vod_clip(
"/vod/{camera_name}/start/{start_ts}/end/{end_ts}", row: Any, start: float, end: float
dependencies=[Depends(require_camera_access)], ) -> tuple[dict[str, Any], int] | None:
description="Returns an HLS playlist for the specified timestamp-range on the specified camera. Append /master.m3u8 or /index.m3u8 for HLS playback.", """Build one nginx-vod clip dict + duration (ms) for a recording row trimmed to [start, end).
)
async def vod_ts( Realization comes entirely from the shared plan_clip, so the coverage
endpoint's realized timelines match this manifest by construction.
"""
plan = plan_clip(row, start, end)
if plan.skipped:
return None
clip: dict[str, Any] = {"type": "source", "path": row.path}
if plan.clip_from_ms is not None:
clip["clipFrom"] = plan.clip_from_ms
if plan.key_frame_durations is not None:
# real gaps enable keyframe-aligned sub-file segments (bootstrap
# ladder); the whole-clip fallback keeps one segment per file,
# the only safe cut without an index
if plan.first_key_frame_offset_ms > 0:
clip["firstKeyFrameOffset"] = plan.first_key_frame_offset_ms
clip["keyFrameDurations"] = plan.key_frame_durations
else:
clip["keyFrameDurations"] = [plan.duration_ms]
logger.debug(
"VOD: added clip %s duration_ms=%s clipFrom=%s",
row.path,
plan.duration_ms,
clip.get("clipFrom"),
)
return clip, plan.duration_ms
async def _vod_response(
camera_name: str, camera_name: str,
start_ts: float, start_ts: float,
end_ts: float, end_ts: float,
force_discontinuity: bool = False, force_discontinuity: bool = False,
): stream_preference: str | None = None,
) -> JSONResponse:
"""Build an nginx-vod mapping JSON for a camera over a timestamp range.
Always a single-sequence mapping; quality selection happens in the
frontend by choosing between this route and the stream-pinned routes.
Args:
camera_name: The camera to build the mapping for
start_ts: Range start as a unix timestamp
end_ts: Range end as a unix timestamp
force_discontinuity: Emit HLS discontinuity markers between clips
stream_preference: Pin the manifest to one stream type ("main" or
"sub"), serving only that stream's recordings
"""
logger.debug( logger.debug(
"VOD: Generating VOD for %s from %s to %s with force_discontinuity=%s", "VOD: Generating VOD for %s from %s to %s with force_discontinuity=%s",
camera_name, camera_name,
@@ -567,104 +681,85 @@ async def vod_ts(
end_ts, end_ts,
force_discontinuity, force_discontinuity,
) )
recordings = ( intervals = resolve_coverage(camera_name, start_ts, end_ts)
Recordings.select(
Recordings.path, # rows contradicting their stream's audio composition are
Recordings.duration, # truncated-shutdown glitches
Recordings.end_time, main_audio = stream_has_audio(intervals, main=True)
Recordings.start_time, sub_audio = stream_has_audio(intervals, main=False)
)
.where( spans = build_spans(
Recordings.start_time.between(start_ts, end_ts) null_audio_glitches(intervals, main_audio, sub_audio),
| Recordings.end_time.between(start_ts, end_ts) stream_preference,
| ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time))
)
.where(Recordings.camera == camera_name)
.order_by(Recordings.start_time.asc())
.iterator()
) )
clips = [] durations: list[int] = []
durations = [] clips: list[dict[str, Any]] = []
min_duration_ms = 100 # Minimum 100ms to ensure at least one video frame # gathered after glitch-nulling and span building, so the policy
max_duration_ms = MAX_SEGMENT_DURATION * 1000 # decisions below reflect the manifest's real contents
video_codecs: set[str] = set()
recording: Recordings audio_presence: set[bool] = set()
for recording in recordings: audio_params: set[tuple[str | None, int | None]] = set()
span_streams: set[bool] = set()
for row, span_start, span_end, span_is_main in spans:
logger.debug( logger.debug(
"VOD: processing recording: %s start=%s end=%s duration=%s", "VOD: processing recording: %s start=%s end=%s duration=%s",
recording.path, row.path,
recording.start_time, row.start_time,
recording.end_time, row.end_time,
recording.duration, row.duration,
) )
built = _build_vod_clip(row, span_start, span_end)
clip = {"type": "source", "path": recording.path} if built is None:
duration = int(recording.duration * 1000)
# adjust start offset if start_ts is after recording.start_time
if start_ts > recording.start_time:
inpoint = int((start_ts - recording.start_time) * 1000)
clip["clipFrom"] = inpoint
duration -= inpoint
logger.debug(
"VOD: applied clipFrom %sms to %s",
inpoint,
recording.path,
)
# adjust end if recording.end_time is after end_ts
if recording.end_time > end_ts:
duration -= int((recording.end_time - end_ts) * 1000)
# nginx-vod-module pushes clipFrom forward to the next keyframe,
# which can leave too few frames and produce an empty/unplayable
# segment. Snap clipFrom back to the preceding keyframe so the
# segment always starts with a decodable frame.
if "clipFrom" in clip:
keyframe_ms = get_keyframe_before(recording.path, clip["clipFrom"])
if keyframe_ms is not None:
gained = clip["clipFrom"] - keyframe_ms
clip["clipFrom"] = keyframe_ms
duration += gained
logger.debug(
"VOD: snapped clipFrom to keyframe at %sms for %s, duration now %sms",
keyframe_ms,
recording.path,
duration,
)
else:
# could not read keyframes, remove clipFrom to use full recording
logger.debug(
"VOD: no keyframe info for %s, removing clipFrom to use full recording",
recording.path,
)
del clip["clipFrom"]
duration = int(recording.duration * 1000)
if recording.end_time > end_ts:
duration -= int((recording.end_time - end_ts) * 1000)
if duration < min_duration_ms:
# skip if the clip has no valid duration (too short to contain frames)
logger.debug(
"VOD: skipping recording %s - resulting duration %sms too short",
recording.path,
duration,
)
continue continue
if min_duration_ms <= duration < max_duration_ms: clips.append(built[0])
clip["keyFrameDurations"] = [duration] durations.append(built[1])
clips.append(clip) span_streams.add(span_is_main)
durations.append(duration) if row.video_codec is not None:
logger.debug( video_codecs.add(row.video_codec)
"VOD: added clip %s duration_ms=%s clipFrom=%s", audio_presence.add(row.has_audio is not False)
recording.path, # legacy rows contribute no signature, so uniformly-unknown
duration, # history keeps the legacy shape
clip.get("clipFrom"), if row.has_audio is not False and (
) row.audio_codec is not None or row.audio_rate is not None
else: ):
logger.warning(f"Recording clip is missing or empty: {recording.path}") audio_params.add((row.audio_codec, row.audio_rate))
# nginx-vod requires a uniform track count per sequence, and adding or
# removing an audio track across an MSE discontinuity is unproven
if len(audio_presence) > 1:
logger.debug(
"VOD: %s mixes audio-bearing and audio-less recordings between "
"%s and %s; serving the range without audio",
camera_name,
start_ts,
end_ts,
)
for clip in clips:
clip["tracks"] = "v"
# discontinuity mode emits per-clip init segments, letting the decoder
# reconfigure at each boundary. Stream type counts as a signature of
# its own: the two encoders differ in SPS/PPS even when codec name and
# audio params match, and a single-init manifest then decode-fails on
# players that only configure from the init segment (iOS)
use_discontinuity = (
len(video_codecs) > 1 or len(audio_params) > 1 or len(span_streams) > 1
)
if use_discontinuity:
logger.debug(
"VOD: %s mixes media signatures between %s and %s (video codecs "
"%s, audio params %s, streams %s); serving a discontinuity "
"manifest with per-clip init segments",
camera_name,
start_ts,
end_ts,
sorted(video_codecs),
sorted(audio_params, key=str),
sorted(span_streams),
)
if not clips: if not clips:
logger.error( logger.error(
@@ -678,16 +773,50 @@ async def vod_ts(
status_code=404, status_code=404,
) )
if len(clips) > NGINX_VOD_MAX_CLIPS:
logger.warning(
"VOD: %s needs %d clips between %s and %s, exceeding nginx's "
"limit of %d; playback of this range will fail. This usually "
"means the camera produced abnormally short recording segments "
"(check the stream's timestamps)",
camera_name,
len(clips),
start_ts,
end_ts,
NGINX_VOD_MAX_CLIPS,
)
# segmentation comes from the vod_* nginx directives plus per-clip
# keyFrameDurations; a segment_duration field here was always ignored
# (nginx-vod parses only camelCase segmentDuration)
hour_ago = datetime.now() - timedelta(hours=1) hour_ago = datetime.now() - timedelta(hours=1)
return JSONResponse( content = {
content={ "cache": hour_ago.timestamp() > start_ts,
"cache": hour_ago.timestamp() > start_ts, "discontinuity": force_discontinuity or use_discontinuity,
"discontinuity": force_discontinuity, "consistentSequenceMediaInfo": True,
"consistentSequenceMediaInfo": True, "durations": durations,
"durations": durations, "sequences": [{"clips": clips}],
"segment_duration": max(durations), }
"sequences": [{"clips": clips}], if use_discontinuity:
} # clip-indexed naming is what makes nginx-vod emit per-clip
# EXT-X-MAP outside of its live mode
content["initialClipIndex"] = 1
return JSONResponse(content=content)
@router.get(
"/vod/{camera_name}/start/{start_ts}/end/{end_ts}",
dependencies=[Depends(require_camera_access)],
description="Returns an HLS playlist for the specified timestamp-range on the specified camera. Append /master.m3u8 or /index.m3u8 for HLS playback.",
)
async def vod_ts(
camera_name: str,
start_ts: float,
end_ts: float,
force_discontinuity: bool = False,
):
return await _vod_response(
camera_name, start_ts, end_ts, force_discontinuity=force_discontinuity
) )
@@ -776,7 +905,43 @@ async def vod_clip(
start_ts: float, start_ts: float,
end_ts: float, end_ts: float,
): ):
return await vod_ts(camera_name, start_ts, end_ts, force_discontinuity=True) # the tracking-details player corrects its timeline from
# sequences[0].clips[0].clipFrom
return await _vod_response(
camera_name,
start_ts,
end_ts,
force_discontinuity=True,
)
# registered after /vod/clip/... on purpose: both routes are six path
# segments, Starlette matches structurally in registration order, and the
# enum validation on {stream} would otherwise 422 every /vod/clip request
@router.get(
"/vod/{camera_name}/{stream}/start/{start_ts}/end/{end_ts}",
dependencies=[Depends(require_camera_access)],
description="Returns an HLS playlist pinned to one stream type (main or sub) for the specified timestamp-range on the specified camera. Append /master.m3u8 or /index.m3u8 for HLS playback.",
)
async def vod_ts_stream(
camera_name: str,
stream: VodStreamPreference,
start_ts: float,
end_ts: float,
force_discontinuity: bool = False,
):
"""VOD for a timestamp range pinned to one stream type.
How the frontend selects quality, now that mappings are always
single-sequence.
"""
return await _vod_response(
camera_name,
start_ts,
end_ts,
force_discontinuity=force_discontinuity,
stream_preference=stream.value,
)
@router.get( @router.get(
@@ -814,13 +979,13 @@ async def event_snapshot(
timestamp_style=request.app.frigate_config.cameras[ timestamp_style=request.app.frigate_config.cameras[
event.camera event.camera
].timestamp_style, ].timestamp_style,
colormap=request.app.frigate_config.model.colormap, colormap=request.app.frigate_config.model_for_camera(event.camera).colormap,
) )
except DoesNotExist: except DoesNotExist:
# see if the object is currently being tracked # see if the object is currently being tracked
try: try:
camera_states: list[CameraState] = ( camera_states: list[CameraState] = (
request.app.detected_frames_processor.camera_states.values() request.app.detected_frames_processor.get_camera_states()
) )
for camera_state in camera_states: for camera_state in camera_states:
if event_id in camera_state.tracked_objects: if event_id in camera_state.tracked_objects:
@@ -898,7 +1063,7 @@ async def event_thumbnail(
if thumbnail_bytes is None: if thumbnail_bytes is None:
# see if the object is currently being tracked # see if the object is currently being tracked
try: try:
camera_states = request.app.detected_frames_processor.camera_states.values() camera_states = request.app.detected_frames_processor.get_camera_states()
for camera_state in camera_states: for camera_state in camera_states:
if event_id in camera_state.tracked_objects: if event_id in camera_state.tracked_objects:
tracked_obj = camera_state.tracked_objects.get(event_id) tracked_obj = camera_state.tracked_objects.get(event_id)
@@ -1127,7 +1292,7 @@ async def event_snapshot_clean(request: Request, event_id: str, download: bool =
# see if the object is currently being tracked # see if the object is currently being tracked
try: try:
camera_states = ( camera_states = (
request.app.detected_frames_processor.camera_states.values() request.app.detected_frames_processor.get_camera_states()
) )
for camera_state in camera_states: for camera_state in camera_states:
if event_id in camera_state.tracked_objects: if event_id in camera_state.tracked_objects:
+102
View File
@@ -1,8 +1,10 @@
"""Notification apis.""" """Notification apis."""
import ipaddress
import logging import logging
import os import os
from typing import Any from typing import Any
from urllib.parse import urlparse
from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import serialization
from fastapi import APIRouter, Depends, Request from fastapi import APIRouter, Depends, Request
@@ -19,6 +21,95 @@ logger = logging.getLogger(__name__)
router = APIRouter(tags=[Tags.notifications]) router = APIRouter(tags=[Tags.notifications])
# Push endpoints are opaque URLs but stay well under this in practice
MAX_ENDPOINT_LENGTH = 2048
# Suffixes that only ever resolve on the local network
INTERNAL_HOST_SUFFIXES = (".local", ".localdomain", ".internal", ".home.arpa")
def _validate_push_endpoint(endpoint: Any) -> str | None:
"""Return a reason the endpoint is unusable, or None when it is valid.
Subscriptions are issued by the browser vendor's push service, so a valid
endpoint is always a public https URL. Anything else is either a broken
registration or an attempt to aim the notification sender somewhere it
should not reach.
"""
if not isinstance(endpoint, str) or not endpoint:
return "endpoint must be a url"
if len(endpoint) > MAX_ENDPOINT_LENGTH:
return "endpoint is too long"
try:
parsed = urlparse(endpoint)
port = parsed.port
except ValueError:
return "endpoint is not a valid url"
if parsed.scheme != "https":
return "endpoint must use https"
if parsed.username or parsed.password:
return "endpoint must not include credentials"
if port is not None and port != 443:
return "endpoint must use the default https port"
hostname = parsed.hostname
if not hostname:
return "endpoint must include a hostname"
try:
address = ipaddress.ip_address(hostname)
except ValueError:
address = None
if address is not None:
# A push service is never reachable at an address only this network can
# route, so anything non-global is a misconfiguration at best
if not address.is_global:
return "endpoint must not use a private address"
elif hostname == "localhost" or "." not in hostname:
return "endpoint must use a fully qualified hostname"
elif hostname.endswith(INTERNAL_HOST_SUFFIXES):
return "endpoint must not use an internal hostname"
# The subscription token lives in the path, and webpush.py assumes there is
# a separator after the host when it builds the VAPID audience
if len(parsed.path) <= 1:
return "endpoint must include a subscription path"
return None
def _validate_subscription(sub: Any) -> str | None:
"""Return a reason the subscription is unusable, or None when it is valid."""
if not isinstance(sub, dict):
return "subscription must be an object"
reason = _validate_push_endpoint(sub.get("endpoint"))
if reason:
return reason
keys = sub.get("keys")
if not isinstance(keys, dict):
return "subscription must include keys"
# WebPusher raises on a missing key, which would break every send for the
# user rather than just this registration
for name in ("p256dh", "auth"):
value = keys.get(name)
if not isinstance(value, str) or not value:
return f"subscription keys must include {name}"
return None
@router.get( @router.get(
"/notifications/pubkey", "/notifications/pubkey",
@@ -71,6 +162,17 @@ def register_notifications(request: Request, body: dict = None):
status_code=400, status_code=400,
) )
reason = _validate_subscription(sub)
if reason:
logger.warning(
"Rejected notification registration for %s: %s", username, reason
)
return JSONResponse(
content={"success": False, "message": f"Invalid subscription: {reason}"},
status_code=400,
)
try: try:
User.update(notification_tokens=User.notification_tokens.append(sub)).where( User.update(notification_tokens=User.notification_tokens.append(sub)).where(
User.username == username User.username == username
+190 -56
View File
@@ -25,8 +25,20 @@ from frigate.api.defs.query.recordings_query_parameters import (
) )
from frigate.api.defs.response.generic_response import GenericResponse from frigate.api.defs.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.const import RECORD_DIR from frigate.const import (
MAX_SEGMENT_DURATION,
RECORD_DIR,
STREAM_TYPE_MAIN,
STREAM_TYPE_SUB,
)
from frigate.models import Event, Recordings from frigate.models import Event, Recordings
from frigate.util.recording_coverage import (
coverage_spans,
known_video_codecs,
realized_timelines,
resolve_coverage,
stream_media_summary,
)
from frigate.util.time import get_dst_transitions from frigate.util.time import get_dst_transitions
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -59,7 +71,7 @@ def get_recordings_storage_usage(request: Request):
@router.get("/recordings/summary", dependencies=[Depends(allow_any_authenticated())]) @router.get("/recordings/summary", dependencies=[Depends(allow_any_authenticated())])
def all_recordings_summary( async def all_recordings_summary(
request: Request, request: Request,
params: MediaRecordingsSummaryQueryParams = Depends(), params: MediaRecordingsSummaryQueryParams = Depends(),
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter), allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
@@ -76,18 +88,23 @@ def all_recordings_summary(
else: else:
camera_list = allowed_cameras camera_list = allowed_cameras
time_range_query = ( min_time: float | None = None
Recordings.select( max_time: float | None = None
fn.MIN(Recordings.start_time).alias("min_time"), for camera in camera_list:
fn.MAX(Recordings.start_time).alias("max_time"), cam_min = (
Recordings.select(fn.MIN(Recordings.start_time))
.where(Recordings.camera == camera)
.scalar()
) )
.where(Recordings.camera << camera_list) if cam_min is None:
.dicts() continue
.get() cam_max = (
) Recordings.select(fn.MAX(Recordings.start_time))
.where(Recordings.camera == camera)
min_time = time_range_query.get("min_time") .scalar()
max_time = time_range_query.get("max_time") )
min_time = cam_min if min_time is None else min(min_time, cam_min)
max_time = cam_max if max_time is None else max(max_time, cam_max)
if min_time is None or max_time is None: if min_time is None or max_time is None:
return JSONResponse(content={}) return JSONResponse(content={})
@@ -97,22 +114,60 @@ def all_recordings_summary(
days: dict[str, bool] = {} days: dict[str, bool] = {}
for period_start, period_end, period_offset in dst_periods: for period_start, period_end, period_offset in dst_periods:
day_expr = ((Recordings.start_time + period_offset) / 86400).cast("int") first_start = max(min_time, period_start - MAX_SEGMENT_DURATION)
first_day = int((first_start + period_offset) // 86400)
last_day = int((min(max_time, period_end) + period_offset) // 86400)
period_query = ( day_idx = first_day
Recordings.select(day_expr.alias("day_idx")) while day_idx <= last_day:
.where( day_str = (dt.date(1970, 1, 1) + dt.timedelta(days=day_idx)).isoformat()
(Recordings.camera << camera_list) day_start = day_idx * 86400 - period_offset
& (Recordings.end_time >= period_start) day_end = day_start + 86400
& (Recordings.start_time <= period_end)
if day_str in days:
day_idx += 1
continue
if day_end <= period_end:
upper = Recordings.start_time < day_end
else:
upper = Recordings.start_time <= period_end
has_recordings = (
Recordings.select(Recordings.id)
.where(
(Recordings.camera << camera_list)
& (Recordings.end_time >= period_start)
& (Recordings.start_time >= day_start)
& upper
)
.exists()
) )
.distinct() if has_recordings:
.namedtuples() days[day_str] = True
) day_idx += 1
continue
for g in period_query: # empty day
day_str = (dt.date(1970, 1, 1) + dt.timedelta(days=g.day_idx)).isoformat() next_start: float | None = None
days[day_str] = True for camera in camera_list:
cam_next = (
Recordings.select(fn.MIN(Recordings.start_time))
.where(
Recordings.camera == camera,
Recordings.start_time >= day_end,
Recordings.start_time <= period_end,
)
.scalar()
)
if cam_next is not None and (
next_start is None or cam_next < next_start
):
next_start = cam_next
if next_start is None:
break
day_idx = max(day_idx + 1, int((next_start + period_offset) // 86400))
return JSONResponse(content=dict(sorted(days.items()))) return JSONResponse(content=dict(sorted(days.items())))
@@ -149,23 +204,28 @@ async def recordings_summary(camera_name: str, timezone: str = "utc"):
period_hour_modifier = f"{hours_offset} hour" period_hour_modifier = f"{hours_offset} hour"
period_minute_modifier = f"{minutes_offset} minute" period_minute_modifier = f"{minutes_offset} minute"
hour_expression = fn.strftime(
"%Y-%m-%d %H",
fn.datetime(
Recordings.start_time,
"unixepoch",
period_hour_modifier,
period_minute_modifier,
),
)
# sub rows duplicate the camera's motion/object stats, so
# aggregating them too would double-count
recording_groups = ( recording_groups = (
Recordings.select( Recordings.select(
fn.strftime( hour_expression.alias("hour"),
"%Y-%m-%d %H",
fn.datetime(
Recordings.start_time,
"unixepoch",
period_hour_modifier,
period_minute_modifier,
),
).alias("hour"),
fn.SUM(Recordings.duration).alias("duration"), fn.SUM(Recordings.duration).alias("duration"),
fn.SUM(Recordings.motion).alias("motion"), fn.SUM(Recordings.motion).alias("motion"),
fn.SUM(Recordings.objects).alias("objects"), fn.SUM(Recordings.objects).alias("objects"),
) )
.where( .where(
(Recordings.camera == camera_name) (Recordings.camera == camera_name)
& (Recordings.stream_type == STREAM_TYPE_MAIN)
& (Recordings.end_time >= period_start) & (Recordings.end_time >= period_start)
& (Recordings.start_time <= period_end) & (Recordings.start_time <= period_end)
) )
@@ -174,6 +234,23 @@ async def recordings_summary(camera_name: str, timezone: str = "utc"):
.namedtuples() .namedtuples()
) )
# sub recordings can outlive main, so hours covered only by sub
# rows are reported too, flagged as sub_only
sub_groups = (
Recordings.select(
hour_expression.alias("hour"),
fn.SUM(Recordings.duration).alias("duration"),
)
.where(
(Recordings.camera == camera_name)
& (Recordings.stream_type == STREAM_TYPE_SUB)
& (Recordings.end_time >= period_start)
& (Recordings.start_time <= period_end)
)
.group_by((Recordings.start_time + period_offset).cast("int") / 3600)
.namedtuples()
)
event_groups = ( event_groups = (
Event.select( Event.select(
fn.strftime( fn.strftime(
@@ -197,17 +274,43 @@ async def recordings_summary(camera_name: str, timezone: str = "utc"):
event_map = {g.hour: g.count for g in event_groups} event_map = {g.hour: g.count for g in event_groups}
for recording_group in recording_groups: hour_stats = [
parts = recording_group.hour.split() (
g.hour,
{
"motion": g.motion,
"objects": g.objects,
"duration": round(g.duration),
},
)
for g in recording_groups
]
main_hours = {group_hour for group_hour, _ in hour_stats}
hour_stats.extend(
(
g.hour,
{
"motion": 0,
"objects": 0,
"duration": round(g.duration),
"sub_only": True,
},
)
for g in sub_groups
if g.hour not in main_hours
)
# restore the most-recent-first ordering after merging in sub hours
hour_stats.sort(key=lambda entry: entry[0], reverse=True)
for group_hour, stats in hour_stats:
parts = group_hour.split()
hour = parts[1] hour = parts[1]
day = parts[0] day = parts[0]
events_count = event_map.get(recording_group.hour, 0) events_count = event_map.get(group_hour, 0)
hour_data = { hour_data = {
"hour": hour, "hour": hour,
"events": events_count, "events": events_count,
"motion": recording_group.motion, **stats,
"objects": recording_group.objects,
"duration": round(recording_group.duration),
} }
if day in days: if day in days:
# merge counts if already present (edge-case at DST boundary) # merge counts if already present (edge-case at DST boundary)
@@ -223,6 +326,35 @@ async def recordings_summary(camera_name: str, timezone: str = "utc"):
return JSONResponse(content=list(days.values())) return JSONResponse(content=list(days.values()))
@router.get(
"/{camera_name}/recordings/coverage",
dependencies=[Depends(require_camera_access)],
)
async def recordings_coverage(
camera_name: str, after: float, before: float, timelines: bool = False
):
"""Returns merged recording coverage spans plus codec compatibility.
codecs_compatible is false only when more than one known video codec
appears across the range's rows, the case where the merged vod route
degrades to a single-stream manifest.
"""
intervals = resolve_coverage(camera_name, after, before)
content = {
"spans": coverage_spans(intervals),
"codecs_compatible": len(known_video_codecs(intervals)) <= 1,
"streams": stream_media_summary(intervals),
}
# pure computation (shared plan_clip, record-time keyframe index), but
# opt-in for payload hygiene: day-level requests need only the spans
if timelines:
content["timelines"] = realized_timelines(intervals)
return JSONResponse(content=content)
@router.get("/{camera_name}/recordings", dependencies=[Depends(require_camera_access)]) @router.get("/{camera_name}/recordings", dependencies=[Depends(require_camera_access)])
async def recordings( async def recordings(
camera_name: str, camera_name: str,
@@ -243,6 +375,8 @@ async def recordings(
) )
.where( .where(
Recordings.camera == camera_name, Recordings.camera == camera_name,
Recordings.stream_type == STREAM_TYPE_MAIN,
Recordings.start_time >= after - MAX_SEGMENT_DURATION,
Recordings.end_time >= after, Recordings.end_time >= after,
Recordings.start_time <= before, Recordings.start_time <= before,
) )
@@ -282,22 +416,22 @@ async def no_recordings(
) )
scale = params.scale scale = params.scale
clauses = [ recordings: list[tuple[float, float]] = []
(Recordings.end_time >= after) & (Recordings.start_time <= before), for camera in camera_list:
(Recordings.camera << camera_list), recordings.extend(
] Recordings.select(Recordings.start_time, Recordings.end_time)
.where(
Recordings.camera == camera,
Recordings.start_time >= after - MAX_SEGMENT_DURATION,
Recordings.end_time >= after,
Recordings.start_time <= before,
)
.tuples()
.iterator()
)
# Get recording start times # the merge pass below expects a single start-ordered timeline
data: list[Recordings] = ( recordings.sort()
Recordings.select(Recordings.start_time, Recordings.end_time)
.where(reduce(operator.and_, clauses))
.order_by(Recordings.start_time.asc())
.dicts()
.iterator()
)
# Convert recordings to list of (start, end) tuples, ordered by start_time
recordings = [(r["start_time"], r["end_time"]) for r in data]
# Merge overlapping/adjacent recordings into covered intervals. The query # Merge overlapping/adjacent recordings into covered intervals. The query
# orders by start_time, so a single pass merges them # orders by start_time, so a single pass merges them
+11 -1
View File
@@ -17,6 +17,7 @@ from frigate.api.auth import (
get_allowed_cameras_for_filter, get_allowed_cameras_for_filter,
get_current_user, get_current_user,
require_camera_access, require_camera_access,
require_full_camera_access,
require_role, require_role,
) )
from frigate.api.defs.query.review_query_parameters import ( from frigate.api.defs.query.review_query_parameters import (
@@ -32,6 +33,7 @@ from frigate.api.defs.response.review_response import (
ReviewSummaryResponse, ReviewSummaryResponse,
) )
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.const import STREAM_TYPE_MAIN
from frigate.embeddings import EmbeddingsContext from frigate.embeddings import EmbeddingsContext
from frigate.models import Recordings, ReviewSegment, UserReviewStatus from frigate.models import Recordings, ReviewSegment, UserReviewStatus
from frigate.review.types import SeverityEnum from frigate.review.types import SeverityEnum
@@ -597,6 +599,8 @@ def motion_activity(
clauses = [(Recordings.start_time > after) & (Recordings.end_time < before)] clauses = [(Recordings.start_time > after) & (Recordings.end_time < before)]
clauses.append(Recordings.motion > 0) clauses.append(Recordings.motion > 0)
# sub rows duplicate the camera's motion stats, so only count main rows
clauses.append(Recordings.stream_type == STREAM_TYPE_MAIN)
if cameras != "all": if cameras != "all":
requested = set(cameras.split(",")) requested = set(cameras.split(","))
@@ -709,6 +713,7 @@ async def get_review(request: Request, review_id: str):
dependencies=[Depends(allow_any_authenticated())], dependencies=[Depends(allow_any_authenticated())],
) )
async def set_not_reviewed( async def set_not_reviewed(
request: Request,
review_id: str, review_id: str,
current_user: dict = Depends(get_current_user), current_user: dict = Depends(get_current_user),
): ):
@@ -727,6 +732,8 @@ async def set_not_reviewed(
status_code=404, status_code=404,
) )
await require_camera_access(review.camera, request=request)
try: try:
user_review = UserReviewStatus.get( user_review = UserReviewStatus.get(
UserReviewStatus.user_id == user_id, UserReviewStatus.user_id == user_id,
@@ -743,9 +750,12 @@ async def set_not_reviewed(
) )
# Intentionally not camera scoped, as the summary correlates each flagged event
# with overlapping activity on other cameras. Restricted to callers who can
# already see every camera, so the unscoped query discloses nothing.
@router.post( @router.post(
"/review/summarize/start/{start_ts}/end/{end_ts}", "/review/summarize/start/{start_ts}/end/{end_ts}",
dependencies=[Depends(require_role(["admin"]))], dependencies=[Depends(require_full_camera_access)],
description="Use GenAI to summarize review items over a period of time.", description="Use GenAI to summarize review items over a period of time.",
) )
def generate_review_summary(request: Request, start_ts: float, end_ts: float): def generate_review_summary(request: Request, start_ts: float, end_ts: float):
+43 -37
View File
@@ -49,6 +49,8 @@ from frigate.debug_replay import (
DebugReplayManager, DebugReplayManager,
cleanup_replay_cameras, cleanup_replay_cameras,
) )
from frigate.detectors.detector_config import SceneEnum
from frigate.detectors.device import build_detector_config, runner_names
from frigate.embeddings import EmbeddingProcess, EmbeddingsContext from frigate.embeddings import EmbeddingProcess, EmbeddingsContext
from frigate.events.audio import AudioProcessor from frigate.events.audio import AudioProcessor
from frigate.events.cleanup import EventCleanup from frigate.events.cleanup import EventCleanup
@@ -69,6 +71,7 @@ from frigate.models import (
User, User,
) )
from frigate.object_detection.base import ObjectDetectProcess from frigate.object_detection.base import ObjectDetectProcess
from frigate.object_detection.util import detection_frame_size
from frigate.output.output import OutputProcess from frigate.output.output import OutputProcess
from frigate.ptz.autotrack import PtzAutoTrackerThread from frigate.ptz.autotrack import PtzAutoTrackerThread
from frigate.ptz.onvif import OnvifController from frigate.ptz.onvif import OnvifController
@@ -98,26 +101,16 @@ class FrigateApp:
self.metrics_manager = manager self.metrics_manager = manager
self.audio_process: mp.Process | None = None self.audio_process: mp.Process | None = None
self.stop_event = stop_event self.stop_event = stop_event
self.detection_queue: Queue = mp.Queue() self.detection_queues: dict[SceneEnum, Queue] = {
model.scene: mp.Queue() for model in config.models
}
self.detectors: dict[str, ObjectDetectProcess] = {} self.detectors: dict[str, ObjectDetectProcess] = {}
self.detection_shms: list[mp.shared_memory.SharedMemory] = [] self.detection_shms: list[mp.shared_memory.SharedMemory] = []
self.log_queue: Queue = mp.Queue() self.log_queue: Queue = mp.Queue()
self.camera_metrics: DictProxy = self.metrics_manager.dict() self.camera_metrics: DictProxy = self.metrics_manager.dict()
self.embeddings_metrics: DataProcessorMetrics | None = (
DataProcessorMetrics( self.embeddings_metrics = DataProcessorMetrics(
self.metrics_manager, list(config.classification.custom.keys()) self.metrics_manager, list(config.classification.custom.keys())
)
if (
config.semantic_search.enabled
or any(
c.objects.genai.enabled or c.review.genai.enabled
for c in config.cameras.values()
)
or config.lpr.enabled
or config.face_recognition.enabled
or len(config.classification.custom) > 0
)
else None
) )
self.ptz_metrics: dict[str, PTZMetrics] = {} self.ptz_metrics: dict[str, PTZMetrics] = {}
self.processes: dict[str, int] = {} self.processes: dict[str, int] = {}
@@ -347,6 +340,7 @@ class FrigateApp:
self.ptz_metrics, self.ptz_metrics,
comms, comms,
) )
self.dispatcher.start_communicators()
def init_profile_manager(self) -> None: def init_profile_manager(self) -> None:
self.profile_manager = ProfileManager( self.profile_manager = ProfileManager(
@@ -355,20 +349,19 @@ class FrigateApp:
self.dispatcher.profile_manager = self.profile_manager self.dispatcher.profile_manager = self.profile_manager
def start_detectors(self) -> None: def start_detectors(self) -> None:
model_cameras: dict[SceneEnum, list[str]] = {
model.scene: [] for model in self.config.models
}
for name in self.config.cameras.keys(): for name in self.config.cameras.keys():
model = self.config.model_for_camera(name)
model_cameras[model.scene].append(name)
try: try:
largest_frame = max(
[
det.model.height * det.model.width * 3
if det.model is not None
else 320
for det in self.config.detectors.values()
]
)
shm_in = UntrackedSharedMemory( shm_in = UntrackedSharedMemory(
name=name, name=name,
create=True, create=True,
size=largest_frame, size=detection_frame_size(model),
) )
except FileExistsError: except FileExistsError:
shm_in = UntrackedSharedMemory(name=name) shm_in = UntrackedSharedMemory(name=name)
@@ -383,15 +376,26 @@ class FrigateApp:
self.detection_shms.append(shm_in) self.detection_shms.append(shm_in)
self.detection_shms.append(shm_out) self.detection_shms.append(shm_out)
for name, detector_config in self.config.detectors.items(): # a device may be listed more than once to run additional inference
self.detectors[name] = ObjectDetectProcess( # processes on it, so names are only unique once de-duplicated
name, all_devices = [
self.detection_queue, device
list(self.config.cameras.keys()), for model in self.config.models
self.config, for device in self.config.devices_for_model(model)
detector_config, ]
self.stop_event, names = iter(runner_names(all_devices))
)
for model in self.config.models:
for device in self.config.devices_for_model(model):
name = next(names)
self.detectors[name] = ObjectDetectProcess(
name,
self.detection_queues[model.scene],
model_cameras[model.scene],
self.config,
build_detector_config(device, model),
self.stop_event,
)
def start_ptz_autotracker(self) -> None: def start_ptz_autotracker(self) -> None:
self.ptz_autotracker_thread = PtzAutoTrackerThread( self.ptz_autotracker_thread = PtzAutoTrackerThread(
@@ -422,7 +426,7 @@ class FrigateApp:
def start_camera_processor(self) -> None: def start_camera_processor(self) -> None:
self.camera_maintainer = CameraMaintainer( self.camera_maintainer = CameraMaintainer(
self.config, self.config,
self.detection_queue, self.detection_queues,
self.detected_frames_queue, self.detected_frames_queue,
self.camera_metrics, self.camera_metrics,
self.ptz_metrics, self.ptz_metrics,
@@ -686,8 +690,10 @@ class FrigateApp:
for detector in self.detectors.values(): for detector in self.detectors.values():
detector.stop() detector.stop()
empty_and_close_queue(self.detection_queue) for detection_queue in self.detection_queues.values():
logger.info("Detection queue closed") empty_and_close_queue(detection_queue)
logger.info("Detection queues closed")
self.detected_frames_processor.join() self.detected_frames_processor.join()
empty_and_close_queue(self.detected_frames_queue) empty_and_close_queue(self.detected_frames_queue)
+2 -1
View File
@@ -18,6 +18,7 @@ from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdateSubscriber, CameraConfigUpdateSubscriber,
) )
from frigate.detectors.detector_config import NON_LOGO_ATTRIBUTES
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -178,7 +179,7 @@ class CameraActivityManager:
return return
for label in camera_config.objects.track: for label in camera_config.objects.track:
if label in self.config.model.non_logo_attributes: if label in NON_LOGO_ATTRIBUTES:
continue continue
new_count = all_objects[label] new_count = all_objects[label]
+12 -16
View File
@@ -15,7 +15,9 @@ from frigate.config.camera.updater import (
CameraConfigUpdateSubscriber, CameraConfigUpdateSubscriber,
) )
from frigate.const import REPLAY_CAMERA_PREFIX from frigate.const import REPLAY_CAMERA_PREFIX
from frigate.detectors.detector_config import SceneEnum
from frigate.models import Regions from frigate.models import Regions
from frigate.object_detection.util import detection_frame_size
from frigate.util.builtin import empty_and_close_queue from frigate.util.builtin import empty_and_close_queue
from frigate.util.image import SharedMemoryFrameManager, UntrackedSharedMemory from frigate.util.image import SharedMemoryFrameManager, UntrackedSharedMemory
from frigate.util.object import get_camera_regions_grid from frigate.util.object import get_camera_regions_grid
@@ -29,7 +31,7 @@ class CameraMaintainer(threading.Thread):
def __init__( def __init__(
self, self,
config: FrigateConfig, config: FrigateConfig,
detection_queue: Queue, detection_queues: dict[SceneEnum, Queue],
detected_frames_queue: Queue, detected_frames_queue: Queue,
camera_metrics: DictProxy, camera_metrics: DictProxy,
ptz_metrics: dict[str, PTZMetrics], ptz_metrics: dict[str, PTZMetrics],
@@ -38,7 +40,7 @@ class CameraMaintainer(threading.Thread):
): ):
super().__init__(name="camera_processor") super().__init__(name="camera_processor")
self.config = config self.config = config
self.detection_queue = detection_queue self.detection_queues = detection_queues
self.detected_frames_queue = detected_frames_queue self.detected_frames_queue = detected_frames_queue
self.stop_event = stop_event self.stop_event = stop_event
self.camera_metrics = camera_metrics self.camera_metrics = camera_metrics
@@ -79,10 +81,11 @@ class CameraMaintainer(threading.Thread):
# create or update region grids for each camera # create or update region grids for each camera
for camera in self.config.cameras.values(): for camera in self.config.cameras.values():
assert camera.name is not None assert camera.name is not None
model = self.config.model_for_camera(camera.name)
self.region_grids[camera.name] = get_camera_regions_grid( self.region_grids[camera.name] = get_camera_regions_grid(
camera.name, camera.name,
camera.detect, camera.detect,
max(self.config.model.width, self.config.model.height), max(model.width, model.height),
) )
def __calculate_shm_frame_count(self) -> int: def __calculate_shm_frame_count(self) -> int:
@@ -114,6 +117,7 @@ class CameraMaintainer(threading.Thread):
return return
camera_stop_event = self.__ensure_camera_stop_event(name) camera_stop_event = self.__ensure_camera_stop_event(name)
model = self.config.model_for_camera(name)
if runtime: if runtime:
self.camera_metrics[name] = CameraMetrics(self.metrics_manager) self.camera_metrics[name] = CameraMetrics(self.metrics_manager)
@@ -123,32 +127,24 @@ class CameraMaintainer(threading.Thread):
self.region_grids[name] = get_camera_regions_grid( self.region_grids[name] = get_camera_regions_grid(
name, name,
config.detect, config.detect,
max(self.config.model.width, self.config.model.height), max(model.width, model.height),
) )
try: try:
largest_frame = max(
[
det.model.height * det.model.width * 3
if det.model is not None
else 320
for det in self.config.detectors.values()
]
)
UntrackedSharedMemory(name=f"out-{name}", create=True, size=20 * 6 * 4) UntrackedSharedMemory(name=f"out-{name}", create=True, size=20 * 6 * 4)
UntrackedSharedMemory( UntrackedSharedMemory(
name=name, name=name,
create=True, create=True,
size=largest_frame, size=detection_frame_size(model),
) )
except FileExistsError: except FileExistsError:
pass pass
camera_process = CameraTracker( camera_process = CameraTracker(
config, config,
self.config.model, model,
self.config.model.merged_labelmap, model.merged_labelmap,
self.detection_queue, self.detection_queues[model.scene],
self.detected_frames_queue, self.detected_frames_queue,
self.camera_metrics[name], self.camera_metrics[name],
self.ptz_metrics[name], self.ptz_metrics[name],
+6 -11
View File
@@ -40,6 +40,7 @@ class CameraState:
self.name = name self.name = name
self.config = config self.config = config
self.camera_config = config.cameras[name] self.camera_config = config.cameras[name]
self.model = config.model_for_camera(name)
self.frame_manager = frame_manager self.frame_manager = frame_manager
self.best_objects: dict[str, TrackedObject] = {} self.best_objects: dict[str, TrackedObject] = {}
self.tracked_objects: dict[str, TrackedObject] = {} self.tracked_objects: dict[str, TrackedObject] = {}
@@ -101,9 +102,7 @@ class CameraState:
thickness = 1 thickness = 1
else: else:
thickness = 2 thickness = 2
color = self.config.model.colormap.get( color = self.model.colormap.get(obj["label"], (255, 255, 255))
obj["label"], (255, 255, 255)
)
else: else:
thickness = 1 thickness = 1
color = (255, 0, 0) color = (255, 0, 0)
@@ -125,9 +124,7 @@ class CameraState:
and obj["frame_time"] == frame_time and obj["frame_time"] == frame_time
): ):
thickness = 5 thickness = 5
color = self.config.model.colormap.get( color = self.model.colormap.get(obj["label"], (255, 255, 255))
obj["label"], (255, 255, 255)
)
# debug autotracking zooming - show the zoom factor box # debug autotracking zooming - show the zoom factor box
if ( if (
@@ -261,9 +258,7 @@ class CameraState:
if draw_options.get("paths"): if draw_options.get("paths"):
for obj in tracked_objects.values(): for obj in tracked_objects.values():
if obj["frame_time"] == frame_time and obj["path_data"]: if obj["frame_time"] == frame_time and obj["path_data"]:
color = self.config.model.colormap.get( color = self.model.colormap.get(obj["label"], (255, 255, 255))
obj["label"], (255, 255, 255)
)
path_points = [ path_points = [
( (
@@ -366,7 +361,7 @@ class CameraState:
for id in new_ids: for id in new_ids:
logger.debug(f"{self.name}: New tracked object ID: {id}") logger.debug(f"{self.name}: New tracked object ID: {id}")
new_obj = tracked_objects[id] = TrackedObject( new_obj = tracked_objects[id] = TrackedObject(
self.config.model, self.model,
self.camera_config, self.camera_config,
self.config.ui, self.config.ui,
self.frame_cache, self.frame_cache,
@@ -510,7 +505,7 @@ class CameraState:
sub_label = None sub_label = None
if obj.obj_data.get("sub_label"): if obj.obj_data.get("sub_label"):
if obj.obj_data["sub_label"][0] in self.config.model.all_attributes: if obj.obj_data["sub_label"][0] in self.model.all_attributes:
label = obj.obj_data["sub_label"][0] label = obj.obj_data["sub_label"][0]
else: else:
label = f"{object_type}-verified" label = f"{object_type}-verified"
+17 -1
View File
@@ -1,11 +1,27 @@
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from collections.abc import Callable from collections.abc import Callable
from typing import Any from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from frigate.comms.dispatcher import Dispatcher
class Communicator(ABC): class Communicator(ABC):
"""pub/sub model via specific protocol.""" """pub/sub model via specific protocol."""
def attach_dispatcher(self, dispatcher: "Dispatcher") -> None:
"""Receive the owning dispatcher.
Transports that need more than the receiver callback (the command topic
surface, the snapshot API) take it here rather than reaching through the
bound receiver.
"""
return None
def start(self) -> None:
"""Start background I/O after receiver wiring is complete."""
return None
@abstractmethod @abstractmethod
def publish(self, topic: str, payload: Any, retain: bool = False) -> None: def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
"""Send data via specific protocol.""" """Send data via specific protocol."""
+132 -77
View File
@@ -11,7 +11,11 @@ from frigate.camera.activity_manager import AudioActivityManager, CameraActivity
from frigate.comms.base_communicator import Communicator from frigate.comms.base_communicator import Communicator
from frigate.comms.runtime_state import RuntimeStatePersistence from frigate.comms.runtime_state import RuntimeStatePersistence
from frigate.comms.webpush import WebPushClient from frigate.comms.webpush import WebPushClient
from frigate.config import BirdseyeModeEnum, FrigateConfig from frigate.config import (
FrigateConfig,
birdseye_modes_from_mqtt_payload,
birdseye_modes_to_mqtt_payload,
)
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdatePublisher, CameraConfigUpdatePublisher,
@@ -45,6 +49,11 @@ from frigate.util.services import restart_frigate
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# <camera>/<command>/<sub_command>/set, one segment longer than the rest
SUB_COMMAND_TOPICS = frozenset({"motion_mask", "object_mask", "zone"})
BARE_COMMAND_TOPICS = frozenset({"onConnect", "restart"})
class Dispatcher: class Dispatcher:
"""Handle communication between Frigate and communicators.""" """Handle communication between Frigate and communicators."""
@@ -84,7 +93,7 @@ class Dispatcher:
"recordings": self._on_recordings_command, "recordings": self._on_recordings_command,
"snapshots": self._on_snapshots_command, "snapshots": self._on_snapshots_command,
"birdseye": self._on_birdseye_command, "birdseye": self._on_birdseye_command,
"birdseye_mode": self._on_birdseye_mode_command, "birdseye_modes": self._on_birdseye_modes_command,
"review_alerts": self._on_alerts_command, "review_alerts": self._on_alerts_command,
"review_detections": self._on_detections_command, "review_detections": self._on_detections_command,
"object_descriptions": self._on_object_description_command, "object_descriptions": self._on_object_description_command,
@@ -99,12 +108,114 @@ class Dispatcher:
} }
self.profile_manager: ProfileManager | None = None self.profile_manager: ProfileManager | None = None
for comm in self.comms:
comm.subscribe(self._receive)
self.web_push_client = next( self.web_push_client = next(
(comm for comm in communicators if isinstance(comm, WebPushClient)), None (comm for comm in communicators if isinstance(comm, WebPushClient)), None
) )
for comm in self.comms:
comm.subscribe(self._receive)
comm.attach_dispatcher(self)
def start_communicators(self) -> None:
"""Start communicators after dispatcher wiring is fully initialized."""
for comm in self.comms:
comm.start()
def is_command_topic(self, topic: str) -> bool:
"""Whether a prefix-stripped topic maps to a command handler.
Transports that fan a whole topic tree in must filter on this:
_receive() republishes anything it does not recognize, so forwarding
unfiltered would echo Frigate's own publishes back.
"""
parts = topic.split("/")
if topic in BARE_COMMAND_TOPICS:
return True
if len(parts) == 2 and parts[1] == "ptz":
return True
if len(parts) == 2 and parts[1] == "set":
return parts[0] in self._global_settings_handlers
if len(parts) == 3 and parts[2] == "set":
return (
parts[1] in self._camera_settings_handlers
and parts[1] not in SUB_COMMAND_TOPICS
)
if len(parts) == 3 and parts[2] == "suspend":
return parts[1] == "notifications"
if len(parts) == 4 and parts[3] == "set":
return parts[1] in SUB_COMMAND_TOPICS
return False
def _build_camera_activity_snapshot(self) -> tuple[dict[str, Any], dict[str, Any]]:
"""Build the current runtime activity snapshot for reconnect consumers."""
camera_status = {
camera: status
for camera, status in self.camera_activity.last_camera_activity.copy().items()
if camera in self.config.cameras
}
audio_detections = self.audio_activity.current_audio_detections.copy()
cameras_with_status = camera_status.keys()
for camera in self.config.cameras.keys():
if camera not in cameras_with_status:
camera_status[camera] = {}
camera_status[camera]["config"] = {
"detect": self.config.cameras[camera].detect.enabled,
"enabled": self.config.cameras[camera].enabled,
"snapshots": self.config.cameras[camera].snapshots.enabled,
"record": self.config.cameras[camera].record.enabled,
"audio": self.config.cameras[camera].audio.enabled,
"audio_transcription": self.config.cameras[
camera
].audio_transcription.live_enabled,
"notifications": self.config.cameras[camera].notifications.enabled,
"notifications_suspended": int(
self.web_push_client.suspended_cameras.get(camera, 0)
)
if self.web_push_client
and camera in self.web_push_client.suspended_cameras
else 0,
"autotracking": self.config.cameras[camera].onvif.autotracking.enabled,
"alerts": self.config.cameras[camera].review.alerts.enabled,
"detections": self.config.cameras[camera].review.detections.enabled,
"object_descriptions": self.config.cameras[
camera
].objects.genai.enabled,
"review_descriptions": self.config.cameras[camera].review.genai.enabled,
}
return camera_status, audio_detections
def publish_runtime_snapshot(
self,
publisher: Callable[[str, Any, bool], None] | None = None,
) -> None:
"""Publish the runtime snapshot for newly connected listeners."""
publish = publisher or self.publish
camera_status, audio_detections = self._build_camera_activity_snapshot()
publish("camera_activity", json.dumps(camera_status), False)
publish("model_state", json.dumps(self.model_state.copy()), False)
publish(
"embeddings_reindex_progress",
json.dumps(self.embeddings_reindex.copy()),
False,
)
publish("birdseye_layout", json.dumps(self.birdseye_layout.copy()), False)
publish("audio_detections", json.dumps(audio_detections), False)
publish(
"profile/state",
self.config.active_profile or "none",
True,
)
if self.web_push_client is not None: if self.web_push_client is not None:
self.web_push_client.set_suspension_broadcaster(self.publish) self.web_push_client.set_suspension_broadcaster(self.publish)
@@ -123,17 +234,11 @@ class Dispatcher:
try: try:
if command_type == "set": if command_type == "set":
# Commands that require a sub-command (mask/zone name)
sub_command_required = {
"motion_mask",
"object_mask",
"zone",
}
if sub_command: if sub_command:
self._camera_settings_handlers[command]( self._camera_settings_handlers[command](
camera_name, sub_command, payload camera_name, sub_command, payload
) )
elif command in sub_command_required: elif command in SUB_COMMAND_TOPICS:
logger.error( logger.error(
"Command %s requires a sub-command (mask/zone name)", "Command %s requires a sub-command (mask/zone name)",
command, command,
@@ -156,10 +261,11 @@ class Dispatcher:
if camera not in self.config.cameras: if camera not in self.config.cameras:
return None return None
model = self.config.model_for_camera(camera)
grid = get_camera_regions_grid( grid = get_camera_regions_grid(
camera, camera,
self.config.cameras[camera].detect, self.config.cameras[camera].detect,
max(self.config.model.width, self.config.model.height), max(model.width, model.height),
) )
return grid return grid
@@ -267,67 +373,11 @@ class Dispatcher:
def handle_birdseye_layout() -> None: def handle_birdseye_layout() -> None:
self.publish("birdseye_layout", json.dumps(self.birdseye_layout.copy())) self.publish("birdseye_layout", json.dumps(self.birdseye_layout.copy()))
def handle_on_connect() -> None:
camera_status = {
camera: status
for camera, status in self.camera_activity.last_camera_activity.copy().items()
if camera in self.config.cameras
}
audio_detections = self.audio_activity.current_audio_detections.copy()
cameras_with_status = camera_status.keys()
for camera in self.config.cameras.keys():
if camera not in cameras_with_status:
camera_status[camera] = {}
camera_status[camera]["config"] = {
"detect": self.config.cameras[camera].detect.enabled,
"enabled": self.config.cameras[camera].enabled,
"snapshots": self.config.cameras[camera].snapshots.enabled,
"record": self.config.cameras[camera].record.enabled,
"audio": self.config.cameras[camera].audio.enabled,
"audio_transcription": self.config.cameras[
camera
].audio_transcription.live_enabled,
"notifications": self.config.cameras[camera].notifications.enabled,
"notifications_suspended": int(
self.web_push_client.suspended_cameras.get(camera, 0)
)
if self.web_push_client
and camera in self.web_push_client.suspended_cameras
else 0,
"autotracking": self.config.cameras[
camera
].onvif.autotracking.enabled,
"alerts": self.config.cameras[camera].review.alerts.enabled,
"detections": self.config.cameras[camera].review.detections.enabled,
"object_descriptions": self.config.cameras[
camera
].objects.genai.enabled,
"review_descriptions": self.config.cameras[
camera
].review.genai.enabled,
}
self.publish("camera_activity", json.dumps(camera_status))
self.publish("model_state", json.dumps(self.model_state.copy()))
self.publish(
"embeddings_reindex_progress",
json.dumps(self.embeddings_reindex.copy()),
)
self.publish("birdseye_layout", json.dumps(self.birdseye_layout.copy()))
self.publish("audio_detections", json.dumps(audio_detections))
self.publish(
"profile/state",
self.config.active_profile or "none",
retain=True,
)
def handle_notification_test() -> None: def handle_notification_test() -> None:
self.publish("notification_test", "Test notification") self.publish("notification_test", "Test notification")
# Dictionary mapping topic to handlers # Dictionary mapping topic to handlers
topic_handlers = { topic_handlers: dict[str, Callable[[], Any]] = {
INSERT_MANY_RECORDINGS: handle_insert_many_recordings, INSERT_MANY_RECORDINGS: handle_insert_many_recordings,
REQUEST_REGION_GRID: handle_request_region_grid, REQUEST_REGION_GRID: handle_request_region_grid,
INSERT_PREVIEW: handle_insert_preview, INSERT_PREVIEW: handle_insert_preview,
@@ -350,7 +400,7 @@ class Dispatcher:
"jobState": handle_job_state, "jobState": handle_job_state,
"audioTranscriptionState": handle_audio_transcription_state, "audioTranscriptionState": handle_audio_transcription_state,
"birdseyeLayout": handle_birdseye_layout, "birdseyeLayout": handle_birdseye_layout,
"onConnect": handle_on_connect, "onConnect": self.publish_runtime_snapshot,
} }
if topic.endswith("set") or topic.endswith("ptz") or topic.endswith("suspend"): if topic.endswith("set") or topic.endswith("ptz") or topic.endswith("suspend"):
@@ -879,11 +929,12 @@ class Dispatcher:
) )
self.publish(f"{camera_name}/birdseye/state", payload, retain=True) self.publish(f"{camera_name}/birdseye/state", payload, retain=True)
def _on_birdseye_mode_command(self, camera_name: str, payload: str) -> None: def _on_birdseye_modes_command(self, camera_name: str, payload: str) -> None:
"""Callback for birdseye mode topic.""" """Callback for birdseye mode topic."""
if payload not in ["CONTINUOUS", "MOTION", "OBJECTS"]: modes = birdseye_modes_from_mqtt_payload(payload)
logger.info(f"Invalid birdseye_mode command: {payload}") if modes is None:
logger.info("Invalid birdseye_modes command: %s", payload)
return return
birdseye_settings = self.config.cameras[camera_name].birdseye birdseye_settings = self.config.cameras[camera_name].birdseye
@@ -892,16 +943,20 @@ class Dispatcher:
logger.info(f"Birdseye mode not enabled for {camera_name}") logger.info(f"Birdseye mode not enabled for {camera_name}")
return return
birdseye_settings.mode = BirdseyeModeEnum(payload.lower()) birdseye_settings.modes = modes
logger.info( logger.info(
f"Setting birdseye mode for {camera_name} to {birdseye_settings.mode}" f"Setting birdseye mode for {camera_name} to {birdseye_settings.modes}"
) )
self.config_updater.publish_update( self.config_updater.publish_update(
CameraConfigUpdateTopic(CameraConfigUpdateEnum.birdseye, camera_name), CameraConfigUpdateTopic(CameraConfigUpdateEnum.birdseye, camera_name),
birdseye_settings, birdseye_settings,
) )
self.publish(f"{camera_name}/birdseye_mode/state", payload, retain=True) self.publish(
f"{camera_name}/birdseye_modes/state",
birdseye_modes_to_mqtt_payload(modes),
retain=True,
)
def _on_camera_notification_command(self, camera_name: str, payload: str) -> None: def _on_camera_notification_command(self, camera_name: str, payload: str) -> None:
"""Callback for camera level notifications topic.""" """Callback for camera level notifications topic."""
+7 -1
View File
@@ -18,10 +18,13 @@ SOCKET_REP_REQ = "ipc:///tmp/cache/comms"
class InterProcessCommunicator(Communicator): class InterProcessCommunicator(Communicator):
def __init__(self) -> None: def __init__(self) -> None:
# bound eagerly so subprocesses starting before start_communicators()
# can still connect; their requests queue in zmq until the reader runs
self.context = zmq.Context() self.context = zmq.Context()
self.socket = self.context.socket(zmq.REP) self.socket = self.context.socket(zmq.REP)
self.socket.bind(SOCKET_REP_REQ) self.socket.bind(SOCKET_REP_REQ)
self.stop_event: MpEvent = mp.Event() self.stop_event: MpEvent = mp.Event()
self.reader_thread: threading.Thread | None = None
def publish(self, topic: str, payload: Any, retain: bool = False) -> None: def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
"""There is no communication back to the processes.""" """There is no communication back to the processes."""
@@ -29,6 +32,8 @@ class InterProcessCommunicator(Communicator):
def subscribe(self, receiver: Callable) -> None: def subscribe(self, receiver: Callable) -> None:
self._dispatcher = receiver self._dispatcher = receiver
def start(self) -> None:
self.reader_thread = threading.Thread(target=self.read) self.reader_thread = threading.Thread(target=self.read)
self.reader_thread.start() self.reader_thread.start()
@@ -61,7 +66,8 @@ class InterProcessCommunicator(Communicator):
def stop(self) -> None: def stop(self) -> None:
self.stop_event.set() self.stop_event.set()
self.reader_thread.join() if self.reader_thread is not None:
self.reader_thread.join()
self.socket.close(linger=0) self.socket.close(linger=0)
self.context.destroy(linger=0) self.context.destroy(linger=0)
+671 -170
View File
@@ -1,16 +1,38 @@
from __future__ import annotations
import logging import logging
import queue
import threading import threading
import time
from collections.abc import Callable from collections.abc import Callable
from typing import Any from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion from paho.mqtt.enums import CallbackAPIVersion
from frigate.comms.base_communicator import Communicator from frigate.comms.base_communicator import Communicator
from frigate.config import FrigateConfig from frigate.config import FrigateConfig, birdseye_modes_to_mqtt_payload
if TYPE_CHECKING:
from frigate.comms.dispatcher import Dispatcher
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
MQTT_LOOP_TIMEOUT = 1.0
MQTT_RECONNECT_INTERVAL = 10.0
MQTT_SHUTDOWN_FLUSH_TIMEOUT = 5.0
MQTT_ON_CONNECT_RATE_LIMIT = 1.0
MQTT_PUBLISH_WAIT_INTERVAL = 0.1
@dataclass(slots=True)
class QueuedPublish:
topic: str
payload: Any
retain: bool
done: threading.Event | None = None
class MqttClient(Communicator): class MqttClient(Communicator):
"""Frigate wrapper for mqtt client.""" """Frigate wrapper for mqtt client."""
@@ -19,28 +41,80 @@ class MqttClient(Communicator):
self.config = config self.config = config
self.mqtt_config = config.mqtt self.mqtt_config = config.mqtt
self.connected = False self.connected = False
self.client: mqtt.Client | None = None
self._dispatcher: Callable[[str, Any], Any] | None = None
self._command_router: Dispatcher | None = None
self._worker: threading.Thread | None = None
self._stop_event = threading.Event()
self._publish_queue: queue.Queue[QueuedPublish] = queue.Queue()
self._callback_queue: queue.Queue[tuple[Any, ...]] = queue.Queue()
self._retained_lock = threading.Lock()
self._pending_retained: dict[str, tuple[Any, bool]] = {}
self._inflight_retained: dict[int, tuple[str, Any]] = {}
self._subscription_mid: int | None = None
self._subscription_ready = False
self._next_connect_time = 0.0
self._last_on_connect_dispatch = 0.0
def subscribe(self, receiver: Callable) -> None: def subscribe(self, receiver: Callable) -> None:
"""Wrapper for allowing dispatcher to subscribe.""" """Wrapper for allowing dispatcher to subscribe."""
self._dispatcher = receiver self._dispatcher = receiver
self._start()
def attach_dispatcher(self, dispatcher: Dispatcher) -> None:
"""Take Dispatcher's command surface and snapshot API."""
self._command_router = dispatcher
def start(self) -> None:
"""Start the MQTT worker after all receiver wiring is complete."""
if self._worker and self._worker.is_alive():
return
self._stop_event.clear()
self._start_worker()
def publish(self, topic: str, payload: Any, retain: bool = False) -> None: def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
"""Wrapper for publishing when client is in valid state.""" """Wrapper for publishing when client is in valid state."""
full_topic = f"{self.mqtt_config.topic_prefix}/{topic}"
if not self.connected: if not self.connected:
logger.debug(f"Unable to publish to {topic}: client is not connected") if retain:
self._queue_retained(full_topic, payload, retain)
else:
logger.debug("Unable to publish to %s: client is not connected", topic)
return return
self.client.publish( self._publish_queue.put(QueuedPublish(full_topic, payload, retain))
f"{self.mqtt_config.topic_prefix}/{topic}",
payload,
qos=self.config.mqtt.qos,
retain=retain,
)
def stop(self) -> None: def stop(self) -> None:
self.publish("available", "stopped", retain=True) if self._worker is None:
self.client.disconnect() return
if self.connected and self._subscription_ready:
publish_done = threading.Event()
self._publish_queue.put(
QueuedPublish(
f"{self.mqtt_config.topic_prefix}/available",
"stopped",
True,
publish_done,
)
)
publish_done.wait(MQTT_SHUTDOWN_FLUSH_TIMEOUT)
self._stop_event.set()
if self.client is not None:
try:
self.client.disconnect()
except Exception:
logger.debug("MQTT disconnect raised during shutdown", exc_info=True)
if self._worker.is_alive():
self._worker.join(MQTT_SHUTDOWN_FLUSH_TIMEOUT + MQTT_LOOP_TIMEOUT)
self._cleanup_client()
self._worker = None
def _notifications_enabled_in_config(self) -> bool: def _notifications_enabled_in_config(self) -> bool:
"""Whether notifications are configured globally or on any camera. """Whether notifications are configured globally or on any camera.
@@ -54,17 +128,17 @@ class MqttClient(Communicator):
for cam in self.config.cameras.values() for cam in self.config.cameras.values()
) )
def _set_initial_topics(self) -> None: def _publish_retained_state(self) -> None:
"""Set initial state topics.""" """Publish retained MQTT state after a successful subscribe."""
for camera_name, camera in self.config.cameras.items(): for camera_name, camera in self.config.cameras.items():
self.publish( self.publish(
f"{camera_name}/enabled/state", f"{camera_name}/enabled/state",
"ON" if camera.enabled_in_config else "OFF", "ON" if camera.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
f"{camera_name}/recordings/state", f"{camera_name}/recordings/state",
"ON" if camera.record.enabled_in_config else "OFF", "ON" if camera.record.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
@@ -74,7 +148,7 @@ class MqttClient(Communicator):
) )
self.publish( self.publish(
f"{camera_name}/audio/state", f"{camera_name}/audio/state",
"ON" if camera.audio.enabled_in_config else "OFF", "ON" if camera.audio.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
@@ -89,7 +163,7 @@ class MqttClient(Communicator):
) )
self.publish( self.publish(
f"{camera_name}/motion/state", f"{camera_name}/motion/state",
"ON", "ON" if camera.motion.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
@@ -99,7 +173,7 @@ class MqttClient(Communicator):
) )
self.publish( self.publish(
f"{camera_name}/ptz_autotracker/state", f"{camera_name}/ptz_autotracker/state",
"ON" if camera.onvif.autotracking.enabled_in_config else "OFF", "ON" if camera.onvif.autotracking.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
@@ -123,9 +197,9 @@ class MqttClient(Communicator):
retain=True, retain=True,
) )
self.publish( self.publish(
f"{camera_name}/birdseye_mode/state", f"{camera_name}/birdseye_modes/state",
( (
camera.birdseye.mode.value.upper() birdseye_modes_to_mqtt_payload(camera.birdseye.modes)
if camera.birdseye.enabled if camera.birdseye.enabled
else "OFF" else "OFF"
), ),
@@ -133,22 +207,22 @@ class MqttClient(Communicator):
) )
self.publish( self.publish(
f"{camera_name}/review_alerts/state", f"{camera_name}/review_alerts/state",
"ON" if camera.review.alerts.enabled_in_config else "OFF", "ON" if camera.review.alerts.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
f"{camera_name}/review_detections/state", f"{camera_name}/review_detections/state",
"ON" if camera.review.detections.enabled_in_config else "OFF", "ON" if camera.review.detections.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
f"{camera_name}/object_descriptions/state", f"{camera_name}/object_descriptions/state",
"ON" if camera.objects.genai.enabled_in_config else "OFF", "ON" if camera.objects.genai.enabled else "OFF",
retain=True, retain=True,
) )
self.publish( self.publish(
f"{camera_name}/review_descriptions/state", f"{camera_name}/review_descriptions/state",
"ON" if camera.review.genai.enabled_in_config else "OFF", "ON" if camera.review.genai.enabled else "OFF",
retain=True, retain=True,
) )
@@ -189,13 +263,521 @@ class MqttClient(Communicator):
) )
self.publish("available", "online", retain=True) self.publish("available", "online", retain=True)
def on_mqtt_command( def _create_client(self) -> mqtt.Client:
self, client: mqtt.Client, userdata: Any, message: mqtt.MQTTMessage """Build a fresh paho client for a single connect attempt."""
) -> None: client = mqtt.Client(
self._dispatcher( callback_api_version=CallbackAPIVersion.VERSION2,
message.topic.replace(f"{self.mqtt_config.topic_prefix}/", "", 1), client_id=self.mqtt_config.client_id,
message.payload.decode(), reconnect_on_failure=False,
) )
client.on_connect = self._on_connect
client.on_disconnect = self._on_disconnect
client.on_message = self._on_message
client.on_subscribe = self._on_subscribe
client.on_publish = self._on_publish
client.will_set(
self.mqtt_config.topic_prefix + "/available",
payload="offline",
qos=1,
retain=True,
)
if self.mqtt_config.tls_ca_certs is not None:
if (
self.mqtt_config.tls_client_cert is not None
and self.mqtt_config.tls_client_key is not None
):
client.tls_set(
self.mqtt_config.tls_ca_certs,
self.mqtt_config.tls_client_cert,
self.mqtt_config.tls_client_key,
)
else:
client.tls_set(self.mqtt_config.tls_ca_certs)
if self.mqtt_config.tls_insecure is not None:
client.tls_insecure_set(self.mqtt_config.tls_insecure)
if self.mqtt_config.user is not None:
client.username_pw_set(
self.mqtt_config.user,
password=self.mqtt_config.password,
)
return client
def _start_worker(self) -> None:
self._worker = threading.Thread(
target=self._worker_main, name="mqtt", daemon=True
)
self._worker.start()
logger.info("MQTT worker started")
def _worker_main(self) -> None:
"""Run the worker loop.
An unexpected crash disables MQTT for this session rather than taking
Frigate down with it, so it has to announce itself: without the offline
publish, consumers keep the last retained values and see a healthy
Frigate that has simply stopped updating.
"""
try:
self._mqtt_loop_worker()
except Exception:
if not self._stop_event.is_set():
logger.exception("MQTT worker crashed, disabling MQTT for this session")
self._stop_event.set()
self._subscription_ready = False
self._publish_offline_availability()
self.connected = False
finally:
# nothing drains the queue once the loop is gone, so release any
# waiter here or stop() blocks for the full flush timeout
self._requeue_disconnected_publishes()
self._cleanup_client()
def _publish_offline_availability(self) -> None:
"""Announce that MQTT is going away after a worker crash.
_cleanup_client() disconnects cleanly, which tells the broker to
suppress the will, so the retained topic would otherwise stay "online".
"""
if self.client is None:
return
try:
message_info = self.client.publish(
f"{self.mqtt_config.topic_prefix}/available",
"offline",
qos=self.config.mqtt.qos,
retain=True,
)
# pumped here rather than through _wait_for_publish() so the drain
# that may have just crashed is not re-entered
deadline = time.monotonic() + MQTT_SHUTDOWN_FLUSH_TIMEOUT
while not message_info.is_published() and time.monotonic() < deadline:
if (
self.client.loop(timeout=MQTT_PUBLISH_WAIT_INTERVAL)
!= mqtt.MQTT_ERR_SUCCESS
):
break
except Exception:
logger.warning(
"MQTT is dormant and the broker could not be told Frigate is offline",
exc_info=True,
)
def _mqtt_loop_worker(self) -> None:
# The worker owns all socket I/O so reconnect, subscribe, and publish
# ordering stays serialized in one place.
while not self._stop_event.is_set():
if self.client is None:
wait_time = self._next_connect_time - time.monotonic()
if wait_time > 0:
self._stop_event.wait(min(wait_time, MQTT_LOOP_TIMEOUT))
continue
if not self._connect_client():
self._next_connect_time = time.monotonic() + MQTT_RECONNECT_INTERVAL
continue
assert self.client is not None
try:
result = self.client.loop(timeout=MQTT_LOOP_TIMEOUT)
except (OSError, mqtt.WebsocketConnectionError) as err:
logger.warning("MQTT loop error: %s", err)
self._schedule_reconnect()
continue
self._drain_callback_queue()
self._drain_publish_queue()
if self._stop_event.is_set():
break
if result != mqtt.MQTT_ERR_SUCCESS and self.client is not None:
logger.error("MQTT loop returned error code: %s", result)
self._schedule_reconnect()
def _connect_client(self) -> bool:
"""Create and connect a new client instance owned by the worker thread."""
try:
self.client = self._create_client()
self.client.connect(self.mqtt_config.host, self.mqtt_config.port, 60)
except Exception as err:
logger.error("Unable to connect to MQTT server: %s", err)
self._cleanup_client()
return False
return True
def _cleanup_client(self) -> None:
"""Drop session-specific state and release the current paho client."""
self.connected = False
self._subscription_ready = False
self._subscription_mid = None
self._requeue_inflight_retained()
client = self.client
self.client = None
if client is None:
return
try:
client.disconnect()
except Exception:
logger.debug("MQTT client cleanup raised disconnect error", exc_info=True)
def _schedule_reconnect(self) -> None:
"""Tear down the current session and arm the next reconnect attempt."""
if self._stop_event.is_set():
return
self.connected = False
self._subscription_ready = False
self._subscription_mid = None
self._requeue_disconnected_publishes()
self._next_connect_time = time.monotonic() + MQTT_RECONNECT_INTERVAL
logger.info("MQTT reconnect scheduled in %.1fs", MQTT_RECONNECT_INTERVAL)
self._cleanup_client()
def _requeue_inflight_retained(self) -> None:
"""Rebuffer retained publishes paho took but the broker never acked.
Dropping the client drops paho's outbound queue with it, and the session
is clean, so the broker will not resume delivery on the new one.
"""
with self._retained_lock:
# mids are insertion ordered, so collapsing by topic keeps the
# newest value when several updates to one topic were in flight
latest = {
topic: payload for topic, payload in self._inflight_retained.values()
}
self._inflight_retained.clear()
for topic, payload in latest.items():
self._queue_retained(topic, payload, True, overwrite=False)
def _buffer_undelivered(
self, queued_publish: QueuedPublish, overwrite: bool = True
) -> None:
"""Handle a publish that never reached the broker.
Releasing the waiter matters on every path: stop() blocks on it, so a
broker error would otherwise stall shutdown for the full flush timeout.
"""
if queued_publish.retain:
self._queue_retained(
queued_publish.topic,
queued_publish.payload,
queued_publish.retain,
overwrite=overwrite,
)
if queued_publish.done is not None:
queued_publish.done.set()
def _requeue_disconnected_publishes(self) -> None:
while True:
try:
queued_publish = self._publish_queue.get_nowait()
except queue.Empty:
break
self._buffer_undelivered(queued_publish)
def _drain_callback_queue(self) -> None:
# Paho callbacks only enqueue transport events; state transitions run
# here on the worker thread.
while True:
try:
event = self._callback_queue.get_nowait()
except queue.Empty:
break
event_type = event[0]
if event_type == "connect":
self._handle_connect_event(event[1])
elif event_type == "connect_failure":
self._handle_connect_failure(event[1])
elif event_type == "disconnect":
self._handle_disconnect_event(event[1])
elif event_type == "subscribed":
self._handle_subscribe_event(event[1], event[2])
elif event_type == "message":
self._handle_inbound_message(event[1], event[2])
elif event_type == "published":
self._handle_publish_event(event[1])
def _drain_publish_queue(self) -> None:
"""Publish queued work only after the session is fully subscribed.
Oldest first: the outage buffer replays before the queue, so a topic
that changed since the reconnect ends up on its newest value rather
than being reverted by the replay.
"""
if self.connected and not self._subscription_ready:
return
self._flush_pending_retained()
while True:
try:
queued_publish = self._publish_queue.get_nowait()
except queue.Empty:
break
if not self.connected:
self._buffer_undelivered(queued_publish)
continue
self._publish_direct(queued_publish)
def _flush_pending_retained(self) -> None:
"""Replay the latest retained state once the broker session is ready."""
if not self.connected or not self._subscription_ready:
return
with self._retained_lock:
pending = list(self._pending_retained.items())
self._pending_retained.clear()
for topic, (payload, retain) in pending:
self._publish_direct(QueuedPublish(topic, payload, retain))
def _publish_direct(self, queued_publish: QueuedPublish) -> None:
"""Publish a queued message from the worker thread's serialized context.
The waiter is released however this exits. The message is already off
the queue by now, so nothing else can recover it for a stop() that is
blocked waiting on it.
"""
try:
if self.client is None:
# never attempted, so anything already buffered for this topic
# was written later and has to survive
self._buffer_undelivered(queued_publish, overwrite=False)
return
try:
message_info = self.client.publish(
queued_publish.topic,
queued_publish.payload,
qos=self.config.mqtt.qos,
retain=queued_publish.retain,
)
except (OSError, mqtt.WebsocketConnectionError) as err:
logger.warning(
"MQTT publish failed for %s: %s", queued_publish.topic, err
)
# a newer buffered value for this topic wins over the failed one
self._buffer_undelivered(queued_publish, overwrite=False)
self._schedule_reconnect()
return
if message_info.rc != mqtt.MQTT_ERR_SUCCESS:
logger.error(
"Unable to publish to %s: mqtt error %s",
queued_publish.topic,
message_info.rc,
)
self._buffer_undelivered(queued_publish, overwrite=False)
self._schedule_reconnect()
return
# a successful rc only means paho accepted the message; above qos 0
# it is not durable until the broker acks, so keep a copy for replay
if queued_publish.retain and not message_info.is_published():
with self._retained_lock:
self._inflight_retained[message_info.mid] = (
queued_publish.topic,
queued_publish.payload,
)
if queued_publish.done is not None:
self._wait_for_publish(message_info)
finally:
if queued_publish.done is not None:
queued_publish.done.set()
def _handle_publish_event(self, mid: int) -> None:
"""Drop the replay copy once the broker has acknowledged the message."""
with self._retained_lock:
self._inflight_retained.pop(mid, None)
def _wait_for_publish(self, message_info: mqtt.MQTTMessageInfo) -> None:
"""Pump the loop until a shutdown-critical publish is acknowledged."""
deadline = time.monotonic() + MQTT_SHUTDOWN_FLUSH_TIMEOUT
while not message_info.is_published() and time.monotonic() < deadline:
if self.client is None:
return
try:
result = self.client.loop(timeout=MQTT_PUBLISH_WAIT_INTERVAL)
except (OSError, mqtt.WebsocketConnectionError) as err:
logger.warning("MQTT publish wait failed: %s", err)
self._schedule_reconnect()
return
self._drain_callback_queue()
if result != mqtt.MQTT_ERR_SUCCESS:
logger.error(
"MQTT loop returned error code while waiting for publish: %s",
result,
)
self._schedule_reconnect()
return
def _queue_retained(
self,
topic: str,
payload: Any,
retain: bool,
overwrite: bool = True,
) -> None:
"""Store the last retained value per topic for replay after reconnect."""
with self._retained_lock:
if overwrite or topic not in self._pending_retained:
self._pending_retained[topic] = (payload, retain)
def _handle_connect_event(self, reason_code: mqtt.ReasonCode) -> None: # type: ignore[name-defined]
"""Begin a new session by subscribing before any replay is published."""
if self.client is None:
return
self.connected = True
self._subscription_ready = False
self._subscription_mid = None
logger.debug("MQTT connected")
try:
result, mid = self.client.subscribe(
f"{self.mqtt_config.topic_prefix}/#",
qos=self.config.mqtt.qos,
)
except (OSError, mqtt.WebsocketConnectionError) as err:
logger.warning("MQTT subscribe failed: %s", err)
self._schedule_reconnect()
return
if result != mqtt.MQTT_ERR_SUCCESS:
logger.error(
"Unable to subscribe to MQTT command tree: mqtt error %s", result
)
self._schedule_reconnect()
return
self._subscription_mid = mid
def _handle_connect_failure(self, reason_code: mqtt.ReasonCode) -> None: # type: ignore[name-defined]
"""Record a failed connect attempt and transition into reconnect state."""
self.connected = False
logger.error(
"Unable to connect to MQTT server: %s", self._reason_code_name(reason_code)
)
self._schedule_reconnect()
def _handle_disconnect_event(self, reason_code: mqtt.ReasonCode) -> None: # type: ignore[name-defined]
"""Handle broker disconnects idempotently from the worker thread."""
if not self.connected:
return
self.connected = False
self._subscription_ready = False
self._subscription_mid = None
if self._stop_event.is_set():
logger.debug("MQTT disconnected")
self._cleanup_client()
return
logger.error("MQTT disconnected: %s", self._reason_code_name(reason_code))
self._schedule_reconnect()
def _handle_subscribe_event(
self,
mid: int,
reason_codes: list[mqtt.ReasonCode], # type: ignore[name-defined]
) -> None:
"""Mark the session ready after SUBACK, then replay retained/runtime state."""
if mid != self._subscription_mid:
return
if any(
getattr(reason_code, "is_failure", False) for reason_code in reason_codes
):
logger.error("MQTT subscription was rejected by the broker")
self._schedule_reconnect()
return
self._subscription_ready = True
self._subscription_mid = None
# a bug in replay should cost a snapshot, not the MQTT session
try:
self._publish_retained_state()
if self._command_router is not None:
self._command_router.publish_runtime_snapshot(self.publish)
except Exception:
logger.exception("Error replaying MQTT state after subscribe")
def _handle_inbound_message(self, topic: str, payload: str) -> None:
"""Forward supported command topics into Dispatcher semantics."""
if self._dispatcher is None:
return
if not self._is_supported_command_topic(topic):
return
if topic == "onConnect":
now = time.monotonic()
if now - self._last_on_connect_dispatch < MQTT_ON_CONNECT_RATE_LIMIT:
logger.debug("Skipping MQTT onConnect replay request due to rate limit")
return
self._last_on_connect_dispatch = now
# a raise here used to end the network thread and take MQTT down
try:
self._dispatcher(topic, payload)
except Exception:
logger.exception("Error handling MQTT command topic %s", topic)
def _is_supported_command_topic(self, topic: str) -> bool:
"""Filter the wildcard subscription down to Dispatcher's command surface.
Load-bearing rather than an optimization: the broker echoes Frigate's own
publishes back through frigate/#, and Dispatcher republishes topics it
does not recognize, so forwarding unfiltered would loop.
"""
if self._command_router is None:
return False
# mirrors the gate on the state topic in _publish_retained_state()
if topic == "notifications/set" and not self._notifications_enabled_in_config():
return False
return self._command_router.is_command_topic(topic)
def _strip_topic_prefix(self, topic: str) -> str:
return topic.replace(f"{self.mqtt_config.topic_prefix}/", "", 1)
def _is_success_reason_code(self, reason_code: mqtt.ReasonCode) -> bool: # type: ignore[name-defined]
if hasattr(reason_code, "is_failure"):
return not bool(reason_code.is_failure)
return bool(reason_code == 0)
def _reason_code_name(self, reason_code: mqtt.ReasonCode) -> str: # type: ignore[name-defined]
if hasattr(reason_code, "getName"):
return str(reason_code.getName())
return str(reason_code)
def _on_connect( def _on_connect(
self, self,
@@ -205,29 +787,11 @@ class MqttClient(Communicator):
reason_code: mqtt.ReasonCode, # type: ignore[name-defined] reason_code: mqtt.ReasonCode, # type: ignore[name-defined]
properties: Any, properties: Any,
) -> None: ) -> None:
"""Mqtt connection callback.""" """Handle broker connect notifications from paho."""
threading.current_thread().name = "mqtt" if self._is_success_reason_code(reason_code):
if reason_code != 0: self._callback_queue.put(("connect", reason_code))
if reason_code == "Server unavailable": else:
logger.error( self._callback_queue.put(("connect_failure", reason_code))
"Unable to connect to MQTT server: MQTT Server unavailable"
)
elif reason_code == "Bad user name or password":
logger.error(
"Unable to connect to MQTT server: MQTT Bad username or password"
)
elif reason_code == "Not authorized":
logger.error("Unable to connect to MQTT server: MQTT Not authorized")
else:
logger.error(
"Unable to connect to MQTT server: Connection refused. Error code: %s",
reason_code.getName(),
)
self.connected = True
logger.debug("MQTT connected")
client.subscribe(f"{self.mqtt_config.topic_prefix}/#", qos=self.config.mqtt.qos)
self._set_initial_topics()
def _on_disconnect( def _on_disconnect(
self, self,
@@ -237,126 +801,63 @@ class MqttClient(Communicator):
reason_code: mqtt.ReasonCode, # type: ignore[name-defined] reason_code: mqtt.ReasonCode, # type: ignore[name-defined]
properties: Any, properties: Any,
) -> None: ) -> None:
"""Mqtt disconnection callback.""" """Handle broker disconnect notifications from paho."""
self.connected = False self._callback_queue.put(("disconnect", reason_code))
logger.error("MQTT disconnected")
def _start(self) -> None: def _on_subscribe(
"""Start mqtt client.""" self,
self.client = mqtt.Client( client: mqtt.Client,
callback_api_version=CallbackAPIVersion.VERSION2, userdata: Any,
client_id=self.mqtt_config.client_id, mid: int,
) reason_codes: list[mqtt.ReasonCode], # type: ignore[name-defined]
self.client.on_connect = self._on_connect properties: Any,
self.client.on_disconnect = self._on_disconnect ) -> None:
self.client.will_set( """Handle subscribe acknowledgements from paho."""
self.mqtt_config.topic_prefix + "/available", self._callback_queue.put(("subscribed", mid, reason_codes))
payload="offline",
qos=1,
retain=True,
)
# register callbacks def _on_publish(
callback_types = [ self,
"enabled", client: mqtt.Client,
"recordings", userdata: Any,
"snapshots", mid: int,
"detect", reason_code: mqtt.ReasonCode, # type: ignore[name-defined]
"audio", properties: Any,
"audio_transcription", ) -> None:
"motion", """Handle publish acknowledgements from paho.
"improve_contrast",
"ptz_autotracker",
"motion_threshold",
"motion_contour_area",
"birdseye",
"birdseye_mode",
"review_alerts",
"review_detections",
"object_descriptions",
"review_descriptions",
"notifications",
]
for name in self.config.cameras.keys(): Only tracked retained messages need an event. At the default qos 0
for callback in callback_types: nothing is tracked, so this stays off the hot publish path.
self.client.message_callback_add( """
f"{self.mqtt_config.topic_prefix}/{name}/{callback}/set", with self._retained_lock:
self.on_mqtt_command, if mid not in self._inflight_retained:
) return
# notifications suspend doesn't follow the /set topic pattern self._callback_queue.put(("published", mid))
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/{name}/notifications/suspend",
self.on_mqtt_command,
)
if self.config.cameras[name].onvif.host: def _on_message(
self.client.message_callback_add( self,
f"{self.mqtt_config.topic_prefix}/{name}/ptz", client: mqtt.Client,
self.on_mqtt_command, userdata: Any,
) message: mqtt.MQTTMessage,
) -> None:
"""Queue inbound MQTT messages for processing in the worker loop."""
topic = self._strip_topic_prefix(message.topic)
for mask_name in self.config.cameras[name].motion.mask.keys(): # Ignore everything outside Frigate's command surface before decoding or
self.client.message_callback_add( # dispatching into the rest of the app.
f"{self.mqtt_config.topic_prefix}/{name}/motion_mask/{mask_name}/set", if not self._is_supported_command_topic(topic):
self.on_mqtt_command,
)
for mask_name in self.config.cameras[name].objects.mask.keys():
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/{name}/object_mask/{mask_name}/set",
self.on_mqtt_command,
)
for zone_name in self.config.cameras[name].zones.keys():
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/{name}/zone/{zone_name}/set",
self.on_mqtt_command,
)
if self._notifications_enabled_in_config():
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/notifications/set",
self.on_mqtt_command,
)
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/profile/set",
self.on_mqtt_command,
)
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/onConnect", self.on_mqtt_command
)
self.client.message_callback_add(
f"{self.mqtt_config.topic_prefix}/restart", self.on_mqtt_command
)
if self.mqtt_config.tls_ca_certs is not None:
if (
self.mqtt_config.tls_client_cert is not None
and self.mqtt_config.tls_client_key is not None
):
self.client.tls_set(
self.mqtt_config.tls_ca_certs,
self.mqtt_config.tls_client_cert,
self.mqtt_config.tls_client_key,
)
else:
self.client.tls_set(self.mqtt_config.tls_ca_certs)
if self.mqtt_config.tls_insecure is not None:
self.client.tls_insecure_set(self.mqtt_config.tls_insecure)
if self.mqtt_config.user is not None:
self.client.username_pw_set(
self.mqtt_config.user, password=self.mqtt_config.password
)
try:
# https://stackoverflow.com/a/55390477
# with connect_async, retries are handled automatically
self.client.connect_async(self.mqtt_config.host, self.mqtt_config.port, 60)
self.client.loop_start()
except Exception as e:
logger.error(f"Unable to connect to MQTT server: {e}")
return return
try:
payload = message.payload.decode()
except UnicodeDecodeError:
logger.debug("Ignoring non-UTF-8 MQTT payload for topic %s", topic)
return
self._callback_queue.put(
(
"message",
topic,
payload,
)
)
+31 -17
View File
@@ -63,14 +63,8 @@ class WebPushClient(Communicator):
self.last_notification_time: float = 0 self.last_notification_time: float = 0
self.user_cameras: dict[str, set[str]] = {} self.user_cameras: dict[str, set[str]] = {}
self.notification_queue: queue.Queue[PushNotification] = queue.Queue() self.notification_queue: queue.Queue[PushNotification] = queue.Queue()
self.notification_thread = threading.Thread( self.notification_thread: threading.Thread | None = None
target=self._process_notifications, daemon=True self.suspension_thread: threading.Thread | None = None
)
self.notification_thread.start()
self.suspension_thread = threading.Thread(
target=self._process_suspensions, daemon=True
)
self.suspension_thread.start()
if not self.config.notifications.email: if not self.config.notifications.email:
logger.warning("Email must be provided for push notifications to be sent.") logger.warning("Email must be provided for push notifications to be sent.")
@@ -89,7 +83,9 @@ class WebPushClient(Communicator):
# notification and auth config updater # notification and auth config updater
self.global_config_subscriber = ConfigSubscriber("config/") self.global_config_subscriber = ConfigSubscriber("config/")
self.config_subscriber = CameraConfigUpdateSubscriber( self.config_subscriber = CameraConfigUpdateSubscriber(
self.config, self.config.cameras, [CameraConfigUpdateEnum.notifications] self.config,
self.config.cameras,
[CameraConfigUpdateEnum.add, CameraConfigUpdateEnum.notifications],
) )
self._refresh_user_cameras() self._refresh_user_cameras()
@@ -97,6 +93,16 @@ class WebPushClient(Communicator):
"""Wrapper for allowing dispatcher to subscribe.""" """Wrapper for allowing dispatcher to subscribe."""
pass pass
def start(self) -> None:
self.notification_thread = threading.Thread(
target=self._process_notifications, daemon=True
)
self.notification_thread.start()
self.suspension_thread = threading.Thread(
target=self._process_suspensions, daemon=True
)
self.suspension_thread.start()
def check_registrations(self) -> None: def check_registrations(self) -> None:
# check for valid claim or create new one # check for valid claim or create new one
now = datetime.datetime.now().timestamp() now = datetime.datetime.now().timestamp()
@@ -213,10 +219,14 @@ class WebPushClient(Communicator):
self.suspended_cameras[camera] = 0 self.suspended_cameras[camera] = 0
self.last_camera_notification_time[camera] = 0 self.last_camera_notification_time[camera] = 0
self._refresh_user_cameras()
if topic == "reviews": if topic == "reviews":
decoded = json.loads(payload) decoded = json.loads(payload)
camera = decoded["before"]["camera"] camera = decoded["before"]["camera"]
if not self.config.cameras[camera].notifications.enabled: camera_config = self.config.cameras.get(camera)
if camera_config is None or not camera_config.notifications.enabled:
return return
if self.is_camera_suspended(camera): if self.is_camera_suspended(camera):
logger.debug(f"Notifications for {camera} are currently suspended.") logger.debug(f"Notifications for {camera} are currently suspended.")
@@ -230,13 +240,14 @@ class WebPushClient(Communicator):
# ensure notifications are enabled and the specific trigger has # ensure notifications are enabled and the specific trigger has
# notification action enabled # notification action enabled
camera_config = self.config.cameras.get(camera)
if ( if (
not self.config.cameras[camera].notifications.enabled camera_config is None
or name not in self.config.cameras[camera].semantic_search.triggers or not camera_config.notifications.enabled
or name not in camera_config.semantic_search.triggers
or "notification" or "notification"
not in self.config.cameras[camera] not in camera_config.semantic_search.triggers[name].actions
.semantic_search.triggers[name]
.actions
): ):
return return
@@ -247,7 +258,9 @@ class WebPushClient(Communicator):
elif topic == "camera_monitoring": elif topic == "camera_monitoring":
decoded = json.loads(payload) decoded = json.loads(payload)
camera = decoded["camera"] camera = decoded["camera"]
if not self.config.cameras[camera].notifications.enabled: camera_config = self.config.cameras.get(camera)
if camera_config is None or not camera_config.notifications.enabled:
return return
if self.is_camera_suspended(camera): if self.is_camera_suspended(camera):
logger.debug(f"Notifications for {camera} are currently suspended.") logger.debug(f"Notifications for {camera} are currently suspended.")
@@ -598,4 +611,5 @@ class WebPushClient(Communicator):
def stop(self) -> None: def stop(self) -> None:
logger.info("Closing notification queue") logger.info("Closing notification queue")
self.notification_thread.join() if self.notification_thread is not None:
self.notification_thread.join()
-1
View File
@@ -466,7 +466,6 @@ class WebSocketClient(Communicator):
def subscribe(self, receiver: Callable) -> None: def subscribe(self, receiver: Callable) -> None:
self._dispatcher = receiver self._dispatcher = receiver
self.start()
def start(self) -> None: def start(self) -> None:
"""Start the websocket client.""" """Start the websocket client."""
+5
View File
@@ -41,6 +41,11 @@ class AudioConfig(FrigateBaseModel):
title="Listen types", title="Listen types",
description="List of audio event types to detect (for example: bark, fire_alarm, speech, yell).", description="List of audio event types to detect (for example: bark, fire_alarm, speech, yell).",
) )
labelmap: dict[int, str] = Field(
default_factory=dict,
title="Audio labelmap customization",
description="Overrides or remapping entries to merge into the standard audio labelmap.",
)
filters: dict[str, AudioFilterConfig] | None = Field( filters: dict[str, AudioFilterConfig] | None = Field(
None, None,
title="Audio filters", title="Audio filters",
+52 -16
View File
@@ -9,21 +9,57 @@ __all__ = [
"BirdseyeConfig", "BirdseyeConfig",
"BirdseyeLayoutConfig", "BirdseyeLayoutConfig",
"BirdseyeModeEnum", "BirdseyeModeEnum",
"birdseye_modes_from_mqtt_payload",
"birdseye_modes_to_mqtt_payload",
] ]
# canonical MQTT payload for an empty mode list
MQTT_NO_MODES = "NONE"
class BirdseyeModeEnum(str, Enum): class BirdseyeModeEnum(str, Enum):
objects = "objects"
motion = "motion"
continuous = "continuous" continuous = "continuous"
motion = "motion"
all_objects = "all_objects"
alerts = "alerts"
detections = "detections"
@classmethod
def get_index(cls, type):
return list(cls).index(type)
@classmethod def birdseye_modes_from_mqtt_payload(payload: str) -> list[BirdseyeModeEnum] | None:
def get(cls, index): """Parse an uppercase MQTT payload into activity modes, or None when invalid."""
return list(cls)[index] raw_modes = payload.split(",")
if any(not raw_mode or raw_mode != raw_mode.upper() for raw_mode in raw_modes):
return None
if raw_modes == [MQTT_NO_MODES]:
return []
modes: list[BirdseyeModeEnum] = []
for raw_mode in raw_modes:
try:
mode = BirdseyeModeEnum(raw_mode.lower())
except ValueError:
return None
if mode in modes:
return None
modes.append(mode)
return modes
def birdseye_modes_to_mqtt_payload(modes: list[BirdseyeModeEnum]) -> str:
"""Serialize activity modes for MQTT state topics."""
payload = ",".join(mode.value.upper() for mode in BirdseyeModeEnum if mode in modes)
return payload or MQTT_NO_MODES
def default_birdseye_modes() -> list[BirdseyeModeEnum]:
"""Return the default Birdseye activity modes."""
return [BirdseyeModeEnum.all_objects]
class BirdseyeLayoutConfig(FrigateBaseModel): class BirdseyeLayoutConfig(FrigateBaseModel):
@@ -47,10 +83,10 @@ class BirdseyeConfig(FrigateBaseModel):
title="Enable Birdseye", title="Enable Birdseye",
description="Enable or disable the Birdseye view feature.", description="Enable or disable the Birdseye view feature.",
) )
mode: BirdseyeModeEnum = Field( modes: list[BirdseyeModeEnum] = Field(
default=BirdseyeModeEnum.objects, default_factory=default_birdseye_modes,
title="Tracking mode", title="Activity types",
description="Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'.", description="Activity types that include cameras in Birdseye.",
) )
restream: bool = Field( restream: bool = Field(
@@ -102,10 +138,10 @@ class BirdseyeCameraConfig(BaseModel):
title="Enable Birdseye", title="Enable Birdseye",
description="Enable or disable the Birdseye view feature.", description="Enable or disable the Birdseye view feature.",
) )
mode: BirdseyeModeEnum = Field( modes: list[BirdseyeModeEnum] = Field(
default=BirdseyeModeEnum.objects, default_factory=default_birdseye_modes,
title="Tracking mode", title="Activity types",
description="Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'.", description="Activity types that include cameras in Birdseye.",
) )
order: int = Field( order: int = Field(
+28 -1
View File
@@ -3,7 +3,12 @@ from enum import Enum
from pydantic import Field, PrivateAttr, model_validator from pydantic import Field, PrivateAttr, model_validator
from frigate.const import CACHE_DIR, CACHE_SEGMENT_FORMAT, REGEX_CAMERA_NAME from frigate.const import (
CACHE_DIR,
CACHE_SEGMENT_FORMAT,
REGEX_CAMERA_NAME,
SUB_CACHE_TAG,
)
from frigate.ffmpeg_presets import ( from frigate.ffmpeg_presets import (
parse_preset_hardware_acceleration_decode, parse_preset_hardware_acceleration_decode,
parse_preset_hardware_acceleration_scale, parse_preset_hardware_acceleration_scale,
@@ -294,6 +299,28 @@ class CameraConfig(FrigateBaseModel):
+ ffmpeg_output_args + ffmpeg_output_args
) )
if (
"record_sub" in ffmpeg_input.roles
and self.record.enabled
and self.record.sub.enabled
):
sub_output_args = self.ffmpeg.output_args.effective_record_sub
record_args = get_ffmpeg_arg_list(
parse_preset_output_record(
sub_output_args,
self.ffmpeg.apple_compatibility,
)
or sub_output_args
)
ffmpeg_output_args = (
record_args
+ [
f"{os.path.join(CACHE_DIR, self.name)}{SUB_CACHE_TAG}@{CACHE_SEGMENT_FORMAT}.mp4"
]
+ ffmpeg_output_args
)
# if there aren't any outputs enabled for this input # if there aren't any outputs enabled for this input
if len(ffmpeg_output_args) == 0: if len(ffmpeg_output_args) == 0:
return None return None
+7
View File
@@ -1,5 +1,7 @@
from pydantic import Field, model_validator from pydantic import Field, model_validator
from frigate.detectors.detector_config import SceneEnum
from ..base import FrigateBaseModel from ..base import FrigateBaseModel
__all__ = ["DetectConfig", "StationaryConfig", "StationaryMaxFramesConfig"] __all__ = ["DetectConfig", "StationaryConfig", "StationaryMaxFramesConfig"]
@@ -60,6 +62,11 @@ class DetectConfig(FrigateBaseModel):
title="Detect width", title="Detect width",
description="Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution.", description="Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution.",
) )
scene: SceneEnum = Field(
default=SceneEnum.all,
title="Detect scene",
description="The environment this camera looks at, used to pick which of the configured models runs on it. Cameras left on 'all' run the model configured with a scene of 'all'.",
)
fps: int = Field( fps: int = Field(
default=5, default=5,
title="Detect FPS", title="Detect FPS",
+15
View File
@@ -42,6 +42,20 @@ class FfmpegOutputArgsConfig(FrigateBaseModel):
title="Record output arguments", title="Record output arguments",
description="Default output arguments for record role streams.", description="Default output arguments for record role streams.",
) )
record_sub: str | list[str] = Field(
default_factory=list,
title="Sub stream record output arguments",
description="Output arguments for record_sub role streams. The record output arguments are used when this is not set.",
)
@property
def effective_record_sub(self) -> str | list[str]:
"""Output arguments used for the record_sub role.
Falls back to the record arguments rather than to the stock preset so
that a customized record value keeps applying to both recorded streams.
"""
return self.record_sub or self.record
class FfmpegConfig(FrigateBaseModel): class FfmpegConfig(FrigateBaseModel):
@@ -99,6 +113,7 @@ class FfmpegConfig(FrigateBaseModel):
class CameraRoleEnum(str, Enum): class CameraRoleEnum(str, Enum):
audio = "audio" audio = "audio"
record = "record" record = "record"
record_sub = "record_sub"
detect = "detect" detect = "detect"
+52
View File
@@ -13,6 +13,7 @@ __all__ = [
"RecordExportConfig", "RecordExportConfig",
"RecordPreviewConfig", "RecordPreviewConfig",
"RecordQualityEnum", "RecordQualityEnum",
"RecordSubConfig",
"EventsConfig", "EventsConfig",
"ReviewRetainConfig", "ReviewRetainConfig",
"RecordRetainConfig", "RecordRetainConfig",
@@ -110,6 +111,34 @@ class RecordExportConfig(FrigateBaseModel):
) )
class RecordSubConfig(FrigateBaseModel):
enabled: bool = Field(
default=False,
title="Enable sub stream recording",
description="Enable recording of a second, lower quality stream for adaptive quality playback and extended retention.",
)
continuous: RecordRetainConfig = Field(
default_factory=RecordRetainConfig,
title="Sub stream continuous retention",
description="Number of days to retain sub stream recordings regardless of tracked objects or motion.",
)
motion: RecordRetainConfig = Field(
default_factory=RecordRetainConfig,
title="Sub stream motion retention",
description="Number of days to retain sub stream recordings triggered by motion.",
)
alerts: ReviewRetainConfig = Field(
default_factory=ReviewRetainConfig,
title="Sub stream alert retention",
description="Retention settings for sub stream recordings of alerts.",
)
detections: ReviewRetainConfig = Field(
default_factory=ReviewRetainConfig,
title="Sub stream detection retention",
description="Retention settings for sub stream recordings of detections.",
)
class RecordConfig(FrigateBaseModel): class RecordConfig(FrigateBaseModel):
enabled: bool = Field( enabled: bool = Field(
default=False, default=False,
@@ -151,12 +180,35 @@ class RecordConfig(FrigateBaseModel):
title="Preview config", title="Preview config",
description="Settings controlling the quality of recording previews shown in the UI.", description="Settings controlling the quality of recording previews shown in the UI.",
) )
sub: RecordSubConfig = Field(
default_factory=RecordSubConfig,
title="Sub stream recording",
description="Settings for recording a second, lower quality stream.",
)
enabled_in_config: bool | None = Field( enabled_in_config: bool | None = Field(
default=None, default=None,
title="Original recording state", title="Original recording state",
description="Indicates whether recording was enabled in the original static configuration.", description="Indicates whether recording was enabled in the original static configuration.",
) )
@property
def effective_alert_days(self) -> float:
"""Alert retention extended to the sub stream window when sub is enabled.
Review items and tracked objects must stay visible for as long as
either stream still has recordings.
"""
if self.sub.enabled:
return max(self.alerts.retain.days, self.sub.alerts.days)
return self.alerts.retain.days
@property
def effective_detection_days(self) -> float:
"""Detection retention extended to the sub window when sub is enabled."""
if self.sub.enabled:
return max(self.detections.retain.days, self.sub.detections.days)
return self.detections.retain.days
@property @property
def event_pre_capture(self) -> int: def event_pre_capture(self) -> int:
return max( return max(
+7 -1
View File
@@ -96,6 +96,7 @@ class CameraConfigUpdateSubscriber:
return return
elif update_type == CameraConfigUpdateEnum.remove: elif update_type == CameraConfigUpdateEnum.remove:
self.config.cameras.pop(camera, None) self.config.cameras.pop(camera, None)
self.config.drop_camera_model(camera)
self.camera_configs.pop(camera, None) self.camera_configs.pop(camera, None)
return return
@@ -129,8 +130,13 @@ class CameraConfigUpdateSubscriber:
config.objects = updated_config config.objects = updated_config
elif update_type == CameraConfigUpdateEnum.record: elif update_type == CameraConfigUpdateEnum.record:
old_enabled_in_config = config.record.enabled_in_config old_enabled_in_config = config.record.enabled_in_config
old_sub_enabled = config.record.sub.enabled
config.record = updated_config config.record = updated_config
if old_enabled_in_config != updated_config.enabled_in_config: # the record and record_sub ffmpeg outputs are gated on these
if (
old_enabled_in_config != updated_config.enabled_in_config
or old_sub_enabled != updated_config.sub.enabled
):
config.recreate_ffmpeg_cmds() config.recreate_ffmpeg_cmds()
elif update_type == CameraConfigUpdateEnum.review: elif update_type == CameraConfigUpdateEnum.review:
config.review = updated_config config.review = updated_config
+285 -68
View File
@@ -11,7 +11,6 @@ from pydantic import (
BaseModel, BaseModel,
ConfigDict, ConfigDict,
Field, Field,
TypeAdapter,
ValidationInfo, ValidationInfo,
field_validator, field_validator,
model_validator, model_validator,
@@ -19,8 +18,9 @@ from pydantic import (
from ruamel.yaml import YAML from ruamel.yaml import YAML
from frigate.const import REGEX_JSON from frigate.const import REGEX_JSON
from frigate.detectors import DetectorConfig, ModelConfig from frigate.detectors import ModelConfig
from frigate.detectors.detector_config import BaseDetectorConfig from frigate.detectors.detector_config import SceneEnum
from frigate.detectors.device import DeviceParseError, DeviceSpec, parse_device
from frigate.plus import PlusApi from frigate.plus import PlusApi
from frigate.util.builtin import ( from frigate.util.builtin import (
deep_merge, deep_merge,
@@ -63,7 +63,7 @@ from .classification import (
SemanticSearchModelEnum, SemanticSearchModelEnum,
) )
from .database import DatabaseConfig from .database import DatabaseConfig
from .env import EnvVars from .env import EnvVars, reload_sources
from .logger import LoggerConfig from .logger import LoggerConfig
from .mqtt import MqttConfig from .mqtt import MqttConfig
from .network import NetworkingConfig from .network import NetworkingConfig
@@ -79,9 +79,14 @@ logger = logging.getLogger(__name__)
yaml = YAML() yaml = YAML()
# Pydantic field default applied when an existing config omits `detectors:`. # Pydantic field default applied when an existing config omits `models:`.
# Kept as cpu tflite for backwards compatibility with 0.17 configs. # Kept as cpu tflite for backwards compatibility with 0.17 configs.
DEFAULT_DETECTORS = {"cpu": {"type": "cpu"}} DEFAULT_MODELS = [{"devices": ["cpu"]}]
def _default_models() -> list[ModelConfig]:
return [ModelConfig.model_validate(model) for model in DEFAULT_MODELS]
# Used by the openvino branch below and rendered into the new-config YAML # Used by the openvino branch below and rendered into the new-config YAML
# template so first-time setups default to openvino on CPU. # template so first-time setups default to openvino on CPU.
@@ -93,7 +98,7 @@ DEFAULT_MODEL = {
"path": "/openvino-model/ssdlite_mobilenet_v2.xml", "path": "/openvino-model/ssdlite_mobilenet_v2.xml",
"labelmap_path": "/openvino-model/coco_91cl_bkgr.txt", "labelmap_path": "/openvino-model/coco_91cl_bkgr.txt",
} }
NEW_CONFIG_DETECTORS = {"ov": {"type": "openvino", "device": "CPU"}} NEW_CONFIG_MODELS = [{"devices": ["openvino:CPU"], **DEFAULT_MODEL}]
DEFAULT_DETECT_DIMENSIONS = {"width": 1280, "height": 720} DEFAULT_DETECT_DIMENSIONS = {"width": 1280, "height": 720}
@@ -109,7 +114,7 @@ DEFAULT_CONFIG = f"""
mqtt: mqtt:
enabled: False enabled: False
{_render_default_yaml({"detectors": NEW_CONFIG_DETECTORS, "model": DEFAULT_MODEL})} {_render_default_yaml({"models": NEW_CONFIG_MODELS})}
cameras: {{}} # No cameras defined, UI wizard should be used cameras: {{}} # No cameras defined, UI wizard should be used
version: {CURRENT_CONFIG_VERSION} version: {CURRENT_CONFIG_VERSION}
""" """
@@ -255,6 +260,15 @@ def verify_config_roles(camera_config: CameraConfig) -> None:
f"Camera {camera_config.name} has record enabled, but record is not assigned to an input." f"Camera {camera_config.name} has record enabled, but record is not assigned to an input."
) )
if (
camera_config.record.enabled
and camera_config.record.sub.enabled
and "record_sub" not in assigned_roles
):
raise ValueError(
f"Camera {camera_config.name} has sub stream recording enabled, but record_sub is not assigned to an input."
)
if camera_config.audio.enabled and "audio" not in assigned_roles: if camera_config.audio.enabled and "audio" not in assigned_roles:
raise ValueError( raise ValueError(
f"Camera {camera_config.name} has audio events enabled, but audio is not assigned to an input." f"Camera {camera_config.name} has audio events enabled, but audio is not assigned to an input."
@@ -275,13 +289,11 @@ def verify_valid_live_stream_names(
) )
def verify_recording_segments_setup_with_reasonable_time( def verify_record_output_args_segment_time(
camera_config: CameraConfig, camera_config: CameraConfig, output_args: str | list[str], role: str
) -> None: ) -> None:
"""Verify that recording segments are setup and segment time is not greater than 60.""" """Verify that a recording role's output args segment at a reasonable time."""
record_args: list[str] = get_ffmpeg_arg_list( record_args: list[str] = get_ffmpeg_arg_list(output_args)
camera_config.ffmpeg.output_args.record
)
if record_args[0].startswith("preset"): if record_args[0].startswith("preset"):
return return
@@ -291,16 +303,32 @@ def verify_recording_segments_setup_with_reasonable_time(
except ValueError: except ValueError:
raise ValueError( raise ValueError(
f"Camera {camera_config.name} has no segment_time in \ f"Camera {camera_config.name} has no segment_time in \
recording output args, segment args are required for record." {role} output args, segment args are required for record."
) from None ) from None
if int(record_args[seg_arg_index + 1]) > 60: if int(record_args[seg_arg_index + 1]) > 60:
raise ValueError( raise ValueError(
f"Camera {camera_config.name} has invalid segment_time output arg, \ f"Camera {camera_config.name} has invalid segment_time in {role} output args, \
segment_time must be 60 or less." segment_time must be 60 or less."
) )
def verify_recording_segments_setup_with_reasonable_time(
camera_config: CameraConfig,
) -> None:
"""Verify that recording segments are setup and segment time is not greater than 60."""
verify_record_output_args_segment_time(
camera_config, camera_config.ffmpeg.output_args.record, "recording"
)
if camera_config.record.sub.enabled:
verify_record_output_args_segment_time(
camera_config,
camera_config.ffmpeg.output_args.effective_record_sub,
"sub stream recording",
)
def verify_zone_objects_are_tracked(camera_config: CameraConfig) -> None: def verify_zone_objects_are_tracked(camera_config: CameraConfig) -> None:
"""Verify that user has not entered zone objects that are not in the tracking config.""" """Verify that user has not entered zone objects that are not in the tracking config."""
for zone_name, zone in camera_config.zones.items(): for zone_name, zone in camera_config.zones.items():
@@ -497,16 +525,11 @@ class FrigateConfig(FrigateBaseModel):
description="User interface preferences such as timezone, time/date formatting, and units.", description="User interface preferences such as timezone, time/date formatting, and units.",
) )
# Detector config # Detection model config
detectors: dict[str, BaseDetectorConfig] = Field( models: list[ModelConfig] = Field(
default=DEFAULT_DETECTORS, default_factory=_default_models,
title="Detector hardware", title="Detection models",
description="Configuration for object detectors (CPU, GPU, ONNX backends) and any detector-specific model settings.", description="Object detection models and the hardware each one runs on. Cameras pick a model by matching their detect.scene against a model's scene.",
)
model: ModelConfig = Field(
default_factory=ModelConfig,
title="Detection model",
description="Settings to configure a custom object detection model and its input shape.",
) )
# GenAI config (named provider configs: name -> GenAIConfig) # GenAI config (named provider configs: name -> GenAIConfig)
@@ -621,11 +644,226 @@ class FrigateConfig(FrigateBaseModel):
) )
_plus_api: PlusApi _plus_api: PlusApi
_model_devices: dict[SceneEnum, list[DeviceSpec]]
_camera_models: dict[str, ModelConfig]
_all_attributes: list[str]
_all_attribute_logos: list[str]
_all_attributes_map: dict[str, list[str]]
_all_labels: set[str]
@property @property
def plus_api(self) -> PlusApi: def plus_api(self) -> PlusApi:
return self._plus_api return self._plus_api
@property
def all_attributes(self) -> list[str]:
"""Every attribute label across all configured models."""
return self._all_attributes
@property
def all_attribute_logos(self) -> list[str]:
"""Every logo attribute label across all configured models."""
return self._all_attribute_logos
@property
def all_attributes_map(self) -> dict[str, list[str]]:
"""Object label to attribute labels, merged across all configured models."""
return self._all_attributes_map
@property
def all_labels(self) -> set[str]:
"""Every object label across all configured models."""
return self._all_labels
@property
def primary_model(self) -> ModelConfig:
"""The model used when no specific camera is in play."""
for model in self.models:
if model.scene == SceneEnum.all:
return model
return self.models[0]
def model_for_camera(self, camera_name: str) -> ModelConfig:
"""Get the detection model a camera runs on.
Cameras added at runtime (wizard, clone, debug replay) are inserted
into cameras after parse, so they miss the cache built during
post_validation and are resolved here on first lookup.
Args:
camera_name: Name of the camera
Returns:
The model matching the camera's detect scene
"""
model = self._camera_models.get(camera_name)
if model is None:
camera = self.cameras.get(camera_name)
scene = camera.detect.scene if camera is not None else SceneEnum.all
model = self._resolve_camera_model(camera_name, scene)
self._camera_models[camera_name] = model
return model
def drop_camera_model(self, camera_name: str) -> None:
"""Forget the cached model for a camera removed at runtime.
A later re-add resolves fresh, so a camera recreated under the same
name with a different detect scene doesn't inherit the removed
camera's model.
Args:
camera_name: Name of the removed camera
"""
self._camera_models.pop(camera_name, None)
def devices_for_model(self, model: ModelConfig) -> list[DeviceSpec]:
"""Get the parsed hardware devices a model runs on.
Args:
model: One of the configured models
Returns:
The parsed device specs, in config order
"""
return self._model_devices[model.scene]
def _load_model(self, model: ModelConfig, detector: str) -> ModelConfig:
"""Apply detector specific defaults to a model and load its weights and labels.
Args:
model: The configured model
detector: The detector type the model runs on
Returns:
The loaded model
"""
model_config = model.model_dump(exclude_unset=True, warnings="none")
if "path" not in model_config:
if detector == "cpu" or detector.endswith("_tfl"):
model_config["path"] = "/cpu_model.tflite"
elif detector == "edgetpu":
model_config["path"] = "/edgetpu_model.tflite"
elif detector == "openvino":
for default_key, default_value in DEFAULT_MODEL.items():
model_config.setdefault(default_key, default_value)
loaded = ModelConfig.model_validate(model_config)
loaded.check_and_load_plus_model(self.plus_api, detector)
loaded.compute_model_hash()
return loaded
def _load_models(self) -> None:
"""Validate the configured models and load each one."""
if not self.models:
raise ValueError("At least one model must be configured under models")
model_devices: dict[SceneEnum, list[DeviceSpec]] = {}
# device string -> the scene of the model that already claimed it
claimed_devices: dict[str, SceneEnum] = {}
for index, model in enumerate(self.models):
scene = model.scene.value
if model.scene in model_devices:
raise ValueError(
f"Multiple models are configured with a scene of '{scene}'. Each model must use a different scene."
)
if not model.devices:
raise ValueError(
f"Model '{scene}' must list at least one entry under devices."
)
try:
devices = [parse_device(device) for device in model.devices]
except DeviceParseError as err:
raise ValueError(
f"Model '{scene}' has an invalid device: {err}"
) from err
detectors = {device.detector for device in devices}
if len(detectors) > 1:
raise ValueError(
f"Model '{scene}' mixes the {', '.join(sorted(detectors))} detectors. All of a model's devices must use the same detector."
)
for device in devices:
if device.raw in claimed_devices and not device.shareable:
other = claimed_devices[device.raw]
where = (
f"twice by model '{scene}'"
if other == model.scene
else f"by both the '{other.value}' and '{scene}' models"
)
raise ValueError(
f"Device '{device.raw}' is used {where}, but it can only run one detection process."
)
claimed_devices[device.raw] = model.scene
self.models[index] = self._load_model(model, devices[0].detector)
model_devices[model.scene] = devices
attributes: set[str] = set()
attribute_logos: set[str] = set()
attributes_map: dict[str, set[str]] = {}
labels: set[str] = set()
for model in self.models:
attributes.update(model.all_attributes)
attribute_logos.update(model.all_attribute_logos)
labels.update(model.merged_labelmap.values())
for label, label_attributes in model.attributes_map.items():
attributes_map.setdefault(label, set()).update(label_attributes)
self._model_devices = model_devices
self._all_attributes = sorted(attributes)
self._all_attribute_logos = sorted(attribute_logos)
self._all_attributes_map = {
label: sorted(label_attributes)
for label, label_attributes in sorted(attributes_map.items())
}
self._all_labels = labels
def _resolve_camera_model(self, name: str, scene: SceneEnum) -> ModelConfig:
"""Resolve which model a camera runs on.
A camera may name a scene no model is configured for, which is valid as
long as an 'all' model is there to fall back to.
Args:
name: Name of the camera
scene: The camera's detect scene, which defaults to 'all'
Returns:
The model the camera runs on
"""
by_scene = {model.scene: model for model in self.models}
model = by_scene.get(scene)
if model is not None:
return model
default = by_scene.get(SceneEnum.all)
if default is None:
raise ValueError(
f"Camera '{name}' has a detect scene of '{scene.value}', but no model is configured for that scene or for 'all'."
)
logger.warning(
"Camera '%s' has a detect scene of '%s', but no model is configured for that scene, so the 'all' model is used",
name,
scene.value,
)
return default
@model_validator(mode="after") @model_validator(mode="after")
def post_validation(self, info: ValidationInfo) -> Self: def post_validation(self, info: ValidationInfo) -> Self:
# Load plus api from context, if possible. # Load plus api from context, if possible.
@@ -670,8 +908,10 @@ class FrigateConfig(FrigateBaseModel):
"'embeddings' in its roles for semantic search." "'embeddings' in its roles for semantic search."
) )
self._load_models()
# set default min_score for object attributes # set default min_score for object attributes
for attribute in self.model.all_attributes: for attribute in self.all_attributes:
existing = self.objects.filters.get(attribute) existing = self.objects.filters.get(attribute)
if existing is None: if existing is None:
self.objects.filters[attribute] = FilterConfig(min_score=0.7) self.objects.filters[attribute] = FilterConfig(min_score=0.7)
@@ -721,44 +961,7 @@ class FrigateConfig(FrigateBaseModel):
exclude_unset=True, exclude_unset=True,
) )
for key, detector in self.detectors.items(): self._camera_models = {}
adapter = TypeAdapter(DetectorConfig)
model_dict = (
detector
if isinstance(detector, dict)
else detector.model_dump(warnings="none")
)
detector_config: BaseDetectorConfig = adapter.validate_python(model_dict)
# users should not set model themselves
if detector_config.model:
logger.warning(
"The model key should be specified at the root level of the config, not under detectors. The nested model key will be ignored."
)
detector_config.model = None
model_config = self.model.model_dump(exclude_unset=True, warnings="none")
if detector_config.model_path:
model_config["path"] = detector_config.model_path
if "path" not in model_config:
if detector_config.type == "cpu" or detector_config.type.endswith(
"_tfl"
):
model_config["path"] = "/cpu_model.tflite"
elif detector_config.type == "edgetpu":
model_config["path"] = "/edgetpu_model.tflite"
elif detector_config.type == "openvino":
for default_key, default_value in DEFAULT_MODEL.items():
model_config.setdefault(default_key, default_value)
model = ModelConfig.model_validate(model_config)
model.check_and_load_plus_model(self.plus_api, detector_config.type)
model.compute_model_hash()
labelmap_objects = model.merged_labelmap.values()
detector_config.model = model
self.detectors[key] = detector_config
for name, camera in self.cameras.items(): for name, camera in self.cameras.items():
modified_global_config = global_config.copy() modified_global_config = global_config.copy()
@@ -785,6 +988,9 @@ class FrigateConfig(FrigateBaseModel):
{"name": name, **merged_config} {"name": name, **merged_config}
) )
camera_model = self._resolve_camera_model(name, camera_config.detect.scene)
self._camera_models[name] = camera_model
if camera_config.ffmpeg.hwaccel_args == "auto": if camera_config.ffmpeg.hwaccel_args == "auto":
camera_config.ffmpeg.hwaccel_args = self.ffmpeg.hwaccel_args camera_config.ffmpeg.hwaccel_args = self.ffmpeg.hwaccel_args
@@ -1005,7 +1211,7 @@ class FrigateConfig(FrigateBaseModel):
verify_profile_overrides_match_base(camera_config) verify_profile_overrides_match_base(camera_config)
verify_autotrack_zones(camera_config) verify_autotrack_zones(camera_config)
verify_motion_and_detect(camera_config) verify_motion_and_detect(camera_config)
verify_objects_track(camera_config, labelmap_objects) verify_objects_track(camera_config, camera_model.merged_labelmap.values())
verify_lpr_and_face(self, camera_config) verify_lpr_and_face(self, camera_config)
# Validate camera profiles reference top-level profile definitions # Validate camera profiles reference top-level profile definitions
@@ -1022,8 +1228,16 @@ class FrigateConfig(FrigateBaseModel):
config.name = name config.name = name
self.objects.parse_all_objects(self.cameras) self.objects.parse_all_objects(self.cameras)
self.model.create_colormap(sorted(self.objects.all_objects))
self.model.check_and_load_plus_model(self.plus_api) # every model shares one colormap so a label is drawn the same color no
# matter which model detected it, so filter attributes across all models
# rather than letting each model filter with only its own
colored_labels = sorted(
set(self.objects.all_objects) - set(self.all_attributes)
)
for model in self.models:
model.create_colormap(colored_labels)
# Check audio transcription and audio detection requirements # Check audio transcription and audio detection requirements
if self.audio_transcription.enabled: if self.audio_transcription.enabled:
@@ -1093,6 +1307,9 @@ class FrigateConfig(FrigateBaseModel):
@classmethod @classmethod
def parse(cls, config, *, is_json=None, safe_load=False, **context): def parse(cls, config, *, is_json=None, safe_load=False, **context):
# Pick up secrets.yaml edits without a restart.
reload_sources()
# If config is a file, read its contents. # If config is a file, read its contents.
if hasattr(config, "read"): if hasattr(config, "read"):
fname = getattr(config, "name", None) fname = getattr(config, "name", None)
+192 -18
View File
@@ -1,20 +1,193 @@
"""Environment variable and secrets handling for the Frigate config."""
import logging
import os import os
import re import re
from collections.abc import Mapping
from pathlib import Path from pathlib import Path
from typing import Annotated from typing import Annotated, Any
from pydantic import AfterValidator, ValidationInfo from pydantic import AfterValidator, ValidationInfo
from ruamel.yaml import YAML, YAMLError
FRIGATE_ENV_VARS = {k: v for k, v in os.environ.items() if k.startswith("FRIGATE_")} from frigate.const import CONFIG_DIR
secrets_dir = os.environ.get("CREDENTIALS_DIRECTORY", "/run/secrets")
# read secret files as env vars too logger = logging.getLogger(__name__)
if os.path.isdir(secrets_dir) and os.access(secrets_dir, os.R_OK):
for secret_file in os.listdir(secrets_dir):
if secret_file.startswith("FRIGATE_"): class UnknownVariableError(ValueError):
FRIGATE_ENV_VARS[secret_file] = ( """Undefined {FRIGATE_*} placeholder. ValueError so pydantic names the field."""
Path(os.path.join(secrets_dir, secret_file)).read_text().strip()
# Substitution sources, lowest precedence first.
_CONFIG_ENV_VARS: dict[str, str] = {}
_SECRETS_FILE: dict[str, str] = {}
# Snapshot: apply_config_env_vars() writes os.environ after import.
_CONTAINER_ENV: dict[str, str] = {
k: v for k, v in os.environ.items() if k.startswith("FRIGATE_")
}
_CREDENTIALS_DIR: dict[str, str] = {}
_SOURCES: tuple[tuple[str, dict[str, str]], ...] = (
("environment_vars config block", _CONFIG_ENV_VARS),
("secrets.yaml", _SECRETS_FILE),
("container environment", _CONTAINER_ENV),
("credentials directory", _CREDENTIALS_DIR),
)
FRIGATE_ENV_VARS: dict[str, str] = {}
_WARNED_COLLISIONS: set[str] = set()
def _rebuild(warn: bool = True) -> None:
"""Merge the sources into FRIGATE_ENV_VARS.
warn=False is for the import-time call, before logging is configured.
"""
merged: dict[str, str] = {}
origin: dict[str, str] = {}
duplicated: set[str] = set()
for label, source in _SOURCES:
for key, value in source.items():
if key in merged and merged[key] != value:
duplicated.add(key)
merged[key] = value
origin[key] = label
if warn:
for key in sorted(duplicated - _WARNED_COLLISIONS):
_WARNED_COLLISIONS.add(key)
logger.warning(
"%s is defined in more than one place, using the value from %s",
key,
origin[key],
) )
# In place: tests hold a reference to this dict.
FRIGATE_ENV_VARS.clear()
FRIGATE_ENV_VARS.update(merged)
def _load_credentials_dir() -> dict[str, str]:
"""Read FRIGATE_* files from the Docker or systemd credentials directory."""
directory = os.environ.get("CREDENTIALS_DIRECTORY", "/run/secrets")
values: dict[str, str] = {}
if not (os.path.isdir(directory) and os.access(directory, os.R_OK)):
return values
for name in os.listdir(directory):
if not name.startswith("FRIGATE_"):
continue
try:
values[name] = Path(os.path.join(directory, name)).read_text().strip()
except (OSError, UnicodeDecodeError):
logger.warning("Unable to read %s in %s, skipping", name, directory)
return values
def _secrets_file_path() -> str | None:
"""Locate secrets.yaml next to the config file."""
config_file = os.environ.get("CONFIG_FILE")
config_dir = os.path.dirname(config_file) if config_file else CONFIG_DIR
for name in ("secrets.yaml", "secrets.yml"):
path = os.path.join(config_dir, name)
if os.path.isfile(path):
return path
return None
def _load_secrets_file() -> dict[str, str]:
"""Read the flat FRIGATE_* map from secrets.yaml, if it exists."""
path = _secrets_file_path()
if path is None:
return {}
try:
with open(path) as f:
raw: Any = YAML(typ="safe").load(f)
except OSError as err:
raise ValueError(f"Unable to read {path}: {err.strerror}") from err
except YAMLError as err:
# The parser message can quote values, so only name a position.
mark = getattr(err, "problem_mark", None)
where = f" near line {mark.line + 1}" if mark is not None else ""
raise ValueError(f"{path} is not valid YAML{where}") from err
if raw is None:
return {}
if not isinstance(raw, dict):
raise ValueError(f"{path} must be a flat map of names to values")
values: dict[str, str] = {}
for key, value in raw.items():
name = str(key)
if isinstance(value, (dict, list)):
raise ValueError(f"{path} value for {name} must be a single value")
if not name.startswith("FRIGATE_"):
logger.warning(
"Ignoring %s in %s, names must start with FRIGATE_", name, path
)
continue
values[name] = "" if value is None else str(value)
return values
def reload_sources(warn: bool = True) -> None:
"""Re-read the file backed sources and rebuild the namespace."""
_CREDENTIALS_DIR.clear()
_CREDENTIALS_DIR.update(_load_credentials_dir())
try:
secrets = _load_secrets_file()
except ValueError as err:
# Keep the last good values; this runs at import and on every parse.
logger.error("Ignoring secrets file, %s", err)
else:
_SECRETS_FILE.clear()
_SECRETS_FILE.update(secrets)
_rebuild(warn)
def apply_config_env_vars(values: Mapping[str, object]) -> None:
"""Install the environment_vars block as the lowest priority source.
Unprefixed keys only set os.environ.
"""
for key, value in values.items():
resolved = str(value)
if key.startswith("FRIGATE_"):
_CONFIG_ENV_VARS[key] = resolved
else:
os.environ[key] = resolved
_rebuild()
# Export the winning value; auth reads FRIGATE_JWT_SECRET from os.environ.
for key in values:
if key.startswith("FRIGATE_"):
os.environ[key] = FRIGATE_ENV_VARS[key]
reload_sources(warn=False)
# Matches a FRIGATE_* identifier following an opening brace. # Matches a FRIGATE_* identifier following an opening brace.
_FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+") _FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+")
@@ -29,12 +202,13 @@ def substitute_frigate_vars(value: str) -> str:
* `{{` and `}}` collapse to literal `{` / `}` (the documented escape). * `{{` and `}}` collapse to literal `{` / `}` (the documented escape).
* `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`; an unknown name * `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`; an unknown name
raises `KeyError` to preserve the existing "Invalid substitution" raises `UnknownVariableError` to preserve the existing "Invalid
error path. substitution" error path.
* A `{` that begins `{FRIGATE_` but is not a well-formed * A `{` that begins `{FRIGATE_` but is not a well-formed
`{FRIGATE_NAME}` placeholder raises `ValueError` (malformed `{FRIGATE_NAME}` placeholder raises `ValueError` (malformed
placeholder). Callers that catch `KeyError` to allow unknown-var placeholder). Callers that catch `UnknownVariableError` to allow
passthrough will still surface malformed syntax as an error. unknown-var passthrough will still surface malformed syntax as an
error.
* Any other `{` or `}` is treated as a literal and passed through. * Any other `{` or `}` is treated as a literal and passed through.
""" """
out: list[str] = [] out: list[str] = []
@@ -58,7 +232,10 @@ def substitute_frigate_vars(value: str) -> str:
): ):
key = ident_match.group(0) key = ident_match.group(0)
if key not in FRIGATE_ENV_VARS: if key not in FRIGATE_ENV_VARS:
raise KeyError(key) raise UnknownVariableError(
f"{key} is not defined in the environment, "
"secrets.yaml, or the environment_vars config"
)
out.append(FRIGATE_ENV_VARS[key]) out.append(FRIGATE_ENV_VARS[key])
i = ident_match.end() + 1 i = ident_match.end() + 1
continue continue
@@ -94,10 +271,7 @@ EnvString = Annotated[str, AfterValidator(validate_env_string)]
def validate_env_vars(v: dict[str, str], info: ValidationInfo) -> dict[str, str]: def validate_env_vars(v: dict[str, str], info: ValidationInfo) -> dict[str, str]:
if isinstance(info.context, dict) and info.context.get("install", False): if isinstance(info.context, dict) and info.context.get("install", False):
for k, val in v.items(): apply_config_env_vars(v)
os.environ[k] = val
if k.startswith("FRIGATE_"):
FRIGATE_ENV_VARS[k] = val
return v return v
+7 -2
View File
@@ -8,6 +8,7 @@ from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from frigate.config.camera.birdseye import birdseye_modes_to_mqtt_payload
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdatePublisher, CameraConfigUpdatePublisher,
@@ -42,8 +43,12 @@ SECTION_STATE_TOPICS: dict[str, list[tuple[str, Callable[[Any], Any]]]] = {
"birdseye": [ "birdseye": [
("birdseye", lambda c: "ON" if c.birdseye.enabled else "OFF"), ("birdseye", lambda c: "ON" if c.birdseye.enabled else "OFF"),
( (
"birdseye_mode", "birdseye_modes",
lambda c: c.birdseye.mode.value.upper() if c.birdseye.enabled else "OFF", lambda c: (
birdseye_modes_to_mqtt_payload(c.birdseye.modes)
if c.birdseye.enabled
else "OFF"
),
), ),
], ],
"detect": [("detect", lambda c: "ON" if c.detect.enabled else "OFF")], "detect": [("detect", lambda c: "ON" if c.detect.enabled else "OFF")],
+6
View File
@@ -23,6 +23,12 @@ SHM_FRAMES_VAR = "SHM_MAX_FRAMES"
REDACTED_CREDENTIAL_SENTINEL = "__FRIGATE_SAVED_CREDENTIAL__" REDACTED_CREDENTIAL_SENTINEL = "__FRIGATE_SAVED_CREDENTIAL__"
# Stream type constants
STREAM_TYPE_MAIN = "main"
STREAM_TYPE_SUB = "sub"
SUB_CACHE_TAG = "@sub"
# Attribute & Object constants # Attribute & Object constants
DEFAULT_ATTRIBUTE_LABEL_MAP = { DEFAULT_ATTRIBUTE_LABEL_MAP = {
@@ -72,7 +72,7 @@ class LicensePlateProcessingMixin:
# Object config # Object config
self.lp_objects: list[str] = [] self.lp_objects: list[str] = []
for obj, attributes in self.config.model.attributes_map.items(): for obj, attributes in self.config.all_attributes_map.items():
if "license_plate" in attributes: if "license_plate" in attributes:
self.lp_objects.append(obj) self.lp_objects.append(obj)
@@ -1172,6 +1172,28 @@ class LicensePlateProcessingMixin:
return rep["plate"], rep["conf"], rep["char_confidences"], rep["area"] return rep["plate"], rep["conf"], rep["char_confidences"], rep["area"]
def _passes_plate_filters(self, camera: str, plate: str) -> bool:
"""Check a plate against the configured length and format filters."""
if len(plate) < self.lpr_config.min_plate_length:
logger.debug(
f"{camera}: Filtered out plate '{plate}' due to length ({len(plate)} < {self.lpr_config.min_plate_length})"
)
return False
if self.lpr_config.format:
try:
if not re.fullmatch(self.lpr_config.format, plate):
logger.debug(
f"{camera}: Filtered out plate '{plate}' due to format mismatch"
)
return False
except re.error:
logger.error(
f"{camera}: Invalid regex in LPR format configuration: {self.lpr_config.format}"
)
return True
def _generate_plate_event(self, camera: str, plate: str, plate_score: float) -> str: def _generate_plate_event(self, camera: str, plate: str, plate_score: float) -> str:
"""Generate a unique ID for a plate event based on camera and text.""" """Generate a unique ID for a plate event based on camera and text."""
now = datetime.datetime.now().timestamp() now = datetime.datetime.now().timestamp()
@@ -1511,10 +1533,14 @@ class LicensePlateProcessingMixin:
plate_id = None plate_id = None
for existing_id, data in self.detected_license_plates.items(): for existing_id, data in self.detected_license_plates.items():
# entries from the object pipeline on this camera have no
# last_seen until they pass the filters below
last_seen = data.get("last_seen")
if ( if (
data["camera"] == camera data["camera"] == camera
and data["last_seen"] is not None and last_seen is not None
and current_time - data["last_seen"] and current_time - last_seen
<= self.config.cameras[camera].lpr.expire_time <= self.config.cameras[camera].lpr.expire_time
): ):
similarity = JaroWinkler.similarity(data["plate"], top_plate) similarity = JaroWinkler.similarity(data["plate"], top_plate)
@@ -1525,6 +1551,11 @@ class LicensePlateProcessingMixin:
) )
break break
if plate_id is None: if plate_id is None:
# the event id doubles as the cluster key, so a plate rejected
# after this point would leave an entry that never expires
if not self._passes_plate_filters(camera, top_plate):
return
plate_id = self._generate_plate_event(camera, top_plate, avg_confidence) plate_id = self._generate_plate_event(camera, top_plate, avg_confidence)
logger.debug( logger.debug(
f"{camera}: New plate event for dedicated LPR camera {plate_id}: {top_plate}" f"{camera}: New plate event for dedicated LPR camera {plate_id}: {top_plate}"
@@ -1569,27 +1600,12 @@ class LicensePlateProcessingMixin:
f"{camera}: Clustering changed top plate '{top_plate}' (conf: {avg_confidence:.3f}) to rep '{rep_plate}' (conf: {rep_conf:.3f})" f"{camera}: Clustering changed top plate '{top_plate}' (conf: {avg_confidence:.3f}) to rep '{rep_plate}' (conf: {rep_conf:.3f})"
) )
# Apply length and format filters to the clustered representative # filter the clustered representative rather than individual OCR
# rather than individual OCR readings, so noisy variants still # readings, so noisy variants still contribute to clustering even
# contribute to clustering even when they don't pass on their own. # when they don't pass on their own
if len(rep_plate) < self.lpr_config.min_plate_length: if not self._passes_plate_filters(camera, rep_plate):
logger.debug(
f"{camera}: Filtered out clustered plate '{rep_plate}' due to length ({len(rep_plate)} < {self.lpr_config.min_plate_length})"
)
return return
if self.lpr_config.format:
try:
if not re.fullmatch(self.lpr_config.format, rep_plate):
logger.debug(
f"{camera}: Filtered out clustered plate '{rep_plate}' due to format mismatch"
)
return
except re.error:
logger.error(
f"{camera}: Invalid regex in LPR format configuration: {self.lpr_config.format}"
)
# Update stored rep # Update stored rep
self.detected_license_plates[id].update( self.detected_license_plates[id].update(
{ {
@@ -83,6 +83,10 @@ class AudioTranscriptionPostProcessor(PostProcessorApi):
""" """
event_id = data["event_id"] event_id = data["event_id"]
camera_name = data["camera"] camera_name = data["camera"]
camera_config = self.config.cameras.get(camera_name)
if camera_config is None:
return
if data_type == PostProcessDataEnum.recording: if data_type == PostProcessDataEnum.recording:
start_ts = data["frame_time"] start_ts = data["frame_time"]
@@ -104,7 +108,7 @@ class AudioTranscriptionPostProcessor(PostProcessorApi):
try: try:
audio_data = get_audio_from_recording( audio_data = get_audio_from_recording(
self.config.cameras[camera_name].ffmpeg, camera_config.ffmpeg,
camera_name, camera_name,
start_ts, start_ts,
end_ts, end_ts,
@@ -63,8 +63,10 @@ class ObjectDescriptionProcessor(PostProcessorApi):
"""Handle an update to a frame for an object.""" """Handle an update to a frame for an object."""
camera_config = self.config.cameras[camera] camera_config = self.config.cameras[camera]
# no need to save our own thumbnails if genai is not enabled if not camera_config.objects.genai.enabled:
# or if the object has become stationary return
# no need to save our own thumbnails if the object has become stationary
if not data["stationary"]: if not data["stationary"]:
if data["id"] not in self.tracked_events: if data["id"] not in self.tracked_events:
self.tracked_events[data["id"]] = [] self.tracked_events[data["id"]] = []
@@ -149,7 +151,12 @@ class ObjectDescriptionProcessor(PostProcessorApi):
logger.error(f"Event {event_id} not found for description regeneration") logger.error(f"Event {event_id} not found for description regeneration")
return return
camera_config = self.config.cameras[str(event.camera)] camera_config = self.config.cameras.get(str(event.camera))
if camera_config is None:
logger.error("Camera %s no longer exists", event.camera)
return
if not camera_config.objects.genai.enabled and not force: if not camera_config.objects.genai.enabled and not force:
logger.error(f"GenAI not enabled for camera {event.camera}") logger.error(f"GenAI not enabled for camera {event.camera}")
return return
@@ -137,7 +137,10 @@ class ReviewDescriptionProcessor(PostProcessorApi):
return return
camera = data["after"]["camera"] camera = data["after"]["camera"]
camera_config = self.config.cameras[camera] camera_config = self.config.cameras.get(camera)
if camera_config is None:
return
if not camera_config.review.genai.enabled: if not camera_config.review.genai.enabled:
return return
@@ -231,8 +234,8 @@ class ReviewDescriptionProcessor(PostProcessorApi):
final_data, final_data,
thumbs, thumbs,
camera_config.review.genai, camera_config.review.genai,
list(self.config.model.merged_labelmap.values()), sorted(self.config.all_labels),
self.config.model.all_attributes, self.config.all_attributes,
), ),
).start() ).start()
+11 -2
View File
@@ -28,6 +28,7 @@ from frigate.data_processing.common.face.model import (
from frigate.types import TrackedObjectUpdateTypesEnum from frigate.types import TrackedObjectUpdateTypesEnum
from frigate.util.builtin import EventsPerSecond, InferenceSpeed from frigate.util.builtin import EventsPerSecond, InferenceSpeed
from frigate.util.image import area from frigate.util.image import area
from frigate.util.path import safe_join, sanitize_path_component
from ..types import DataProcessorMetrics from ..types import DataProcessorMetrics
from .api import RealTimeProcessorApi from .api import RealTimeProcessorApi
@@ -409,9 +410,17 @@ class FaceRealTimeProcessor(RealTimeProcessorApi):
) )
# write face to library # write face to library
folder = os.path.join(FACE_DIR, label) sanitized_label = sanitize_path_component(label)
folder = safe_join(FACE_DIR, label)
if sanitized_label is None or folder is None:
return {
"message": f"Invalid face name: {label}",
"success": False,
}
file = os.path.join( file = os.path.join(
folder, f"{label}_{datetime.datetime.now().timestamp()}.webp" folder, f"{sanitized_label}_{datetime.datetime.now().timestamp()}.webp"
) )
os.makedirs(folder, exist_ok=True) os.makedirs(folder, exist_ok=True)
+34 -5
View File
@@ -3,7 +3,7 @@ import json
import logging import logging
import os import os
from enum import Enum from enum import Enum
from typing import Any from typing import Any, ClassVar
import requests import requests
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
@@ -15,6 +15,9 @@ from frigate.util.builtin import generate_color_palette, load_labels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# attributes that are recognized rather than shown as a logo
NON_LOGO_ATTRIBUTES = ["face", "license_plate"]
class PixelFormatEnum(str, Enum): class PixelFormatEnum(str, Enum):
rgb = "rgb" rgb = "rgb"
@@ -44,7 +47,27 @@ class ModelTypeEnum(str, Enum):
yologeneric = "yolo-generic" yologeneric = "yolo-generic"
class SceneEnum(str, Enum):
"""The camera environment a detection model is intended for."""
all = "all"
indoor = "indoor"
outdoor = "outdoor"
indoor_thermal = "indoor_thermal"
outdoor_thermal = "outdoor_thermal"
class ModelConfig(BaseModel): class ModelConfig(BaseModel):
scene: SceneEnum = Field(
default=SceneEnum.all,
title="Model scene",
description="The camera environment this model is used for. Cameras select a model by setting detect.scene to a matching value, and 'all' is used by any camera that does not set one.",
)
devices: list[str] = Field(
default_factory=list,
title="Detection hardware",
description="Hardware this model runs on, as '<detector>' or '<detector>:<device>' (for example 'edgetpu:pci:0' or 'openvino:GPU'). Listing the same device more than once runs additional inference processes on it.",
)
path: str | None = Field( path: str | None = Field(
None, None,
title="Custom object detector model path", title="Custom object detector model path",
@@ -111,7 +134,7 @@ class ModelConfig(BaseModel):
@property @property
def non_logo_attributes(self) -> list[str]: def non_logo_attributes(self) -> list[str]:
return ["face", "license_plate"] return NON_LOGO_ATTRIBUTES
@property @property
def all_attributes(self) -> list[str]: def all_attributes(self) -> list[str]:
@@ -201,9 +224,7 @@ class ModelConfig(BaseModel):
unique_attributes.update(attributes) unique_attributes.update(attributes)
self._all_attributes = list(unique_attributes) self._all_attributes = list(unique_attributes)
self._all_attribute_logos = list( self._all_attribute_logos = list(unique_attributes - set(NON_LOGO_ATTRIBUTES))
unique_attributes - set(["face", "license_plate"])
)
self._merged_labelmap = { self._merged_labelmap = {
**{int(key): val for key, val in model_info["labelMap"].items()}, **{int(key): val for key, val in model_info["labelMap"].items()},
@@ -234,6 +255,14 @@ class ModelConfig(BaseModel):
class BaseDetectorConfig(BaseModel): class BaseDetectorConfig(BaseModel):
# how the trailing part of a device string ("openvino:GPU" -> "GPU") maps onto
# this detector's fields, and whether the same device may be listed more than
# once to run additional inference processes against it. Most accelerators
# multiplex fine, so this is opt-out rather than opt-in.
device_spec_field: ClassVar[str] = "device"
device_spec_type: ClassVar[type] = str
shareable: ClassVar[bool] = True
# the type field must be defined in all subclasses # the type field must be defined in all subclasses
type: str = Field( type: str = Field(
default="cpu", default="cpu",
+19 -1
View File
@@ -2,7 +2,7 @@ import importlib
import logging import logging
import pkgutil import pkgutil
from enum import Enum from enum import Enum
from typing import Annotated, Union from typing import Annotated, Union, get_args
from pydantic import Field from pydantic import Field
@@ -39,3 +39,21 @@ DetectorConfig = Annotated[
Union[tuple(BaseDetectorConfig.__subclasses__())], # noqa: UP007 Union[tuple(BaseDetectorConfig.__subclasses__())], # noqa: UP007
Field(discriminator="type"), Field(discriminator="type"),
] ]
def _discriminator_value(config_class: type[BaseDetectorConfig]) -> str | None:
"""Read the Literal value of a detector config class' type field."""
field = config_class.model_fields.get("type")
if field is None:
return None
values = get_args(field.annotation)
return values[0] if values else None
config_types: dict[str, type[BaseDetectorConfig]] = {
key: config_class
for config_class in BaseDetectorConfig.__subclasses__()
if (key := _discriminator_value(config_class)) is not None
}
+113
View File
@@ -0,0 +1,113 @@
"""Parsing of detection hardware device strings."""
import logging
from dataclasses import dataclass
from pydantic import TypeAdapter, ValidationError
from frigate.detectors.detector_config import BaseDetectorConfig, ModelConfig
from frigate.detectors.detector_types import DetectorConfig, config_types
logger = logging.getLogger(__name__)
_detector_adapter: TypeAdapter[BaseDetectorConfig] = TypeAdapter(DetectorConfig)
@dataclass(frozen=True)
class DeviceSpec:
"""A parsed `<detector>` or `<detector>:<device>` string."""
raw: str
detector: str
device: str | None
@property
def shareable(self) -> bool:
"""Whether this device may be listed more than once."""
return config_types[self.detector].shareable
class DeviceParseError(ValueError):
pass
def parse_device(raw: str) -> DeviceSpec:
"""Parse a device string into its detector type and detector specific device.
Args:
raw: The configured device string, for example 'edgetpu:pci:0'
Returns:
The parsed spec
Raises:
DeviceParseError: If the detector type is unknown or the device is not
valid for that detector
"""
detector, separator, device = raw.partition(":")
if detector not in config_types:
raise DeviceParseError(
f"'{raw}' does not name a known detector. Available detectors are {', '.join(sorted(config_types))}"
)
spec = DeviceSpec(raw=raw, detector=detector, device=device if separator else None)
# surface a bad device now rather than when the detection process starts
build_detector_config(spec, None)
return spec
def build_detector_config(
spec: DeviceSpec, model: ModelConfig | None
) -> BaseDetectorConfig:
"""Build the detector config a device string describes.
Args:
spec: The parsed device spec
model: The model this detector runs, if it has been resolved yet
Returns:
The validated detector config
Raises:
DeviceParseError: If the device is not valid for this detector type
"""
config: dict[str, object] = {"type": spec.detector, "model": model}
if spec.device is not None:
config_class = config_types[spec.detector]
try:
config[config_class.device_spec_field] = config_class.device_spec_type(
spec.device
)
except ValueError as err:
raise DeviceParseError(
f"'{spec.raw}' is not a valid {spec.detector} device: {err}"
) from err
try:
return _detector_adapter.validate_python(config)
except ValidationError as err:
raise DeviceParseError(f"'{spec.raw}' is not a valid device: {err}") from err
def runner_names(devices: list[DeviceSpec]) -> list[str]:
"""Build a unique name for each device, since a shareable device may repeat.
Args:
devices: Every device spec across every configured model, in config order
Returns:
A name per device, suffixed with '#2', '#3', etc. on repeats
"""
names: list[str] = []
seen: dict[str, int] = {}
for spec in devices:
count = seen.get(spec.raw, 0) + 1
seen[spec.raw] = count
names.append(spec.raw if count == 1 else f"{spec.raw}#{count}")
return names
+368
View File
@@ -0,0 +1,368 @@
"""Discovery of object detection hardware attached to the system.
Every probe here is a filesystem read. Nothing shells out, initializes a
runtime, or opens a device, so this is cheap enough to run from the API process
while detector children hold the hardware.
Hardware is reported whether or not this image ships a detector that can drive
it. Matching hardware to an image is a separate concern.
"""
import logging
import os
from glob import glob
from pydantic import BaseModel, Field
from frigate.const import SUPPORTED_RK_SOCS
from frigate.detectors.detector_types import config_types
from frigate.util.services import enumerate_drm_devices
logger = logging.getLogger(__name__)
# roots the probes read from, so tests can point them at a fixture tree
SYS_ROOT = "/sys"
DEV_ROOT = "/dev"
PROC_ROOT = "/proc"
ETC_ROOT = "/etc"
# a Coral reports as Global Unichip until its firmware is loaded, then as Google
CORAL_USB_IDS = {("1a6e", "089a"), ("18d1", "9302")}
INTEL_DRM_DRIVERS = ("i915", "xe")
AMD_DRM_DRIVERS = ("amdgpu",)
class HardwareUnit(BaseModel):
"""One physical piece of hardware."""
device: str = Field(
title="Device string",
description="The value to put in a model's devices list, for example 'edgetpu:pci:1'.",
)
label: str = Field(
title="Unit label",
description="How to identify this unit among others of the same kind, for example 'PCIe 1'.",
)
class DetectionHardware(BaseModel):
"""A kind of detection hardware, and every unit of it that was found."""
key: str = Field(
title="Hardware key",
description="Stable identifier for this kind of hardware.",
)
detector: str = Field(
title="Detector type",
description="The detector that drives this hardware.",
)
name: str = Field(
title="Hardware name",
description="Human readable name for this kind of hardware.",
)
units: list[HardwareUnit] = Field(
title="Units",
description="Each physical piece of this hardware that was found.",
)
count: int = Field(
title="Unit count",
description="How many units were found.",
)
unlimited: bool = Field(
title="Unlimited detectors",
description="Whether this hardware can run more inference processes than there are units.",
)
def _read(path: str) -> str | None:
"""Read a small file, returning None if it cannot be read."""
try:
with open(path) as f:
return f.read().strip()
except OSError:
return None
def _is_shareable(detector: str) -> bool:
"""Whether a detector lets the same device run more than one process."""
config_class = config_types.get(detector)
# a detector missing from this image is assumed to behave like most of them
return config_class.shareable if config_class else True
def _hardware(
key: str, detector: str, name: str, units: list[HardwareUnit]
) -> DetectionHardware:
return DetectionHardware(
key=key,
detector=detector,
name=name,
units=units,
count=len(units),
unlimited=_is_shareable(detector),
)
def detect_coral_pci() -> DetectionHardware | None:
"""Find PCIe and M.2 Coral accelerators, which register as apex devices."""
names = sorted(
os.path.basename(path) for path in glob(f"{SYS_ROOT}/class/apex/apex_*")
)
if not names:
return None
units = [
HardwareUnit(device=f"edgetpu:pci:{index}", label=f"PCIe {index}")
for index in range(len(names))
]
return _hardware("edgetpu:pci", "edgetpu", "Coral EdgeTPU (PCIe)", units)
def detect_coral_usb() -> DetectionHardware | None:
"""Find USB Coral accelerators by their USB vendor and product ids."""
found = 0
for device_dir in sorted(glob(f"{SYS_ROOT}/bus/usb/devices/*")):
vendor = _read(os.path.join(device_dir, "idVendor"))
product = _read(os.path.join(device_dir, "idProduct"))
if vendor and product and (vendor.lower(), product.lower()) in CORAL_USB_IDS:
found += 1
if not found:
return None
units = [
HardwareUnit(device=f"edgetpu:usb:{index}", label=f"USB {index}")
for index in range(found)
]
return _hardware("edgetpu:usb", "edgetpu", "Coral EdgeTPU (USB)", units)
def _drm_devices(drivers: tuple[str, ...]) -> list[str]:
"""PCI addresses of DRM devices bound to one of the given drivers."""
return sorted(
pdev for pdev, driver in enumerate_drm_devices().items() if driver in drivers
)
def detect_intel_gpu() -> DetectionHardware | None:
"""Find Intel GPUs through their DRM driver."""
pdevs = _drm_devices(INTEL_DRM_DRIVERS)
if not pdevs:
return None
# OpenVINO reports a lone GPU as "GPU" and enumerates them as GPU.0, GPU.1
# only when there is more than one
if len(pdevs) == 1:
units = [HardwareUnit(device="openvino:GPU", label=pdevs[0])]
else:
units = [
HardwareUnit(device=f"openvino:GPU.{index}", label=pdev)
for index, pdev in enumerate(pdevs)
]
return _hardware("openvino:GPU", "openvino", "Intel GPU", units)
def detect_intel_npu() -> DetectionHardware | None:
"""Find Intel NPUs, which register as accel devices bound to intel_vpu."""
units = []
for accel_path in sorted(glob(f"{SYS_ROOT}/class/accel/accel*")):
try:
driver = os.path.basename(os.readlink(f"{accel_path}/device/driver"))
except OSError:
continue
if driver != "intel_vpu":
continue
units.append(
HardwareUnit(device="openvino:NPU", label=os.path.basename(accel_path))
)
if not units:
return None
# OpenVINO has no way to address a specific NPU, so only the first is usable
return _hardware("openvino:NPU", "openvino", "Intel NPU", units[:1])
def detect_amd_gpu() -> DetectionHardware | None:
"""Find AMD GPUs through their DRM driver."""
pdevs = _drm_devices(AMD_DRM_DRIVERS)
if not pdevs:
return None
# ROCm runs through onnx, whose MIGraphX provider takes no device index, so
# only one is addressable
units = [HardwareUnit(device="onnx", label=pdevs[0])]
return _hardware("onnx:amd", "onnx", "AMD GPU", units)
def detect_nvidia_gpu() -> DetectionHardware | None:
"""Find discrete Nvidia GPUs through the nvidia driver's proc entries."""
units = []
for index, gpu_dir in enumerate(sorted(glob(f"{PROC_ROOT}/driver/nvidia/gpus/*"))):
information = _read(os.path.join(gpu_dir, "information")) or ""
name = f"GPU {index}"
for line in information.splitlines():
if line.startswith("Model:"):
name = line.split(":", 1)[1].strip()
break
units.append(HardwareUnit(device=f"onnx:{index}", label=name))
if not units:
return None
# the model name is more useful as the hardware name when there is only one
name = units[0].label if len(units) == 1 else "NVIDIA GPU"
return _hardware("onnx:nvidia", "onnx", name, units)
def detect_jetson() -> DetectionHardware | None:
"""Find an Nvidia Jetson, whose integrated GPU runs through tensorrt."""
is_jetson = os.path.isfile(f"{ETC_ROOT}/nv_tegra_release") or os.path.exists(
f"{SYS_ROOT}/devices/gpu.0/load"
)
if not is_jetson:
return None
units = [HardwareUnit(device="tensorrt:0", label="Integrated GPU")]
return _hardware("tensorrt", "tensorrt", "NVIDIA Jetson", units)
def _dev_units(pattern: str, device: str, label: str) -> list[HardwareUnit]:
"""Build units from device nodes matching a glob."""
return [
HardwareUnit(device=device.format(index=index), label=f"{label} {index}")
for index in range(len(glob(f"{DEV_ROOT}/{pattern}")))
]
def detect_hailo() -> DetectionHardware | None:
"""Find Hailo accelerators by their device nodes."""
nodes = sorted(glob(f"{DEV_ROOT}/hailo*"))
if not nodes:
return None
# the hailo runtime schedules across every attached device itself, so there
# is nothing to address individually
units = [HardwareUnit(device="hailo8l:PCIe", label=os.path.basename(nodes[0]))]
return _hardware("hailo8l", "hailo8l", "Hailo", units)
def detect_memryx() -> DetectionHardware | None:
"""Find MemryX accelerators by their device nodes."""
units = _dev_units("memx*", "memryx:PCIe:{index}", "PCIe")
if not units:
return None
return _hardware("memryx", "memryx", "MemryX MX3", units)
def detect_rockchip() -> DetectionHardware | None:
"""Find a Rockchip NPU by reading the SoC from the device tree."""
compatible = _read(f"{PROC_ROOT}/device-tree/compatible")
if not compatible:
return None
soc = compatible.split(",")[-1].strip("\x00")
if soc not in SUPPORTED_RK_SOCS:
return None
units = [HardwareUnit(device="rknn", label=soc.upper())]
return _hardware("rknn", "rknn", f"Rockchip NPU ({soc.upper()})", units)
def detect_axengine() -> DetectionHardware | None:
"""Find an AXERA accelerator by its control device node."""
if not os.path.exists(f"{DEV_ROOT}/axcl_host"):
return None
units = [HardwareUnit(device="axengine", label="AXERA")]
return _hardware("axengine", "axengine", "AXERA NPU", units)
def detect_synaptics() -> DetectionHardware | None:
"""Find a Synaptics NPU by its device node."""
if not os.path.exists(f"{DEV_ROOT}/synap"):
return None
units = [HardwareUnit(device="synaptics", label="Synaptics")]
return _hardware("synaptics", "synaptics", "Synaptics NPU", units)
def detect_cpu() -> DetectionHardware:
"""The CPU, which is always available."""
units = [HardwareUnit(device="cpu", label="CPU")]
return _hardware("cpu", "cpu", "CPU", units)
# ordered so accelerators are offered ahead of the CPU fallback
PROBES = (
detect_coral_pci,
detect_coral_usb,
detect_hailo,
detect_memryx,
detect_intel_npu,
detect_intel_gpu,
detect_nvidia_gpu,
detect_jetson,
detect_amd_gpu,
detect_rockchip,
detect_axengine,
detect_synaptics,
detect_cpu,
)
class HardwareProber:
"""Probes for detection hardware, caching the result for the process."""
_hardware: list[DetectionHardware] | None = None
def probe(self, refresh: bool = False) -> list[DetectionHardware]:
"""Get the detection hardware attached to this system.
Args:
refresh: Probe again instead of using the cached result
Returns:
Every kind of detection hardware that was found
"""
if self._hardware is not None and not refresh:
return self._hardware
found = []
for probe in PROBES:
try:
hardware = probe()
except Exception:
logger.warning("Failed to probe for %s", probe.__name__, exc_info=True)
continue
if hardware is not None:
found.append(hardware)
logger.debug("Detected hardware: %s", [h.key for h in found])
self._hardware = found
return found
hardware_prober = HardwareProber()
+4 -1
View File
@@ -1,5 +1,5 @@
import logging import logging
from typing import Literal from typing import ClassVar, Literal
from pydantic import ConfigDict, Field from pydantic import ConfigDict, Field
@@ -27,6 +27,9 @@ class CpuDetectorConfig(BaseDetectorConfig):
title="CPU", title="CPU",
) )
device_spec_field: ClassVar[str] = "num_threads"
device_spec_type: ClassVar[type] = int
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
num_threads: int = Field( num_threads: int = Field(
default=3, default=3,
+4 -1
View File
@@ -1,7 +1,7 @@
import logging import logging
import math import math
import os import os
from typing import Literal from typing import ClassVar, Literal
import cv2 import cv2
import numpy as np import numpy as np
@@ -28,6 +28,9 @@ class EdgeTpuDetectorConfig(BaseDetectorConfig):
title="EdgeTPU", title="EdgeTPU",
) )
# a TPU can only be opened by one process
shareable: ClassVar[bool] = False
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: str = Field( device: str = Field(
default=None, default=None,
+4 -1
View File
@@ -5,7 +5,7 @@ import shutil
import urllib.request import urllib.request
import zipfile import zipfile
from queue import Queue from queue import Queue
from typing import Literal from typing import ClassVar, Literal
import cv2 import cv2
import numpy as np import numpy as np
@@ -37,6 +37,9 @@ class MemryXDetectorConfig(BaseDetectorConfig):
title="MemryX", title="MemryX",
) )
# an accelerator can only be opened by one process
shareable: ClassVar[bool] = False
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: str = Field( device: str = Field(
default="PCIe", default="PCIe",
+1 -1
View File
@@ -28,7 +28,7 @@ class OvDetectorConfig(BaseDetectorConfig):
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: str = Field( device: str = Field(
default=None, default="AUTO",
title="Device Type", title="Device Type",
description="The device to use for OpenVINO inference (e.g. 'CPU', 'GPU', 'NPU').", description="The device to use for OpenVINO inference (e.g. 'CPU', 'GPU', 'NPU').",
) )
+4 -1
View File
@@ -2,7 +2,7 @@ import logging
import os.path import os.path
import re import re
import urllib.request import urllib.request
from typing import Literal from typing import ClassVar, Literal
import cv2 import cv2
import numpy as np import numpy as np
@@ -35,6 +35,9 @@ class RknnDetectorConfig(BaseDetectorConfig):
title="RKNN", title="RKNN",
) )
device_spec_field: ClassVar[str] = "num_cores"
device_spec_type: ClassVar[type] = int
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
num_cores: int = Field( num_cores: int = Field(
default=0, default=0,
+3 -1
View File
@@ -14,7 +14,7 @@ try:
except ModuleNotFoundError: except ModuleNotFoundError:
TRT_SUPPORT = False TRT_SUPPORT = False
from typing import Literal from typing import ClassVar, Literal
from pydantic import ConfigDict, Field from pydantic import ConfigDict, Field
@@ -53,6 +53,8 @@ class TensorRTDetectorConfig(BaseDetectorConfig):
title="TensorRT", title="TensorRT",
) )
device_spec_type: ClassVar[type] = int
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: int = Field( device: int = Field(
default=0, title="GPU Device Index", description="The GPU device index to use." default=0, title="GPU Device Index", description="The GPU device index to use."
+11 -5
View File
@@ -21,6 +21,7 @@ from frigate.db.sqlitevecq import SqliteVecQueueDatabase
from frigate.models import Event from frigate.models import Event
from frigate.util.builtin import serialize from frigate.util.builtin import serialize
from frigate.util.classification import kickoff_model_training from frigate.util.classification import kickoff_model_training
from frigate.util.path import safe_join
from frigate.util.process import FrigateProcess from frigate.util.process import FrigateProcess
from .maintainer import EmbeddingMaintainer from .maintainer import EmbeddingMaintainer
@@ -33,7 +34,7 @@ class EmbeddingProcess(FrigateProcess):
def __init__( def __init__(
self, self,
config: FrigateConfig, config: FrigateConfig,
metrics: DataProcessorMetrics | None, metrics: DataProcessorMetrics,
stop_event: MpEvent, stop_event: MpEvent,
) -> None: ) -> None:
super().__init__( super().__init__(
@@ -234,11 +235,16 @@ class EmbeddingsContext:
) )
def delete_face_ids(self, face: str, ids: list[str]) -> None: def delete_face_ids(self, face: str, ids: list[str]) -> None:
folder = os.path.join(FACE_DIR, face) folder = safe_join(FACE_DIR, face)
for id in ids:
file_path = os.path.join(folder, id)
if os.path.isfile(file_path): if folder is None:
logger.warning("Not deleting faces for invalid name %s", face)
return
for id in ids:
file_path = safe_join(folder, id)
if file_path and os.path.isfile(file_path):
os.unlink(file_path) os.unlink(file_path)
if face != "train" and len(os.listdir(folder)) == 0: if face != "train" and len(os.listdir(folder)) == 0:
+82 -21
View File
@@ -78,6 +78,16 @@ logger = logging.getLogger(__name__)
MAX_THUMBNAILS = 10 MAX_THUMBNAILS = 10
GENAI_UPDATE_TOPICS = frozenset(
{
CameraConfigUpdateEnum.add.name,
CameraConfigUpdateEnum.objects.name,
CameraConfigUpdateEnum.object_genai.name,
CameraConfigUpdateEnum.review.name,
CameraConfigUpdateEnum.review_genai.name,
}
)
class EmbeddingMaintainer(threading.Thread): class EmbeddingMaintainer(threading.Thread):
"""Handle embedding queue and post event updates.""" """Handle embedding queue and post event updates."""
@@ -85,7 +95,7 @@ class EmbeddingMaintainer(threading.Thread):
def __init__( def __init__(
self, self,
config: FrigateConfig, config: FrigateConfig,
metrics: DataProcessorMetrics | None, metrics: DataProcessorMetrics,
stop_event: MpEvent, stop_event: MpEvent,
) -> None: ) -> None:
super().__init__(name="embeddings_maintainer") super().__init__(name="embeddings_maintainer")
@@ -220,16 +230,6 @@ class EmbeddingMaintainer(threading.Thread):
# post processors # post processors
self.post_processors: list[PostProcessorApi] = [] self.post_processors: list[PostProcessorApi] = []
if any(c.review.genai.enabled_in_config for c in self.config.cameras.values()):
self.post_processors.append(
ReviewDescriptionProcessor(
self.config,
self.requestor,
self.metrics,
self.genai_manager,
)
)
if self.config.lpr.enabled: if self.config.lpr.enabled:
self.post_processors.append( self.post_processors.append(
LicensePlatePostProcessor( LicensePlatePostProcessor(
@@ -252,9 +252,9 @@ class EmbeddingMaintainer(threading.Thread):
) )
) )
semantic_trigger_processor: SemanticTriggerProcessor | None = None self.semantic_trigger_processor: SemanticTriggerProcessor | None = None
if self.config.semantic_search.enabled: if self.config.semantic_search.enabled:
semantic_trigger_processor = SemanticTriggerProcessor( self.semantic_trigger_processor = SemanticTriggerProcessor(
db, db,
self.config, self.config,
self.requestor, self.requestor,
@@ -262,9 +262,49 @@ class EmbeddingMaintainer(threading.Thread):
metrics, metrics,
self.embeddings, self.embeddings,
) )
self.post_processors.append(semantic_trigger_processor) self.post_processors.append(self.semantic_trigger_processor)
if any(c.objects.genai.enabled_in_config for c in self.config.cameras.values()): self._sync_genai_processors()
self.stop_event = stop_event
# recordings data
self.recordings_available_through: dict[str, float] = {}
def _sync_genai_processors(self) -> None:
"""Create GenAI post processors for cameras that have GenAI enabled.
Called at startup and again after camera config updates so enabling
GenAI on the first camera does not require a restart. Processors are
never removed once created.
A profile can turn GenAI on without setting enabled_in_config, so both
flags are checked.
"""
cameras = self.config.cameras.values()
if any(
c.review.genai.enabled or c.review.genai.enabled_in_config for c in cameras
) and not any(
isinstance(p, ReviewDescriptionProcessor) for p in self.post_processors
):
logger.debug("Initializing review description processor")
self.post_processors.append(
ReviewDescriptionProcessor(
self.config,
self.requestor,
self.metrics,
self.genai_manager,
)
)
if any(
c.objects.genai.enabled or c.objects.genai.enabled_in_config
for c in cameras
) and not any(
isinstance(p, ObjectDescriptionProcessor) for p in self.post_processors
):
logger.debug("Initializing object description processor")
self.post_processors.append( self.post_processors.append(
ObjectDescriptionProcessor( ObjectDescriptionProcessor(
self.config, self.config,
@@ -272,19 +312,21 @@ class EmbeddingMaintainer(threading.Thread):
self.requestor, self.requestor,
self.metrics, self.metrics,
self.genai_manager, self.genai_manager,
semantic_trigger_processor, self.semantic_trigger_processor,
) )
) )
self.stop_event = stop_event def _check_camera_config_updates(self) -> None:
"""Apply camera config updates and register newly enabled processors."""
updated_topics = self.config_updater.check_for_updates()
# recordings data if updated_topics.keys() & GENAI_UPDATE_TOPICS:
self.recordings_available_through: dict[str, float] = {} self._sync_genai_processors()
def run(self) -> None: def run(self) -> None:
"""Maintain a SQLite-vec database for semantic search.""" """Maintain a SQLite-vec database for semantic search."""
while not self.stop_event.is_set(): while not self.stop_event.is_set():
self.config_updater.check_for_updates() self._check_camera_config_updates()
self._check_enrichment_config_updates() self._check_enrichment_config_updates()
self._process_requests() self._process_requests()
self._process_updates() self._process_updates()
@@ -567,6 +609,18 @@ class EmbeddingMaintainer(threading.Thread):
# Embed the thumbnail # Embed the thumbnail
self._embed_thumbnail(event_id, thumbnail) self._embed_thumbnail(event_id, thumbnail)
# every post processor below reads config.cameras[camera], but
# tracked_events still has to be released or the thumbnails held
# for this event leak, same as the two exits above
if camera not in self.config.cameras:
logger.debug("Skipping post processing for removed camera %s", camera)
for processor in self.post_processors:
if isinstance(processor, ObjectDescriptionProcessor):
processor.cleanup_event(event_id)
continue
# call any defined post processors # call any defined post processors
for processor in self.post_processors: for processor in self.post_processors:
if isinstance(processor, LicensePlatePostProcessor): if isinstance(processor, LicensePlatePostProcessor):
@@ -624,11 +678,18 @@ class EmbeddingMaintainer(threading.Thread):
to_remove = [] to_remove = []
for id, data in self.detected_license_plates.items(): for id, data in self.detected_license_plates.items():
camera_config = self.config.cameras.get(data["camera"])
if camera_config is None:
# camera was removed, drop the entry rather than expiring it
to_remove.append(id)
continue
last_seen = data.get("last_seen", 0) last_seen = data.get("last_seen", 0)
if not last_seen: if not last_seen:
continue continue
if now - last_seen > self.config.cameras[data["camera"]].lpr.expire_time: if now - last_seen > camera_config.lpr.expire_time:
to_remove.append(id) to_remove.append(id)
for id in to_remove: for id in to_remove:
self.event_metadata_publisher.publish( self.event_metadata_publisher.publish(
+29 -7
View File
@@ -210,7 +210,11 @@ class AudioEventMaintainer(threading.Thread):
# per-camera stop signal so a single maintainer can be torn down at # per-camera stop signal so a single maintainer can be torn down at
# runtime (e.g. on camera removal) without stopping the whole process # runtime (e.g. on camera removal) without stopping the whole process
self.camera_stop_event = threading.Event() self.camera_stop_event = threading.Event()
self.detector = AudioTfl(stop_event, self.camera_config.audio.num_threads) self.detector = AudioTfl(
stop_event,
self.camera_config.audio.num_threads,
self.camera_config.audio.labelmap,
)
self.shape = (int(round(AUDIO_DURATION * AUDIO_SAMPLE_RATE)),) self.shape = (int(round(AUDIO_DURATION * AUDIO_SAMPLE_RATE)),)
self.chunk_size = int(round(AUDIO_DURATION * AUDIO_SAMPLE_RATE * 2)) self.chunk_size = int(round(AUDIO_DURATION * AUDIO_SAMPLE_RATE * 2))
self.logger = logging.getLogger(f"audio.{self.camera_config.name}") self.logger = logging.getLogger(f"audio.{self.camera_config.name}")
@@ -392,7 +396,10 @@ class AudioEventMaintainer(threading.Thread):
while not self.stop_event.is_set() and not self.camera_stop_event.is_set(): while not self.stop_event.is_set() and not self.camera_stop_event.is_set():
# check if there is an updated config # check if there is an updated config
self.config_subscriber.check_for_updates() updated_topics = self.config_subscriber.check_for_updates()
if CameraConfigUpdateEnum.audio.name in updated_topics:
self.detector.update_labelmap(self.camera_config.audio.labelmap)
enabled = self.camera_config.enabled enabled = self.camera_config.enabled
if enabled != self.was_enabled: if enabled != self.was_enabled:
@@ -451,10 +458,17 @@ class AudioEventMaintainer(threading.Thread):
class AudioTfl: class AudioTfl:
def __init__(self, stop_event: threading.Event, num_threads: int = 2) -> None: def __init__(
self,
stop_event: threading.Event,
num_threads: int = 2,
labelmap: dict[int, str] | None = None,
) -> None:
self.stop_event = stop_event self.stop_event = stop_event
self.num_threads = num_threads self.num_threads = num_threads
self.labels = load_labels("/audio-labelmap.txt", prefill=521) self._default_labels = load_labels("/audio-labelmap.txt", prefill=521)
self.labels: dict[int, str] = {}
self.update_labelmap(labelmap or {})
# Suppress TFLite delegate creation messages that bypass Python logging # Suppress TFLite delegate creation messages that bypass Python logging
with suppress_stderr_during("tflite_interpreter_init"): with suppress_stderr_during("tflite_interpreter_init"):
self.interpreter = Interpreter( self.interpreter = Interpreter(
@@ -466,6 +480,10 @@ class AudioTfl:
self.tensor_input_details = self.interpreter.get_input_details() self.tensor_input_details = self.interpreter.get_input_details()
self.tensor_output_details = self.interpreter.get_output_details() self.tensor_output_details = self.interpreter.get_output_details()
def update_labelmap(self, labelmap: dict[int, str]) -> None:
"""Merge configured label overrides into the default audio labelmap."""
self.labels = {**self._default_labels, **labelmap}
def _detect_raw(self, tensor_input: np.ndarray) -> np.ndarray: def _detect_raw(self, tensor_input: np.ndarray) -> np.ndarray:
self.interpreter.set_tensor(self.tensor_input_details[0]["index"], tensor_input) self.interpreter.set_tensor(self.tensor_input_details[0]["index"], tensor_input)
self.interpreter.invoke() self.interpreter.invoke()
@@ -504,10 +522,14 @@ class AudioTfl:
raw_detections = self._detect_raw(tensor_input) raw_detections = self._detect_raw(tensor_input)
detected_labels: set[str] = set()
for d in raw_detections: for d in raw_detections:
if d[1] < threshold: if d[1] < threshold:
break break
detections.append( label = self.labels[int(d[0])]
(self.labels[int(d[0])], float(d[1]), (d[2], d[3], d[4], d[5])) if label in detected_labels:
) continue
detected_labels.add(label)
detections.append((label, float(d[1]), (d[2], d[3], d[4], d[5])))
return detections return detections
+8 -8
View File
@@ -197,9 +197,11 @@ class EventCleanup(threading.Thread):
def expire_clips(self) -> list[str]: def expire_clips(self) -> list[str]:
## Expire events from unlisted cameras based on the global config ## Expire events from unlisted cameras based on the global config
# effective days cover the sub window, keeping tracked objects in
# Explore while sub recordings and review items still exist
expire_days = max( expire_days = max(
self.config.record.alerts.retain.days, self.config.record.effective_alert_days,
self.config.record.detections.retain.days, self.config.record.effective_detection_days,
) )
file_extension = None # mp4 clips are no longer stored in /clips file_extension = None # mp4 clips are no longer stored in /clips
update_params = {"has_clip": False} update_params = {"has_clip": False}
@@ -278,15 +280,13 @@ class EventCleanup(threading.Thread):
## Expire events from cameras based on the camera config ## Expire events from cameras based on the camera config
for name, camera in self.config.cameras.items(): for name, camera in self.config.cameras.items():
expire_days = max( # effective days cover the sub window, keeping tracked objects
camera.record.alerts.retain.days, # in Explore while sub recordings and review items still exist
camera.record.detections.retain.days,
)
alert_expire_date = ( alert_expire_date = (
now - datetime.timedelta(days=camera.record.alerts.retain.days) now - datetime.timedelta(days=camera.record.effective_alert_days)
).timestamp() ).timestamp()
detection_expire_date = ( detection_expire_date = (
now - datetime.timedelta(days=camera.record.detections.retain.days) now - datetime.timedelta(days=camera.record.effective_detection_days)
).timestamp() ).timestamp()
# grab all events after specific time # grab all events after specific time
expired_events = ( expired_events = (
+5 -8
View File
@@ -159,7 +159,8 @@ class EventProcessor(threading.Thread):
if width is None or height is None: if width is None or height is None:
return return
first_detector = list(self.config.detectors.values())[0] camera_model = self.config.model_for_camera(camera)
camera_detector = self.config.devices_for_model(camera_model)[0].detector
start_time = event_data["start_time"] start_time = event_data["start_time"]
end_time = ( end_time = (
@@ -229,13 +230,9 @@ class EventProcessor(threading.Thread):
Event.thumbnail: event_data.get("thumbnail"), Event.thumbnail: event_data.get("thumbnail"),
Event.has_clip: event_data["has_clip"], Event.has_clip: event_data["has_clip"],
Event.has_snapshot: event_data["has_snapshot"], Event.has_snapshot: event_data["has_snapshot"],
Event.model_hash: first_detector.model.model_hash Event.model_hash: camera_model.model_hash,
if first_detector.model Event.model_type: camera_model.model_type,
else None, Event.detector_type: camera_detector,
Event.model_type: first_detector.model.model_type
if first_detector.model
else None,
Event.detector_type: first_detector.type,
Event.data: { Event.data: {
"box": box, "box": box,
"region": region, "region": region,
+2 -2
View File
@@ -245,7 +245,7 @@ class GeminiClient(GenAIClient):
) )
gemini_messages.append( gemini_messages.append(
types.Content( types.Content(
role="function", role="user",
parts=[ parts=[
types.Part.from_function_response( types.Part.from_function_response(
name=msg.get("name") name=msg.get("name")
@@ -501,7 +501,7 @@ class GeminiClient(GenAIClient):
) )
gemini_messages.append( gemini_messages.append(
types.Content( types.Content(
role="function", role="user",
parts=[ parts=[
types.Part.from_function_response( types.Part.from_function_response(
name=msg.get("name") name=msg.get("name")
+66 -122
View File
@@ -262,6 +262,10 @@ def get_tool_definitions(
`attribute` parameter is exposed for filtering by their labels. When the `attribute` parameter is exposed for filtering by their labels. When the
embeddings model only understands English (JinaV1), the `semantic_query` embeddings model only understands English (JinaV1), the `semantic_query`
description instructs the model to write the query in English. description instructs the model to write the query in English.
Descriptions here stay mechanical: which tool to reach for, and how the
filters relate to each other, is stated once in the system prompt so the
guidance is not paid for twice on every request.
""" """
search_objects_properties: dict[str, Any] = { search_objects_properties: dict[str, Any] = {
"camera": { "camera": {
@@ -270,26 +274,13 @@ def get_tool_definitions(
}, },
"label": { "label": {
"type": "string", "type": "string",
"description": ( "description": "Tracked object class to filter by.",
"Generic object class to filter by — one of the tracked detector "
"labels such as 'person', 'package', 'car', 'dog', 'bird'. Use "
"this for broad queries like 'show me all cars today'. Combine "
"with semantic_query when the user also describes appearance or "
"behavior (e.g. label='person', semantic_query='riding a lawn "
"mower')."
),
}, },
"sub_label": { "sub_label": {
"type": "string", "type": "string",
"description": ( "description": (
"Filter by a DISCRETE NAMED entity recognized in the detection. " "Name recognized in the detection: a person, delivery company, "
"Use this for: a known person's name ('John'), a delivery " "animal species or breed, or license plate."
"company ('Amazon', 'UPS'), a recognized animal species or "
"breed ('blue jay', 'cardinal', 'golden retriever'), or a "
"license plate string. When filtering by a specific name, set "
"only sub_label and leave label unset. Do NOT use sub_label "
"for descriptions of appearance, clothing, or actions — those "
"belong in semantic_query."
), ),
}, },
"after": { "after": {
@@ -313,20 +304,11 @@ def get_tool_definitions(
} }
if attribute_classifications: if attribute_classifications:
model_outline = "; ".join(
f"{m['name']} (applies to {', '.join(m['objects']) or 'any object'})"
for m in attribute_classifications
)
search_objects_properties["attribute"] = { search_objects_properties["attribute"] = {
"type": "string", "type": "string",
"description": ( "description": (
"Filter by a classification attribute label produced by a " "Attribute label produced by a configured classification model "
"configured attribute classification model. Use this INSTEAD " "(case-sensitive)."
"of semantic_query when the user's request matches one of "
"these classifications. Configured models: "
f"{model_outline}. "
"Set the value to the attribute label that matches the user's "
"phrasing (case-sensitive)."
), ),
} }
@@ -334,29 +316,12 @@ def get_tool_definitions(
search_objects_properties["semantic_query"] = { search_objects_properties["semantic_query"] = {
"type": "string", "type": "string",
"description": ( "description": (
"Optional natural-language description of a PHYSICAL " "Description of an appearance or activity, used to semantically "
"CHARACTERISTIC, APPEARANCE, or ACTIVITY the user mentioned, " "narrow results."
"used to semantically narrow results. Only set this when the "
"user describes something beyond what label and sub_label can "
"express on their own.\n"
"USE for descriptive phrases like: 'riding a lawn mower', "
"'wearing a red jacket', 'carrying a package', 'walking a "
"dog', 'on a bicycle', 'holding an umbrella'.\n"
"DO NOT USE for:\n"
"- specific named people, pets, or delivery companies → use sub_label\n"
"- animal species or breed names like 'blue jay', 'cardinal', "
"'golden retriever' → use sub_label\n"
"- license plate strings → use sub_label\n"
"- generic object queries like 'all cars today' or 'every "
"person' → use label alone with no semantic_query\n"
"When set, combine with label/time/camera/zone filters as "
"usual (e.g. label='person', semantic_query='riding a lawn "
"mower', after='2024-05-01T00:00:00Z')."
+ ( + (
" The configured embeddings model only understands " " The configured embeddings model only understands English, so "
"English, so always write semantic_query in English, " "always write this in English, translating the user's "
"translating the user's description if they phrased it " "description if they phrased it in another language."
"in another language."
if embeddings_language == "english" if embeddings_language == "english"
else "" else ""
) )
@@ -364,26 +329,10 @@ def get_tool_definitions(
} }
search_objects_description = ( search_objects_description = (
"Search the historical record of detected objects in Frigate. " "Search the historical record of tracked detections. Use this ONLY for "
"Use this ONLY for questions about the PAST — e.g. 'did anyone come by today?', " "questions about the PAST, e.g. 'did anyone come by today?', 'when was the "
"'when was the last car?', 'show me detections from yesterday'. " "last car?'. For alerting on future events use start_camera_watch instead."
"Do NOT use this for monitoring or alerting requests about future events — "
"use start_camera_watch instead for those. "
"An 'object' in Frigate represents a tracked detection (e.g., a person, package, car).\n\n"
"Choose filters based on what the user is asking for:\n"
"- Generic class query ('show me all cars today'): set `label` only.\n"
"- Specific NAMED entity (known person, delivery company, animal "
"species/breed like 'blue jay' or 'golden retriever', license "
"plate): set `sub_label` only and leave `label` unset.\n"
) )
if semantic_search_enabled:
search_objects_description += (
"- Physical CHARACTERISTIC, APPEARANCE, or ACTIVITY that is not a "
"discrete name ('person riding a lawn mower', 'someone in a red "
"jacket', 'person carrying a package'): set `semantic_query` with "
"the descriptive phrase, optionally alongside `label` for the "
"object class. Do NOT put descriptive phrases in sub_label."
)
return [ return [
{ {
@@ -398,20 +347,30 @@ def get_tool_definitions(
"required": [], "required": [],
}, },
}, },
{
"type": "function",
"function": {
"name": "get_categorized_object_names",
"description": (
"Every name that can be attached as a sub_label, grouped by object "
"type: recognized faces, named license plates, classification "
"categories, and delivery logos. Takes no arguments and always "
"returns the complete map."
),
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
},
},
{ {
"type": "function", "type": "function",
"function": { "function": {
"name": "find_similar_objects", "name": "find_similar_objects",
"description": ( "description": (
"Find tracked objects that are visually and semantically similar " "Find tracked objects visually and semantically similar to a "
"to a specific past event. Use this when the user references a " "specific past event. Requires semantic search to be enabled."
"particular object they have seen and wants to find other "
"sightings of the same or similar one ('that green car', 'the "
"person in the red jacket', 'the package that was delivered'). "
"Prefer this over search_objects whenever the user's intent is "
"'find more like this specific one.' Use search_objects first "
"only if you need to locate the anchor event. Requires semantic "
"search to be enabled."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -473,9 +432,8 @@ def get_tool_definitions(
"function": { "function": {
"name": "set_camera_state", "name": "set_camera_state",
"description": ( "description": (
"Change a camera's feature state (e.g., turn detection on/off, enable/disable recordings). " "Change a camera's feature state, e.g. turn detection on or off. "
"Use camera='*' to apply to all cameras at once. " "Only call this when the user explicitly asks to change a setting. "
"Only call this tool when the user explicitly asks to change a camera setting. "
"Requires admin privileges." "Requires admin privileges."
), ),
"parameters": { "parameters": {
@@ -495,7 +453,7 @@ def get_tool_definitions(
"motion", "motion",
"enabled", "enabled",
"birdseye", "birdseye",
"birdseye_mode", "birdseye_modes",
"improve_contrast", "improve_contrast",
"ptz_autotracker", "ptz_autotracker",
"motion_contour_area", "motion_contour_area",
@@ -510,14 +468,14 @@ def get_tool_definitions(
], ],
"description": ( "description": (
"The feature to change. Most features accept ON or OFF. " "The feature to change. Most features accept ON or OFF. "
"birdseye_mode accepts CONTINUOUS, MOTION, or OBJECTS. " "birdseye_modes accepts CONTINUOUS, MOTION, ALL_OBJECTS, ALERTS, DETECTIONS, NONE, or a comma-separated combination. "
"motion_contour_area and motion_threshold accept a number. " "motion_contour_area and motion_threshold accept a number. "
"profile accepts a profile name or 'none' to deactivate (requires camera='*')." "profile accepts a profile name or 'none' to deactivate (requires camera='*')."
), ),
}, },
"value": { "value": {
"type": "string", "type": "string",
"description": "The value to set. ON or OFF for toggles, a number for thresholds, a profile name or 'none' for profile.", "description": "The value to set, as accepted by the chosen feature.",
}, },
}, },
"required": ["camera", "feature", "value"], "required": ["camera", "feature", "value"],
@@ -529,11 +487,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "get_live_context", "name": "get_live_context",
"description": ( "description": (
"Get the current live image and detection information for a single camera: objects being tracked, " "Current live image and detections (tracked objects, zones, "
"zones, timestamps. Use this to understand what is visible in the live view. " "timestamps) for one camera. Use this for questions about what is "
"Call this when answering questions about what is happening right now on a specific camera. " "happening right now. Call it again for each additional camera."
"Operates on one camera at a time; call the tool again for each additional camera. "
"Wildcards and empty values are not accepted."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -541,8 +497,8 @@ def get_tool_definitions(
"camera": { "camera": {
"type": "string", "type": "string",
"description": ( "description": (
"Exact name of a single camera to get live context for. " "Exact name of a single camera. Wildcards (e.g. '*', "
"Wildcards (e.g. '*', 'all') and empty strings are not accepted." "'all') and empty strings are not accepted."
), ),
}, },
}, },
@@ -555,10 +511,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "start_camera_watch", "name": "start_camera_watch",
"description": ( "description": (
"Start a continuous VLM watch job that monitors a camera and sends a notification " "Start a continuous watch job that monitors a camera and notifies "
"when a specified condition is met. Use this when the user wants to be alerted about " "the user when a condition is met, e.g. 'tell me when guests "
"a future event, e.g. 'tell me when guests arrive' or 'notify me when the package is picked up'. " "arrive'. Only one watch job can run at a time. Returns a job ID."
"Only one watch job can run at a time. Returns a job ID."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -598,10 +553,7 @@ def get_tool_definitions(
"type": "function", "type": "function",
"function": { "function": {
"name": "stop_camera_watch", "name": "stop_camera_watch",
"description": ( "description": "Cancel the currently running watch job.",
"Cancel the currently running VLM watch job. Use this when the user wants to "
"stop a previously started watch, e.g. 'stop watching the front door'."
),
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": {}, "properties": {},
@@ -614,11 +566,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "get_profile_status", "name": "get_profile_status",
"description": ( "description": (
"Get the current profile status including the active profile and " "Get the active profile and when each profile was last activated. "
"timestamps of when each profile was last activated. Use this to " "Call this before get_recap to derive the time window for requests "
"determine time periods for recap requests — e.g. when the user asks " "like 'what happened while I was away?'."
"'what happened while I was away?', call this first to find the relevant "
"time window based on profile activation history."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -632,11 +582,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "get_recap", "name": "get_recap",
"description": ( "description": (
"Get a recap of all activity (alerts and detections) for a given time period. " "Get all activity (alerts and detections) for a time period, as a "
"Use this after calling get_profile_status to retrieve what happened during " "chronological list with camera, objects, zones, and descriptions "
"a specific window — e.g. 'what happened while I was away?'. Returns a " "when available. Summarize the results for the user."
"chronological list of activity with camera, objects, zones, and GenAI-generated "
"descriptions when available. Summarize the results for the user."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -723,14 +671,13 @@ def build_chat_system_prompt(
) )
speed_units_section = f"\n\nReport object speeds to the user in {speed_unit}." speed_units_section = f"\n\nReport object speeds to the user in {speed_unit}."
semantic_search_section = "" filter_routing_section = (
"\n\nWhen routing a search_objects call, pick filters by the shape of the user's request:\n"
"- Generic class ('show me all cars today'): set `label` only.\n"
"- Specific named entity — a known person ('John'), delivery company ('Amazon'), animal species/breed ('blue jay', 'golden retriever'), or license plate: set `sub_label` only and leave `label` unset. Call get_categorized_object_names first and use the exact spelling it returns; a guessed spelling matches nothing. If the name is absent, say it is not configured rather than searching for it."
)
if semantic_search_enabled: if semantic_search_enabled:
semantic_search_section = ( filter_routing_section += "\n- Physical characteristic, appearance, or activity that is NOT a discrete name ('riding a lawn mower', 'someone in a red jacket'): set `semantic_query` with the descriptive phrase, optionally combined with `label`. Never put descriptive phrases in `sub_label`."
"\n\nWhen routing a search_objects call, pick filters by the shape of the user's request:\n"
"- Generic class ('show me all cars today'): set `label` only.\n"
"- Specific named entity — a known person ('John'), delivery company ('Amazon'), animal species/breed ('blue jay', 'cardinal', 'golden retriever'), or license plate: set `sub_label` only and leave `label` unset.\n"
"- Physical characteristic, appearance, or activity that is NOT a discrete name ('find me people riding a lawn mower', 'someone in a red jacket', 'a person carrying a package'): set `semantic_query` with the descriptive phrase, optionally combined with `label` for the object class. Never put descriptive phrases in `sub_label`."
)
attribute_classification_section = "" attribute_classification_section = ""
if attribute_classifications: if attribute_classifications:
@@ -739,9 +686,9 @@ def build_chat_system_prompt(
for m in attribute_classifications for m in attribute_classifications
) )
attribute_classification_section = ( attribute_classification_section = (
"\n\nAttribute classification models are configured for the following object types:\n" "\n\nConfigured attribute classification models:\n"
f"{model_lines}\n" f"{model_lines}\n"
"When the user's request matches one of these classifications, set the search_objects `attribute` field to the matching label rather than using `semantic_query`. Reserve `semantic_query` for descriptive phrases that fall outside the configured attribute labels." "When the user's request matches one of these classifications, set the search_objects `attribute` field to the matching label (case-sensitive) rather than using `semantic_query`. Reserve `semantic_query` for descriptive phrases outside the configured attribute labels."
) )
return f"""You are a helpful assistant for Frigate, a security camera NVR system. You help users answer questions about their cameras, detected objects, and events. return f"""You are a helpful assistant for Frigate, a security camera NVR system. You help users answer questions about their cameras, detected objects, and events.
@@ -750,9 +697,6 @@ Current server local date and time: {current_date_str} at {current_time_str}
Do not start your response with phrases like "I will check...", "Let me see...", or "Let me look...". Answer directly. Do not start your response with phrases like "I will check...", "Let me see...", or "Let me look...". Answer directly.
Always present times to the user in the server's local timezone. When tool results include start_time_local and end_time_local, use those exact strings when listing or describing detection times—do not convert or invent timestamps. Do not use UTC or ISO format with Z for the user-facing answer unless the tool result only provides Unix timestamps without local time fields. Always present times in the server's local timezone. When tool results include start_time_local and end_time_local, quote those strings exactly; never convert or invent timestamps, and fall back to UTC or ISO format only when a result has no local time fields. Resolve relative dates like "today" or "this week" against the current date above, and pass dates to tools in ISO 8601 (e.g. {current_date_str}T00:00:00Z for the start of today).
When users ask about "today", "yesterday", "this week", etc., use the current date above as reference.
When searching for objects or events, use ISO 8601 format for dates (e.g., {current_date_str}T00:00:00Z for the start of today).
Always be accurate with time calculations based on the current date provided.
When a user refers to a specific object they have seen or describe with identifying details ("that green car", "the person in the red jacket", "a package left today"), prefer the find_similar_objects tool over search_objects. Use search_objects first only to locate the anchor event, then pass its id to find_similar_objects. For generic queries like "show me all cars today", keep using search_objects. If a user message begins with [attached_event:<id>], treat that event id as the anchor for any similarity or "tell me more" request in the same message and call find_similar_objects with that id.{semantic_search_section}{attribute_classification_section}{cameras_section}{speed_units_section}""" When the user refers to a specific object they have seen ("that green car", "the person in the red jacket", "a package left today"), prefer find_similar_objects over search_objects, using search_objects only to locate the anchor event and passing its id along. Keep search_objects for generic queries like "show me all cars today". If a user message begins with [attached_event:<id>], treat that id as the anchor for any similarity or "tell me more" request in the same message.{filter_routing_section}{attribute_classification_section}{cameras_section}{speed_units_section}"""
+5 -1
View File
@@ -115,6 +115,10 @@ def query_recordings(source_camera: str, start_ts: float, end_ts: float) -> Mode
return cast(ModelSelect, query) return cast(ModelSelect, query)
class NoRecordingsError(ValueError):
"""Raised when no recordings exist in the requested time range."""
class DebugReplaySource(ABC): class DebugReplaySource(ABC):
"""Abstract source for a debug replay session. """Abstract source for a debug replay session.
@@ -187,7 +191,7 @@ class RecordingDebugReplaySource(DebugReplaySource):
raise ValueError("End time must be after start time") raise ValueError("End time must be after start time")
if not query_recordings(self._camera, self._start_ts, self._end_ts).count(): if not query_recordings(self._camera, self._start_ts, self._end_ts).count():
raise ValueError( raise NoRecordingsError(
f"No recordings found for camera '{self._camera}' in the specified time range" f"No recordings found for camera '{self._camera}' in the specified time range"
) )
+2 -1
View File
@@ -15,7 +15,7 @@ import numpy as np
from frigate.comms.inter_process import InterProcessRequestor from frigate.comms.inter_process import InterProcessRequestor
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.const import UPDATE_JOB_STATE from frigate.const import STREAM_TYPE_MAIN, UPDATE_JOB_STATE
from frigate.jobs.job import Job from frigate.jobs.job import Job
from frigate.jobs.manager import ( from frigate.jobs.manager import (
get_job_by_id, get_job_by_id,
@@ -485,6 +485,7 @@ class MotionSearchRunner(threading.Thread):
) )
) )
.where(Recordings.camera == camera_name) .where(Recordings.camera == camera_name)
.where(Recordings.stream_type == STREAM_TYPE_MAIN)
.order_by(Recordings.start_time.asc()) .order_by(Recordings.start_time.asc())
) )
+2 -20
View File
@@ -17,6 +17,7 @@ import numpy as np
from frigate.config import CameraConfig from frigate.config import CameraConfig
from frigate.ffmpeg_presets import parse_preset_hardware_acceleration_decode from frigate.ffmpeg_presets import parse_preset_hardware_acceleration_decode
from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.services import auto_detect_hwaccel from frigate.util.services import auto_detect_hwaccel
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -88,25 +89,6 @@ def _read_exact(stream: IO[bytes], size: int) -> bytes | None:
return bytes(buf) return bytes(buf)
def _terminate(proc: sp.Popen[bytes]) -> None:
"""Stop an ffmpeg decode process promptly."""
# Close the read end first so a blocked ffmpeg write unblocks (ffmpeg then
# sees a broken pipe), then signal it. The resulting ffmpeg write error is
# harmless and goes to the captured stderr.
if proc.stdout is not None:
try:
proc.stdout.close()
except OSError:
pass
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except sp.TimeoutExpired:
proc.kill()
proc.wait()
KEYFRAME_MAX_GAP_SECONDS = 2.0 KEYFRAME_MAX_GAP_SECONDS = 2.0
@@ -222,7 +204,7 @@ def _run_vod_decode(
count += 1 count += 1
yield frame yield frame
finally: finally:
_terminate(proc) terminate_ffmpeg_stream(proc)
stderr_file.close() stderr_file.close()
if count == 0 and software_retry and not should_stop(): if count == 0 and software_retry and not should_stop():
+6
View File
@@ -79,6 +79,12 @@ class Recordings(Model):
segment_size = FloatField(default=0) # this should be stored as MB segment_size = FloatField(default=0) # this should be stored as MB
regions = IntegerField(null=True) regions = IntegerField(null=True)
motion_heatmap = JSONField(null=True) # 16x16 grid, 256 values (0-255) motion_heatmap = JSONField(null=True) # 16x16 grid, 256 values (0-255)
keyframes = JSONField(null=True) # ms offsets; NULL = unprobed (legacy rows)
stream_type = CharField(default="main", max_length=8)
has_audio = BooleanField(null=True) # NULL = unknown (legacy rows)
audio_rate = IntegerField(null=True) # Hz; NULL = unknown (legacy rows)
audio_codec = CharField(null=True, max_length=20) # NULL = unknown (legacy rows)
video_codec = CharField(null=True, max_length=20) # NULL = unknown (legacy rows)
class ExportCase(Model): class ExportCase(Model):
+13 -1
View File
@@ -5,7 +5,19 @@ import threading
from numpy import ndarray from numpy import ndarray
from frigate.detectors.detector_config import InputTensorEnum from frigate.detectors.detector_config import InputTensorEnum, ModelConfig
def detection_frame_size(model: ModelConfig) -> int:
"""Get the shared memory size a camera needs to hand frames to a model.
Args:
model: The model the camera runs on
Returns:
Size in bytes of one model input frame
"""
return model.height * model.width * 3
class RequestStore: class RequestStore:
+179 -130
View File
@@ -9,6 +9,7 @@ import queue
import subprocess as sp import subprocess as sp
import threading import threading
import traceback import traceback
from dataclasses import dataclass
from multiprocessing.synchronize import Event as MpEvent from multiprocessing.synchronize import Event as MpEvent
from typing import Any from typing import Any
@@ -16,9 +17,11 @@ import cv2
import numpy as np import numpy as np
from frigate.comms.inter_process import InterProcessRequestor from frigate.comms.inter_process import InterProcessRequestor
from frigate.comms.review_updater import ReviewDataSubscriber
from frigate.config import BirdseyeModeEnum, FfmpegConfig, FrigateConfig from frigate.config import BirdseyeModeEnum, FfmpegConfig, FrigateConfig
from frigate.const import BASE_DIR, BIRDSEYE_PIPE, INSTALL_DIR, UPDATE_BIRDSEYE_LAYOUT from frigate.const import BASE_DIR, BIRDSEYE_PIPE, INSTALL_DIR, UPDATE_BIRDSEYE_LAYOUT
from frigate.output.ws_auth import ws_has_camera_access from frigate.output.ws_auth import ws_has_camera_access
from frigate.review.types import SeverityEnum
from frigate.util.image import ( from frigate.util.image import (
SharedMemoryFrameManager, SharedMemoryFrameManager,
copy_yuv_to_position, copy_yuv_to_position,
@@ -28,6 +31,15 @@ from frigate.util.image import (
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class BirdseyeActivity:
"""Activity signals used to decide whether a camera is shown in Birdseye."""
has_object: bool
has_motion: bool
severity: str | None
def get_standard_aspect_ratio(width: int, height: int) -> tuple[int, int]: def get_standard_aspect_ratio(width: int, height: int) -> tuple[int, int]:
"""Ensure that only standard aspect ratios are used.""" """Ensure that only standard aspect ratios are used."""
# it is important that all ratios have the same scale # it is important that all ratios have the same scale
@@ -357,6 +369,7 @@ class BirdsEyeFrameManager:
settings.detect.height, settings.detect.height,
], ],
"last_active_frame": 0.0, "last_active_frame": 0.0,
"live_active": False,
"current_frame": 0.0, "current_frame": 0.0,
"layout_frame": 0.0, "layout_frame": 0.0,
"channel_dims": { "channel_dims": {
@@ -408,19 +421,33 @@ class BirdsEyeFrameManager:
channel_dims, channel_dims,
) )
def camera_active( def camera_threshold_active(
self, mode: Any, object_box_count: int, motion_box_count: int self,
modes: list[BirdseyeModeEnum],
activity: BirdseyeActivity,
) -> bool: ) -> bool:
if mode == BirdseyeModeEnum.continuous: """Return whether activity subject to inactivity_threshold is present."""
return True return (BirdseyeModeEnum.motion in modes and activity.has_motion) or (
BirdseyeModeEnum.all_objects in modes and activity.has_object
)
if mode == BirdseyeModeEnum.motion and motion_box_count > 0: def camera_live_active(
return True self,
modes: list[BirdseyeModeEnum],
if mode == BirdseyeModeEnum.objects and object_box_count > 0: activity: BirdseyeActivity,
return True ) -> bool:
"""Return whether activity that ends the moment it stops is present."""
return False return (
BirdseyeModeEnum.continuous in modes
or (
BirdseyeModeEnum.alerts in modes
and activity.severity == SeverityEnum.alert
)
or (
BirdseyeModeEnum.detections in modes
and activity.severity == SeverityEnum.detection
)
)
def get_camera_coordinates(self) -> dict[str, dict[str, int]]: def get_camera_coordinates(self) -> dict[str, dict[str, int]]:
"""Return the coordinates of each camera in the current layout.""" """Return the coordinates of each camera in the current layout."""
@@ -451,9 +478,15 @@ class BirdsEyeFrameManager:
and self.config.cameras[cam].birdseye.enabled and self.config.cameras[cam].birdseye.enabled
and self.config.cameras[cam].enabled_in_config and self.config.cameras[cam].enabled_in_config
and self.config.cameras[cam].enabled and self.config.cameras[cam].enabled
and cam_data["last_active_frame"] > 0 and (
and cam_data["current_frame_time"] - cam_data["last_active_frame"] cam_data["live_active"]
< self.config.birdseye.inactivity_threshold or (
cam_data["last_active_frame"] > 0
and cam_data["current_frame_time"]
- cam_data["last_active_frame"]
< self.config.birdseye.inactivity_threshold
)
)
] ]
) )
logger.debug(f"Active cameras: {active_cameras}") logger.debug(f"Active cameras: {active_cameras}")
@@ -470,7 +503,9 @@ class BirdsEyeFrameManager:
limited_active_cameras = sorted( limited_active_cameras = sorted(
active_cameras, active_cameras,
key=lambda active_camera: ( key=lambda active_camera: (
self.cameras[active_camera]["current_frame_time"] 0.0
if self.cameras[active_camera]["live_active"]
else self.cameras[active_camera]["current_frame_time"]
- self.cameras[active_camera]["last_active_frame"] - self.cameras[active_camera]["last_active_frame"]
), ),
) )
@@ -604,112 +639,92 @@ class BirdsEyeFrameManager:
) -> list[list[Any]] | None: ) -> list[list[Any]] | None:
"""Calculate the optimal layout for 2+ cameras.""" """Calculate the optimal layout for 2+ cameras."""
def map_layout( def find_available_x(
camera_layout: list[list[Any]], row_height: int current_x: int,
) -> tuple[int, int, list[list[Any]] | None]: width: int,
"""Map the calculated layout.""" reserved_ranges: list[tuple[int, int]],
candidate_layout = [] max_width: int,
starting_x = 0 ) -> int | None:
x = 0 """Find the first horizontal slot that does not collide with reservations."""
max_width = 0 x = current_x
y = 0
for row in camera_layout: for reserved_start, reserved_end in sorted(reserved_ranges):
final_row = [] if x >= reserved_end:
max_width = max(max_width, x) continue
x = starting_x
for cameras in row:
camera_dims = self.cameras[cameras[0]]["dimensions"].copy()
camera_aspect = cameras[1]
if camera_dims[1] > camera_dims[0]: if x + width <= reserved_start:
scaled_height = int(row_height * 2) return x
scaled_width = int(scaled_height * camera_aspect)
starting_x = scaled_width
else:
scaled_height = row_height
scaled_width = int(scaled_height * camera_aspect)
# layout is too large x = max(x, reserved_end)
if (
x + scaled_width > self.canvas.width
or y + scaled_height > self.canvas.height
):
return x + scaled_width, y + scaled_height, None
final_row.append((cameras[0], (x, y, scaled_width, scaled_height))) if x + width <= max_width:
x += scaled_width return x
y += row_height
candidate_layout.append(final_row)
if max_width == 0:
max_width = x
return max_width, y, candidate_layout
canvas_aspect_x, canvas_aspect_y = self.canvas.get_aspect(coefficient)
camera_layout: list[list[Any]] = []
camera_layout.append([])
starting_x = 0
x = starting_x
y = 0
y_i = 0
max_y = 0
for camera in cameras_to_add:
camera_dims = self.cameras[camera]["dimensions"].copy()
camera_aspect_x, camera_aspect_y = self.canvas.get_camera_aspect(
camera, camera_dims[0], camera_dims[1]
)
if camera_dims[1] > camera_dims[0]:
portrait = True
else:
portrait = False
if (x + camera_aspect_x) <= canvas_aspect_x:
# insert if camera can fit on current row
camera_layout[y_i].append(
(
camera,
camera_aspect_x / camera_aspect_y,
)
)
if portrait:
starting_x = camera_aspect_x
else:
max_y = max(
max_y,
camera_aspect_y,
)
x += camera_aspect_x
else:
# move on to the next row and insert
y += max_y
y_i += 1
camera_layout.append([])
x = starting_x
if x + camera_aspect_x > canvas_aspect_x:
return None
camera_layout[y_i].append(
(
camera,
camera_aspect_x / camera_aspect_y,
)
)
x += camera_aspect_x
if y + max_y > canvas_aspect_y:
return None return None
row_height = int(self.canvas.height / coefficient) def map_layout(row_height: int) -> tuple[int, int, list[list[Any]] | None]:
total_width, total_height, standard_candidate_layout = map_layout( """Lay out cameras row by row while reserving portrait spans for the next row."""
camera_layout, row_height candidate_layout: list[list[Any]] = []
) reserved_ranges: dict[int, list[tuple[int, int]]] = {}
current_row: list[Any] = []
row_index = 0
row_y = 0
row_x = 0
max_width = 0
max_height = 0
for camera in cameras_to_add:
camera_dims = self.cameras[camera]["dimensions"].copy()
camera_aspect_x, camera_aspect_y = self.canvas.get_camera_aspect(
camera, camera_dims[0], camera_dims[1]
)
portrait = camera_dims[1] > camera_dims[0]
scaled_height = row_height * 2 if portrait else row_height
scaled_width = int(scaled_height * (camera_aspect_x / camera_aspect_y))
while True:
x = find_available_x(
row_x,
scaled_width,
reserved_ranges.get(row_index, []),
self.canvas.width,
)
if x is not None and row_y + scaled_height <= self.canvas.height:
current_row.append(
(camera, (x, row_y, scaled_width, scaled_height))
)
row_x = x + scaled_width
max_width = max(max_width, row_x)
max_height = max(max_height, row_y + scaled_height)
if portrait:
reserved_ranges.setdefault(row_index + 1, []).append(
(x, row_x)
)
break
if current_row:
candidate_layout.append(current_row)
current_row = []
row_index += 1
row_y = row_index * row_height
row_x = 0
if row_y + scaled_height > self.canvas.height:
overflow_width = max(max_width, scaled_width)
overflow_height = row_y + scaled_height
return overflow_width, overflow_height, None
if current_row:
candidate_layout.append(current_row)
return max_width, max_height, candidate_layout
row_height = max(1, int(self.canvas.height / coefficient))
total_width, total_height, standard_candidate_layout = map_layout(row_height)
if not standard_candidate_layout: if not standard_candidate_layout:
# if standard layout didn't work # if standard layout didn't work
@@ -718,9 +733,9 @@ class BirdsEyeFrameManager:
total_width / self.canvas.width, total_width / self.canvas.width,
total_height / self.canvas.height, total_height / self.canvas.height,
) )
row_height = int(row_height / scale_down_percent) row_height = max(1, int(row_height / scale_down_percent))
total_width, total_height, standard_candidate_layout = map_layout( total_width, total_height, standard_candidate_layout = map_layout(
camera_layout, row_height row_height
) )
if not standard_candidate_layout: if not standard_candidate_layout:
@@ -734,8 +749,8 @@ class BirdsEyeFrameManager:
1 / (total_width / self.canvas.width), 1 / (total_width / self.canvas.width),
1 / (total_height / self.canvas.height), 1 / (total_height / self.canvas.height),
) )
row_height = int(row_height * scale_up_percent) row_height = max(1, int(row_height * scale_up_percent))
_, _, scaled_layout = map_layout(camera_layout, row_height) _, _, scaled_layout = map_layout(row_height)
if scaled_layout: if scaled_layout:
return scaled_layout return scaled_layout
@@ -745,8 +760,7 @@ class BirdsEyeFrameManager:
def update( def update(
self, self,
camera: str, camera: str,
object_count: int, activity: BirdseyeActivity,
motion_count: int,
frame_time: float, frame_time: float,
frame: np.ndarray, frame: np.ndarray,
) -> tuple[bool, bool]: ) -> tuple[bool, bool]:
@@ -760,22 +774,30 @@ class BirdsEyeFrameManager:
return False, False return False, False
force_update = False force_update = False
camera_state = self.cameras.get(camera)
if camera_state is None:
return False, False
# disabling birdseye is a little tricky # disabling birdseye is a little tricky
if not camera_config.birdseye.enabled or not camera_config.enabled: if not camera_config.birdseye.enabled or not camera_config.enabled:
# if we've rendered a frame (we have a value for last_active_frame) # if we've rendered a frame (we have activity state) then clear it
# then we need to set it to zero if camera_state["last_active_frame"] > 0 or camera_state["live_active"]:
if self.cameras[camera]["last_active_frame"] > 0: camera_state["last_active_frame"] = 0
self.cameras[camera]["last_active_frame"] = 0 camera_state["live_active"] = False
force_update = True force_update = True
else: else:
return False, False return False, False
# update the last active frame for the camera # update the last active frame for the camera
self.cameras[camera]["current_frame"] = frame.copy() camera_state["current_frame"] = frame.copy()
self.cameras[camera]["current_frame_time"] = frame_time camera_state["current_frame_time"] = frame_time
if self.camera_active(camera_config.birdseye.mode, object_count, motion_count): modes = camera_config.birdseye.modes
self.cameras[camera]["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)
now = datetime.datetime.now().timestamp() now = datetime.datetime.now().timestamp()
@@ -834,6 +856,8 @@ class Birdseye:
self.frame_manager = SharedMemoryFrameManager() self.frame_manager = SharedMemoryFrameManager()
self.stop_event = stop_event self.stop_event = stop_event
self.requestor = InterProcessRequestor() self.requestor = InterProcessRequestor()
self.review_subscriber = ReviewDataSubscriber("")
self.review_severity: dict[str, str] = {}
self.idle_fps: float = self.config.birdseye.idle_heartbeat_fps self.idle_fps: float = self.config.birdseye.idle_heartbeat_fps
self._idle_interval: float | None = ( self._idle_interval: float | None = (
(1.0 / self.idle_fps) if self.idle_fps > 0 else None (1.0 / self.idle_fps) if self.idle_fps > 0 else None
@@ -864,6 +888,21 @@ class Birdseye:
self.birdseye_manager.clear_frame() self.birdseye_manager.clear_frame()
self.__send_new_frame() self.__send_new_frame()
def check_review_updates(self) -> None:
"""Drain review updates so each camera's active severity stays current."""
while True:
update = self.review_subscriber.check_for_update(timeout=0)
if update is None:
break
camera = update["after"]["camera"]
if update["type"] == "end":
self.review_severity.pop(camera, None)
else:
self.review_severity[camera] = update["after"]["severity"]
def add_camera(self, camera: str) -> None: def add_camera(self, camera: str) -> None:
"""Add a camera to the birdseye manager.""" """Add a camera to the birdseye manager."""
self.birdseye_manager.add_camera(camera) self.birdseye_manager.add_camera(camera)
@@ -872,6 +911,7 @@ class Birdseye:
def remove_camera(self, camera: str) -> None: def remove_camera(self, camera: str) -> None:
"""Remove a camera from the birdseye manager.""" """Remove a camera from the birdseye manager."""
self.birdseye_manager.remove_camera(camera) self.birdseye_manager.remove_camera(camera)
self.review_severity.pop(camera, None)
logger.debug(f"Removed camera {camera} from birdseye") logger.debug(f"Removed camera {camera} from birdseye")
def write_data( def write_data(
@@ -882,10 +922,18 @@ class Birdseye:
frame_time: float, frame_time: float,
frame: np.ndarray, frame: np.ndarray,
) -> None: ) -> None:
activity = BirdseyeActivity(
has_object=any(
not tracked_object["false_positive"]
for tracked_object in current_tracked_objects
),
has_motion=bool(motion_boxes),
severity=self.review_severity.get(camera),
)
frame_changed, frame_layout_changed = self.birdseye_manager.update( frame_changed, frame_layout_changed = self.birdseye_manager.update(
camera, camera,
len([o for o in current_tracked_objects if not o["stationary"]]), activity,
len(motion_boxes),
frame_time, frame_time,
frame, frame,
) )
@@ -906,5 +954,6 @@ class Birdseye:
self.__send_new_frame() self.__send_new_frame()
def stop(self) -> None: def stop(self) -> None:
self.review_subscriber.stop()
self.converter.join() self.converter.join()
self.broadcaster.join() self.broadcaster.join()
+17 -7
View File
@@ -51,8 +51,12 @@ def check_disabled_camera_update(
for camera, last_update in write_times.items(): for camera, last_update in write_times.items():
offline_time = now - last_update offline_time = now - last_update
camera_config = config.cameras.get(camera)
if config.cameras[camera].enabled: if camera_config is None:
continue
if camera_config.enabled:
has_enabled_camera = True has_enabled_camera = True
else: else:
# flag camera as offline when it is disabled # flag camera as offline when it is disabled
@@ -62,8 +66,8 @@ def check_disabled_camera_update(
# last camera update was more than 1 second ago # last camera update was more than 1 second ago
# need to send empty data to birdseye because current # need to send empty data to birdseye because current
# frame is now out of date # frame is now out of date
cam_width = config.cameras[camera].detect.width cam_width = camera_config.detect.width
cam_height = config.cameras[camera].detect.height cam_height = camera_config.detect.height
if cam_width is None or cam_height is None: if cam_width is None or cam_height is None:
raise ValueError(f"Camera {camera} detect dimensions not configured") raise ValueError(f"Camera {camera} detect dimensions not configured")
@@ -184,6 +188,11 @@ class OutputProcess(FrigateProcess):
self.config.birdseye = birdseye_config self.config.birdseye = birdseye_config
logger.debug("Applied dynamic birdseye config update") logger.debug("Applied dynamic birdseye config update")
# drain review updates every iteration, not just when birdseye is
# being consumed, so a dropped end never strands a camera
if birdseye is not None:
birdseye.check_review_updates()
# check if there is an updated config # check if there is an updated config
updates = config_subscriber.check_for_updates() updates = config_subscriber.check_for_updates()
@@ -309,10 +318,11 @@ class OutputProcess(FrigateProcess):
regions, regions,
) = data ) = data
frame = frame_manager.get( camera_config = self.config.cameras.get(camera)
frame_name, self.config.cameras[camera].frame_shape_yuv
) if camera_config is not None:
frame_manager.close(frame_name) frame_manager.get(frame_name, camera_config.frame_shape_yuv)
frame_manager.close(frame_name)
detection_subscriber.stop() detection_subscriber.stop()
+21 -20
View File
@@ -799,14 +799,24 @@ class PtzAutoTracker:
except TimeoutError: except TimeoutError:
continue continue
# both are popped when the camera is deleted, so resolve them once
# here and use the locals for the rest of the move; a move already
# in flight then finishes against valid objects
metrics = self.ptz_metrics.get(camera)
camera_config = self.config.cameras.get(camera)
if metrics is None or camera_config is None:
logger.debug("%s: Dropping queued move, camera was removed", camera)
continue
async with self.move_queue_locks[camera]: async with self.move_queue_locks[camera]:
frame_time, pan, tilt, zoom = move_data frame_time, pan, tilt, zoom = move_data
# if we're receiving move requests during a PTZ move, ignore them # if we're receiving move requests during a PTZ move, ignore them
if ptz_moving_at_frame_time( if ptz_moving_at_frame_time(
frame_time, frame_time,
self.ptz_metrics[camera].start_time.value, metrics.start_time.value,
self.ptz_metrics[camera].stop_time.value, metrics.stop_time.value,
): ):
logger.debug( logger.debug(
f"{camera}: Move queue: PTZ moving, dequeueing move request - frame time: {frame_time}, final pan: {pan}, final tilt: {tilt}, final zoom: {zoom}" f"{camera}: Move queue: PTZ moving, dequeueing move request - frame time: {frame_time}, final pan: {pan}, final tilt: {tilt}, final zoom: {zoom}"
@@ -815,7 +825,7 @@ class PtzAutoTracker:
else: else:
if ( if (
self.config.cameras[camera].onvif.autotracking.zooming camera_config.onvif.autotracking.zooming
== ZoomingModeEnum.relative == ZoomingModeEnum.relative
): ):
await self.onvif._move_relative(camera, pan, tilt, zoom, 1) await self.onvif._move_relative(camera, pan, tilt, zoom, 1)
@@ -824,25 +834,22 @@ class PtzAutoTracker:
await self.onvif._move_relative(camera, pan, tilt, 0, 1) await self.onvif._move_relative(camera, pan, tilt, 0, 1)
# Wait until the camera finishes moving # Wait until the camera finishes moving
while not self.ptz_metrics[camera].motor_stopped.is_set(): while not metrics.motor_stopped.is_set():
await self.onvif.get_camera_status(camera) await self.onvif.get_camera_status(camera)
if ( if zoom > 0 and metrics.zoom_level.value != zoom:
zoom > 0
and self.ptz_metrics[camera].zoom_level.value != zoom
):
await self.onvif._zoom_absolute(camera, zoom, 1) await self.onvif._zoom_absolute(camera, zoom, 1)
# Wait until the camera finishes moving # Wait until the camera finishes moving
while not self.ptz_metrics[camera].motor_stopped.is_set(): while not metrics.motor_stopped.is_set():
await self.onvif.get_camera_status(camera) await self.onvif.get_camera_status(camera)
if self.config.cameras[camera].onvif.autotracking.movement_weights: if camera_config.onvif.autotracking.movement_weights:
logger.debug( logger.debug(
f"{camera}: Predicted movement time: {self._predict_movement_time(camera, pan, tilt)}" f"{camera}: Predicted movement time: {self._predict_movement_time(camera, pan, tilt)}"
) )
logger.debug( logger.debug(
f"{camera}: Actual movement time: {self.ptz_metrics[camera].stop_time.value - self.ptz_metrics[camera].start_time.value}" f"{camera}: Actual movement time: {metrics.stop_time.value - metrics.start_time.value}"
) )
# save metrics for better estimate calculations # save metrics for better estimate calculations
@@ -851,21 +858,15 @@ class PtzAutoTracker:
and len(self.move_metrics[camera]) and len(self.move_metrics[camera])
< AUTOTRACKING_MAX_MOVE_METRICS < AUTOTRACKING_MAX_MOVE_METRICS
and (pan != 0 or tilt != 0) and (pan != 0 or tilt != 0)
and self.config.cameras[ and camera_config.onvif.autotracking.calibrate_on_startup
camera
].onvif.autotracking.calibrate_on_startup
): ):
logger.debug(f"{camera}: Adding new values to move metrics") logger.debug(f"{camera}: Adding new values to move metrics")
self.move_metrics[camera].append( self.move_metrics[camera].append(
{ {
"pan": pan, "pan": pan,
"tilt": tilt, "tilt": tilt,
"start_timestamp": self.ptz_metrics[ "start_timestamp": metrics.start_time.value,
camera "end_timestamp": metrics.stop_time.value,
].start_time.value,
"end_timestamp": self.ptz_metrics[
camera
].stop_time.value,
} }
) )
+92 -56
View File
@@ -72,7 +72,11 @@ class OnvifController:
self.config_subscriber = CameraConfigUpdateSubscriber( self.config_subscriber = CameraConfigUpdateSubscriber(
self.config, self.config,
self.config.cameras, self.config.cameras,
[CameraConfigUpdateEnum.onvif], [
CameraConfigUpdateEnum.onvif,
CameraConfigUpdateEnum.add,
CameraConfigUpdateEnum.remove,
],
) )
asyncio.run_coroutine_threadsafe(self._init_cameras(), self.loop) asyncio.run_coroutine_threadsafe(self._init_cameras(), self.loop)
@@ -101,6 +105,16 @@ class OnvifController:
if update_type == CameraConfigUpdateEnum.onvif.name: if update_type == CameraConfigUpdateEnum.onvif.name:
for cam_name in cameras: for cam_name in cameras:
await self._reinit_camera(cam_name) await self._reinit_camera(cam_name)
elif update_type == CameraConfigUpdateEnum.add.name:
# a camera added at runtime only needs ONVIF set up if
# it actually has an onvif host configured
for cam_name in cameras:
cam = self.config.cameras.get(cam_name)
if cam and cam.onvif.host:
await self._reinit_camera(cam_name)
elif update_type == CameraConfigUpdateEnum.remove.name:
for cam_name in cameras:
await self._remove_camera(cam_name)
except Exception: except Exception:
logger.error("Error checking for ONVIF config updates") logger.error("Error checking for ONVIF config updates")
@@ -113,6 +127,18 @@ class OnvifController:
except Exception: except Exception:
logger.debug(f"Error closing ONVIF session for {cam_name}") logger.debug(f"Error closing ONVIF session for {cam_name}")
async def _remove_camera(self, cam_name: str) -> None:
"""Tear down the ONVIF session for a camera removed at runtime."""
if cam_name not in self.cams and cam_name not in self.camera_configs:
return
logger.debug(f"Tearing down ONVIF for {cam_name} after camera removal")
await self._close_camera(cam_name)
self.cams.pop(cam_name, None)
self.camera_configs.pop(cam_name, None)
self.failed_cams.pop(cam_name, None)
self.status_locks.pop(cam_name, None)
async def _reinit_camera(self, cam_name: str) -> None: async def _reinit_camera(self, cam_name: str) -> None:
"""Re-initialize a camera after config change.""" """Re-initialize a camera after config change."""
logger.info(f"Re-initializing ONVIF for {cam_name} due to config change") logger.info(f"Re-initializing ONVIF for {cam_name} due to config change")
@@ -180,6 +206,11 @@ class OnvifController:
return False return False
async def _init_onvif(self, camera_name: str) -> bool: async def _init_onvif(self, camera_name: str) -> bool:
camera_config = self.config.cameras.get(camera_name)
if camera_config is None:
return False
onvif: ONVIFCamera = self.cams[camera_name]["onvif"] onvif: ONVIFCamera = self.cams[camera_name]["onvif"]
try: try:
await onvif.update_xaddrs() await onvif.update_xaddrs()
@@ -235,7 +266,7 @@ class OnvifController:
p.token, p.token,
) )
configured_profile = self.config.cameras[camera_name].onvif.profile configured_profile = camera_config.onvif.profile
profile = None profile = None
if configured_profile is not None: if configured_profile is not None:
@@ -339,7 +370,7 @@ class OnvifController:
except (AttributeError, TypeError): except (AttributeError, TypeError):
fov_space_id = None fov_space_id = None
autotracking_config = self.config.cameras[camera_name].onvif.autotracking autotracking_config = camera_config.onvif.autotracking
autotracking_enabled = ( autotracking_enabled = (
autotracking_config.enabled_in_config and autotracking_config.enabled autotracking_config.enabled_in_config and autotracking_config.enabled
) )
@@ -614,6 +645,11 @@ class OnvifController:
logger.error(f"{camera_name} does not support ONVIF RelativeMove (FOV).") logger.error(f"{camera_name} does not support ONVIF RelativeMove (FOV).")
return return
metrics = self.ptz_metrics.get(camera_name)
if metrics is None:
return
logger.debug( logger.debug(
f"{camera_name} called RelativeMove: pan: {pan} tilt: {tilt} zoom: {zoom}" f"{camera_name} called RelativeMove: pan: {pan} tilt: {tilt} zoom: {zoom}"
) )
@@ -627,15 +663,11 @@ class OnvifController:
self.cams[camera_name]["active"] = True self.cams[camera_name]["active"] = True
# only track start_time for autotracking # only track start_time for autotracking
if self.ptz_metrics[camera_name].autotracker_enabled.value: if metrics.autotracker_enabled.value:
self.ptz_metrics[camera_name].motor_stopped.clear() metrics.motor_stopped.clear()
logger.debug( logger.debug(f"{camera_name}: PTZ start time: {metrics.frame_time.value}")
f"{camera_name}: PTZ start time: {self.ptz_metrics[camera_name].frame_time.value}" metrics.start_time.value = metrics.frame_time.value
) metrics.stop_time.value = 0
self.ptz_metrics[camera_name].start_time.value = self.ptz_metrics[
camera_name
].frame_time.value
self.ptz_metrics[camera_name].stop_time.value = 0
move_request = self.cams[camera_name]["relative_move_request"] move_request = self.cams[camera_name]["relative_move_request"]
@@ -697,9 +729,14 @@ class OnvifController:
logger.error(f"{preset} is not a valid preset for {camera_name}") logger.error(f"{preset} is not a valid preset for {camera_name}")
return return
metrics = self.ptz_metrics.get(camera_name)
if metrics is None:
return
self.cams[camera_name]["active"] = True self.cams[camera_name]["active"] = True
self.ptz_metrics[camera_name].start_time.value = 0 metrics.start_time.value = 0
self.ptz_metrics[camera_name].stop_time.value = 0 metrics.stop_time.value = 0
move_request = self.cams[camera_name]["move_request"] move_request = self.cams[camera_name]["move_request"]
preset_token = self.cams[camera_name]["presets"][preset] preset_token = self.cams[camera_name]["presets"][preset]
@@ -738,6 +775,11 @@ class OnvifController:
logger.error(f"{camera_name} does not support ONVIF AbsoluteMove zooming.") logger.error(f"{camera_name} does not support ONVIF AbsoluteMove zooming.")
return return
metrics = self.ptz_metrics.get(camera_name)
if metrics is None:
return
logger.debug(f"{camera_name} called AbsoluteMove: zoom: {zoom}") logger.debug(f"{camera_name} called AbsoluteMove: zoom: {zoom}")
if self.cams[camera_name]["active"]: if self.cams[camera_name]["active"]:
@@ -747,14 +789,10 @@ class OnvifController:
return return
self.cams[camera_name]["active"] = True self.cams[camera_name]["active"] = True
self.ptz_metrics[camera_name].motor_stopped.clear() metrics.motor_stopped.clear()
logger.debug( logger.debug(f"{camera_name}: PTZ start time: {metrics.frame_time.value}")
f"{camera_name}: PTZ start time: {self.ptz_metrics[camera_name].frame_time.value}" metrics.start_time.value = metrics.frame_time.value
) metrics.stop_time.value = 0
self.ptz_metrics[camera_name].start_time.value = self.ptz_metrics[
camera_name
].frame_time.value
self.ptz_metrics[camera_name].stop_time.value = 0
move_request = self.cams[camera_name]["absolute_move_request"] move_request = self.cams[camera_name]["absolute_move_request"]
# function takes in 0 to 1 for zoom, interpolate to the values of the camera. # function takes in 0 to 1 for zoom, interpolate to the values of the camera.
@@ -875,16 +913,18 @@ class OnvifController:
Returns camera details including features and presets if available. Returns camera details including features and presets if available.
""" """
if not self.config.cameras[camera_name].enabled: camera_config = self.config.cameras.get(camera_name)
if camera_config is None:
return {}
if not camera_config.enabled:
logger.debug( logger.debug(
f"Camera {camera_name} disabled, won't try to initialize ONVIF" f"Camera {camera_name} disabled, won't try to initialize ONVIF"
) )
return {} return {}
if camera_name not in self.cams.keys() and ( if camera_name not in self.cams.keys() and (not camera_config.onvif.host):
camera_name not in self.config.cameras
or not self.config.cameras[camera_name].onvif.host
):
logger.debug(f"ONVIF is not configured for {camera_name}") logger.debug(f"ONVIF is not configured for {camera_name}")
return {} return {}
@@ -985,6 +1025,12 @@ class OnvifController:
logger.error(f"ONVIF is not configured for {camera_name}") logger.error(f"ONVIF is not configured for {camera_name}")
return return
metrics = self.ptz_metrics.get(camera_name)
camera_config = self.config.cameras.get(camera_name)
if metrics is None or camera_config is None:
return
if not self.cams[camera_name]["init"]: if not self.cams[camera_name]["init"]:
if not await self._init_onvif(camera_name): if not await self._init_onvif(camera_name):
return return
@@ -1023,36 +1069,29 @@ class OnvifController:
zoom_status is None or zoom_status == "IDLE" zoom_status is None or zoom_status == "IDLE"
): ):
self.cams[camera_name]["active"] = False self.cams[camera_name]["active"] = False
if not self.ptz_metrics[camera_name].motor_stopped.is_set(): if not metrics.motor_stopped.is_set():
self.ptz_metrics[camera_name].motor_stopped.set() metrics.motor_stopped.set()
logger.debug( logger.debug(
f"{camera_name}: PTZ stop time: {self.ptz_metrics[camera_name].frame_time.value}" f"{camera_name}: PTZ stop time: {metrics.frame_time.value}"
) )
self.ptz_metrics[camera_name].stop_time.value = self.ptz_metrics[ metrics.stop_time.value = metrics.frame_time.value
camera_name
].frame_time.value
else: else:
self.cams[camera_name]["active"] = True self.cams[camera_name]["active"] = True
if self.ptz_metrics[camera_name].motor_stopped.is_set(): if metrics.motor_stopped.is_set():
self.ptz_metrics[camera_name].motor_stopped.clear() metrics.motor_stopped.clear()
logger.debug( logger.debug(
f"{camera_name}: PTZ start time: {self.ptz_metrics[camera_name].frame_time.value}" f"{camera_name}: PTZ start time: {metrics.frame_time.value}"
) )
self.ptz_metrics[camera_name].start_time.value = self.ptz_metrics[ metrics.start_time.value = metrics.frame_time.value
camera_name metrics.stop_time.value = 0
].frame_time.value
self.ptz_metrics[camera_name].stop_time.value = 0
if ( if camera_config.onvif.autotracking.zooming != ZoomingModeEnum.disabled:
self.config.cameras[camera_name].onvif.autotracking.zooming
!= ZoomingModeEnum.disabled
):
# store absolute zoom level as 0 to 1 interpolated from the values of the camera # store absolute zoom level as 0 to 1 interpolated from the values of the camera
self.ptz_metrics[camera_name].zoom_level.value = numpy.interp( metrics.zoom_level.value = numpy.interp(
round(status.Position.Zoom.x, 2), round(status.Position.Zoom.x, 2),
[ [
self.cams[camera_name]["absolute_zoom_range"]["XRange"]["Min"], self.cams[camera_name]["absolute_zoom_range"]["XRange"]["Min"],
@@ -1061,25 +1100,22 @@ class OnvifController:
[0, 1], [0, 1],
) )
logger.debug( logger.debug(
f"{camera_name}: Camera zoom level: {self.ptz_metrics[camera_name].zoom_level.value}" f"{camera_name}: Camera zoom level: {metrics.zoom_level.value}"
) )
# some hikvision cams won't update MoveStatus, so warn if it hasn't changed # some hikvision cams won't update MoveStatus, so warn if it hasn't changed
if ( if (
not self.ptz_metrics[camera_name].motor_stopped.is_set() not metrics.motor_stopped.is_set()
and not self.ptz_metrics[camera_name].reset.is_set() and not metrics.reset.is_set()
and self.ptz_metrics[camera_name].start_time.value != 0 and metrics.start_time.value != 0
and self.ptz_metrics[camera_name].frame_time.value and metrics.frame_time.value > (metrics.start_time.value + 10)
> (self.ptz_metrics[camera_name].start_time.value + 10) and metrics.stop_time.value == 0
and self.ptz_metrics[camera_name].stop_time.value == 0
): ):
logger.debug( logger.debug(
f"Start time: {self.ptz_metrics[camera_name].start_time.value}, Stop time: {self.ptz_metrics[camera_name].stop_time.value}, Frame time: {self.ptz_metrics[camera_name].frame_time.value}" f"Start time: {metrics.start_time.value}, Stop time: {metrics.stop_time.value}, Frame time: {metrics.frame_time.value}"
) )
# set the stop time so we don't come back into this again and spam the logs # set the stop time so we don't come back into this again and spam the logs
self.ptz_metrics[camera_name].stop_time.value = self.ptz_metrics[ metrics.stop_time.value = metrics.frame_time.value
camera_name
].frame_time.value
logger.warning( logger.warning(
f"Camera {camera_name} is still in ONVIF 'MOVING' status." f"Camera {camera_name} is still in ONVIF 'MOVING' status."
) )
+135 -30
View File
@@ -12,7 +12,14 @@ from typing import Any
from playhouse.sqlite_ext import SqliteExtDatabase from playhouse.sqlite_ext import SqliteExtDatabase
from frigate.config import CameraConfig, FrigateConfig, RetainModeEnum from frigate.config import CameraConfig, FrigateConfig, RetainModeEnum
from frigate.const import CACHE_DIR, CLIPS_DIR, MAX_WAL_SIZE, RECORD_DIR from frigate.const import (
CACHE_DIR,
CLIPS_DIR,
MAX_WAL_SIZE,
RECORD_DIR,
STREAM_TYPE_MAIN,
STREAM_TYPE_SUB,
)
from frigate.models import Previews, Recordings, ReviewSegment, UserReviewStatus from frigate.models import Previews, Recordings, ReviewSegment, UserReviewStatus
from frigate.util.builtin import clear_and_unlink from frigate.util.builtin import clear_and_unlink
from frigate.util.media import remove_empty_directories from frigate.util.media import remove_empty_directories
@@ -20,6 +27,29 @@ from frigate.util.media import remove_empty_directories
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def _filter_reviews_for_pass(
reviews: list[Any],
now: datetime.datetime,
alerts_days: float,
detections_days: float,
) -> list[Any]:
"""Limit reviews to those still within this pass's per-severity retention window.
Review rows survive to the longer of the main and sub retention windows,
so a pass that honored all of them would let extended sub retention keep
main recordings alive too. Filtering preserves sort order for the overlap
loop in expire_existing_camera_recordings.
"""
alert_cutoff = (now - datetime.timedelta(days=alerts_days)).timestamp()
detection_cutoff = (now - datetime.timedelta(days=detections_days)).timestamp()
return [
r
for r in reviews
if r.end_time is None
or (r.end_time >= (alert_cutoff if r.severity == "alert" else detection_cutoff))
]
class RecordingCleanup(threading.Thread): class RecordingCleanup(threading.Thread):
"""Cleanup existing recordings based on retention config.""" """Cleanup existing recordings based on retention config."""
@@ -65,11 +95,14 @@ class RecordingCleanup(threading.Thread):
self, config: CameraConfig, now: datetime.datetime self, config: CameraConfig, now: datetime.datetime
) -> set[Path]: ) -> set[Path]:
"""Delete review segments that are expired""" """Delete review segments that are expired"""
alert_expire_date = ( # review rows survive to the longer of the main and sub windows so
now - datetime.timedelta(days=config.record.alerts.retain.days) # they stay visible while either stream still has recordings
).timestamp() alert_days = config.record.effective_alert_days
detection_days = config.record.effective_detection_days
alert_expire_date = (now - datetime.timedelta(days=alert_days)).timestamp()
detection_expire_date = ( detection_expire_date = (
now - datetime.timedelta(days=config.record.detections.retain.days) now - datetime.timedelta(days=detection_days)
).timestamp() ).timestamp()
expired_reviews = ( expired_reviews = (
ReviewSegment.select(ReviewSegment.id, ReviewSegment.thumb_path) ReviewSegment.select(ReviewSegment.id, ReviewSegment.thumb_path)
@@ -109,8 +142,11 @@ class RecordingCleanup(threading.Thread):
def expire_existing_camera_recordings( def expire_existing_camera_recordings(
self, self,
stream_type: str,
continuous_expire_date: float, continuous_expire_date: float,
motion_expire_date: float, motion_expire_date: float,
alerts_retain_mode: RetainModeEnum,
detections_retain_mode: RetainModeEnum,
config: CameraConfig, config: CameraConfig,
reviews: list[Any], reviews: list[Any],
) -> set[Path]: ) -> set[Path]:
@@ -130,6 +166,11 @@ class RecordingCleanup(threading.Thread):
) )
.where( .where(
(Recordings.camera == config.name) (Recordings.camera == config.name)
& (Recordings.stream_type == stream_type)
& (
Recordings.start_time
< max(continuous_expire_date, motion_expire_date)
)
& ( & (
( (
(Recordings.end_time < continuous_expire_date) (Recordings.end_time < continuous_expire_date)
@@ -175,9 +216,9 @@ class RecordingCleanup(threading.Thread):
): ):
keep = True keep = True
mode = ( mode = (
config.record.alerts.retain.mode alerts_retain_mode
if review.severity == "alert" if review.severity == "alert"
else config.record.detections.retain.mode else detections_retain_mode
) )
break break
@@ -216,6 +257,10 @@ class RecordingCleanup(threading.Thread):
Recordings.id << deleted_recordings_list[i : i + max_deletes] Recordings.id << deleted_recordings_list[i : i + max_deletes]
).execute() ).execute()
# previews follow main retention, so only the main pass expires them
if stream_type != STREAM_TYPE_MAIN:
return maybe_empty_dirs
previews = ( previews = (
Previews.select( Previews.select(
Previews.id, Previews.id,
@@ -292,27 +337,45 @@ class RecordingCleanup(threading.Thread):
expire_before = ( expire_before = (
datetime.datetime.now() - datetime.timedelta(days=expire_days) datetime.datetime.now() - datetime.timedelta(days=expire_days)
).timestamp() ).timestamp()
no_camera_recordings = (
Recordings.select( # enumerate the distinct cameras with one index seek each
Recordings.id, db_cameras: list[str] = []
Recordings.path, last_camera: str | None = None
) while True:
.where( query = Recordings.select(Recordings.camera)
Recordings.camera.not_in(list(self.config.cameras.keys())), # type: ignore[call-arg, arg-type, misc] if last_camera is not None:
Recordings.end_time < expire_before, query = query.where(Recordings.camera > last_camera)
) next_camera = query.order_by(Recordings.camera.asc()).limit(1).scalar()
.namedtuples() if next_camera is None:
.iterator() break
) db_cameras.append(next_camera)
last_camera = next_camera
maybe_empty_dirs = set() maybe_empty_dirs = set()
deleted_recordings = set() deleted_recordings = set()
for recording in no_camera_recordings: for camera in db_cameras:
recording_path = Path(recording.path) if camera in self.config.cameras:
recording_path.unlink(missing_ok=True) continue
deleted_recordings.add(recording.id)
maybe_empty_dirs.add(recording_path.parent) no_camera_recordings = (
Recordings.select(
Recordings.id,
Recordings.path,
)
.where(
Recordings.camera == camera,
Recordings.end_time < expire_before,
)
.namedtuples()
.iterator()
)
for recording in no_camera_recordings:
recording_path = Path(recording.path)
recording_path.unlink(missing_ok=True)
deleted_recordings.add(recording.id)
maybe_empty_dirs.add(recording_path.parent)
logger.debug(f"Expiring {len(deleted_recordings)} recordings") logger.debug(f"Expiring {len(deleted_recordings)} recordings")
# delete up to 100,000 at a time # delete up to 100,000 at a time
@@ -342,6 +405,20 @@ class RecordingCleanup(threading.Thread):
) )
).timestamp() ).timestamp()
# computed here so the reviews window below covers both passes
sub_continuous_expire_date = (
now - datetime.timedelta(days=config.record.sub.continuous.days)
).timestamp()
sub_motion_expire_date = (
now
- datetime.timedelta(
days=max(
config.record.sub.motion.days,
config.record.sub.continuous.days,
) # can't keep motion for less than continuous
)
).timestamp()
# Get all the reviews to check against # Get all the reviews to check against
reviews = ( reviews = (
ReviewSegment.select( ReviewSegment.select(
@@ -351,18 +428,46 @@ class RecordingCleanup(threading.Thread):
) )
.where( .where(
ReviewSegment.camera == camera, ReviewSegment.camera == camera,
# candidate recordings can extend up to continuous_expire_date # candidate recordings reach the later of the two passes'
# (the no-motion no-audio branch of the recordings query), # continuous cutoffs, so reviews must cover that whole
# so reviews must cover that full range to avoid deleting # range or segments overlapping recent alerts get deleted
# segments that overlap recent alerts/detections. ReviewSegment.start_time
ReviewSegment.start_time < continuous_expire_date, < max(continuous_expire_date, sub_continuous_expire_date),
) )
.order_by(ReviewSegment.start_time) .order_by(ReviewSegment.start_time)
.namedtuples() .namedtuples()
) )
maybe_empty_dirs |= self.expire_existing_camera_recordings( maybe_empty_dirs |= self.expire_existing_camera_recordings(
continuous_expire_date, motion_expire_date, config, reviews STREAM_TYPE_MAIN,
continuous_expire_date,
motion_expire_date,
config.record.alerts.retain.mode,
config.record.detections.retain.mode,
config,
_filter_reviews_for_pass(
reviews,
now,
config.record.alerts.retain.days,
config.record.detections.retain.days,
),
)
# runs even when sub recording is disabled so old rows still
# expire
maybe_empty_dirs |= self.expire_existing_camera_recordings(
STREAM_TYPE_SUB,
sub_continuous_expire_date,
sub_motion_expire_date,
config.record.sub.alerts.mode,
config.record.sub.detections.mode,
config,
_filter_reviews_for_pass(
reviews,
now,
config.record.sub.alerts.days,
config.record.sub.detections.days,
),
) )
logger.debug(f"End camera: {camera}.") logger.debug(f"End camera: {camera}.")
+38 -30
View File
@@ -12,6 +12,7 @@ import threading
from collections.abc import Callable from collections.abc import Callable
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from typing import Any
import pytz # type: ignore[import-untyped] import pytz # type: ignore[import-untyped]
from peewee import DoesNotExist from peewee import DoesNotExist
@@ -24,6 +25,8 @@ from frigate.const import (
EXPORT_DIR, EXPORT_DIR,
MAX_PLAYLIST_SECONDS, MAX_PLAYLIST_SECONDS,
PREVIEW_FRAME_TYPE, PREVIEW_FRAME_TYPE,
STREAM_TYPE_MAIN,
STREAM_TYPE_SUB,
) )
from frigate.ffmpeg_presets import ( from frigate.ffmpeg_presets import (
EncodeTypeEnum, EncodeTypeEnum,
@@ -283,6 +286,29 @@ class RecordingExporter(threading.Thread):
return input_duration * factor return input_duration * factor
def _get_recordings_for_range(self, stream_type: str) -> list[Any]:
"""Fetch one stream type's recording rows overlapping the export range."""
return list(
Recordings.select(
Recordings.start_time,
Recordings.end_time,
)
.where(
Recordings.start_time.between(self.start_time, self.end_time)
| Recordings.end_time.between(self.start_time, self.end_time)
| (
(self.start_time > Recordings.start_time)
& (self.end_time < Recordings.end_time)
)
)
.where(
(Recordings.camera == self.camera)
& (Recordings.stream_type == stream_type)
)
.order_by(Recordings.start_time.asc())
.iterator()
)
def _sum_source_duration_seconds(self) -> float | None: def _sum_source_duration_seconds(self) -> float | None:
"""Sum saved-video seconds inside [start_time, end_time]. """Sum saved-video seconds inside [start_time, end_time].
@@ -293,19 +319,12 @@ class RecordingExporter(threading.Thread):
""" """
try: try:
if self.playback_source == PlaybackSourceEnum.recordings: if self.playback_source == PlaybackSourceEnum.recordings:
rows = ( # never mix streams in one estimate; use main when available
Recordings.select(Recordings.start_time, Recordings.end_time) # and fall back to sub for expired-main history
.where( rows = self._get_recordings_for_range(STREAM_TYPE_MAIN)
Recordings.start_time.between(self.start_time, self.end_time)
| Recordings.end_time.between(self.start_time, self.end_time) if not rows:
| ( rows = self._get_recordings_for_range(STREAM_TYPE_SUB)
(self.start_time > Recordings.start_time)
& (self.end_time < Recordings.end_time)
)
)
.where(Recordings.camera == self.camera)
.iterator()
)
else: else:
rows = ( rows = (
Previews.select(Previews.start_time, Previews.end_time) Previews.select(Previews.start_time, Previews.end_time)
@@ -691,23 +710,12 @@ class RecordingExporter(threading.Thread):
if type(internal_port) is str: if type(internal_port) is str:
internal_port = int(internal_port.split(":")[-1]) internal_port = int(internal_port.split(":")[-1])
recordings = list( # never mix streams in one playlist; use main when available and
Recordings.select( # fall back to sub for expired-main history
Recordings.start_time, recordings = self._get_recordings_for_range(STREAM_TYPE_MAIN)
Recordings.end_time,
) if not recordings:
.where( recordings = self._get_recordings_for_range(STREAM_TYPE_SUB)
Recordings.start_time.between(self.start_time, self.end_time)
| Recordings.end_time.between(self.start_time, self.end_time)
| (
(self.start_time > Recordings.start_time)
& (self.end_time < Recordings.end_time)
)
)
.where(Recordings.camera == self.camera)
.order_by(Recordings.start_time.asc())
.iterator()
)
playlist_lines: list[str] = [] playlist_lines: list[str] = []
if (self.end_time - self.start_time) <= MAX_PLAYLIST_SECONDS: if (self.end_time - self.start_time) <= MAX_PLAYLIST_SECONDS:
+342 -89
View File
@@ -15,6 +15,7 @@ from typing import Any
import numpy as np import numpy as np
import psutil import psutil
from peewee import fn
from frigate.comms.detections_updater import DetectionSubscriber, DetectionTypeEnum from frigate.comms.detections_updater import DetectionSubscriber, DetectionTypeEnum
from frigate.comms.inter_process import InterProcessRequestor from frigate.comms.inter_process import InterProcessRequestor
@@ -35,15 +36,48 @@ from frigate.const import (
MAX_SEGMENT_DURATION, MAX_SEGMENT_DURATION,
MAX_SEGMENTS_IN_CACHE, MAX_SEGMENTS_IN_CACHE,
RECORD_DIR, RECORD_DIR,
STREAM_TYPE_MAIN,
STREAM_TYPE_SUB,
SUB_CACHE_TAG,
) )
from frigate.models import Recordings, ReviewSegment from frigate.models import Recordings, ReviewSegment
from frigate.review.types import SeverityEnum from frigate.review.types import SeverityEnum
from frigate.util.media import get_keyframe_offsets
from frigate.util.services import get_video_properties from frigate.util.services import get_video_properties
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
STALE_RECORDINGS_INFO_TTL = MAX_SEGMENTS_IN_CACHE * MAX_SEGMENT_DURATION * 2 STALE_RECORDINGS_INFO_TTL = MAX_SEGMENTS_IN_CACHE * MAX_SEGMENT_DURATION * 2
# cache filenames have whole-second resolution, so a contiguous segment's
# parsed start lands up to 1s before the previous segment's true end
SEGMENT_CHAIN_TOLERANCE_S = 1.0
# against an mtime-measured start, disagreement beyond this means
# accumulated probe-duration error and the chain re-anchors on the mtime
SEGMENT_CHAIN_DRIFT_LIMIT_S = 0.5
# probing every cached segment at once starves the camera and detection
# processes, and the probes then blow their own timeouts together, so
# segments get discarded as corrupt and the record watchdog restarts ffmpeg
MAX_CONCURRENT_SEGMENT_PROBES = 4
def parse_cache_segment_name(basename: str) -> tuple[str, str, str] | None:
"""Parse a cache segment basename into (camera, stream_type, date).
Main segments are named {camera}@{date}; sub segments {camera}@sub@{date}.
"""
try:
prefix, date = basename.rsplit("@", maxsplit=1)
except ValueError:
return None
if prefix.endswith(SUB_CACHE_TAG):
return (prefix[: -len(SUB_CACHE_TAG)], STREAM_TYPE_SUB, date)
return (prefix, STREAM_TYPE_MAIN, date)
class SegmentInfo: class SegmentInfo:
def __init__( def __init__(
@@ -83,6 +117,10 @@ class SegmentInfo:
class RecordingMaintainer(threading.Thread): class RecordingMaintainer(threading.Thread):
# move_files replaces this per cycle: an asyncio primitive binds to the
# first event loop that contends it, and every cycle runs in a new loop
probe_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEGMENT_PROBES)
def __init__(self, config: FrigateConfig, stop_event: MpEvent): def __init__(self, config: FrigateConfig, stop_event: MpEvent):
super().__init__(name="recording_maintainer") super().__init__(name="recording_maintainer")
self.config = config self.config = config
@@ -100,10 +138,101 @@ class RecordingMaintainer(threading.Thread):
self.stop_event = stop_event self.stop_event = stop_event
self.object_recordings_info: dict[str, list] = defaultdict(list) self.object_recordings_info: dict[str, list] = defaultdict(list)
self.audio_recordings_info: dict[str, list] = defaultdict(list) self.audio_recordings_info: dict[str, list] = defaultdict(list)
self.end_time_cache: dict[str, tuple[datetime.datetime, float]] = {} # cache_path -> (end_time, duration, has_audio, audio_rate,
# audio_codec, video_codec, keyframes)
self.end_time_cache: dict[
str,
tuple[
datetime.datetime,
float,
bool | None,
int | None,
str | None,
str | None,
list[int] | None,
],
] = {}
# last known capture end per (camera, stream_type); 0.0 marks a key
# whose DB seed found no rows
self.last_segment_end: dict[tuple[str, str], float] = {}
self.unexpected_cache_files_logged: bool = False self.unexpected_cache_files_logged: bool = False
def _get_last_segment_end(self, camera: str, stream_type: str) -> float | None:
"""Return the last known capture end time for a camera stream.
Lazily seeds from the most recent stored recording so start-time
chains survive restarts.
"""
key = (camera, stream_type)
if key not in self.last_segment_end:
last_db_end = (
Recordings.select(fn.MAX(Recordings.end_time))
.where(
Recordings.camera == camera,
Recordings.stream_type == stream_type,
)
.scalar()
)
# the 0.0 sentinel keeps the seed query from repeating
self.last_segment_end[key] = last_db_end if last_db_end is not None else 0.0
return self.last_segment_end[key] or None
def _resolve_segment_start(
self,
camera: str,
stream_type: str,
filename_start: datetime.datetime,
duration: float,
cache_path: str,
) -> datetime.datetime:
"""Resolve a segment's true start time from its cache file.
Cache filenames carry whole-second resolution, so the parsed start
sits up to 1s early. The cache file's mtime is the wall clock when
ffmpeg rolled the segment, so mtime minus the probed duration
restores the fractional start. Contiguous segments still chain to
the previous segment's end so rows stay exactly adjacent.
"""
filename_ts = filename_start.timestamp()
measured: float | None = None
try:
mtime = os.path.getmtime(cache_path)
except OSError:
mtime = None
if mtime is not None:
candidate = mtime - duration
# media shorter than its wall span (a stalled stream, an early
# close) derives a start past the truncation window, where the
# floored filename start is safer
if 0 <= candidate - filename_ts < SEGMENT_CHAIN_TOLERANCE_S:
measured = candidate
last_end = self._get_last_segment_end(camera, stream_type)
if measured is not None:
if (
last_end is not None
and abs(last_end - measured) < SEGMENT_CHAIN_DRIFT_LIMIT_S
):
return datetime.datetime.fromtimestamp(last_end, tz=datetime.UTC)
return datetime.datetime.fromtimestamp(measured, tz=datetime.UTC)
# no usable mtime: capture is continuous within a run, so a
# filename start just before the previous end chains to that end
if (
last_end is not None
and 0 <= last_end - filename_ts < SEGMENT_CHAIN_TOLERANCE_S
):
return datetime.datetime.fromtimestamp(last_end, tz=datetime.UTC)
return filename_start
async def move_files(self) -> None: async def move_files(self) -> None:
self.probe_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEGMENT_PROBES)
cache_files = [ cache_files = [
d d
for d in os.listdir(CACHE_DIR) for d in os.listdir(CACHE_DIR)
@@ -117,13 +246,17 @@ class RecordingMaintainer(threading.Thread):
for cache in cache_files: for cache in cache_files:
cache_path = os.path.join(CACHE_DIR, cache) cache_path = os.path.join(CACHE_DIR, cache)
basename = os.path.splitext(cache)[0] basename = os.path.splitext(cache)[0]
try: parsed = parse_cache_segment_name(basename)
camera, date = basename.rsplit("@", maxsplit=1) if parsed is None:
except ValueError:
if not self.unexpected_cache_files_logged: if not self.unexpected_cache_files_logged:
logger.warning("Skipping unexpected files in cache") logger.warning("Skipping unexpected files in cache")
self.unexpected_cache_files_logged = True self.unexpected_cache_files_logged = True
continue continue
camera, stream_type, date = parsed
# this topic feeds main-stream health/sync consumers only
if stream_type == STREAM_TYPE_SUB:
continue
start_time = datetime.datetime.strptime( start_time = datetime.datetime.strptime(
date, CACHE_SEGMENT_FORMAT date, CACHE_SEGMENT_FORMAT
@@ -167,8 +300,10 @@ class RecordingMaintainer(threading.Thread):
except psutil.Error: except psutil.Error:
continue continue
# group recordings by camera (skip in-use for validation/moving) # group recordings by camera and stream type (skip in-use for validation/moving)
grouped_recordings: defaultdict[str, list[dict[str, Any]]] = defaultdict(list) grouped_recordings: defaultdict[tuple[str, str], list[dict[str, Any]]] = (
defaultdict(list)
)
for cache in cache_files: for cache in cache_files:
# Skip files currently in use # Skip files currently in use
if cache in files_in_use: if cache in files_in_use:
@@ -176,32 +311,35 @@ class RecordingMaintainer(threading.Thread):
cache_path = os.path.join(CACHE_DIR, cache) cache_path = os.path.join(CACHE_DIR, cache)
basename = os.path.splitext(cache)[0] basename = os.path.splitext(cache)[0]
try: parsed = parse_cache_segment_name(basename)
camera, date = basename.rsplit("@", maxsplit=1) if parsed is None:
except ValueError:
if not self.unexpected_cache_files_logged: if not self.unexpected_cache_files_logged:
logger.warning("Skipping unexpected files in cache") logger.warning("Skipping unexpected files in cache")
self.unexpected_cache_files_logged = True self.unexpected_cache_files_logged = True
continue continue
camera, stream_type, date = parsed
# important that start_time is utc because recordings are stored and compared in utc # important that start_time is utc because recordings are stored and compared in utc
start_time = datetime.datetime.strptime( start_time = datetime.datetime.strptime(
date, CACHE_SEGMENT_FORMAT date, CACHE_SEGMENT_FORMAT
).astimezone(datetime.UTC) ).astimezone(datetime.UTC)
grouped_recordings[camera].append( grouped_recordings[(camera, stream_type)].append(
{ {
"cache_path": cache_path, "cache_path": cache_path,
"start_time": start_time, "start_time": start_time,
"stream_type": stream_type,
} }
) )
# delete all cached files past the most recent MAX_SEGMENTS_IN_CACHE # delete all cached files past the most recent MAX_SEGMENTS_IN_CACHE
keep_count = MAX_SEGMENTS_IN_CACHE keep_count = MAX_SEGMENTS_IN_CACHE
for camera in grouped_recordings.keys(): for key in grouped_recordings.keys():
camera, stream_type = key
# sort based on start time # sort based on start time
grouped_recordings[camera] = sorted( grouped_recordings[key] = sorted(
grouped_recordings[camera], key=lambda s: s["start_time"] grouped_recordings[key], key=lambda s: s["start_time"]
) )
camera_info = self.object_recordings_info[camera] camera_info = self.object_recordings_info[camera]
@@ -216,7 +354,7 @@ class RecordingMaintainer(threading.Thread):
r["start_time"].timestamp() r["start_time"].timestamp()
< most_recently_processed_frame_time < most_recently_processed_frame_time
), ),
grouped_recordings[camera], grouped_recordings[key],
) )
) )
) )
@@ -226,103 +364,133 @@ class RecordingMaintainer(threading.Thread):
logger.warning( logger.warning(
f"Unable to keep up with recording segments in cache for {camera}. Keeping the {keep_count} most recent segments out of {processed_segment_count} and discarding the rest..." f"Unable to keep up with recording segments in cache for {camera}. Keeping the {keep_count} most recent segments out of {processed_segment_count} and discarding the rest..."
) )
to_remove = grouped_recordings[camera][:-keep_count] to_remove = grouped_recordings[key][:-keep_count]
for rec in to_remove: for rec in to_remove:
cache_path = rec["cache_path"] cache_path = rec["cache_path"]
Path(cache_path).unlink(missing_ok=True) Path(cache_path).unlink(missing_ok=True)
self.end_time_cache.pop(cache_path, None) self.end_time_cache.pop(cache_path, None)
grouped_recordings[camera] = grouped_recordings[camera][-keep_count:] grouped_recordings[key] = grouped_recordings[key][-keep_count:]
# see if detection has failed and unprocessed segments need to be deleted # see if detection has failed and unprocessed segments need to be deleted
unprocessed_segment_count = ( unprocessed_segment_count = (
len(grouped_recordings[camera]) - processed_segment_count len(grouped_recordings[key]) - processed_segment_count
) )
if unprocessed_segment_count > keep_count: if unprocessed_segment_count > keep_count:
logger.warning( logger.warning(
f"Too many unprocessed recording segments in cache for {camera}. This likely indicates an issue with the detect stream, keeping the {keep_count} most recent segments out of {unprocessed_segment_count} and discarding the rest..." f"Too many unprocessed recording segments in cache for {camera}. This likely indicates an issue with the detect stream, keeping the {keep_count} most recent segments out of {unprocessed_segment_count} and discarding the rest..."
) )
to_remove = grouped_recordings[camera][:-keep_count] to_remove = grouped_recordings[key][:-keep_count]
for rec in to_remove: for rec in to_remove:
cache_path = rec["cache_path"] cache_path = rec["cache_path"]
Path(cache_path).unlink(missing_ok=True) Path(cache_path).unlink(missing_ok=True)
self.end_time_cache.pop(cache_path, None) self.end_time_cache.pop(cache_path, None)
grouped_recordings[camera] = grouped_recordings[camera][-keep_count:] grouped_recordings[key] = grouped_recordings[key][-keep_count:]
tasks = [] # frame stats are shared per camera across stream types, so trimming
for camera, recordings in grouped_recordings.items(): # to one stream's oldest cache would pop frames the other still needs
min_start_per_camera: dict[str, float] = {}
for key, recordings in grouped_recordings.items():
camera, _ = key
oldest_start = recordings[0]["start_time"].timestamp()
if (
camera not in min_start_per_camera
or oldest_start < min_start_per_camera[camera]
):
min_start_per_camera[camera] = oldest_start
for camera, min_start in min_start_per_camera.items():
# clear out all the object recording info for old frames # clear out all the object recording info for old frames
while ( while (
len(self.object_recordings_info[camera]) > 0 len(self.object_recordings_info[camera]) > 0
and self.object_recordings_info[camera][0][0] and self.object_recordings_info[camera][0][0] < min_start
< recordings[0]["start_time"].timestamp()
): ):
self.object_recordings_info[camera].pop(0) self.object_recordings_info[camera].pop(0)
# clear out all the audio recording info for old frames # clear out all the audio recording info for old frames
while ( while (
len(self.audio_recordings_info[camera]) > 0 len(self.audio_recordings_info[camera]) > 0
and self.audio_recordings_info[camera][0][0] and self.audio_recordings_info[camera][0][0] < min_start
< recordings[0]["start_time"].timestamp()
): ):
self.audio_recordings_info[camera].pop(0) self.audio_recordings_info[camera].pop(0)
# get all reviews with the end time after the start of the oldest cache file tasks = []
# or with end_time None reviews_by_camera: dict[str, Any] = {}
reviews = ( for key, recordings in grouped_recordings.items():
ReviewSegment.select( camera, stream_type = key
ReviewSegment.start_time,
ReviewSegment.end_time, # get all reviews with the end time after the start of the oldest
ReviewSegment.severity, # cache file or with end_time None; shared across stream types
ReviewSegment.data, if camera not in reviews_by_camera:
reviews_by_camera[camera] = (
ReviewSegment.select(
ReviewSegment.start_time,
ReviewSegment.end_time,
ReviewSegment.severity,
ReviewSegment.data,
)
.where(
ReviewSegment.camera == camera,
(ReviewSegment.end_time == None)
| (ReviewSegment.end_time >= min_start_per_camera[camera]),
)
.order_by(ReviewSegment.start_time)
) )
.where( reviews = reviews_by_camera[camera]
ReviewSegment.camera == camera,
(ReviewSegment.end_time == None)
| (
ReviewSegment.end_time
>= recordings[0]["start_time"].timestamp()
),
)
.order_by(ReviewSegment.start_time)
)
tasks.extend( tasks.extend(
[self.validate_and_move_segment(camera, reviews, r) for r in recordings] [self.validate_and_move_segment(camera, reviews, r) for r in recordings]
) )
# publish most recently available recording time and None if disabled # publish most recently available recording time and None if disabled
camera_cfg = self.config.cameras.get(camera) if stream_type == STREAM_TYPE_MAIN:
self.recordings_publisher.publish( camera_cfg = self.config.cameras.get(camera)
( self.recordings_publisher.publish(
camera, (
recordings[0]["start_time"].timestamp() camera,
if camera_cfg and camera_cfg.record.enabled recordings[0]["start_time"].timestamp()
else None, if camera_cfg and camera_cfg.record.enabled
None, else None,
), None,
RecordingsDataTypeEnum.saved.value, ),
) RecordingsDataTypeEnum.saved.value,
)
self._expire_stale_recordings_info(grouped_recordings) self._expire_stale_recordings_info(grouped_recordings)
recordings_to_insert: list[dict[str, Any] | None] = await asyncio.gather(*tasks) # one segment must not abort the cycle: an exception propagating out
# of gather would abandon the other segments' in-flight probes
# fire and forget recordings entries results: list[dict[str, Any] | None | BaseException] = await asyncio.gather(
self.requestor.send_data( *tasks, return_exceptions=True
INSERT_MANY_RECORDINGS,
[r for r in recordings_to_insert if r is not None],
) )
recordings_to_insert: list[dict[str, Any]] = []
for result in results:
if isinstance(result, BaseException):
logger.error(
"Failed to validate and move a recording segment", exc_info=result
)
continue
if result is not None:
recordings_to_insert.append(result)
# fire and forget recordings entries
self.requestor.send_data(INSERT_MANY_RECORDINGS, recordings_to_insert)
def _expire_stale_recordings_info( def _expire_stale_recordings_info(
self, grouped_recordings: defaultdict[str, list[dict[str, Any]]] self, grouped_recordings: defaultdict[tuple[str, str], list[dict[str, Any]]]
) -> None: ) -> None:
expire_before = datetime.datetime.now().timestamp() - STALE_RECORDINGS_INFO_TTL expire_before = datetime.datetime.now().timestamp() - STALE_RECORDINGS_INFO_TTL
# a camera is still active when any of its streams cached segments
cameras_with_cache = {camera for camera, _ in grouped_recordings}
for recordings_info in ( for recordings_info in (
self.object_recordings_info, self.object_recordings_info,
self.audio_recordings_info, self.audio_recordings_info,
): ):
for camera in list(recordings_info.keys()): for camera in list(recordings_info.keys()):
if camera in grouped_recordings: if camera in cameras_with_cache:
continue continue
info = recordings_info[camera] info = recordings_info[camera]
while info and info[0][0] < expire_before: while info and info[0][0] < expire_before:
@@ -337,64 +505,121 @@ class RecordingMaintainer(threading.Thread):
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
cache_path: str = recording["cache_path"] cache_path: str = recording["cache_path"]
start_time: datetime.datetime = recording["start_time"] start_time: datetime.datetime = recording["start_time"]
stream_type: str = recording["stream_type"]
# Just delete files if camera removed or recordings are turned off # Just delete files if camera removed or recordings are turned off
if ( if (
camera not in self.config.cameras camera not in self.config.cameras
or not self.config.cameras[camera].record.enabled or not self.config.cameras[camera].record.enabled
or (
stream_type == STREAM_TYPE_SUB
and not self.config.cameras[camera].record.sub.enabled
)
): ):
self.drop_segment(cache_path) self.drop_segment(cache_path)
return None return None
if cache_path in self.end_time_cache: if cache_path in self.end_time_cache:
end_time, duration = self.end_time_cache[cache_path] (
end_time,
duration,
has_audio,
audio_rate,
audio_codec,
video_codec,
keyframes,
) = self.end_time_cache[cache_path]
# recover the resolved start rather than reusing the truncated
# filename timestamp
start_time = end_time - datetime.timedelta(seconds=duration)
else: else:
segment_info = await get_video_properties( async with self.probe_semaphore:
self.config.ffmpeg, cache_path, get_duration=True segment_info = await get_video_properties(
) self.config.ffmpeg, cache_path, get_duration=True
)
if not segment_info.get("has_valid_video", False): if not segment_info.get("has_valid_video", False):
logger.warning( logger.warning(
f"Invalid or missing video stream in segment {cache_path}. Discarding." f"Invalid or missing video stream in segment {cache_path}. Discarding."
) )
self.recordings_publisher.publish( if stream_type == STREAM_TYPE_MAIN:
(camera, start_time.timestamp(), cache_path), self.recordings_publisher.publish(
RecordingsDataTypeEnum.invalid.value, (camera, start_time.timestamp(), cache_path),
) RecordingsDataTypeEnum.invalid.value,
)
self.drop_segment(cache_path) self.drop_segment(cache_path)
return None return None
duration = float(segment_info.get("duration", -1)) duration = float(segment_info.get("duration", -1))
has_audio = segment_info.get("has_audio")
audio_rate = segment_info.get("audio_rate")
audio_codec = segment_info.get("audio_codec")
video_codec = segment_info.get("video_codec")
# ensure duration is within expected length # ensure duration is within expected length
if 0 < duration < MAX_SEGMENT_DURATION: if 0 < duration < MAX_SEGMENT_DURATION:
# playback snaps mid-file entry points against these offsets
# instead of probing files on demand
async with self.probe_semaphore:
keyframes = await get_keyframe_offsets(cache_path)
start_time = self._resolve_segment_start(
camera, stream_type, start_time, duration, cache_path
)
end_time = start_time + datetime.timedelta(seconds=duration) end_time = start_time + datetime.timedelta(seconds=duration)
self.end_time_cache[cache_path] = (end_time, duration) self.end_time_cache[cache_path] = (
end_time,
duration,
has_audio,
audio_rate,
audio_codec,
video_codec,
keyframes,
)
# segments later discarded by retention still advance the
# chain for the next kept segment
self.last_segment_end[(camera, stream_type)] = end_time.timestamp()
else: else:
if duration == -1: if duration == -1:
logger.warning(f"Failed to probe corrupt segment {cache_path}") logger.warning(f"Failed to probe corrupt segment {cache_path}")
logger.warning(f"Discarding a corrupt recording segment: {cache_path}") logger.warning(f"Discarding a corrupt recording segment: {cache_path}")
self.recordings_publisher.publish( if stream_type == STREAM_TYPE_MAIN:
(camera, start_time.timestamp(), cache_path), self.recordings_publisher.publish(
RecordingsDataTypeEnum.invalid.value, (camera, start_time.timestamp(), cache_path),
) RecordingsDataTypeEnum.invalid.value,
)
self.drop_segment(cache_path) self.drop_segment(cache_path)
return None return None
# this segment has a valid duration and has video data, so publish an update # this segment has a valid duration and has video data, so publish an update
self.recordings_publisher.publish( if stream_type == STREAM_TYPE_MAIN:
(camera, start_time.timestamp(), cache_path), self.recordings_publisher.publish(
RecordingsDataTypeEnum.valid.value, (camera, start_time.timestamp(), cache_path),
) RecordingsDataTypeEnum.valid.value,
)
record_config = self.config.cameras[camera].record record_config = self.config.cameras[camera].record
# sub's alerts/detections carry the retain mode directly, unlike
# main's nested retain config
if stream_type == STREAM_TYPE_SUB:
continuous_days = record_config.sub.continuous.days
motion_days = record_config.sub.motion.days
alerts_retain_mode = record_config.sub.alerts.mode
detections_retain_mode = record_config.sub.detections.mode
else:
continuous_days = record_config.continuous.days
motion_days = record_config.motion.days
alerts_retain_mode = record_config.alerts.retain.mode
detections_retain_mode = record_config.detections.retain.mode
segment_stats: SegmentInfo | None = None segment_stats: SegmentInfo | None = None
highest = None highest = None
if record_config.continuous.days > 0: if continuous_days > 0:
highest = "continuous" highest = "continuous"
elif record_config.motion.days > 0: elif motion_days > 0:
highest = "motion" highest = "motion"
# if we have continuous or motion recording enabled # if we have continuous or motion recording enabled
@@ -426,11 +651,17 @@ class RecordingMaintainer(threading.Thread):
if not segment_stats.should_discard_segment(record_mode): if not segment_stats.should_discard_segment(record_mode):
return await self.move_segment( return await self.move_segment(
camera, camera,
stream_type,
start_time, start_time,
end_time, end_time,
duration, duration,
cache_path, cache_path,
segment_stats, segment_stats,
has_audio,
audio_rate,
audio_codec,
video_codec,
keyframes,
) )
# we fell through the continuous / motion check, so we need to check the review items # we fell through the continuous / motion check, so we need to check the review items
@@ -459,9 +690,9 @@ class RecordingMaintainer(threading.Thread):
if overlaps: if overlaps:
record_mode = ( record_mode = (
record_config.alerts.retain.mode alerts_retain_mode
if review.severity == "alert" if review.severity == "alert"
else record_config.detections.retain.mode else detections_retain_mode
) )
if segment_stats is None: if segment_stats is None:
@@ -471,11 +702,17 @@ class RecordingMaintainer(threading.Thread):
# move from cache to recordings immediately # move from cache to recordings immediately
return await self.move_segment( return await self.move_segment(
camera, camera,
stream_type,
start_time, start_time,
end_time, end_time,
duration, duration,
cache_path, cache_path,
segment_stats, segment_stats,
has_audio,
audio_rate,
audio_codec,
video_codec,
keyframes,
) )
else: else:
self.drop_segment(cache_path) self.drop_segment(cache_path)
@@ -614,17 +851,24 @@ class RecordingMaintainer(threading.Thread):
async def move_segment( async def move_segment(
self, self,
camera: str, camera: str,
stream_type: str,
start_time: datetime.datetime, start_time: datetime.datetime,
end_time: datetime.datetime, end_time: datetime.datetime,
duration: float, duration: float,
cache_path: str, cache_path: str,
segment_info: SegmentInfo, segment_info: SegmentInfo,
has_audio: bool | None = None,
audio_rate: int | None = None,
audio_codec: str | None = None,
video_codec: str | None = None,
keyframes: list[int] | None = None,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
# directory will be in utc due to start_time being in utc # directory will be in utc due to start_time being in utc
# sub segments get a tagged directory to avoid filename collisions
directory = os.path.join( directory = os.path.join(
RECORD_DIR, RECORD_DIR,
start_time.strftime("%Y-%m-%d/%H"), start_time.strftime("%Y-%m-%d/%H"),
camera, camera if stream_type == STREAM_TYPE_MAIN else f"{camera}{SUB_CACHE_TAG}",
) )
os.makedirs(directory, exist_ok=True) os.makedirs(directory, exist_ok=True)
@@ -684,6 +928,7 @@ class RecordingMaintainer(threading.Thread):
return { return {
Recordings.id.name: f"{start_time.timestamp()}-{rand_id}", Recordings.id.name: f"{start_time.timestamp()}-{rand_id}",
Recordings.camera.name: camera, Recordings.camera.name: camera,
Recordings.stream_type.name: stream_type,
Recordings.path.name: file_path, Recordings.path.name: file_path,
Recordings.start_time.name: start_time.timestamp(), Recordings.start_time.name: start_time.timestamp(),
Recordings.end_time.name: end_time.timestamp(), Recordings.end_time.name: end_time.timestamp(),
@@ -695,6 +940,11 @@ class RecordingMaintainer(threading.Thread):
Recordings.dBFS.name: segment_info.average_dBFS, Recordings.dBFS.name: segment_info.average_dBFS,
Recordings.segment_size.name: segment_size, Recordings.segment_size.name: segment_size,
Recordings.motion_heatmap.name: segment_info.motion_heatmap, Recordings.motion_heatmap.name: segment_info.motion_heatmap,
Recordings.has_audio.name: has_audio,
Recordings.audio_rate.name: audio_rate,
Recordings.audio_codec.name: audio_codec,
Recordings.video_codec.name: video_codec,
Recordings.keyframes.name: keyframes,
} }
except Exception as e: except Exception as e:
logger.error(f"Unable to store recording segment {cache_path}") logger.error(f"Unable to store recording segment {cache_path}")
@@ -745,7 +995,9 @@ class RecordingMaintainer(threading.Thread):
regions, regions,
) = data ) = data
if self.config.cameras[camera].record.enabled: camera_config = self.config.cameras.get(camera)
if camera_config is not None and camera_config.record.enabled:
self.object_recordings_info[camera].append( self.object_recordings_info[camera].append(
( (
frame_time, frame_time,
@@ -762,7 +1014,9 @@ class RecordingMaintainer(threading.Thread):
audio_detections, audio_detections,
) = data ) = data
if self.config.cameras[camera].record.enabled: camera_config = self.config.cameras.get(camera)
if camera_config is not None and camera_config.record.enabled:
self.audio_recordings_info[camera].append( self.audio_recordings_info[camera].append(
( (
frame_time, frame_time,
@@ -784,11 +1038,10 @@ class RecordingMaintainer(threading.Thread):
try: try:
asyncio.run(self.move_files()) asyncio.run(self.move_files())
except Exception as e: except Exception:
logger.error( logger.exception(
"Error occurred when attempting to maintain recording cache" "Error occurred when attempting to maintain recording cache"
) )
logger.error(e)
duration = datetime.datetime.now().timestamp() - run_start duration = datetime.datetime.now().timestamp() - run_start
wait_time = max(0, 5 - duration) wait_time = max(0, 5 - duration)
+54 -42
View File
@@ -392,6 +392,37 @@ class ReviewSegmentMaintainer(threading.Thread):
return self._publish_segment_end(segment, prev_data) return self._publish_segment_end(segment, prev_data)
return None return None
def get_manual_event_severity(self, camera: str, label: str) -> SeverityEnum | None:
"""Determine the review severity for a manual event label.
Alert labels take precedence over detection labels, matching how
tracked objects are categorized. Labels in neither list default to
alerts so manual events keep their historical severity.
"""
review_config = self.config.cameras[camera].review
# label contains 'label: sub_label', only the label is categorized
label = label.split(": ")[0]
if review_config.alerts.enabled and label in review_config.alerts.labels:
return SeverityEnum.alert
if (
review_config.detections.enabled
and review_config.detections.labels is not None
and label in review_config.detections.labels
):
return SeverityEnum.detection
if review_config.alerts.enabled:
return SeverityEnum.alert
return None
def _handle_camera_removed(self, camera: str) -> None:
"""Close out a deleted camera's segment so a reused name cannot inherit it."""
self.forcibly_end_segment(camera)
self.indefinite_events.pop(camera, None)
def update_existing_segment( def update_existing_segment(
self, self,
segment: PendingReviewSegment, segment: PendingReviewSegment,
@@ -450,7 +481,7 @@ class ReviewSegmentMaintainer(threading.Thread):
if not object["sub_label"]: if not object["sub_label"]:
segment.detections[object["id"]] = object["label"] segment.detections[object["id"]] = object["label"]
elif object["sub_label"][0] in self.config.model.all_attributes: elif object["sub_label"][0] in self.config.all_attributes:
segment.detections[object["id"]] = object["sub_label"][0] segment.detections[object["id"]] = object["sub_label"][0]
else: else:
segment.detections[object["id"]] = f"{object['label']}-verified" segment.detections[object["id"]] = f"{object['label']}-verified"
@@ -588,7 +619,7 @@ class ReviewSegmentMaintainer(threading.Thread):
for object in activity.get_all_objects(): for object in activity.get_all_objects():
if not object["sub_label"]: if not object["sub_label"]:
detections[object["id"]] = object["label"] detections[object["id"]] = object["label"]
elif object["sub_label"][0] in self.config.model.all_attributes: elif object["sub_label"][0] in self.config.all_attributes:
detections[object["id"]] = object["sub_label"][0] detections[object["id"]] = object["sub_label"][0]
else: else:
detections[object["id"]] = f"{object['label']}-verified" detections[object["id"]] = f"{object['label']}-verified"
@@ -640,6 +671,10 @@ class ReviewSegmentMaintainer(threading.Thread):
for camera in updated_topics["enabled"]: for camera in updated_topics["enabled"]:
self.forcibly_end_segment(camera) self.forcibly_end_segment(camera)
if "remove" in updated_topics:
for camera in updated_topics["remove"]:
self._handle_camera_removed(camera)
result = self.detection_subscriber.check_for_update(timeout=1) result = self.detection_subscriber.check_for_update(timeout=1)
if not result: if not result:
@@ -734,24 +769,19 @@ class ReviewSegmentMaintainer(threading.Thread):
manual_info["label"] manual_info["label"]
) )
if topic == DetectionTypeEnum.api: if topic == DetectionTypeEnum.api:
# manual_info["label"] contains 'label: sub_label' severity = self.get_manual_event_severity(
# so split out the label without modifying manual_info camera, manual_info["label"]
det_labels = self.config.cameras[ )
camera
].review.detections.labels if severity == SeverityEnum.alert:
if (
self.config.cameras[camera].review.detections.enabled
and det_labels is not None
and manual_info["label"].split(": ")[0] in det_labels
):
current_segment.last_detection_time = manual_info[
"end_time"
]
elif self.config.cameras[camera].review.alerts.enabled:
current_segment.severity = SeverityEnum.alert current_segment.severity = SeverityEnum.alert
current_segment.last_alert_time = manual_info[ current_segment.last_alert_time = manual_info[
"end_time" "end_time"
] ]
elif severity == SeverityEnum.detection:
current_segment.last_detection_time = manual_info[
"end_time"
]
elif ( elif (
topic == DetectionTypeEnum.lpr topic == DetectionTypeEnum.lpr
and self.config.cameras[camera].review.detections.enabled and self.config.cameras[camera].review.detections.enabled
@@ -765,21 +795,12 @@ class ReviewSegmentMaintainer(threading.Thread):
current_segment.detections[manual_info["event_id"]] = ( current_segment.detections[manual_info["event_id"]] = (
manual_info["label"] manual_info["label"]
) )
if ( if topic == DetectionTypeEnum.api:
topic == DetectionTypeEnum.api
and self.config.cameras[camera].review.alerts.enabled
):
# manual_info["label"] contains 'label: sub_label'
# so split out the label without modifying manual_info
det_labels = self.config.cameras[
camera
].review.detections.labels
if ( if (
not self.config.cameras[ self.get_manual_event_severity(
camera camera, manual_info["label"]
].review.detections.enabled )
or det_labels is None == SeverityEnum.alert
or manual_info["label"].split(": ")[0] not in det_labels
): ):
current_segment.severity = SeverityEnum.alert current_segment.severity = SeverityEnum.alert
elif ( elif (
@@ -853,18 +874,9 @@ class ReviewSegmentMaintainer(threading.Thread):
detections, detections,
) )
elif topic == DetectionTypeEnum.api: elif topic == DetectionTypeEnum.api:
severity = None severity = self.get_manual_event_severity(
# manual_info["label"] contains 'label: sub_label' camera, manual_info["label"]
# so split out the label without modifying manual_info )
det_labels = self.config.cameras[camera].review.detections.labels
if (
self.config.cameras[camera].review.detections.enabled
and det_labels is not None
and manual_info["label"].split(": ")[0] in det_labels
):
severity = SeverityEnum.detection
elif self.config.cameras[camera].review.alerts.enabled:
severity = SeverityEnum.alert
if severity: if severity:
api_segment = PendingReviewSegment( api_segment = PendingReviewSegment(

Some files were not shown because too many files have changed in this diff Show More