Compare commits

..
Author SHA1 Message Date
Nicolas MowenandGitHub ab20815584 Fix NPU turbo key and priviledges set (#24138) 2026-08-30 12:15:49 -05:00
Josh HawkinsandGitHub 890512b054 Container security hardening (phase 3, breaking) (#24081)
* Run the frigate service as the frigate user

* Run go2rtc as its own restricted user

* Run nginx as the frigate user with writable state in /tmp/nginx

* Disable bandwidth stats gracefully when not running as root

* Hand TensorRT model cache ownership to the runtime user

* Document non-root operation and per-hardware device access

* Create /media/frigate after the ownership sweep

* Assert non-root services, JWT migration, and escape hatch in CI

* only write the sweep sentinel when a media volume is mounted

* tolerate homekit config chown failures in the go2rtc run script

* chown the s6 log pipe so non-root nginx can reopen /dev/stdout

* set HOME to /config for non-root services

* run smoke nginx -t and the write probe as the runtime user

* re-own the nginx shm cache on service restart

* discard stdout for the unprivileged smoke nginx -t

* unwrap hard-wrapped prose in the installation docs

* report progress during the ownership sweep

* document EXTRA_GROUPS as the only device access path for dropped services

* expand the non-root device access docs with diagnosis steps and udev rules

* document network storage ownership and the remaining detector hardware

* skip lost+found during the ownership sweep

* hand /tmp/cache to the runtime user before services start

* make bundled models readable by the runtime user

* reload nginx by signaling the master instead of parsing its config as root

* harden root writes into unprivileged-owned paths

Restrict the sweep sentinel to a mount at or below /media/frigate so a
parent /media mount cannot bless a later-shadowed volume. Rebuild
/tmp/nginx root-owned each start so root's cp and tempio writes cannot
follow a symlink an unprivileged nginx planted in the previous run.

* collapse the duplicated sentinel comment

* add a service-runs-as-root helper for granular root services

* validate FRIGATE_ROOT_SERVICES and fail fast on unknown names

* let services listed in FRIGATE_ROOT_SERVICES skip the privilege drop

* record the root-services mode in the sentinel and sweep small trees each boot

* cache the runtime ids in the ownership helper

* chown recordings, previews, and exports to the runtime user at create

* chown the database files after init

* recommend FRIGATE_ROOT_SERVICES in the bandwidth stats warning

* assert granular root services in CI

* document FRIGATE_ROOT_SERVICES

* own every directory level created for a recording segment

* clear the cached runtime ids when ownership tests finish

* skip missing media paths in the per-boot ownership sweep

* clarify granular root services docs

* clean up

* install acl for device access grants

* grant runtime users access to mapped device nodes at boot

* assert device access grants in CI

* document automatic device access grants

* stop telling users device access needs host side setup

* clarify the non-root docs

* link the migration script to the repo

* group the manual device setup under one section

* harden against symlink attacks

/config is owned by the unprivileged runtime user after the ownership sweep, so root operations on files there could be redirected by a planted symlink.

- go2rtc HomeKit setup: replace the root yq/jq normalization and chown with an O_NOFOLLOW helper (prepare_homekit.py), so a symlink at go2rtc_homekit.yml can't redirect a root write or chown onto another file
- go2rtc binary override: ignore /config/go2rtc whenever the service runs as root, so a planted binary can't exec as root under FRIGATE_ROOT_SERVICES
- sweep sentinel: read and write it through safe-sentinel, which trusts only a root-owned regular file and never follows a symlink, so it can't be forged to skip the migration or symlinked to clobber a root file
- ownership sweep: chown with -execdir so a parent directory swapped for a symlink mid-walk can't redirect the chown out of the volume
- validate inputs: restrict DEVICE_ACL_PATHS to /dev, require nonzero numeric EXTRA_GROUPS, and reject PUID/PGID that collide with the go2rtc ids
- docs: correct the TLS key ownership note to match what actually happens

* tweak docs

* stop the ownership sweep chasing entries other mechanisms own

* keep custom binaries out of root services only under granular root
2026-08-30 08:14:43 -06:00
Josh HawkinsandGitHub a1fd978cab switch nginx-vod-module to the maintained dio-az fork (#24123)
The `v1.x` line is the same muxed fMP4 code as Kaltura's 1.31 with fixes backported, so the mapping JSON, manifest routes, and ffmpeg consumers are unchanged. The `MAX_CLIPS` patch applies as-is and the HEVC workaround is rewritten for the fork's reformatted source.

`vod_hls_version 6` is now explicit because the fork replaced Kaltura's automatic version calculation with a directive that defaults to 4 and only warns when fmp4 needs 6, so playlists were being stamped `EXT-X-VERSION:4` while carrying `EXT-X-MAP`. The `error_page 502 =404` hack is gone: https://github.com/kaltura/nginx-vod-module/issues/468 is a `vod_mode remote` bug and we're `mapped`, so those 502s were really `_vod_response` returning 404 upstream. The fork maps that through now, and the hack was also turning real 5xx into "no recordings".
2026-08-28 12:48:52 -06:00
Josh HawkinsandGitHub 5de5cee3c6 Fix LPR vehicle message for multiple models (#24119)
* use the camera's model for the lpr vehicle check

`FrigateConfig.model` became `models[]` in the detector refactor, so this didn't compile on 0.19. Each camera has its own detector/model pair now, so the check resolves the camera's scene with `getModelForCamera` instead of looking at every model.

* use camera config model

* fix export test
2026-08-28 12:26:05 -05:00
Josh Hawkins e99eb77ca1 Add Apple compatibility switch to the camera wizard (#24115)
* add apple compatibility switch to the camera wizard

* don't require every record stream to be h265
2026-08-27 20:30:36 -05:00
Josh Hawkins bb1e556ba9 Add onboarding wizard for new installations (#24102)
* add onboarding wizard for new users

* resolve hwaccel per camera and clarify recording retention

The hwaccel step listed every preset Frigate ships, so an Intel box was offered Raspberry Pi and Rockchip decoding, and the codec specific presets (`preset-intel-qsv-h264` vs `-h265`) were offered as global values that break as soon as two cameras use different codecs. `/hardware/hwaccel` now returns the decoding families the probed hardware can actually use, each carrying a preset per codec, and the wizard resolves the family against the detect stream codec the camera wizard already probed: one global `ffmpeg.hwaccel_args` when every camera agrees, per-camera `cameras.<name>.ffmpeg.hwaccel_args` when they don't. The global stays on `auto` in that case so cameras added later still resolve at startup. A gen13+ Intel machine keeps its QuickSync recommendation with mixed h264 and h265 cameras instead of dropping to vaapi.

The recording step's "Days to retain recordings" only wrote alert and detection retention, and the storage estimate under it assumed continuous recording. It now asks what to record in plain language, writes `record.continuous.days` to match, shows the estimate only for continuous, and drops the spinner arrows on the number input.

* clean up

* add light/dark mode icon switcher

* use yml as default config file extension when not found

* i18n tweaks

* gate the setup wizard on cameras instead of a config key

* render setup wizard steps by key

* share the setup wizard e2e helpers and mock users

* add an account step to the setup wizard

* add setup wizard account step e2e coverage

* cover the account step's restart behavior

* button consistency

* fix test

* docs

* fixes
2026-08-27 20:30:36 -05:00
Josh Hawkins 4f0c1b8ee7 Fix 500 when an event thumbnail file is empty (#24110)
* fix 500 when an event thumbnail file is empty

* fix test
2026-08-27 20:30:36 -05:00
Josh Hawkins a2085e27f6 Fix inconsistent export download filenames (#24111)
* fix inconsistent export download filenames

Zip entries in a case download were named from `Export.name`, the friendly display name, while an individual download uses the file name on disk. The two have always been formatted differently, so one export came out as `front_door_20260823_020615-20260823_020734_abc123.mp4` on its own and `front door 2026-08-23 020615 2026-08-23 020734.mp4` inside a zip. Zip entries now use the on-disk file name, and renaming an export renames its file, so there's only one name to download under. The rename is blocked while ffmpeg still holds the file.

* cap filename length and catch duplicate names

* fix export rename and stop blocking the event loop

* move the rename rollback off the event loop

* no awaits
2026-08-27 20:30:36 -05:00
Josh Hawkins 194e9bef69 Recording fixes (#24072)
* pin genai review frames to the main stream

* retain previews as long as either stream has recordings

* watch sub stream recording health separately from main

* reject record_sub on the same input as record and document the role

* derive recording paths from the cache segment timestamp

Recording paths carry one second of resolution, but since sub stream recording start times are resolved to fractional wall clock, anchored to the cache file mtime and chained to the previous segment's end. A stream cutting segments faster than once a second resolves consecutive segments into the same second, so two rows collide on the unique path index and the batch insert fails. The cache segment name is unique per camera stream and second by construction because ffmpeg names segments with strftime, so the recording path is now built from that timestamp while the row keeps the resolved start time. This also restores the path semantics from before sub stream recording, when start times came straight from the cache filename.

Nothing derives times from recording paths: playback offsets, stream switching, and export all use the row's start time, which is unchanged, and the recordings sync matches files by exact path string.

* keep the rest of a recording batch when one row conflicts

* only publish record_sub status when a sub stream is configured

* don't shadow camera_cfg when publishing empty cache streams

* back off restarts when a recording stream goes stale

* give the shared sub stream grace on any capture thread reset

* include segment details in recording discard warnings
2026-08-27 20:30:35 -05:00
Josh Hawkins 9d109bfd12 Container security hardening (phase 2) (#24068)
* Create frigate and go2rtc runtime users in the image

* Add single fix-ownership helper for volume permission migration

* Add init-usermod oneshot for PUID and PGID remapping

* Chown newly created runtime directories to the frigate user

* Run sentinel-guarded ownership sweep during prepare

* Add host-side volume permission migration script

* Guard log directory ownership for user-mode startup

* Fall back to plain s6-log when running without root

* Assert PUID remapping and sweep sentinel in CI smoke test

* Skip the ownership sweep in the devcontainer

* Pin FRIGATE_RUN_AS_ROOT in ownership tests

* Do not record the sweep as complete when a chown failed

* Validate PUID and PGID in the migration script

* Treat a failed ownership scan as an incomplete sweep

* Reject PUID and PGID of 0 during remapping

* Handle symlinks, dry runs, and sentinel write failures in the sweep

* Treat an absent sweep root as an incomplete sweep
2026-08-27 20:30:35 -05:00
Josh Hawkins dcda458a82 Container security hardening (phase 1) (#24061)
* Verify s6-overlay downloads against pinned checksums

* Verify go2rtc download against pinned checksums

The v1.9.14 release publishes no checksums file, just the bare per-platform binaries, so these digests come from a one-time fetch rather than upstream. That pins the artifact against later substitution, which is the realistic threat for a version we stay on for months, but it does not verify the original download. The stage moves from `ADD --link` to a script because `ADD --checksum` can't express an architecture-dependent URL.

* Verify main image downloads against pinned checksums

Covers everything the main image downloads on the default path: tempio, the hailort runtime tarball and wheel, the six ffmpeg builds, the libedgetpu deb, and the thirteen Intel driver debs. The hailort tarball was streamed straight into `tar`, which can't be verified before extraction, so it downloads to `/tmp` first. The three ffmpeg blocks per arch collapse into one `install_ffmpeg` helper since they only differed by URL and install dir, and the Intel debs go through a `fetch_intel_deb` helper for the same reason.

The Intel debs are the ones that mattered most here. They're installed as root with `dpkg` on the default amd64 path and had no verification at all. compute-runtime publishes a `ww<week>.sum` asset with every release and npu-driver published `checksum.sha256` on v1.19.0, so those eight digests came from upstream rather than from us. intel-graphics-compiler and level-zero publish none, so those five and everything else here come from a one-time fetch, which pins the artifact against later substitution but doesn't verify the original download. The comment above the map says which is which and how to refresh them, since npu-driver has stopped publishing sums since v1.19.0 and that provenance won't survive the next bump.

Still unpinned: `get-pip.py`, which is a rolling URL where a digest would just break the build on pypa's next edit, and the per-variant artifacts for Axera, Synaptics, and Jetson. apt repositories are out of scope since apt already verifies signatures.

* Restrict generated TLS key permissions

OpenSSL 3.x already writes the key at 600 on its own, so this pins the guarantee rather than fixing an observed leak: the mode no longer depends on the openssl version or the umask the service happens to start with. Only the generated pair is touched. User-mounted certs take the other branch and are never chmod'd, which matters when they're mounted read-only.

* Add security headers and server_tokens off

Adds `X-Content-Type-Options: nosniff` and `Referrer-Policy: strict-origin-when-cross-origin`, and turns off nginx version disclosure.

No `X-Frame-Options` and no CSP `frame-ancestors`. HA's Webpage card and iframe panels frame Frigate's own address cross-origin, and either header would break them silently with nothing in Frigate's logs to explain it. Ingress is same-origin and would survive `SAMEORIGIN`, but Frigate can't tell the two apart from inside the container. `security_headers.conf` is a plain file in the image rather than a generated one, so anyone who does want framing restrictions can bind-mount it.

`add_header` doesn't inherit into a block that declares its own, so the include goes in per block, all nine of them, including the four nested static-asset locations that serve the JS bundles. Those are the ones nosniff actually matters for.

The run script now reads `get_nginx_settings.py` once into a variable instead of shelling out per template. That script imports the frigate config machinery, which is noticeable on an SBC.

Not fixed here: `listen.conf` is included at server level and carries `Strict-Transport-Security`, so those same nine blocks already drop HSTS under TLS today. Folding it into this file would change existing TLS behavior on nine paths, so it needs its own PR.

* Restrict go2rtc config file permissions

* Log failed login attempts with source address

Failed logins returned a bare 401 and left nothing behind, so credential stuffing was invisible unless you were already watching nginx access logs. Both failure branches now log a warning with the attempted username and the client address.

The address comes from `get_remote_addr()`, the same helper the login rate limiter keys on, so the two agree on who the client is and the trusted-proxy handling is consistent. Logging a raw `x-forwarded-for` instead would let an attacker forge the source address in the very log line meant to catch them.

The response is unchanged and identical either way. Which factor failed is only visible in the log, never to the client, and the password is never logged.

* Recommend least-privilege container options in install docs

The compose generator pushed `privileged: true` into every file it produced, no matter what hardware you picked, and it's the default tab on the install page so it's what most people copy. It now emits `security_opt: no-new-privileges:true` instead, and only adds `privileged: true` for hardware that actually needs it, with the reason inline. MemryX is the only one today, since it needs to reach the max-manager. Rockchip and Synaptics only want privileged during initial setup and their documented end state is device mappings, so neither gets it.

`no-new-privileges` merges into the same `security_opt` block as any device-specific entries, so Rockchip still gets its `apparmor=unconfined` and `systempaths=unconfined` without a duplicate key.

The static example now has `privileged` commented out, and there's a short section on the options worth adding, with a note that `cap_drop: ALL` breaks `telemetry.stats.network_bandwidth` since nethogs needs NET_ADMIN/NET_RAW.

* Add amd64 container smoke test to CI

Boots the built amd64 image against a minimal config and asserts the two security headers, that the Server header no longer carries a version, that no frame-ancestors is present, that nginx accepts its own config, and the two file modes. This is also the harness the rest of the hardening work extends.

The two negative assertions are written as `if grep; then exit 1; fi` rather than `! grep`. Bash exempts a negated command from `set -e`, so the `!` form would have passed even with the version and frame-ancestors both present, which is the opposite of what a regression net is for.
2026-08-27 20:30:35 -05:00
Josh Hawkins 6c6683034e Tweaks (#24067)
* improve keyframes messages

* don't pad the labelmap with unknown

`load_labels()` prefilled 91 `unknown` entries before reading the label file, so any model with fewer than 91 classes kept that padding in `merged_labelmap` and `unknown` showed up as a selectable object type in the objects settings UI. The padding only existed so `RemoteObjectDetector.detect` could index the labelmap without a KeyError, and it didn't even cover the empty-file case or Frigate+, which never had a prefill. Both lookups now skip class ids the labelmap doesn't name and warn once per id.
2026-08-27 20:30:35 -05:00
Josh Hawkins 3ce3217db2 Add secrets.yaml and unify variable substitution sources (#24044)
* 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.

* 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.

* 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.

* docs

* clarify docs
2026-08-27 20:30:35 -05:00
Josh Hawkins 8a0c848914 add recognized plate picker to lpr known plates in settings (#24059) 2026-08-27 20:30:35 -05:00
Josh Hawkins fa4002cbe2 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-27 20:30:35 -05:00
Josh Hawkins a94b532655 fix the model lookup KeyError for cameras added at runtime (#24026) 2026-08-27 20:30:35 -05:00
Josh Hawkins fec73c887e 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-27 20:30:35 -05:00
Nicolas MowenandJosh Hawkins da135da0fb 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-27 20:30:35 -05:00
Josh Hawkins f5e398036e 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-27 20:30:35 -05:00
Nicolas MowenandJosh Hawkins 2dd700aa5a Refactor detector and model management (#23995)
* Refactor detector and model management

* Fix model resolution field
2026-08-27 20:30:35 -05:00
Ersa Oktavian RamadanandJosh Hawkins 378fbec416 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-27 20:30:35 -05:00
Josh Hawkins 91a93167d2 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-27 20:30:35 -05:00
Josh Hawkins dfe6428111 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-27 20:30:35 -05:00
Josh Hawkins 5e37b2c5c2 Refactor birdseye activity modes as a list and add alerts/detections (#24012)
* backend

* tests

* frontend and i18n

* e2e test schema

* docs
2026-08-27 20:30:35 -05:00
Josh Hawkins 36607133e5 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-27 20:30:35 -05:00
Josh Hawkins 622fc97671 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-27 20:30:35 -05:00
Josh Hawkins 5d807587ab 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-27 20:30:35 -05:00
Josh Hawkins 31bbf910c7 stop creating a config subscriber per capture thread (#24002) 2026-08-27 20:30:35 -05:00
Josh Hawkins f0d7c1d7d4 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-27 20:30:35 -05:00
Ersa Oktavian RamadanandJosh Hawkins a83219af56 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-27 20:30:35 -05:00
Josh Hawkins 4a2fb2f09c 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-27 20:30:35 -05:00
Nicolas MowenandJosh Hawkins 68893b28fc Don't require object type for parameter in categorized names tool 2026-08-27 20:30:35 -05:00
fbb904302c 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-27 20:30:35 -05:00
DoFabienandJosh Hawkins e425ab5f90 Improve recording timeline and VOD query performance (#23862)
* Improve recording timeline and VOD query performance

* Add recording query boundary tests
2026-08-27 20:30:35 -05:00
Nicolas MowenandJosh Hawkins f486f7d57e GenAI Chat Prompt Refinements (#23864)
* Prompt refactoring and optimization

* Update spec
2026-08-27 20:30:35 -05:00
Nicolas MowenandJosh Hawkins c0adab1228 Update to 0.19 2026-08-27 20:30:35 -05:00
Josh HawkinsandGitHub ca18b8dc13 fix export case download with non-ascii names (#24100)
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
2026-08-26 14:42:34 -06:00
Josh HawkinsandGitHub 5197881ef7 Add more vehicle types to default attribute map (#24097)
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
* run lpr on more vehicle types by default

before, a config change to attribute_map was required

* logging tweaks

* remove arg

* use attributes for frontend check

* docs

* only check thumbnail attributes the object can have
2026-08-26 08:23:15 -06:00
Josh HawkinsandGitHub 18c77faea5 fix classification attribute access for viewers (not custom roles) (#24092)
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
2026-08-25 14:40:26 -05:00
Nicolas MowenandGitHub 41c8d6cc6b Set GPU_QUEUE_THROTTLE to low (#24088)
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
2026-08-24 16:57:52 -05:00
Josh HawkinsandGitHub 271051f15b don't migrate embeddings as a valid role for genai providers (#24086) 2026-08-24 12:05:57 -06:00
nulledyandGitHub 65fe6b610a Compare severity in send_alert's no-op update check (#24084)
send_alert()'s short circuit for skipping a no-op "update" push only
compared object and zone counts between before/after, never severity.
Both underlying collections are cumulative and deduplicated (objects
is a set of labels, zones only appends a zone not already present),
so a segment being promoted from detection to alert can leave both
counts unchanged, silently dropping the single most notable
transition in a review's life. Add a severity comparison to the same
check so a detection -> alert promotion always notifies.
2026-08-24 12:50:32 -05:00
Josh HawkinsandGitHub 41bc24cce4 use extended graph optimization for jinav2 (#24079)
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
The CUDA execution provider returns an identical vector for every image when jina-clip-v2 is built below ORT_ENABLE_EXTENDED, so every thumbnail embedding written on a GPU was the same normalized garbage and semantic search returned the same results for any query. Reproduced on two different NVIDIA cards, across onnxruntime 1.22 and 1.24, and on both the 0.17 and 0.18 CUDA stacks, so it isn't specific to any of those. ORT_ENABLE_ALL isn't an option because it fails to build on CPU with a SimplifiedLayerNormFusion error, leaving EXTENDED as the only level that works on both providers. jinav1 is unaffected and stays on BASIC.
2026-08-24 09:13:16 -05:00
Josh HawkinsandGitHub 0254a11874 Docs tweaks (#24074)
* add recording validation message explanations to docs

* tweaks
2026-08-24 06:04:40 -06:00
93 changed files with 5403 additions and 508 deletions
+175 -4
View File
@@ -59,10 +59,16 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Start container
run: |
mkdir -p /tmp/frigate-config
mkdir -p /tmp/frigate-config /tmp/frigate-media
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config/config.yml
# simulate a root-era install: root-owned 0600 jwt secret pre-exists
docker run --rm -v /tmp/frigate-config:/config --entrypoint bash \
${{ steps.setup.outputs.image-name }}-amd64 \
-c "python3 -c 'import secrets; open(\"/config/.jwt_secret\",\"w\").write(secrets.token_hex(64))' && chmod 600 /config/.jwt_secret && chown 0:0 /config/.jwt_secret"
docker run -d --name frigate --shm-size 256m \
-v /tmp/frigate-config:/config \
-v /tmp/frigate-media:/media/frigate \
--mount type=tmpfs,target=/tmp/cache,tmpfs-size=100000000 \
-p 5000:5000 -p 8971:8971 \
${{ steps.setup.outputs.image-name }}-amd64
- name: Wait for API
@@ -91,16 +97,181 @@ jobs:
echo "response carries frame-ancestors, which breaks cross-origin iframe embedding"
exit 1
fi
docker exec frigate /usr/local/nginx/sbin/nginx -t
# -t as root would chown the live cache and temp dirs to the `user`
# directive user; stdout discarded because -t reopens the config's
# /dev/stdout logs and the docker exec pipe is root-owned
docker exec frigate /command/s6-setuidgid frigate bash -c '/usr/local/nginx/sbin/nginx -e stderr -t -c /tmp/nginx/conf/nginx.conf >/dev/null'
docker exec frigate stat -c %a /etc/letsencrypt/live/frigate/privkey.pem | grep -qx 600
docker exec frigate stat -c %a /dev/shm/go2rtc.yaml | grep -qx 640
- name: Assert services run as non-root
run: |
ps_out=$(docker exec frigate ps -eo user=,comm=)
echo "$ps_out"
assert_nonroot() {
# the process must exist AND no instance of it may run as root
echo "$ps_out" | grep -qw "$1" || { echo "$1 is not running"; exit 1; }
if echo "$ps_out" | grep -w "$1" | grep -q '^root'; then
echo "$1 is running as root"; exit 1
fi
}
assert_nonroot python3
assert_nonroot go2rtc
assert_nonroot nginx
# root-era jwt secret must have been captured by the sweep and the
# auth stack must be functional: wrong creds => clean 401, not 500
docker exec frigate stat -c %u /config/.jwt_secret | grep -qx "$(docker exec frigate id -u frigate)"
code=$(curl -s -o /dev/null -w '%{http_code}' -X POST http://127.0.0.1:5000/api/login \
-H 'content-type: application/json' -d '{"user":"admin","password":"definitely-wrong"}')
[ "$code" = "401" ] || { echo "login endpoint returned $code"; exit 1; }
# a root nginx -t above would have chowned the runtime dirs to root
owners=$(docker exec frigate stat -c %U /tmp/nginx /dev/shm/nginx_cache)
echo "$owners"
if echo "$owners" | grep -qvx frigate; then
echo "nginx runtime dirs are not owned by frigate"; exit 1
fi
# runtime user can write recordings storage
docker exec frigate /command/s6-setuidgid frigate touch /media/frigate/.write-probe
docker exec frigate rm /media/frigate/.write-probe
# tmpfs mount per the docs: arrives root-owned, holds the ZMQ IPC sockets
docker exec frigate /command/s6-setuidgid frigate touch /tmp/cache/.write-probe
docker exec frigate rm /tmp/cache/.write-probe
# models are baked in as root and archive members can carry root-only modes
docker exec frigate /command/s6-setuidgid frigate sh -c '
for f in /cpu_model.tflite /edgetpu_model.tflite /cpu_audio_model.tflite \
/labelmap.txt /audio-labelmap.txt /openvino-model/*; do
[ -e "$f" ] || continue
test -r "$f" || { echo "$f is not readable by the runtime user"; exit 1; }
done'
- name: Assert device access grants
run: |
# a fake accelerator node created after boot, then the oneshot re-run
docker exec frigate mknod /dev/apex_9 c 120 99
docker exec frigate /etc/s6-overlay/s6-rc.d/init-devices/run
acl=$(docker exec frigate getfacl -p /dev/apex_9)
echo "$acl"
echo "$acl" | grep -q "user:frigate:rw-"
echo "$acl" | grep -q "user:go2rtc:rw-"
# the usb tree gets recursive grants plus a default ACL that
# newly created nodes inherit (the Coral re-enumeration path)
docker exec frigate sh -c 'mkdir -p /dev/bus/usb/001 && mknod /dev/bus/usb/001/002 c 189 1'
docker exec frigate /etc/s6-overlay/s6-rc.d/init-devices/run
docker exec frigate getfacl -p /dev/bus/usb/001 | grep -q "user:frigate:rwx"
docker exec frigate sh -c 'mknod /dev/bus/usb/001/099 c 189 98 && chmod 664 /dev/bus/usb/001/099'
inherited=$(docker exec frigate getfacl -p /dev/bus/usb/001/099)
echo "$inherited"
echo "$inherited" | grep -q "user:frigate:rw-"
# getfacl prints granted perms even when the mask clamps them to
# nothing, with a trailing "#effective:" comment; a clamped ACL must
# fail this assertion, not sneak past it. The check is scoped to the
# runtime users because the inherited group:: entry is always clamped
# on a non-directory, so an unscoped grep could never pass.
if echo "$inherited" | grep -E "^user:(frigate|go2rtc):" | grep -q "effective"; then
echo "inherited ACL is mask-clamped and grants no real access"; exit 1
fi
# hardware that is absent must stay silent: the literal table entries
# are not globs, so nullglob does not drop them and only an existence
# check keeps them from warning on every boot
out=$(docker exec frigate /etc/s6-overlay/s6-rc.d/init-devices/run)
echo "$out"
if echo "$out" | grep -q "WARN"; then
echo "grant warned about device nodes that do not exist"; exit 1
fi
- name: Assert escape hatch restores root
run: |
mkdir -p /tmp/frigate-config-root
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config-root/config.yml
# pre-seed so the absence check proves the rm -f, not a vacuous pass
echo "2:1000:1000" > /tmp/frigate-config-root/.permissions_version
docker run -d --name frigate-root --shm-size 256m \
-e FRIGATE_RUN_AS_ROOT=true \
-v /tmp/frigate-config-root:/config \
${{ steps.setup.outputs.image-name }}-amd64
up=0
for i in $(seq 1 60); do
docker exec frigate-root curl -fs http://127.0.0.1:5000/api/version && up=1 && break
sleep 5
done
if [ "$up" -ne 1 ]; then echo "escape hatch container never healthy"; docker logs frigate-root; exit 1; fi
ps_out=$(docker exec frigate-root ps -eo user=,comm=)
echo "$ps_out"
echo "$ps_out" | grep -w python3 | grep -q '^root'
echo "$ps_out" | grep -w go2rtc | grep -q '^root'
echo "$ps_out" | grep -w nginx | grep -q '^root'
# an if, not ! test: bash exempts negated commands from set -e
if docker exec frigate-root test -f /config/.permissions_version; then
echo "escape hatch did not delete the sweep sentinel"; exit 1
fi
docker rm -f frigate-root
- name: Assert granular root services
run: |
mkdir -p /tmp/frigate-config-granular /tmp/frigate-media-granular
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config-granular/config.yml
docker run -d --name frigate-granular --shm-size 256m \
-e FRIGATE_ROOT_SERVICES=frigate \
-v /tmp/frigate-config-granular:/config \
-v /tmp/frigate-media-granular:/media/frigate \
${{ steps.setup.outputs.image-name }}-amd64
up=0
for i in $(seq 1 60); do
docker exec frigate-granular curl -fs http://127.0.0.1:5000/api/version && up=1 && break
sleep 5
done
if [ "$up" -ne 1 ]; then echo "granular container never became healthy"; docker logs frigate-granular; exit 1; fi
ps_out=$(docker exec frigate-granular ps -eo user=,comm=)
echo "$ps_out"
# the listed service runs as root
echo "$ps_out" | grep -w python3 | grep -q '^root'
# unlisted services still drop; ifs because set -e exempts negated commands
if echo "$ps_out" | grep -w go2rtc | grep -q '^root'; then
echo "go2rtc is unexpectedly running as root"; exit 1
fi
if echo "$ps_out" | grep -w nginx | grep -q '^root'; then
echo "nginx is unexpectedly running as root"; exit 1
fi
# the sweep still ran and the sentinel records the mode
docker exec frigate-granular cat /config/.permissions_version | grep -qx "2:1000:1000:frigate"
# the root frigate process chowns the db it creates (first-boot immediacy)
docker exec frigate-granular stat -c %u /config/frigate.db | grep -qx 1000
# plant a root-owned straggler; the per-boot sweep must reclaim it on restart
docker exec frigate-granular sh -c 'mkdir -p /media/frigate/clips && touch /media/frigate/clips/straggler.webp'
docker restart frigate-granular
up=0
for i in $(seq 1 60); do
docker exec frigate-granular curl -fs http://127.0.0.1:5000/api/version && up=1 && break
sleep 5
done
if [ "$up" -ne 1 ]; then echo "granular container never came back after restart"; docker logs frigate-granular; exit 1; fi
docker exec frigate-granular stat -c %u /media/frigate/clips/straggler.webp | grep -qx 1000
docker rm -f frigate-granular
- name: Assert unknown root service fails fast
run: |
mkdir -p /tmp/frigate-config-badsvc
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config-badsvc/config.yml
docker run -d --name frigate-badsvc --shm-size 256m \
-e FRIGATE_ROOT_SERVICES=frigatee \
-v /tmp/frigate-config-badsvc:/config \
${{ steps.setup.outputs.image-name }}-amd64
found=0
for i in $(seq 1 12); do
if docker logs frigate-badsvc 2>&1 | grep -q "unknown service 'frigatee'"; then found=1; break; fi
sleep 5
done
if [ "$found" -ne 1 ]; then
echo "no fail-fast error for an unknown service name"; docker logs frigate-badsvc; exit 1
fi
# the failed oneshot blocks startup through the dependency chain
if docker exec frigate-badsvc curl -fs http://127.0.0.1:5000/api/version; then
echo "container came up despite an invalid FRIGATE_ROOT_SERVICES"; exit 1
fi
docker rm -f frigate-badsvc
- name: Assert PUID/PGID remapping
run: |
mkdir -p /tmp/frigate-config-puid
mkdir -p /tmp/frigate-config-puid /tmp/frigate-media-puid
printf 'mqtt:\n enabled: false\ncameras: {}\n' > /tmp/frigate-config-puid/config.yml
docker run -d --name frigate-puid --shm-size 256m \
-e PUID=1500 -e PGID=1500 \
-v /tmp/frigate-config-puid:/config \
-v /tmp/frigate-media-puid:/media/frigate \
${{ steps.setup.outputs.image-name }}-amd64
up=0
for i in $(seq 1 60); do
@@ -110,7 +281,7 @@ jobs:
if [ "$up" -ne 1 ]; then echo "PUID container never became healthy"; docker logs frigate-puid; exit 1; fi
docker exec frigate-puid id -u frigate | grep -qx 1500
docker exec frigate-puid id -g frigate | grep -qx 1500
docker exec frigate-puid cat /config/.permissions_version | grep -qx "1:1500:1500"
docker exec frigate-puid cat /config/.permissions_version | grep -qx "2:1500:1500"
# second boot must skip the sweep (sentinel hit). Poll rather than
# sleep: the string can only come from the second boot (the first
# had no sentinel), so grepping the full log is unambiguous.
+2
View File
@@ -146,6 +146,8 @@ RUN wget -q https://github.com/openvinotoolkit/open_model_zoo/raw/master/data/da
RUN wget -qO - https://www.kaggle.com/api/v1/models/google/yamnet/tfLite/classification-tflite/1/download | tar xvz && mv 1.tflite cpu_audio_model.tflite
COPY audio-labelmap.txt .
RUN chmod -R a+rX /rootfs
FROM wget AS s6-overlay
ARG TARGETARCH
+8 -8
View File
@@ -3,7 +3,7 @@
set -euxo pipefail
NGINX_VERSION="1.27.4"
VOD_MODULE_VERSION="1.31"
VOD_MODULE_VERSION="v1.9.1"
SECURE_TOKEN_MODULE_VERSION="1.5"
SET_MISC_MODULE_VERSION="v0.33"
NGX_DEVEL_KIT_VERSION="v0.3.3"
@@ -31,24 +31,24 @@ wget -nv https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz
tar -zxf nginx-${NGINX_VERSION}.tar.gz -C /tmp/nginx --strip-components=1
rm nginx-${NGINX_VERSION}.tar.gz
mkdir /tmp/nginx-vod-module
wget -nv https://github.com/kaltura/nginx-vod-module/archive/refs/tags/${VOD_MODULE_VERSION}.tar.gz
wget -nv https://github.com/dio-az/nginx-vod-module/archive/refs/tags/${VOD_MODULE_VERSION}.tar.gz
tar -zxf ${VOD_MODULE_VERSION}.tar.gz -C /tmp/nginx-vod-module --strip-components=1
rm ${VOD_MODULE_VERSION}.tar.gz
# Patch MAX_CLIPS to allow more clips to be added than the default 128
sed -i 's/MAX_CLIPS (128)/MAX_CLIPS (1080)/g' /tmp/nginx-vod-module/vod/media_set.h
patch -d /tmp/nginx-vod-module/ -p1 << 'EOF'
--- a/vod/avc_hevc_parser.c 2022-06-27 11:38:10.000000000 +0000
+++ b/vod/avc_hevc_parser.c 2023-01-16 11:25:10.900521298 +0000
@@ -3,6 +3,9 @@
--- a/vod/avc_hevc_parser.c
+++ b/vod/avc_hevc_parser.c
@@ -2,6 +2,9 @@
bool_t
avc_hevc_parser_rbsp_trailing_bits(bit_reader_state_t* reader)
{
avc_hevc_parser_rbsp_trailing_bits(bit_reader_state_t* reader) {
+ // https://github.com/blakeblackshear/frigate/issues/4572
+ return TRUE;
+
uint32_t one_bit;
if (reader->stream.eof_reached)
if (reader->stream.eof_reached) {
EOF
+1 -1
View File
@@ -10,7 +10,7 @@ apt-get -qq install --no-install-recommends -y \
gnupg \
wget \
lbzip2 \
procps vainfo \
procps vainfo acl \
unzip locales tzdata libxml2 xz-utils \
python3.11 \
curl \
@@ -6,6 +6,24 @@ set -o errexit -o nounset -o pipefail
# Logs should be sent to stdout so that s6 can collect them
# Not `nginx -s reload`: that has root parse /tmp/nginx/conf, which the
# unprivileged nginx user can rewrite, and nginx chowns path directives on load.
function reload_nginx() {
local pid
if ! pid=$(cat /tmp/nginx/nginx.pid 2>/dev/null); then
echo "[ERROR] No nginx pid file found, not reloading"
return 0
fi
if [[ ! "$pid" =~ ^[0-9]+$ ]] || [[ "$(cat "/proc/${pid}/comm" 2>/dev/null)" != "nginx" ]]; then
echo "[ERROR] nginx pid file does not name a running nginx process, not reloading"
return 0
fi
kill -HUP "$pid"
}
echo "[INFO] Starting certsync..."
lefile="/etc/letsencrypt/live/frigate/fullchain.pem"
@@ -49,7 +67,7 @@ do
then
echo "[INFO] Reloading nginx to refresh TLS certificate"
echo "$lefile: $leprint"
/usr/local/nginx/sbin/nginx -s reload
reload_nginx
fi
sleep 60
@@ -4,6 +4,19 @@
set -o errexit -o nounset -o pipefail
runs_as_root=0
if [[ "$(id -u)" -eq 0 ]]; then
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]] || /usr/local/bin/service-runs-as-root frigate; then
runs_as_root=1
fi
fi
# /root survives s6-setuidgid and breaks cache writes after the drop; set
# before opt_in_out so the opt-out marker lands where the service will look
if [[ "$runs_as_root" -eq 0 ]]; then
export HOME=/config
fi
# opt out of openvino telemetry
if [ -e /usr/local/bin/opt_in_out ]; then
/usr/local/bin/opt_in_out --opt_out > /dev/null 2>&1
@@ -30,4 +43,8 @@ cd /opt/frigate || echo "[ERROR] Failed to change working directory to /opt/frig
# Replace the bash process with the Frigate process, redirecting stderr to stdout
exec 2>&1
exec python3 -u -m frigate
if [[ "$(id -u)" -ne 0 || "$runs_as_root" -eq 1 ]]; then
exec python3 -u -m frigate
else
exec s6-setuidgid frigate python3 -u -m frigate
fi
@@ -4,6 +4,20 @@
set -o errexit -o nounset -o pipefail
runs_as_root=0
if [[ "$(id -u)" -eq 0 ]]; then
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]] || /usr/local/bin/service-runs-as-root go2rtc; then
runs_as_root=1
fi
fi
# Root via FRIGATE_ROOT_SERVICES only; the escape hatch sweeps nothing and
# leaves no unprivileged service, so /config/go2rtc stays as safe as pre-drop.
granular_root=0
if [[ "$runs_as_root" -eq 1 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
granular_root=1
fi
# Logs should be sent to stdout so that s6 can collect them
function get_ip_and_port_from_supervisor() {
@@ -50,42 +64,6 @@ function set_libva_version() {
export LIBAVFORMAT_VERSION_MAJOR
}
function setup_homekit_config() {
local config_path="$1"
if [[ ! -f "${config_path}" ]]; then
echo "[INFO] Creating empty config file for HomeKit..."
: > "${config_path}"
fi
# Convert YAML to JSON for jq processing
local temp_json="/tmp/cache/homekit_config.json"
yq eval -o=json "${config_path}" > "${temp_json}" 2>/dev/null || {
echo "[WARNING] Failed to convert HomeKit config to JSON, skipping cleanup"
return 0
}
# Use jq to extract the homekit section, if it exists
local homekit_json
homekit_json=$(jq '
if has("homekit") then {homekit: .homekit} else null end
' "${temp_json}" 2>/dev/null) || homekit_json="null"
# If no homekit section, write an empty config file
if [[ "${homekit_json}" == "null" ]]; then
: > "${config_path}"
else
# Convert homekit JSON back to YAML and write to the config file
echo "${homekit_json}" | yq eval -P - > "${config_path}" 2>/dev/null || {
echo "[WARNING] Failed to convert cleaned config to YAML, creating minimal config"
: > "${config_path}"
}
fi
# Clean up temp files
rm -f "${temp_json}"
}
set_libva_version
if [[ -f "/dev/shm/go2rtc.yaml" ]]; then
@@ -106,13 +84,23 @@ else
echo "[WARNING] Unable to remove existing go2rtc config. Changes made to your frigate config file may not be recognized. Please remove the /dev/shm/go2rtc.yaml from your docker host manually."
fi
# HomeKit configuration persistence setup
# HomeKit persistence. The helper is symlink-safe; hand off to go2rtc only when dropping.
readonly homekit_config_path="/config/go2rtc_homekit.yml"
setup_homekit_config "${homekit_config_path}"
if [[ "$(id -u)" -eq 0 && "$runs_as_root" -eq 0 ]]; then
python3 /usr/local/go2rtc/prepare_homekit.py "${homekit_config_path}" --chown
chown go2rtc:go2rtc /dev/shm/go2rtc.yaml 2>/dev/null || true
else
python3 /usr/local/go2rtc/prepare_homekit.py "${homekit_config_path}"
fi
readonly config_path="/config"
if [[ -x "${config_path}/go2rtc" ]]; then
# the sweep hands /config to uid 1000, so a root service must not exec from it
if [[ "$granular_root" -eq 1 && -x "${config_path}/go2rtc" ]]; then
echo "[WARN] Ignoring '${config_path}/go2rtc' because FRIGATE_ROOT_SERVICES runs this service as root and /config is owned by the runtime user; using the embedded binary"
echo "[WARN] Use FRIGATE_RUN_AS_ROOT=true instead if you need both a custom go2rtc build and root"
readonly binary_path="/usr/local/go2rtc/bin/go2rtc"
elif [[ -x "${config_path}/go2rtc" ]]; then
readonly binary_path="${config_path}/go2rtc"
echo "[WARN] Using go2rtc binary from '${binary_path}' instead of the embedded one"
else
@@ -125,4 +113,8 @@ echo "[INFO] Starting go2rtc..."
# Use HomeKit config as the primary config so writebacks go there
# The main config from Frigate will be loaded as a secondary config
exec 2>&1
exec "${binary_path}" -config="${homekit_config_path}" -config=/dev/shm/go2rtc.yaml
if [[ "$(id -u)" -ne 0 || "$runs_as_root" -eq 1 ]]; then
exec "${binary_path}" -config="${homekit_config_path}" -config=/dev/shm/go2rtc.yaml
else
exec s6-setuidgid go2rtc "${binary_path}" -config="${homekit_config_path}" -config=/dev/shm/go2rtc.yaml
fi
+104
View File
@@ -0,0 +1,104 @@
#!/command/with-contenv bash
# shellcheck shell=bash
# Grant the runtime users access to mapped-in device nodes with POSIX ACLs,
# so --device works without host-side group or udev setup.
# No-op when: started with --user (euid != 0), FRIGATE_RUN_AS_ROOT=true,
# or FRIGATE_DEVICE_ACLS=false.
set -o errexit -o nounset -o pipefail
if [[ "$(id -u)" -ne 0 ]]; then
exit 0
fi
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
exit 0
fi
if [[ "${FRIGATE_DEVICE_ACLS:-true}" == "false" ]]; then
echo "[INFO] FRIGATE_DEVICE_ACLS=false: skipping device access grants"
exit 0
fi
shopt -s nullglob
device_globs=(
"/dev/dri/*"
"/dev/accel/*"
"/dev/apex_*"
"/dev/hailo*"
"/dev/video*"
"/dev/kfd"
"/dev/rknpu*"
"/dev/mpp_service"
"/dev/rga"
"/dev/dma_heap/*"
"/dev/nvhost*"
"/dev/nvmap"
"/dev/nvidia*"
"/dev/memx*"
)
IFS=',' read -ra extra_globs <<< "${DEVICE_ACL_PATHS:-}"
for extra in "${extra_globs[@]}"; do
extra="${extra//[[:space:]]/}"
if [[ -z "$extra" ]]; then
continue
fi
if [[ "$extra" != /dev/* || "$extra" == *..* ]]; then
echo "[ERROR] DEVICE_ACL_PATHS entries must be under /dev, got '${extra}'" >&2
exit 1
fi
device_globs+=("$extra")
done
granted=0
failed=0
grant() {
local node="$1"
# nullglob only drops patterns that hold a metacharacter, so a literal
# table entry for absent hardware arrives here verbatim. Warn only about
# nodes that exist and could not be granted.
if [[ ! -e "$node" ]]; then
return 0
fi
local spec="u:frigate:rw,u:go2rtc:rw"
# directories need traverse or nothing under them is reachable
if [[ -d "$node" ]]; then
spec="u:frigate:rwx,u:go2rtc:rwx"
fi
if setfacl -m "$spec" "$node" 2>/dev/null; then
granted=$((granted + 1))
else
failed=$((failed + 1))
echo "[WARN] could not grant device access on ${node}; see EXTRA_GROUPS in the non-root docs for the fallback"
fi
}
for glob in "${device_globs[@]}"; do
# shellcheck disable=SC2231
for node in $glob; do
grant "$node"
done
done
# USB devices re-enumerate (the Coral uploads firmware and reattaches as a new
# node), so the directories also get a default ACL new nodes inherit. The
# inherited grant is clamped by the creating mode's group bits, which is rw on
# udev hosts (0664) and nothing on raw devtmpfs (0600); hardware-verified.
if [[ -d /dev/bus/usb ]]; then
while IFS= read -r -d '' node; do
grant "$node"
done < <(find /dev/bus/usb -mindepth 1 -print0)
while IFS= read -r -d '' dir; do
setfacl -d -m "u:frigate:rw,u:go2rtc:rw" "$dir" 2>/dev/null || \
echo "[WARN] could not set a default ACL on ${dir}; a re-enumerating USB device may lose access"
done < <(find /dev/bus/usb -type d -print0)
fi
if [[ "$failed" -gt 0 ]]; then
echo "[INFO] device access: granted ${granted} node(s), ${failed} failed"
elif [[ "$granted" -gt 0 ]]; then
echo "[INFO] device access: granted ${granted} node(s) to the runtime users"
fi
@@ -0,0 +1 @@
oneshot
@@ -0,0 +1 @@
/etc/s6-overlay/s6-rc.d/init-devices/run
@@ -2,7 +2,7 @@
# shellcheck shell=bash
# Remap the frigate user to PUID/PGID and register EXTRA_GROUPS.
# No-op when: started with --user (euid != 0), FRIGATE_RUN_AS_ROOT=true,
# or PUID/PGID already match.
# or PUID/PGID already match. FRIGATE_ROOT_SERVICES is validated here too.
set -o errexit -o nounset -o pipefail
@@ -12,10 +12,31 @@ if [[ "$(id -u)" -ne 0 ]]; then
fi
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
if [[ -n "${FRIGATE_ROOT_SERVICES:-}" ]]; then
echo "[INFO] FRIGATE_RUN_AS_ROOT=true: ignoring FRIGATE_ROOT_SERVICES"
fi
echo "[INFO] FRIGATE_RUN_AS_ROOT=true: skipping user remapping"
exit 0
fi
# a typo must fail the boot, not silently drop a service to non-root
if [[ -n "${FRIGATE_ROOT_SERVICES:-}" ]]; then
IFS=',' read -ra root_services <<< "${FRIGATE_ROOT_SERVICES}"
for entry in "${root_services[@]}"; do
entry="${entry//[[:space:]]/}"
if [[ -z "$entry" ]]; then
continue
fi
case "$entry" in
frigate|go2rtc|nginx) ;;
*)
echo "[ERROR] FRIGATE_ROOT_SERVICES contains unknown service '${entry}'; valid names are frigate, go2rtc, nginx" >&2
exit 1
;;
esac
done
fi
puid="${PUID:-1000}"
pgid="${PGID:-1000}"
@@ -32,6 +53,15 @@ if [[ "$puid" -eq 0 || "$pgid" -eq 0 ]]; then
exit 1
fi
# Colliding with the go2rtc ids would merge the two users and collapse the
# separation between the main process and the network-facing restreamer.
go2rtc_uid="$(id -u go2rtc)"
go2rtc_gid="$(id -g go2rtc)"
if [[ "$puid" -eq "$go2rtc_uid" || "$pgid" -eq "$go2rtc_gid" ]]; then
echo "[ERROR] PUID/PGID must not equal the go2rtc service ids (${go2rtc_uid}:${go2rtc_gid})." >&2
exit 1
fi
current_uid="$(id -u frigate)"
current_gid="$(id -g frigate)"
@@ -50,6 +80,10 @@ fi
# EXTRA_GROUPS: numeric host GIDs granting device access (e.g. host render/video)
if [[ -n "${EXTRA_GROUPS:-}" ]]; then
for gid in ${EXTRA_GROUPS//,/ }; do
if ! [[ "$gid" =~ ^[0-9]+$ ]] || [[ "$gid" -eq 0 ]]; then
echo "[ERROR] EXTRA_GROUPS must be nonzero numeric GIDs, got '${gid}'" >&2
exit 1
fi
if ! getent group "$gid" >/dev/null; then
groupadd -o -g "$gid" "frigate-extra-${gid}"
fi
@@ -2,4 +2,4 @@
set -e
# Wait for PID file to exist.
while ! test -f /run/nginx.pid; do sleep 1; done
while ! test -f /tmp/nginx/nginx.pid; do sleep 1; done
@@ -4,6 +4,13 @@
set -o errexit -o nounset -o pipefail
runs_as_root=0
if [[ "$(id -u)" -eq 0 ]]; then
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]] || /usr/local/bin/service-runs-as-root nginx; then
runs_as_root=1
fi
fi
# Logs should be sent to stdout so that s6 can collect them
echo "[INFO] Starting NGINX..."
@@ -59,10 +66,18 @@ function set_worker_processes() {
cpus=4
fi
# we need to catch any errors because sed will fail if user has bind mounted a custom nginx file
sed -i "s/worker_processes auto;/worker_processes ${cpus};/" /usr/local/nginx/conf/nginx.conf || true
sed -i "s/worker_processes auto;/worker_processes ${cpus};/" /tmp/nginx/conf/nginx.conf
}
# Rebuilt root-owned every start: a symlink planted by the previously
# unprivileged nginx would redirect the root cp/tempio writes below onto any
# root file. rm does not traverse symlinks; the bare mkdir fails closed if raced.
rm -rf /tmp/nginx
mkdir /tmp/nginx
mkdir -p /tmp/nginx/conf /tmp/nginx/client_body /tmp/nginx/proxy \
/tmp/nginx/fastcgi /tmp/nginx/uwsgi /tmp/nginx/scgi
cp -r /usr/local/nginx/conf/. /tmp/nginx/conf/
set_worker_processes
# ensure the directory for ACME challenges exists
@@ -87,15 +102,37 @@ nginx_settings=$(python3 /usr/local/nginx/get_nginx_settings.py)
# build templates for optional FRIGATE_BASE_PATH environment variable
echo "$nginx_settings" | \
tempio -template /usr/local/nginx/templates/base_path.gotmpl \
-out /usr/local/nginx/conf/base_path.conf
-out /tmp/nginx/conf/base_path.conf
# build templates for additional network settings
echo "$nginx_settings" | \
tempio -template /usr/local/nginx/templates/listen.gotmpl \
-out /usr/local/nginx/conf/listen.conf
-out /tmp/nginx/conf/listen.conf
if [[ "$(id -u)" -eq 0 && "$runs_as_root" -eq 0 ]]; then
chown -R frigate:frigate /tmp/nginx
# heal the cache: a root `nginx -t` chowns every cycle path to the `user` directive user
if [ -d /dev/shm/nginx_cache ]; then
chown -R frigate:frigate /dev/shm/nginx_cache
fi
# nginx reopens /dev/stdout by path for its logs, and s6 made the pipe
# root-owned 0600; without this the non-root master exits EACCES
chown frigate /dev/stdout
# self-signed certs are root-generated; tolerant because mounted certs may be :ro
if [ -f "$letsencrypt_path/privkey.pem" ]; then
chown frigate:frigate "$letsencrypt_path/privkey.pem" "$letsencrypt_path/fullchain.pem" 2>/dev/null || true
fi
fi
# Replace the bash process with the NGINX process, redirecting stderr to stdout
exec 2>&1
exec \
s6-notifyoncheck -t 30000 -n 1 \
nginx
# -e stderr: the compiled-in error log path is not writable by the runtime user
if [[ "$(id -u)" -ne 0 || "$runs_as_root" -eq 1 ]]; then
exec \
s6-notifyoncheck -t 30000 -n 1 \
nginx -e stderr -c /tmp/nginx/conf/nginx.conf
else
exec \
s6-notifyoncheck -t 30000 -n 1 \
s6-setuidgid frigate nginx -e stderr -c /tmp/nginx/conf/nginx.conf
fi
@@ -153,7 +153,50 @@ if [[ "$(id -u)" -eq 0 ]]; then
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" == "true" ]]; then
rm -f /config/.permissions_version
else
/usr/local/bin/fix-ownership --sentinel /config/.permissions_version \
# Only when a mount backs /media/frigate itself: under a parent /media
# mount, a dedicated volume added later would be shadowed and skipped
sentinel_args=(--sentinel /config/.permissions_version)
root_services_mode=""
if [[ -n "${FRIGATE_ROOT_SERVICES:-}" ]]; then
# || true: an all-empty list (",") fails grep -v and errexit would kill the boot
root_services_mode=$(tr ',' '\n' <<< "${FRIGATE_ROOT_SERVICES//[[:space:]]/}" | grep -v '^$' | sort -u | paste -sd, - || true)
if [[ -n "$root_services_mode" ]]; then
sentinel_args+=(--mode "$root_services_mode")
fi
fi
if ! awk '$2 == "/media/frigate" || $2 ~ /^\/media\/frigate\//' /proc/mounts | grep -q .; then
sentinel_args=()
fi
/usr/local/bin/fix-ownership "${sentinel_args[@]}" \
"${PUID:-1000}" "${PGID:-1000}" /config /media/frigate
# Root services write clips stragglers and caches mid-run; realign the
# small trees every boot. Recordings are chowned at create instead.
if [[ -n "$root_services_mode" ]]; then
# only sweep what exists; clips and exports appear after the first run
boot_sweep_paths=(/config)
for extra in /media/frigate/clips /media/frigate/exports; do
if [[ -d "$extra" ]]; then
boot_sweep_paths+=("$extra")
fi
done
/usr/local/bin/fix-ownership \
"${PUID:-1000}" "${PGID:-1000}" "${boot_sweep_paths[@]}"
fi
fi
fi
# Must stay after the sweep, which reads an absent /media/frigate as an
# unmounted volume rather than a swept one
if [[ "$(id -u)" -eq 0 && ! -d /media/frigate ]]; then
mkdir -p /media/frigate
if [[ "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
chown "${PUID:-1000}:${PGID:-1000}" /media/frigate
fi
fi
# usually a tmpfs mount: root-owned on arrival and outside the swept volumes
if [[ "$(id -u)" -eq 0 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
mkdir -p /tmp/cache
chown "${PUID:-1000}:${PGID:-1000}" /tmp/cache
fi
+79 -14
View File
@@ -1,15 +1,17 @@
#!/bin/bash
# Single source of truth for aligning volume ownership with the runtime user.
#
# Usage: fix-ownership [--dry-run] [--sentinel FILE] UID GID PATH [PATH...]
# Usage: fix-ownership [--dry-run] [--sentinel FILE] [--mode STRING] UID GID PATH [PATH...]
#
# --dry-run report what would change, touch nothing
# --sentinel skip entirely when FILE already records "SCHEMA:UID:GID";
# write it after a successful run (used by the boot path so
# multi-TB volumes are swept once per UID/schema change, not
# on every boot)
# --mode append STRING to the sentinel, so changing it re-sweeps once
#
# Only files whose uid OR gid differs are touched, so re-runs are cheap.
# lost+found is skipped: fsck fills it with root-only recovered fragments.
# Top-level /config additionally grants group frigate-data TRAVERSE ONLY
# (g+rx) so the separate go2rtc user can reach its pre-created HomeKit file
# on hosts where /config is mounted 0700. Never g+w: directory write means
@@ -22,10 +24,11 @@ set -o errexit -o nounset -o pipefail
# Permissions-layout epoch. Bump to force a one-time re-sweep on upgrade
# (e.g. when the privilege-drop release must capture files created as root
# since the previous sweep).
schema=1
schema=2
dry_run=0
sentinel=""
mode=""
while [[ "${1:-}" == --* ]]; do
case "$1" in
@@ -36,12 +39,18 @@ while [[ "${1:-}" == --* ]]; do
exit 2
fi
sentinel="$2"; shift 2 ;;
--mode)
if [[ -z "${2:-}" ]]; then
echo "[ERROR] fix-ownership: --mode requires a value" >&2
exit 2
fi
mode="$2"; shift 2 ;;
*) echo "[ERROR] fix-ownership: unknown option $1" >&2; exit 2 ;;
esac
done
if [[ $# -lt 3 ]]; then
echo "Usage: fix-ownership [--dry-run] [--sentinel FILE] UID GID PATH..." >&2
echo "Usage: fix-ownership [--dry-run] [--sentinel FILE] [--mode STRING] UID GID PATH..." >&2
exit 2
fi
@@ -54,11 +63,21 @@ if [[ "$(id -u)" -ne 0 ]]; then
exit 0
fi
# A dry run always inspects: the sentinel records what a past sweep did, not
# what the volume looks like now, and reporting from it would hide later drift.
if [[ "$dry_run" -eq 0 && -n "$sentinel" && -f "$sentinel" && "$(cat "$sentinel")" == "${schema}:${target_uid}:${target_gid}" ]]; then
echo "[INFO] fix-ownership: ${target_uid}:${target_gid} (schema ${schema}) already applied, skipping"
exit 0
# The list folds into the sentinel so entering or leaving a granular root mode
# re-sweeps once, catching whatever the other ownership mechanisms missed.
sentinel_content="${schema}:${target_uid}:${target_gid}"
if [[ -n "$mode" ]]; then
sentinel_content="${sentinel_content}:${mode}"
fi
# safe-sentinel reports only a root-owned regular file, so a forged or
# symlinked sentinel in the runtime-user-owned /config can't suppress the sweep
if [[ "$dry_run" -eq 0 && -n "$sentinel" ]]; then
if existing=$(/usr/local/bin/safe-sentinel read "$sentinel" 2>/dev/null) && \
[[ "$existing" == "$sentinel_content" ]]; then
echo "[INFO] fix-ownership: ${target_uid}:${target_gid} (schema ${schema}) already applied, skipping"
exit 0
fi
fi
# A sweep that could not chown everything must not be recorded as complete:
@@ -66,6 +85,26 @@ fi
# unreachable once services run unprivileged.
swept_clean=1
# Entries another mechanism deliberately owns. Chowning them undoes that work
# and leaves the same "mismatch" waiting for the next boot, so /config could
# never report itself clean: /config is chgrp'd to frigate-data below so go2rtc
# can traverse it, and the HomeKit file is handed to the go2rtc user by the
# go2rtc service. Only the GROUP on /config is exempt; a root-owned /config
# must still be chowned or the runtime user cannot write there at all.
# Shared by the counting and the chowning walk so the two cannot disagree.
mismatch_expr=(
"(" -not -uid "$target_uid"
-o "(" -not -gid "$target_gid" -a ! -path /config ")"
")"
-a ! -path /config/go2rtc_homekit.yml
)
if [[ -n "$sentinel" ]]; then
# safe-sentinel keeps the sentinel root-owned on purpose and rejects one
# owned by anybody else, so chowning it here would suppress the skip and
# make every boot re-sweep. Only the trailing write puts it back today.
mismatch_expr+=(-a ! -path "$sentinel")
fi
for path in "$@"; do
# An absent root is an incomplete sweep, not a finished one: /media/frigate
# is not in the image, so a boot before the volume is mounted would
@@ -76,11 +115,13 @@ for path in "$@"; do
continue
fi
echo "[INFO] fix-ownership: scanning ${path} for ownership mismatches; this may take a while on large filesystems"
# find may fail mid-walk on a live volume (file deleted under it) or on a
# stale mount. Tolerate it rather than aborting under errexit, but never
# read a failed scan as "nothing to do": that would record the sweep as
# complete without having looked.
if ! count=$(find "$path" \( -not -uid "$target_uid" -o -not -gid "$target_gid" \) -printf '.' 2>/dev/null | wc -c); then
if ! count=$(find "$path" -name lost+found -prune -o "${mismatch_expr[@]}" -printf '.' 2>/dev/null | wc -c); then
swept_clean=0
echo "[WARN] fix-ownership: could not scan ${path}; will retry on next boot"
continue
@@ -98,17 +139,41 @@ for path in "$@"; do
echo "[WARN] fix-ownership: ${path} contains symlinked directories; ownership behind them is not managed and must be aligned by hand"
fi
echo "[WARN] fix-ownership: adjusting ownership of ${count} entries under ${path}; on large recordings volumes this can take a long time"
echo "[WARN] fix-ownership: adjusting ownership of ${count} entries under ${path}"
if [[ "$dry_run" -eq 1 ]]; then
echo "[INFO] fix-ownership: dry run, not changing ${path}"
continue
fi
find "$path" \( -not -uid "$target_uid" -o -not -gid "$target_gid" \) \
-exec chown -h "${target_uid}:${target_gid}" {} + || {
# -execdir chowns from the entry's own directory, so a parent swapped for a
# symlink mid-walk can't redirect the chown out of the volume
started=$SECONDS
if find "$path" -name lost+found -prune -o "${mismatch_expr[@]}" \
-print -execdir chown -h "${target_uid}:${target_gid}" {} + \
| awk -v total="$count" -v path="$path" '
BEGIN { next_pct = 5 }
{
pct = int(NR * 100 / total)
if (pct > 100) pct = 100
if (pct >= next_pct) {
printf "[INFO] fix-ownership: %s %d%% (%d/%d entries)\n", path, pct, NR, total
# mawk block-buffers to a pipe; without fflush the whole
# progress log arrives at once
fflush()
while (next_pct <= pct) next_pct += 5
}
}'; then
elapsed=$((SECONDS - started))
if [[ "$elapsed" -ge 60 ]]; then
elapsed="$((elapsed / 60))m $((elapsed % 60))s"
else
elapsed="${elapsed}s"
fi
echo "[INFO] fix-ownership: finished ${path} in ${elapsed}"
else
swept_clean=0
echo "[WARN] fix-ownership: some entries under ${path} could not be updated (deleted mid-sweep or chown denied); will retry on next mismatch"
}
fi
done
# go2rtc (separate user) must be able to REACH its HomeKit state in /config.
@@ -124,6 +189,6 @@ if [[ "$dry_run" -eq 0 && -d /config ]]; then
fi
if [[ "$dry_run" -eq 0 && -n "$sentinel" && "$swept_clean" -eq 1 ]]; then
echo "${schema}:${target_uid}:${target_gid}" > "$sentinel" || \
/usr/local/bin/safe-sentinel write "$sentinel" "$sentinel_content" || \
echo "[WARN] fix-ownership: could not write ${sentinel}; the sweep will run again on next boot"
fi
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Read or write the ownership sweep sentinel without following symlinks.
The sentinel lives in /config, which the unprivileged runtime user owns, so it
can be swapped for a symlink. read trusts only a root-owned regular file; write
never follows a symlink or fifo onto another file.
Usage:
safe-sentinel read PATH print content, exit 0 only if root-owned regular file
safe-sentinel write PATH CONTENT write CONTENT to a regular file at PATH
"""
import errno
import os
import stat
import sys
MODE = 0o644
def do_read(path: str) -> int:
try:
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
except OSError:
return 1
try:
st = os.fstat(fd)
if not stat.S_ISREG(st.st_mode) or st.st_uid != 0:
return 1
sys.stdout.buffer.write(os.read(fd, 4096))
finally:
os.close(fd)
return 0
def do_write(path: str, content: str) -> int:
# O_NONBLOCK so a fifo fails fast (ENXIO) instead of blocking the open.
flags = os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK
replace = (errno.ELOOP, errno.ENXIO)
try:
fd = os.open(path, flags, MODE)
if not stat.S_ISREG(os.fstat(fd).st_mode):
os.close(fd)
raise OSError(errno.ELOOP, "not a regular file")
except OSError as err:
if err.errno not in replace:
raise
os.unlink(path)
fd = os.open(path, flags | os.O_EXCL, MODE)
try:
os.ftruncate(fd, 0)
os.write(fd, content.encode())
# keep it root-owned so a later sweep that chowned the old sentinel to
# the runtime user can't make the next read reject and re-sweep
os.fchown(fd, 0, 0)
finally:
os.close(fd)
return 0
def main(argv: list[str]) -> int:
if len(argv) == 3 and argv[1] == "read":
return do_read(argv[2])
if len(argv) == 4 and argv[1] == "write":
try:
return do_write(argv[2], argv[3])
except OSError:
return 1
print("usage: safe-sentinel read PATH | write PATH CONTENT", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main(sys.argv))
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# Exit 0 when FRIGATE_ROOT_SERVICES names the given service. Membership only:
# the euid and FRIGATE_RUN_AS_ROOT checks stay in the callers.
#
# Usage: service-runs-as-root SERVICE
set -o nounset
service="${1:?usage: service-runs-as-root SERVICE}"
IFS=',' read -ra entries <<< "${FRIGATE_ROOT_SERVICES:-}"
for entry in "${entries[@]}"; do
entry="${entry//[[:space:]]/}"
if [[ "$entry" == "$service" ]]; then
exit 0
fi
done
exit 1
@@ -0,0 +1,97 @@
"""Normalize the go2rtc HomeKit file and hand it to go2rtc, as root.
Runs before the drop. The file is in the runtime-user-owned /config, so a
planted symlink could redirect the root write or chown onto another file;
every operation goes through an O_NOFOLLOW fd to prevent that.
Usage: prepare_homekit.py PATH [--chown]
"""
import errno
import grp
import io
import os
import pwd
import stat
import sys
from ruamel.yaml import YAML
RUNTIME_OWNER = "go2rtc"
SHARED_GROUP = "frigate-data"
MODE = 0o664
MAX_BYTES = 10 * 1024 * 1024
def open_nofollow(path: str) -> int:
"""Return an fd to a regular file at path, never following a symlink."""
flags = os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW
try:
fd = os.open(path, flags, MODE)
except OSError as err:
if err.errno != errno.ELOOP:
raise
os.unlink(path)
return os.open(path, flags | os.O_EXCL, MODE)
# A fifo or other non-regular file would hang or misbehave on read; replace it.
if not stat.S_ISREG(os.fstat(fd).st_mode):
os.close(fd)
os.unlink(path)
return os.open(path, flags | os.O_EXCL, MODE)
return fd
def normalize(content: str) -> str:
"""Keep only the homekit section, matching the previous yq/jq behavior."""
yaml = YAML(typ="safe")
try:
data = yaml.load(content)
except Exception:
return ""
if not isinstance(data, dict) or "homekit" not in data:
return ""
buf = io.StringIO()
yaml.dump({"homekit": data["homekit"]}, buf)
return buf.getvalue()
def main() -> int:
if len(sys.argv) < 2:
print("[ERROR] prepare_homekit: PATH is required", file=sys.stderr)
return 2
path = sys.argv[1]
do_chown = "--chown" in sys.argv[2:]
fd = open_nofollow(path)
try:
content = os.read(fd, MAX_BYTES).decode("utf-8", "replace")
normalized = normalize(content)
os.ftruncate(fd, 0)
os.lseek(fd, 0, os.SEEK_SET)
os.write(fd, normalized.encode("utf-8"))
if do_chown:
# tolerate a chown-refusing mount (NFS root_squash): pairing
# persistence degrades, the service does not
try:
uid = pwd.getpwnam(RUNTIME_OWNER).pw_uid
gid = grp.getgrnam(SHARED_GROUP).gr_gid
os.fchown(fd, uid, gid)
os.fchmod(fd, MODE)
except (KeyError, OSError):
print(
f"[WARN] Could not hand {path} to the go2rtc user; "
"HomeKit pairing changes may not persist"
)
finally:
os.close(fd)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,9 +1,13 @@
# Loaded with -c from the /tmp/nginx/conf copy: relative includes follow the -c
# file, all other path directives follow --prefix and must stay absolute.
daemon off;
# ignored by a non-root master; keeps workers root under FRIGATE_RUN_AS_ROOT
user root;
worker_processes auto;
error_log /dev/stdout warn;
pid /var/run/nginx.pid;
pid /tmp/nginx/nginx.pid;
events {
worker_connections 1024;
@@ -13,6 +17,12 @@ http {
map_hash_bucket_size 256;
server_tokens off;
client_body_temp_path /tmp/nginx/client_body;
proxy_temp_path /tmp/nginx/proxy;
fastcgi_temp_path /tmp/nginx/fastcgi;
uwsgi_temp_path /tmp/nginx/uwsgi;
scgi_temp_path /tmp/nginx/scgi;
include mime.types;
default_type application/octet-stream;
@@ -122,6 +132,10 @@ http {
# Smaller segments, faster generation, better browser compatibility
vod_hls_container_format fmp4;
# fMP4 playlists use EXT-X-MAP, which requires HLS protocol
# version 6 (RFC 8216 section 7); the module default is 4
vod_hls_version 6;
secure_token $args;
secure_token_types application/vnd.apple.mpegurl;
@@ -130,14 +144,6 @@ http {
expires off;
keepalive_disable safari;
# vod module returns 502 for non-existent media
# https://github.com/kaltura/nginx-vod-module/issues/468
error_page 502 =404 /vod-not-found;
}
location = /vod-not-found {
return 404;
}
location /stream/ {
+10
View File
@@ -36,6 +36,16 @@ if ! [[ "$puid" =~ ^[0-9]+$ && "$pgid" =~ ^[0-9]+$ ]]; then
fi
echo "[INFO] Using image ${IMAGE} (override with FRIGATE_IMAGE=...)"
if ! docker image inspect "${IMAGE}" >/dev/null 2>&1; then
echo "[INFO] ${IMAGE} is not present locally and has to be pulled first; this may take a while"
fi
if [[ -n "$dry_run_flag" ]]; then
echo "[INFO] Dry run: reporting what would change under ${config_dir} and ${media_dir}, changing nothing"
else
echo "[INFO] Aligning ${config_dir} and ${media_dir} to ${puid}:${pgid}; this may take a while on large filesystems"
fi
# shellcheck disable=SC2086
docker run --rm \
-v "${config_dir}:/config" \
@@ -13,6 +13,16 @@ TRT_VER=${TRT_VER:-$(cat /etc/TENSORRT_VER)}
OUTPUT_FOLDER="${MODEL_CACHE_DIR}/${TRT_VER}"
YOLO_MODELS=${YOLO_MODELS:-""}
# This runs as root after prepare's sentinel-guarded sweep, so the dirs and
# engines it creates below are the runtime user's to fix up, on every exit path
function hand_off_ownership() {
if [[ "$(id -u)" -eq 0 && "${FRIGATE_RUN_AS_ROOT:-false}" != "true" ]]; then
/usr/local/bin/fix-ownership "${PUID:-1000}" "${PGID:-1000}" \
/config/model_cache "${MODEL_CACHE_DIR}"
fi
}
trap hand_off_ownership EXIT
# Create output folder
mkdir -p ${OUTPUT_FOLDER}
+7 -1
View File
@@ -397,6 +397,10 @@ To do this:
2. Update the `ffmpeg.path` in your Frigate config to `/config/custom-ffmpeg`.
3. Restart Frigate and the custom version will be used if the steps above were done correctly.
Both binaries have to be executable by Frigate's unprivileged runtime user, so `chmod 755` them after extracting. The startup ownership sweep runs only once, so anything you add to `/config` later keeps whatever ownership and mode you gave it.
There is one exception, and it only affects [`FRIGATE_ROOT_SERVICES`](/configuration/non_root#keeping-individual-services-root) listing `frigate`. That mode runs Frigate as root while still handing `/config` to the unprivileged runtime user, so anything running as that user could swap the binary and gain root. A build inside any of Frigate's writable volumes (`/config`, `/media/frigate`, the cache and shm dirs) is ignored there and the bundled one is used, with a warning in the log. Keep the build somewhere root-owned (any absolute `ffmpeg.path` works, so a read-only bind mount such as `/opt/custom-ffmpeg` is enough) if you need both. The default mode and `FRIGATE_RUN_AS_ROOT=true` are unaffected and behave exactly as they always have.
### Custom go2rtc version
Frigate currently includes go2rtc v1.9.14, there may be certain cases where you want to run a different version of go2rtc.
@@ -405,9 +409,11 @@ To do this:
1. Download the go2rtc build to the `/config` folder.
2. Rename the build to `go2rtc`.
3. Give `go2rtc` execute permission.
3. Give `go2rtc` execute permission for all users (`chmod 755`). It runs as its own `go2rtc` user, which doesn't own the file, so owner-only execute permission isn't enough.
4. Restart Frigate and the custom version will be used, you can verify by checking go2rtc logs.
The same exception applies, and again only to [`FRIGATE_ROOT_SERVICES`](/configuration/non_root#keeping-individual-services-root) listing `go2rtc`: the binary is ignored there and the embedded one is used, with a warning in the log. Unlike `ffmpeg.path`, the go2rtc binary location is not configurable, so there is no outside-`/config` alternative. Use `FRIGATE_RUN_AS_ROOT=true` instead if you need both a custom go2rtc build and root. The default mode and the escape hatch both honor `/config/go2rtc` exactly as they always have.
## Validating your config.yml file updates
When frigate starts up, it checks whether your config file is valid, and if it is not, the process exits. To minimize interruptions when updating your config, you have three options -- you can edit the config via the WebUI which has built in validation, use the config API, or you can validate on the command line using the frigate docker container.
+3 -1
View File
@@ -22,7 +22,9 @@ The following ports are available to access the Frigate web UI.
## Onboarding
On startup, an admin user and password are generated and printed in the logs. It is recommended to set a new password for the admin account after logging in for the first time under Settings > Users.
On startup, an admin user and password are generated and printed in the logs. It is recommended to set a new password for the admin account after logging in for the first time.
On a new install the [setup wizard](../guides/getting_started.md#configuring-frigate) offers this as its first step, along with creating accounts for anyone else who needs access. You can also do both at any time under <NavPath path="Settings > Users" />.
## Resetting admin password
+1 -1
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
## Adding a camera with the Add Camera Wizard
The Add Camera Wizard is the recommended way to add a camera. Click **Add Camera** in <NavPath path="Settings > Global configuration > Camera management" />. The wizard connects to your camera, tests each stream, and writes the camera's configuration for you, including the [go2rtc](go2rtc.md) restream and the live view stream mapping, so a standard setup needs no hand-written YAML.
The Add Camera Wizard is the recommended way to add a camera. Click **Add Camera** in <NavPath path="Settings > Global configuration > Camera management" />, or use it from the [setup wizard](../guides/getting_started.md#configuring-frigate) on a new install. The wizard connects to your camera, tests each stream, and writes the camera's configuration for you, including the [go2rtc](go2rtc.md) restream and the live view stream mapping, so a standard setup needs no hand-written YAML.
### Step 1: Name and connection
@@ -8,7 +8,7 @@ import TabItem from "@theme/TabItem";
import NavPath from "@site/src/components/NavPath";
import FaqItem from "@site/src/components/FaqItem";
Frigate can recognize license plates on vehicles and automatically add the detected characters to the `recognized_license_plate` field or a [known](#matching) name as a `sub_label` to tracked objects of type `car` or `motorcycle`. A common use case may be to read the license plates of cars pulling into a driveway or cars passing by on a street.
Frigate can recognize license plates on vehicles and automatically add the detected characters to the `recognized_license_plate` field or a [known](#matching) name as a `sub_label` to tracked objects of type `car`, `motorcycle`, `bus`, `truck`, `school_bus`, or `garbage_truck`, depending on which of those labels your model detects. A common use case may be to read the license plates of cars pulling into a driveway or cars passing by on a street.
LPR works best when the license plate is clearly visible to the camera. For moving vehicles, Frigate continuously refines the recognition process, keeping the most confident result. When a vehicle becomes stationary, LPR continues to run for a short time after to attempt recognition.
@@ -24,7 +24,7 @@ When a plate is recognized, the details are:
- Viewable in the Details pane in Review/History.
- Viewable in the Tracked Object Details pane in Explore (sub labels and recognized license plates).
- Filterable through the More Filters menu in Explore.
- Published via the `frigate/events` MQTT topic as a `sub_label` ([known](#matching)) or `recognized_license_plate` (unknown) for the `car` or `motorcycle` tracked object.
- Published via the `frigate/events` MQTT topic as a `sub_label` ([known](#matching)) or `recognized_license_plate` (unknown) for the vehicle tracked object.
- Published via the `frigate/tracked_object_update` MQTT topic with `name` (if [known](#matching)) and `plate`.
## Model Requirements
@@ -35,7 +35,7 @@ Users without a model that detects license plates can still run LPR. Frigate use
:::note
In the default mode, Frigate's LPR needs to first detect a `car` or `motorcycle` before it can recognize a license plate. If you're using a dedicated LPR camera and have a zoomed-in view where a `car` or `motorcycle` will not be detected, you can still run LPR, but the configuration parameters will differ from the default mode. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section below.
In the default mode, Frigate's LPR needs to first detect a vehicle before it can recognize a license plate. If you're using a dedicated LPR camera and have a zoomed-in view where a vehicle will not be detected, you can still run LPR, but the configuration parameters will differ from the default mode. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section below.
:::
@@ -86,7 +86,7 @@ cameras:
</TabItem>
</ConfigTabs>
For non-dedicated LPR cameras, ensure that your camera is configured to detect objects of type `car` or `motorcycle`, and that a car or motorcycle is actually being detected by Frigate. Otherwise, LPR will not run.
For non-dedicated LPR cameras, ensure that your camera is configured to detect vehicle objects, and that a vehicle is actually being detected by Frigate. Otherwise, LPR will not run. The object types that can carry a plate are defined by your model's `attributes_map`, so if your model detects other vehicle labels, you can add them there.
Like the other real-time processors in Frigate, license plate recognition runs on the camera stream defined by the `detect` role in your config. To ensure optimal performance, select a suitable resolution for this stream in your camera's firmware that fits your specific scene and requirements.
@@ -158,7 +158,7 @@ lpr:
Navigate to <NavPath path="Settings > Enrichments > License plate recognition" />.
- **Known plates**: Assign custom `sub_label` values to `car` and `motorcycle` objects when a recognized plate matches a known value. These labels appear in the UI, filters, and notifications. Unknown plates are still saved but are added to the `recognized_license_plate` field rather than the `sub_label`.
- **Known plates**: Assign custom `sub_label` values to vehicle objects when a recognized plate matches a known value. These labels appear in the UI, filters, and notifications. Unknown plates are still saved but are added to the `recognized_license_plate` field rather than the `sub_label`.
- **Match distance**: Allows for minor variations (missing/incorrect characters) when matching a detected plate to a known plate. For example, setting to `1` allows a plate `ABCDE` to match `ABCBE` or `ABCD`. This parameter will _not_ operate on known plates that are defined as regular expressions.
</TabItem>
@@ -316,7 +316,7 @@ lpr:
:::note
If a camera is configured to detect `car` or `motorcycle` but you don't want Frigate to run LPR for that camera, disable LPR at the camera level:
If a camera is configured to detect vehicles but you don't want Frigate to run LPR for that camera, disable LPR at the camera level:
<ConfigTabs>
<TabItem value="ui">
@@ -456,7 +456,7 @@ With this setup:
- Snapshots will have license plate bounding boxes on them.
- The `frigate/events` MQTT topic will publish tracked object updates.
- Debug view will display `license_plate` bounding boxes.
- If you are using a Frigate+ model and want to submit images from your dedicated LPR camera for model training and fine-tuning, annotate both the `car` / `motorcycle` and the `license_plate` in the snapshots on the Frigate+ website, even if the car is barely visible.
- If you are using a Frigate+ model and want to submit images from your dedicated LPR camera for model training and fine-tuning, annotate both the vehicle and the `license_plate` in the snapshots on the Frigate+ website, even if the vehicle is barely visible.
### Using the Secondary LPR Pipeline (Without Frigate+)
@@ -611,9 +611,9 @@ If you are still having issues detecting plates, start with a basic configuratio
</FaqItem>
<FaqItem id="can-i-run-lpr-without-detecting-car-or-motorcycle-objects" question={<>Can I run LPR without detecting <code>car</code> or <code>motorcycle</code> objects?</>}>
<FaqItem id="can-i-run-lpr-without-detecting-car-or-motorcycle-objects" question={<>Can I run LPR without detecting vehicle objects?</>}>
In normal LPR mode, Frigate requires a `car` or `motorcycle` to be detected first before recognizing a license plate. If you have a dedicated LPR camera, you can change the camera `type` to `"lpr"` to use the Dedicated LPR Camera algorithm. This comes with important caveats, though. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section above.
In normal LPR mode, Frigate requires a vehicle to be detected first before recognizing a license plate. If you have a dedicated LPR camera, you can change the camera `type` to `"lpr"` to use the Dedicated LPR Camera algorithm. This comes with important caveats, though. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section above.
</FaqItem>
@@ -699,7 +699,7 @@ lpr:
4. Ensure the characters on detected plates are being _recognized_.
- Check the **Plate recognition** inference time in Enrichment metrics (<NavPath path="System metrics > Enrichments" />). High inference times (> 100ms) could lead to poor recognition results, especially for dedicated LPR cameras where the plate crosses the frame quickly.
- Enable `debug_save_plates` to save images of detected text on plates to the clips directory (`/media/frigate/clips/lpr`). Ensure these images are readable and the text is clear.
- Watch the debug view to see plates recognized in real-time. For non-dedicated LPR cameras, the `car` or `motorcycle` label will change to the recognized plate when LPR is enabled and working.
- Watch the debug view to see plates recognized in real-time. For non-dedicated LPR cameras, the vehicle's label will change to the recognized plate when LPR is enabled and working.
- Adjust `recognition_threshold` settings per the suggestions [above](#advanced-configuration).
</FaqItem>
@@ -714,13 +714,13 @@ LPR's performance impact depends on your hardware. Ensure you have at least 4GB
The YOLOv9 license plate detector model will run (and the metric will appear) if you've enabled LPR but haven't defined `license_plate` as an object to track, either at the global or camera level.
If you are detecting `car` or `motorcycle` on cameras where you don't want to run LPR, make sure you disable LPR it at the camera level. And if you do want to run LPR on those cameras, make sure you define `license_plate` as an object to track.
If you are detecting vehicles on cameras where you don't want to run LPR, make sure you disable LPR it at the camera level. And if you do want to run LPR on those cameras, make sure you define `license_plate` as an object to track.
</FaqItem>
<FaqItem id="it-looks-like-frigate-picked-up-my-cameras-timestamp-or-overlay-text-as-the-license-plate-how-can-i-prevent-this" question="It looks like Frigate picked up my camera's timestamp or overlay text as the license plate. How can I prevent this?">
This could happen if cars or motorcycles travel close to your camera's timestamp or overlay text. You could either move the text through your camera's firmware, or apply a mask to it in Frigate.
This could happen if vehicles travel close to your camera's timestamp or overlay text. You could either move the text through your camera's firmware, or apply a mask to it in Frigate.
If you are using a model that natively detects `license_plate`, add an _object mask_ of type `license_plate` and a _motion mask_ over your text.
+280
View File
@@ -0,0 +1,280 @@
---
id: non_root
title: Running as a non-root user
---
# Running as a non-root user
Frigate's services run as an unprivileged user inside the container. The main Frigate process and nginx run as `frigate`, and go2rtc runs as its own more restricted `go2rtc` user. Only the s6 init system and the certsync helper stay root.
The runtime user is uid/gid `1000:1000` by default. You can change it with `PUID`/`PGID`, or bypass Frigate's user handling entirely with Docker's own `user:`.
Most upgrades need nothing. Frigate aligns your volume ownership on the first boot and grants access to your hardware at startup. The sections below cover the cases that need attention: large storage volumes, network storage, and hardware the automatic grant can't reach.
## Run modes
| Mode | How to enable | Ownership of `/config` and `/media/frigate` | `read_only: true` |
| ------------------- | ------------------------------- | ------------------------------------------------------ | ----------------- |
| Default | nothing, this is the default | Aligned to `1000:1000` on first boot | Not supported |
| `PUID`/`PGID` | `PUID=1001`, `PGID=1001` | Aligned to the values you set, on first boot | Not supported |
| Docker-native user | `user: "1001:1001"` | You own it, Frigate never changes ownership | Not supported |
| Root (escape hatch) | `FRIGATE_RUN_AS_ROOT=true` | Never touched | Not supported |
| Granular root | `FRIGATE_ROOT_SERVICES=frigate` | Aligned at boot; recordings and exports also at create | Not supported |
`PUID`/`PGID` remapping runs `usermod` at startup, which writes to `/etc/passwd`, so it can't work with a read-only root filesystem. That combination stops at startup with a message pointing here.
`FRIGATE_RUN_AS_ROOT` is matched against the exact lowercase string `true`. `True`, `TRUE`, and `1` are all ignored. `FRIGATE_DEVICE_ACLS` works the same way: only the lowercase string `false` turns off the automatic device grants.
### Keeping individual services root
`FRIGATE_ROOT_SERVICES` takes a comma separated list of `frigate`, `go2rtc`, and `nginx`. A listed service keeps running as root, and everything else about non-root operation still applies: `PUID`/`PGID` remapping, the ownership sweep, and ownership of the files those services create.
There are two reasons to use it:
- Your detector hardware won't work as an unprivileged user, even after reading [Hardware device access](#hardware-device-access). `FRIGATE_ROOT_SERVICES=frigate` keeps the main process and its detectors as root while nginx and go2rtc stay unprivileged.
- You want everything to run as root but still want your files owned by `PUID`/`PGID` instead of root. `FRIGATE_ROOT_SERVICES=frigate,go2rtc,nginx` does that.
Try the device grants and `EXTRA_GROUPS` first. The `frigate` service runs the API and every ffmpeg process that decodes your camera streams, so listing it puts those back on root as well, not just your detectors.
A listed service also stops honoring a [custom ffmpeg or go2rtc build](/configuration/advanced/system#custom-dependencies) kept in `/config`, since that directory stays owned by the unprivileged user and a binary there would run as root. `FRIGATE_RUN_AS_ROOT=true` has no such restriction.
Recordings and exports are owned by `PUID`/`PGID` as soon as they're written, even by a root service. Snapshots, thumbnails, and other files under `clips/` are corrected on each restart, so they can show as root-owned from the host until then. A listed service also keeps root's home directory, so library caches go to the container layer instead of `/config`.
Listing all three services is not the same as `FRIGATE_RUN_AS_ROOT=true`. The escape hatch never touches ownership; the list keeps the ownership handling active. A few more details:
- An unknown name in the list stops the container at startup, rather than silently leaving a service unprivileged.
- Changing the list runs the full ownership sweep once on the next boot.
- If both are set, `FRIGATE_RUN_AS_ROOT=true` wins and the list is ignored.
- With Docker's `user:`, the list does nothing, since the container never has root to keep.
## Migrating an existing install
Volumes from earlier versions of Frigate are owned by root, so ownership has to be aligned with the runtime user once. This happens automatically on the first boot after upgrading.
On large recordings volumes, do it from the host beforehand instead. The boot sweep runs before any service starts, so a multi-terabyte `/media/frigate` can hold the container in startup long enough for Docker's healthcheck to mark it unhealthy, and orchestrators that watch health will restart it mid-sweep. If you'd rather not run the script, raise the healthcheck start period instead (`--start-period=1800s`, or `start_period: 1800s` under `healthcheck:` in compose).
Grab [`fix-permissions.sh`](https://github.com/blakeblackshear/frigate/blob/dev/docker/migration/fix-permissions.sh) from the Frigate repo and dry run it first:
```bash
./fix-permissions.sh --dry-run /path/to/your/config /path/to/your/storage
```
That reports how many entries would change and touches nothing. When it looks right, run it without `--dry-run`:
```bash
./fix-permissions.sh /path/to/your/config /path/to/your/storage
```
Pass `PUID` and `PGID` as the third and fourth arguments if you're not using the default `1000:1000`. The script wraps the same helper the container uses, so the result is identical either way. Override the image it pulls with `FRIGATE_IMAGE=...` if you're not on `stable`.
Both the script and the boot sweep report progress, so you can tell a slow sweep from a stuck one:
```
[INFO] fix-ownership: scanning /media/frigate for ownership mismatches; this may take a while on large filesystems
[WARN] fix-ownership: adjusting ownership of 4823941 entries under /media/frigate
[INFO] fix-ownership: /media/frigate 5% (241197/4823941 entries)
[INFO] fix-ownership: /media/frigate 10% (482394/4823941 entries)
[INFO] fix-ownership: finished /media/frigate in 12m 4s
```
The scan has no percentage because the total isn't known until it finishes. Watch the boot sweep with `docker logs -f frigate`.
Once the volumes are aligned, start Frigate normally. A file at `/config/.permissions_version` records what was done, so later boots skip the sweep unless you change `PUID`/`PGID`.
If something under your volumes can't be chowned, a read-only btrfs snapshot directory for example, the sweep warns and names the path and doesn't record the migration as finished. It retries on the next boot instead. Either move those paths outside `/media/frigate` or expect the scan to repeat.
### Network storage
Recordings on a NAS behave differently, so check what you have before migrating:
```bash
findmnt -T /path/to/your/storage -o TARGET,FSTYPE,OPTIONS
```
**SMB and CIFS** don't store per-file ownership at all. It's synthesized from the mount options, so a per-file `chown` fails and isn't needed. Mount the share as the uid and gid Frigate runs as, and every file already looks correct to the sweep:
```
//nas/frigate /media/frigate cifs credentials=/root/.smb,uid=1000,gid=1000,file_mode=0664,dir_mode=0775 0 0
```
**NFS** exports default to `root_squash` on most servers, which maps the container's root to `nobody`. The chown then fails, you get `[WARN] fix-ownership: some entries under /media/frigate could not be updated`, and since the sweep didn't finish it doesn't record the migration, so it retries on every boot.
The best fix is to not chown over NFS at all. Do it on the server, where there's no squash and no network round trip per file:
```bash
# on the NAS itself, against the exported directory
chown -R 1000:1000 /export/frigate
```
Frigate's sweep then finds nothing to change and records the migration normally. If you can't get a shell on the server, you can export temporarily with `no_root_squash`, migrate, and put it back, or leave ownership alone and set `PUID`/`PGID` to whichever uid already owns the files.
Either way the uid has to mean the same thing on both machines. NFS sends numeric uids, so container uid 1000 is uid 1000 on the server no matter what the usernames are.
Expect the first boot to be slow even when nothing needs changing, because checking ownership costs a round trip per file. That's a one-time cost. **If the sweep runs on every boot rather than once, ownership isn't actually being applied**, and the warning above will say so.
Keep `/config` on local storage either way. Frigate's database is SQLite and network shares handle its locking poorly. That's a long-standing recommendation, not something running non-root introduces.
## Rolling back
Set `FRIGATE_RUN_AS_ROOT=true` and restart. Everything runs as root again, exactly as it did before. This is the fastest way to get a broken install running while you sort out a device permission problem.
The escape hatch never changes ownership, and it clears the record of the last sweep on startup, so switching back to non-root later corrects whatever root created in the meantime. Toggling in either direction is safe.
## Hardware device access
Frigate grants the runtime user access to your devices at startup. Pass your hardware with `--device` (or `devices:` in compose) and detection and hardware acceleration work with no group or udev setup on the host.
The grant covers the common accelerator and camera nodes: GPU render nodes, Intel/AMD NPUs (`/dev/accel`), Coral, Hailo, Rockchip, Jetson, `/dev/video*`, and the USB bus. For hardware it misses, add your own paths with `DEVICE_ACL_PATHS`, a comma separated list of globs:
```yaml
environment:
DEVICE_ACL_PATHS: "/dev/mydev*"
```
Set `FRIGATE_DEVICE_ACLS=false` if you manage device permissions yourself and want Frigate to leave them alone.
Frigate grants access by adding an ACL entry for the runtime users. The device's owner and mode are unchanged, and nothing is made world accessible. One thing to know: `--device` nodes belong to the container, but a bind mounted `/dev/bus/usb` (the usual Coral USB setup) shares the host's device nodes, so the entry is visible on the host until udev recreates the node.
### Manual setup
You only need this for hardware the automatic grant can't reach, or for Docker's `user:` mode, where there's no root startup to do the granting.
Your accelerator most likely worked in older versions because Frigate ran as root. Device nodes are usually owned by `root:root`, and root either matches the group or skips the check entirely. The runtime user does neither, so a device that worked before can become unreadable with no change to your Frigate config.
#### Read what your device requires
Find the node and look at its owner, group, and mode:
```bash
ls -ln /dev/dri/renderD128
crw-rw---- 1 0 105 226, 128 Jul 5 10:12 /dev/dri/renderD128
# ^ ^ ^
# | | group GID 105
# | owner UID 0 (root)
# mode: owner rw, group rw, other none
```
Then work out which of the three permission sets applies to the runtime user. It isn't the owner, since that's root, so it gets the group bits if it belongs to that GID and otherwise falls through to "other". In the example above "other" is empty, so without membership in group 105 the runtime user can't open the node.
Watch for a node that looks permissive but isn't. A USB Coral defaults to this:
```bash
ls -ln /dev/bus/usb/004/003
crw-rw-r-- 1 0 0 189, 386 Jul 5 10:12 /dev/bus/usb/004/003
```
The group is `0`, so "other" applies to the runtime user, and "other" here is read only. `libedgetpu` needs to write to the node, so detection fails with `No EdgeTPU was detected` as though no Coral were attached. Read access alone isn't enough for most accelerators.
#### Grant access
Give the runtime user the GID with `EXTRA_GROUPS`, a comma separated list of numeric host GIDs. They're added to both the `frigate` and `go2rtc` users, which matters because go2rtc needs its own render and video access for hardware accelerated restreams.
```yaml
environment:
EXTRA_GROUPS: "105,44" # host render and video GIDs
```
Use numeric GIDs from the host, not names. Group names don't have to match between the host and the container, and the kernel only checks the number. If the GID doesn't exist in the image, Frigate creates a placeholder group for it.
Two things that look like they should work but don't:
- Docker's `group_add` has no effect in the default or `PUID` modes. Frigate rebuilds the supplementary group list from `/etc/group` when it drops privileges, which discards what Docker passed in. It is the right tool with Docker's `user:`, where no privilege drop happens and `EXTRA_GROUPS` does nothing.
- `privileged: true` doesn't help. It grants capabilities to root, and the runtime user isn't root, so the file permissions on the node still apply.
If the node's group is `root` or the mode denies the group, no `EXTRA_GROUPS` value will help. You need a udev rule first.
#### Verify access
Check the group landed, then check the runtime user can open the node. Test for write, not just read:
```bash
docker exec frigate id frigate
docker exec frigate /command/s6-setuidgid frigate sh -c 'test -w /dev/dri/renderD128 && echo ok'
docker exec frigate /command/s6-setuidgid go2rtc sh -c 'test -w /dev/dri/renderD128 && echo ok'
```
A permission check is only a proxy for the driver working. These exercise the real libraries as the runtime user:
```bash
docker exec frigate /command/s6-setuidgid frigate vainfo
docker exec frigate /command/s6-setuidgid frigate python3 -c "import openvino as ov; print(ov.Core().available_devices)"
```
`vainfo` should reach `va_openDriver() returns 0` and list profiles. Complaints about `XDG_RUNTIME_DIR` or an X server above that are normal. OpenVINO should list `GPU`; if it returns only `CPU`, detection has fallen back and inference will be much slower without an error in the log.
To tell a permissions problem from anything else, start the container once with `FRIGATE_RUN_AS_ROOT=true`. If the device works as root and not otherwise, it's node permissions and a udev rule is the fix. If it's missing either way, the problem is your device mapping or the host, and isn't related to running non-root.
#### udev rules by device
Rules go in `/etc/udev/rules.d/` on the host and take effect after:
```bash
sudo udevadm control --reload-rules && sudo udevadm trigger
```
A device that's already connected sometimes keeps its original ownership through a trigger. If `ls -ln` doesn't show the new group, replug it, or reboot for a built-in device.
**Coral USB** needs two rules, because the device re-enumerates after loading firmware. It appears as Global Unichip `1a6e` before and Google `18d1` after, with a different node each time. A rule covering only `1a6e` gives you a Coral that starts up once and then disappears mid-run.
```
SUBSYSTEM=="usb", ATTRS{idVendor}=="1a6e", GROUP="plugdev", MODE="0664"
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", GROUP="plugdev", MODE="0664"
```
Map the whole `/dev/bus/usb` rather than a single node, for the same reason. Most hosts put `plugdev` at GID 46 and the image agrees, so a USB Coral often needs no `EXTRA_GROUPS` entry. Confirm with `getent group plugdev` and add the number if your host differs.
**Coral PCIe** is often `crw------- root root`, which only root can open:
```
SUBSYSTEM=="apex", MODE="0660", GROUP="apex"
```
Create the group with `sudo groupadd -f apex`, then add its GID to `EXTRA_GROUPS`.
**Hailo** works the same way. Grant `/dev/hailo0` a group and add that GID:
```
SUBSYSTEM=="hailo_chardev", MODE="0660", GROUP="hailo"
```
**Intel and AMD GPUs** usually need nothing beyond `EXTRA_GROUPS`, since most distributions ship a `render` group that owns `/dev/dri/renderD128`. The GID often differs between the host and the image, so pass the host's number rather than assuming the name resolves. Debian based images have no `render` group at all.
#### Quick reference
What each device needs when you're setting it up by hand. The automatic grant covers most of these already, so start here only if it didn't.
| Hardware | Device(s) | What non-root needs |
| ------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Intel/AMD GPU (VAAPI/QSV) | `/dev/dri/renderD128` | Host render GID in `EXTRA_GROUPS`, from `getent group render` |
| Intel/AMD NPU | `/dev/accel` | udev rule granting a group, then that GID in `EXTRA_GROUPS` |
| Coral USB | `/dev/bus/usb` | udev rules for both `1a6e` and `18d1`; usually already covered by `plugdev` 46 |
| Coral PCIe | `/dev/apex_0` | udev rule granting a group, then that GID in `EXTRA_GROUPS` |
| Hailo | `/dev/hailo0` | udev rule granting a group, then that GID in `EXTRA_GROUPS` |
| NVIDIA | nvidia runtime | Nothing, works with the nvidia-container-toolkit defaults |
| AMD ROCm | `/dev/kfd`, `/dev/dri` | Host `video` and `render` GIDs in `EXTRA_GROUPS` |
| Raspberry Pi | `/dev/video11` | Host `video` GID in `EXTRA_GROUPS` |
| Rockchip | `/dev/dri`, `/dev/dma_heap`, `/dev/rga`, `/dev/mpp_service` | Commonly `root:root` `0600`, so all four need udev rules. If you can't grant all four, use `FRIGATE_RUN_AS_ROOT` |
| Axera (AXCL) | `/dev/ax_*` per the AXCL driver docs | Unverified. Check node ownership on your hardware before assuming this works |
| Synaptics SL1680 | per the Synaptics docs | Unverified |
| MemryX | per the MemryX docs | Still requires `privileged: true`, which means root. Out of scope for non-root operation |
| Nvidia Jetson | nvidia runtime plus Jetson nodes | Unverified. The nvidia runtime handles mapping, but check `/dev/nvhost-*` ownership on your board |
| VeriSilicon NPU (Teflon) | per the driver, commonly `/dev/galcore` | Unverified. Check node ownership on your hardware before assuming this works |
| CPU detector | none | Nothing, no device is opened |
| ZMQ detector | none | Nothing, inference happens over a socket |
| Apple Silicon | none | Nothing, the NPU client runs on the host and Frigate reaches it over the network |
## Known limitations
`telemetry.stats.network_bandwidth` uses nethogs, which needs `CAP_NET_ADMIN` and `CAP_NET_RAW` and therefore root. The stat is turned off automatically when Frigate isn't running as root, with one warning in the log. Use `FRIGATE_ROOT_SERVICES=frigate` (or `FRIGATE_RUN_AS_ROOT=true`) if you need it.
go2rtc's ffmpeg processes no longer appear in Intel GPU stats. Frigate reads per-process GPU usage from `/proc/<pid>/fdinfo`, which the kernel won't let one user read for another user's processes, so anything go2rtc spawns is invisible to it. Overall GPU utilization is unaffected.
If you mount your own TLS certificate at `/etc/letsencrypt/live/frigate`, the private key has to be readable by the runtime user, which runs nginx. Frigate hands the key to that user at startup if the mount is writable; on a read-only mount, make the key readable by uid 1000 (or your `PUID`) yourself.
If you're debugging nginx, run the config check as the runtime user with stdout discarded:
```bash
docker exec frigate /command/s6-setuidgid frigate bash -c 'nginx -t -c /tmp/nginx/conf/nginx.conf >/dev/null'
```
Running `nginx -t` as root hands nginx's runtime directories to root as a side effect, which breaks the running workers until the service restarts, and the config's `/dev/stdout` logs can't be reopened through a root-owned `docker exec` pipe. The results print on stderr either way.
@@ -338,6 +338,8 @@ models:
### Intel NPU host requirements {#intel-npu-requirements}
The NPU device must be passed into the container by adding `/dev/accel:/dev/accel` to the `devices` section of your compose file. Frigate grants the runtime user access to the device automatically; see [hardware device access](/configuration/non_root#hardware-device-access) if you manage device permissions yourself.
The NPU firmware is loaded by the host kernel and is not part of the Frigate image. Everything else the NPU needs is bundled in the container, so host NPU libraries should never be mounted in.
Frigate bundles a specific version of Intel's [linux-npu-driver](https://github.com/intel/linux-npu-driver/releases), and the host firmware must come from that release or a newer one. Firmware older than the bundled driver may fail with `MAPPED_INFERENCE_VERSION is NOT compatible with the ELF`, where `Expected` is the version the firmware supports and `received` is the version the bundled compiler produced. Distributions often package older firmware than the driver Frigate ships, so check the build date on the host with `sudo dmesg | grep -i vpu` and update it there if needed.
+1 -1
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
Recordings can be enabled and are stored at `/media/frigate/recordings`. The folder structure for the recordings is `YYYY-MM-DD/HH/<camera_name>/MM.SS.mp4` in **UTC time**. These recordings are written directly from your camera stream without re-encoding. Each camera supports a configurable retention policy. Frigate chooses the largest matching retention value between the recording retention and the tracked object retention when determining if a recording should be removed.
New recording segments are written from the camera stream to cache, they are only moved to disk if they match the setup recording retention policy.
New recording segments are written from the camera stream to cache, they are only moved to disk if they pass a validation check and match the setup recording retention policy.
:::tip
+5 -8
View File
@@ -548,9 +548,7 @@ services:
### Recommended security options
Frigate does not need elevated container privileges for most setups. The
following hardens the container; add the `devices`/`group_add` entries your
hardware requires (see the hardware acceleration docs):
Frigate does not need elevated container privileges for most setups. The following hardens the container; add the `devices`/`group_add` entries your hardware requires (see the hardware acceleration docs):
```yaml
services:
@@ -564,15 +562,14 @@ services:
:::note
`telemetry.stats.network_bandwidth` uses nethogs, which requires root with
NET_ADMIN/NET_RAW capabilities. If you enable that stat, omit `cap_drop: [ALL]`
or add `cap_add: [NET_ADMIN, NET_RAW]`.
`telemetry.stats.network_bandwidth` uses nethogs, which requires root with NET_ADMIN/NET_RAW capabilities. If you enable that stat, omit `cap_drop: [ALL]` or add `cap_add: [NET_ADMIN, NET_RAW]`.
Platforms that genuinely require `privileged: true` (MemryX, some QNAP setups)
are called out in their own sections and are unaffected by this guidance.
Platforms that genuinely require `privileged: true` (MemryX, some QNAP setups) are called out in their own sections and are unaffected by this guidance.
:::
Frigate's services run as an unprivileged user inside the container. See [Running as a non-root user](../configuration/non_root.md) for the run modes, the one time volume ownership migration, and what each accelerator needs on the host.
**Docker CLI**
If you can't use Docker Compose, you can run the container with something similar to this:
+59 -8
View File
@@ -4,6 +4,7 @@ title: Getting started
---
import ConfigTabs from "@site/src/components/ConfigTabs";
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import NavPath from "@site/src/components/NavPath";
@@ -132,21 +133,68 @@ services:
- "8554:8554" # RTSP feeds
```
Now you should be able to start Frigate by running `docker compose up -d` from within the folder containing `docker-compose.yml`. On startup, an admin user and password will be created and outputted in the logs. You can see this by running `docker logs frigate`. Frigate should now be accessible at `https://server_ip:8971` where you can login with the `admin` user and finish configuration using the Settings UI.
Now you should be able to start Frigate by running `docker compose up -d` from within the folder containing `docker-compose.yml`. On startup, an admin user and password will be created and outputted in the logs. You can see this by running `docker logs frigate`. Frigate should now be accessible at `https://server_ip:8971` where you can login with the `admin` user. With no cameras configured yet, the setup wizard runs on first login and walks you through the rest.
## Configuring Frigate
This section assumes that you already have an environment setup as described in [Installation](../frigate/installation.md). You should also configure your cameras according to the [camera setup guide](/frigate/camera_setup). Pay particular attention to the section on choosing a detect resolution.
### Step 1: Start Frigate
<Tabs
groupId="setup-method"
defaultValue="wizard"
values={[
{ label: "Setup wizard", value: "wizard" },
{ label: "Manual", value: "manual" },
]}
> <TabItem value="wizard">
The first time you open Frigate with no cameras configured, the setup wizard walks you through the basics. Every step can be skipped, everything it sets can be changed later in Settings, and once you finish or dismiss it, it doesn't come back.
:::note
Frigate only sees hardware that has been passed into the container. If you plan to use a GPU, a Coral, or another accelerator, add the device to your `docker-compose.yml` and restart before running the wizard, otherwise it won't appear in the detection or hardware acceleration steps. The Manual tab shows the device entries for an Intel or AMD GPU and for a Coral, and the [hardware acceleration](../configuration/hardware_acceleration_video.md) and [object detectors](../configuration/object_detectors.md) docs cover the rest.
:::
**Account**
Set a password for the `admin` account to replace the generated one from the logs, and add accounts for anyone else who needs access. This step is hidden if you have turned authentication off.
**Add a camera**
Opens the [Add Camera Wizard](../configuration/cameras.md#adding-a-camera-with-the-add-camera-wizard), which connects to the camera, tests each stream, and writes its configuration for you. You can add more than one before moving on.
**Object detection**
Lists the detection hardware Frigate found on your system, such as a Coral, an Intel GPU or NPU, or a discrete GPU, and configures the one you pick. NVIDIA and AMD GPUs need a model before detection can start, so the wizard offers your Frigate+ models if you have them, or lets you finish setup and add one later under <NavPath path="Settings > System > Detection models" />.
**Hardware acceleration**
Offers only the decoding methods your hardware supports. Auto picks one based on that hardware and the codec your camera sends, so a mixed h264 and h265 setup gets the right preset per camera.
**Recording**
Choose whether to record only when something is detected or around the clock, and how long to keep it.
The last screen summarizes what was set up. If a step changed something that needs a restart, the button restarts Frigate and returns you to the Live view once it is back.
The wizard configures the essentials only. Motion masks are not included and should be set up afterward, once you can identify the areas of the frame that trigger unwanted motion. See the [masks documentation](../configuration/masks.md). Zones, tracked object types, notifications, and MQTT are also configured in Settings.
</TabItem>
<TabItem value="manual">
On a new install the setup wizard opens first. Click **Skip setup and configure manually** on its welcome screen to dismiss it, and the steps below apply. The wizard won't come back once dismissed.
**Step 1: Start Frigate**
At this point you should be able to start Frigate and a basic config will be created automatically.
### Step 2: Add a camera
**Step 2: Add a camera**
Click the **Add Camera** button in <NavPath path="Settings > Global configuration > Camera management" /> to use the camera setup wizard to get your first camera added into Frigate. See [Adding a camera with the Add Camera Wizard](../configuration/cameras.md#adding-a-camera-with-the-add-camera-wizard) for a walkthrough of each step.
### Step 3: Configure hardware acceleration (recommended)
**Step 3: Configure hardware acceleration (recommended)**
Now that you have a working camera configuration, set up hardware acceleration to minimize the CPU required to decode your video streams. See the [hardware acceleration](../configuration/hardware_acceleration_video.md) docs for examples applicable to your hardware.
@@ -190,7 +238,7 @@ cameras:
</TabItem>
</ConfigTabs>
### Step 4: Configure detectors
**Step 4: Configure detectors**
By default, Frigate will use a single OpenVINO detector running on the CPU.
@@ -299,7 +347,7 @@ More details on available detectors can be found [here](../configuration/object_
Restart Frigate and you should start seeing detections for `person`. If you want to track other objects, they can be configured in <NavPath path="Settings > Global configuration > Objects" /> or via the [configuration file reference](../configuration/advanced/reference.md).
### Step 5: Setup motion masks
**Step 5: Setup motion masks**
Now that you have optimized your configuration for decoding the video stream, you will want to check to see where to implement motion masks. Click on the camera from the main dashboard, then select the gear icon in the top right, enable the [Debug view](/usage/live#the-single-camera-view), and finally enable the switch for Motion Boxes. Watch for areas that continuously trigger unwanted motion to be detected. Common areas to mask include camera timestamps and trees that frequently blow in the wind. The goal is to avoid wasting object detection cycles looking at these areas.
@@ -336,7 +384,7 @@ cameras:
coordinates: "0,461,3,0,1919,0,1919,843,1699,492,1344,458,1346,336,973,317,869,375,866,432"
```
### Step 6: Enable recordings
**Step 6: Enable recordings**
In order to review activity in the Frigate UI, recordings need to be enabled.
@@ -385,7 +433,10 @@ If you only plan to use Frigate for recording, it is still recommended to define
By default, Frigate will retain video of all tracked objects for 10 days. The full set of options for recording can be found [here](../configuration/advanced/reference.md).
### Step 7: Complete config
</TabItem>
</Tabs>
### Complete config
At this point you have a complete config with basic functionality.
+7 -5
View File
@@ -66,17 +66,19 @@ An FFmpeg message meaning it probed the stream but never saw enough decodable vi
## Recording
<FaqItem id="no-new-recording-segments" question="No new recording segments were created for <camera> in the last 120s">
<FaqItem id="no-new-recording-segments" question="No new recording segments were created (or: No new valid recording segments were created / No valid segments created since last invalid segment) for <camera> in the last 120s">
Frigate's record watchdog is restarting the record FFmpeg process because no valid segment has reached the cache. This means the record stream is not connecting or the segments are being rejected (see the audio-codec entry below).
Frigate's record watchdog is restarting the record FFmpeg process because the camera stopped producing usable recordings. The wording distinguishes the cases: `No new recording segments` means no new segment file reached the cache, so ffmpeg isn't getting video out of the record stream; the two `valid` variants mean recordings are arriving but keep failing validation. Either way the fault is on the camera or network side, and the restart is Frigate trying to recover.
See [Recordings: the record stream isn't connecting](/troubleshooting/recordings#the-record-stream-isnt-connecting).
See [Recordings: no new recording segments were created](/troubleshooting/recordings#no-new-recording-segments-were-created).
</FaqItem>
<FaqItem id="invalid-or-missing-video-stream-in-segment" question="Invalid or missing video stream in segment. Discarding.">
<FaqItem id="invalid-or-missing-video-stream-in-segment" question="Invalid or missing video stream in segment. Discarding. / Discarding a corrupt recording segment / Failed to probe corrupt segment / Invalid recording segment detected">
A cached recording segment failed validation (no readable video stream) and was deleted. The most common cause is a segment that was truncated because the record FFmpeg process was killed mid-write, so this often appears alongside, and as a consequence of, the record-stream restarts above. A segment containing only audio triggers it too.
A cached recording segment failed validation and was deleted, either because it had no readable video stream or because its length was impossible. This nearly always means the camera stopped sending usable video partway through the segment: a camera that rebooted, dropped the connection, or ran out of simultaneous connections, or an unreliable link such as WiFi or a failing switch port. Broken camera timestamps (a "Smart Codec" / H.264+ mode) cause the corrupt-segment variants. The same stream failure trips the record watchdog, so the restarts above usually appear alongside these messages.
See [Recordings: invalid or missing video stream in segment](/troubleshooting/recordings#invalid-or-missing-video-stream-in-segment).
</FaqItem>
+44
View File
@@ -209,6 +209,50 @@ If the record stream uses a "Smart Codec"/H.264+ mode or changes encoding parame
</FaqItem>
<FaqItem id="invalid-or-missing-video-stream-in-segment" question="I see the message: WARNING : Invalid or missing video stream in segment ... Discarding.">
Every recording segment is validated before it leaves the cache. Frigate probes each finished `.mp4` in `/tmp/cache` and requires a readable video stream and a valid duration before moving to storage. A segment that fails is deleted, so those ~10 seconds of footage are lost. Three messages come from this check:
- `Invalid or missing video stream in segment <path>. Discarding.` The segment holds no video, or could not be read at all.
- `Failed to probe corrupt segment <path>` followed by `Discarding a corrupt recording segment: <path>`. The segment was read, but its length could not be determined.
- `Discarding a corrupt recording segment: <path>` on its own. The segment's length is impossible (empty, or longer than ten minutes), which points at broken timestamps coming from the camera.
For each one, the camera watchdog also logs `Invalid recording segment detected for <camera> at <timestamp>`.
:::warning
This is almost always a **camera or network problem**, not a Frigate one. A segment is only complete once ffmpeg has finished writing it, so anything that interrupts the stream partway through leaves behind a file that cannot be saved. Frigate is reporting the interruption, not causing it.
:::
#### Start with the camera and the network
- **The camera dropped the connection.** Cameras reboot, reinitialize their stream when switching to night mode, and cut clients off when they are overloaded or out of simultaneous connections. Count everything pulling from the camera at once: Frigate's detect and record streams, go2rtc, a phone app, and any other NVR each use one. Routing all roles through a single [RTSP restream](/configuration/restream#reduce-connections-to-camera) so the camera only ever sees one connection often resolves this by itself.
- **The link to the camera is unreliable.** WiFi cameras, powerline adapters, a saturated uplink, a failing switch port, or a marginal cable all produce this pattern, and usually only on one camera at a time. WiFi cameras are [not recommended](https://ipcamtalk.com/threads/multiple-cameras-high-bandwidth.77100/#post-861110).
- **The camera cannot reliably send what it is being asked for.** A high bitrate 4K stream can be more than the camera's own hardware can encode and push out under load. Lower the bitrate, or record a lower-resolution profile.
- **The camera is using a "Smart Codec", H.264+, or H.265+ mode.** These change encoding parameters mid-stream and produce the broken timestamps behind the corrupt-segment variant. Turn the mode off and set the camera's keyframe interval equal to its frame rate. See [Segments are only ~1 second long](#segments-are-only-1-second-long).
Read the rest of the Frigate and/or go2rtc log around the **first** occurrence. When the camera or the network is at fault, other messages show up with it, such as `No frames received from <camera> in 20 seconds`, `Non-monotonic DTS`, `RTP: PT=xx: bad cseq`, `error while decoding MB`, or a connection timeout. Each of those is explained in [Common error messages](/troubleshooting/common_errors). To confirm the camera is the source, open its stream in the [go2rtc web interface](/troubleshooting/go2rtc) on port `1984` or play the same URL in VLC, and leave it running long enough for the failures to happen again.
#### If the camera and network check out
- **Audio the recording cannot store.** Some cameras send G.711 audio, which cannot be saved in an MP4 and stops segments from finalizing. See [Incompatible audio codec](#incompatible-audio-codec-recordings-silently-fail-to-save).
- **Frigate itself was stopped or restarted.** A single warning per camera around a restart is expected and needs no action.
- **The system ran out of room or memory.** A full `/tmp/cache`, or the host killing Frigate for using too much memory, cuts off the segment being written. Both leave other errors in the log alongside this one. See [No space left on device](#errno-28-no-space-left-on-device).
</FaqItem>
<FaqItem id="no-new-recording-segments-were-created" question="I see the message: ERROR : No new recording segments were created for <camera> in the last 120s. Restarting the ffmpeg record process...">
When a camera stops producing usable recordings for two minutes, Frigate restarts that camera's record process to try to recover. The wording tells you how far the recordings got:
- **`No new recording segments were created`**: no new segment file showed up in the cache at all, so ffmpeg isn't getting video out of the record stream. The camera is unreachable or refusing the connection, the stream URL, path, or credentials are wrong, or the camera accepted the connection and then sent nothing. See [The record stream isn't connecting](#the-record-stream-isnt-connecting).
- **`No new valid recording segments were created`** and **`No valid segments created since last invalid segment`**: recordings are arriving, but they keep failing validation, so the camera is sending video that cannot be saved. See [Invalid or missing video stream in segment](#invalid-or-missing-video-stream-in-segment) above.
The restart is Frigate recovering from a problem, not causing one. One of these after a camera reboot or a brief network drop is normal. Seeing them repeat every couple of minutes means the camera or the network is still failing, and the restarts can extend the damage, because each one cuts off the segment that was being written. Work from the earliest failure in that camera's log rather than from the restarts.
</FaqItem>
<FaqItem id="i-see-the-message-warning--unable-to-keep-up-with-recording-segments-in-cache-for-camera-keeping-the-5-most-recent-segments-out-of-6-and-discarding-the-rest" question="I see the message: WARNING : Unable to keep up with recording segments in cache for camera. Keeping the 5 most recent segments out of 6 and discarding the rest...">
This warning means the recording maintainer cannot move recording segments from the RAM cache to disk fast enough. When the cache fills up, Frigate discards the oldest segments to avoid running out of memory and crashing, so you lose recorded footage. This is almost always a storage throughput or system resource problem. Work through the steps below to identify which.
+1
View File
@@ -122,6 +122,7 @@ const sidebars: SidebarsConfig = {
"configuration/ffmpeg_presets",
"configuration/pwa",
"configuration/tls",
"configuration/non_root",
],
},
{
+91 -4
View File
@@ -1476,12 +1476,10 @@ paths:
- Classification
summary: Get custom classification attributes
description: |-
**Access:** Any authenticated user.
**Access:** Authenticated user with access to all cameras.
Returns custom classification attributes for a given object type.
Only includes models with classification_type set to 'attribute'.
Callers without access to every camera only receive values that have been
recorded on the cameras they can access.
By default returns a flat sorted list of all attribute labels.
If group_by_model is true, returns attributes grouped by model name.
operationId: get_custom_attributes_classification_attributes_get
@@ -1513,7 +1511,7 @@ paths:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateUserAuth: []
x-required-role: any
x-required-role: all_cameras
/classification/{name}/train:
get:
tags:
@@ -4055,6 +4053,58 @@ paths:
security:
- frigateAdminAuth: []
x-required-role: admin
/hardware/hwaccel:
get:
tags:
- Hardware
summary: Hwaccel Recommendation
description: |-
**Access:** Admin role required.
Get the hardware decoding this system can do.
Args:
detector: Hardware key of the detection hardware in use, which biases
the recommendation toward that hardware's GPU
codecs: Comma separated codecs of the streams that will be decoded,
used to drop families that cannot decode one of them
Returns:
The recommended family (empty when none fits) and every usable family
operationId: hwaccel_recommendation_hardware_hwaccel_get
parameters:
- name: detector
in: query
required: false
schema:
anyOf:
- type: string
- type: 'null'
title: Detector
- name: codecs
in: query
required: false
schema:
anyOf:
- type: string
- type: 'null'
title: Codecs
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/HwaccelRecommendation'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
/events:
get:
tags:
@@ -8672,6 +8722,43 @@ components:
- label
title: HardwareUnit
description: One physical piece of hardware.
HwaccelFamily:
properties:
key:
type: string
title: Family key
description: Stable identifier for this kind of hardware decoding.
presets:
additionalProperties:
type: string
type: object
title: Presets
description: The ffmpeg preset for each codec this family decodes, or
a single 'any' preset when it decodes every codec.
type: object
required:
- key
- presets
title: HwaccelFamily
description: A kind of hardware decoding, and the presets that drive it.
HwaccelRecommendation:
properties:
recommended:
type: string
title: Recommended family
description: Key of the family that fits this system best, or an empty
string when none does.
available:
items:
$ref: '#/components/schemas/HwaccelFamily'
type: array
title: Available families
description: Every family this system's hardware can use, best first.
type: object
required:
- recommended
title: HwaccelRecommendation
description: The hardware decoding this system can do.
Last24HoursReview:
properties:
reviewed_alert:
+4 -96
View File
@@ -11,14 +11,10 @@ from typing import Any
import cv2
from fastapi import APIRouter, Depends, Request, UploadFile
from fastapi.responses import JSONResponse
from peewee import DoesNotExist, fn
from peewee import DoesNotExist
from playhouse.shortcuts import model_to_dict
from frigate.api.auth import (
allow_any_authenticated,
get_allowed_cameras_for_filter,
require_role,
)
from frigate.api.auth import require_full_camera_access, require_role
from frigate.api.defs.request.classification_body import (
AudioTranscriptionBody,
DeleteFaceImagesBody,
@@ -743,81 +739,19 @@ def get_classification_dataset(name: str):
)
def get_observed_attributes(
model_attributes: dict[str, list[str]],
object_labels: set[str],
allowed_cameras: list[str],
) -> dict[str, set[str]]:
"""Get the attribute values recorded on the given cameras.
Args:
model_attributes: Labels each attribute model can emit, keyed by model name
object_labels: Object types those models run on
allowed_cameras: Cameras the caller has access to
Returns:
Values seen for each model, keyed by model name
"""
if not model_attributes or not object_labels or not allowed_cameras:
return {}
model_names = list(model_attributes.keys())
query = (
Event.select(
*[
fn.json_extract(Event.data, f'$."{model_name}"')
for model_name in model_names
]
)
.where(
(Event.camera << allowed_cameras) & (Event.label << sorted(object_labels))
)
.distinct()
.tuples()
)
targets = {
model_name: set(attributes)
for model_name, attributes in model_attributes.items()
}
observed: dict[str, set[str]] = {model_name: set() for model_name in model_names}
for row in query.iterator():
found = False
for model_name, value in zip(model_names, row):
if isinstance(value, str) and value not in observed[model_name]:
observed[model_name].add(value)
found = True
if found and all(
observed[model_name] >= targets[model_name] for model_name in model_names
):
break
return observed
@router.get(
"/classification/attributes",
dependencies=[Depends(allow_any_authenticated())],
dependencies=[Depends(require_full_camera_access)],
summary="Get custom classification attributes",
description="""Returns custom classification attributes for a given object type.
Only includes models with classification_type set to 'attribute'.
Callers without access to every camera only receive values that have been
recorded on the cameras they can access.
By default returns a flat sorted list of all attribute labels.
If group_by_model is true, returns attributes grouped by model name.""",
)
def get_custom_attributes(
request: Request,
object_type: str = None,
group_by_model: bool = False,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
request: Request, object_type: str = None, group_by_model: bool = False
):
models_with_attributes = {}
objects_by_model = {}
for (
model_key,
@@ -848,32 +782,6 @@ def get_custom_attributes(
if attributes:
model_name = model_config.name or model_key
models_with_attributes[model_name] = sorted(attributes)
objects_by_model[model_name] = model_objects
# the dataset holds every label a model can emit, including ones never
# applied to an event, so callers without full camera access are limited to
# the values actually recorded on the cameras they can see
all_cameras = set(request.app.frigate_config.cameras.keys())
if models_with_attributes and not all_cameras.issubset(allowed_cameras):
observed = get_observed_attributes(
models_with_attributes,
set().union(*objects_by_model.values()),
allowed_cameras,
)
models_with_attributes = {
model_name: [
attribute
for attribute in attributes
if attribute in observed.get(model_name, set())
]
for model_name, attributes in models_with_attributes.items()
}
models_with_attributes = {
model_name: attributes
for model_name, attributes in models_with_attributes.items()
if attributes
}
if group_by_model:
return JSONResponse(content=models_with_attributes)
+84 -8
View File
@@ -1,7 +1,9 @@
"""Export apis."""
import contextlib
import datetime
import logging
import os
import random
import string
import time
@@ -9,12 +11,13 @@ import zipfile
from collections import deque
from collections.abc import Iterator
from pathlib import Path
from urllib.parse import quote
import psutil
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pathvalidate import sanitize_filename
from peewee import DoesNotExist
from peewee import DatabaseError, DoesNotExist, IntegrityError
from playhouse.shortcuts import model_to_dict
from frigate.api.auth import (
@@ -70,6 +73,7 @@ from frigate.record.export import (
DEFAULT_TIME_LAPSE_FFMPEG_ARGS,
ChaptersEnum,
PlaybackSourceEnum,
export_video_path,
validate_ffmpeg_args,
)
from frigate.util.path import sanitize_contained_path
@@ -403,14 +407,17 @@ class _StreamingZipBuffer:
def _unique_archive_name(export: Export, used: set[str]) -> str:
base = sanitize_filename(export.name) if export.name else None
if not base:
base = f"{export.camera}_{int(export.date)}"
"""Zip entry name for an export, de-duplicated within the archive.
The on-disk name is the one the user sees either way: renaming an export
renames its file, so a zip entry and an individual download can't drift.
"""
source = Path(export.video_path)
candidate = source.name
candidate = f"{base}.mp4"
counter = 1
while candidate in used:
candidate = f"{base}_{counter}.mp4"
candidate = f"{source.stem}_{counter}{source.suffix}"
counter += 1
used.add(candidate)
@@ -453,6 +460,22 @@ def _stream_case_archive(exports: list[Export]) -> Iterator[bytes]:
yield from buffer.drain()
def _content_disposition(filename: str, ascii_fallback: str) -> str:
"""Build an attachment Content-Disposition that survives non-ASCII names.
Header values are encoded as latin-1, so a name outside that range cannot
go in filename at all. RFC 6266 handles this with a pair: a plain ASCII
filename for old clients, plus a percent-encoded UTF-8 filename* that
every current browser prefers.
"""
ascii_name = filename if filename.isascii() else ascii_fallback
return (
f'attachment; filename="{ascii_name}"; '
f"filename*=UTF-8''{quote(filename, safe='')}"
)
@router.get(
"/cases/{case_id}/download",
dependencies=[Depends(allow_any_authenticated())],
@@ -495,7 +518,9 @@ def download_export_case(
_stream_case_archive(exports),
media_type="application/zip",
headers={
"Content-Disposition": f'attachment; filename="{archive_base}.zip"',
"Content-Disposition": _content_disposition(
f"{archive_base}.zip", f"{case_id}.zip"
),
},
)
@@ -908,8 +933,59 @@ async def export_rename(event_id: str, body: ExportRenameBody, request: Request)
status_code=404,
)
if export.in_progress:
return JSONResponse(
content={
"success": False,
"message": "Export is still being written and can't be renamed yet.",
},
status_code=400,
)
new_path = export_video_path(body.name, export.id)
old_path = export.video_path
moved = new_path != old_path
# move the file first so a rename that can't happen leaves the row alone
if moved:
try:
os.rename(old_path, new_path)
except OSError:
logger.exception("Failed to rename export file for %s", event_id)
return JSONResponse(
content={"success": False, "message": "Failed to rename export."},
status_code=500,
)
export.name = body.name
export.save()
export.video_path = new_path
try:
export.save()
except DatabaseError as err:
# the queue database has no transactions, so undo the move by hand
if moved:
with contextlib.suppress(OSError):
os.rename(new_path, old_path)
if isinstance(err, IntegrityError):
logger.warning(
"Export %s cannot be renamed, %s is taken", event_id, new_path
)
return JSONResponse(
content={
"success": False,
"message": "Another export already uses that name.",
},
status_code=409,
)
logger.exception("Failed to save renamed export %s", event_id)
return JSONResponse(
content={"success": False, "message": "Failed to rename export."},
status_code=500,
)
return JSONResponse(
content=(
{
+27
View File
@@ -7,6 +7,7 @@ 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
from frigate.util.hwaccel import HwaccelRecommendation, hwaccel_options
logger = logging.getLogger(__name__)
@@ -28,3 +29,29 @@ def probe_hardware(refresh: bool = False) -> list[DetectionHardware]:
Every kind of detection hardware that was found
"""
return hardware_prober.probe(refresh=refresh)
@router.get(
"/hardware/hwaccel",
response_model=HwaccelRecommendation,
dependencies=[Depends(require_role(["admin"]))],
)
def hwaccel_recommendation(
detector: str | None = None, codecs: str | None = None
) -> HwaccelRecommendation:
"""Get the hardware decoding this system can do.
Args:
detector: Hardware key of the detection hardware in use, which biases
the recommendation toward that hardware's GPU
codecs: Comma separated codecs of the streams that will be decoded,
used to drop families that cannot decode one of them
Returns:
The recommended family (empty when none fits) and every usable family
"""
wanted = {
codec.strip().lower() for codec in (codecs or "").split(",") if codec.strip()
}
recommended, available = hwaccel_options(detector, wanted)
return HwaccelRecommendation(recommended=recommended, available=available)
+9 -2
View File
@@ -1060,7 +1060,7 @@ async def event_thumbnail(
except DoesNotExist:
thumbnail_bytes = None
if thumbnail_bytes is None:
if not thumbnail_bytes:
# see if the object is currently being tracked
try:
camera_states = request.app.detected_frames_processor.get_camera_states()
@@ -1076,7 +1076,7 @@ async def event_thumbnail(
status_code=404,
)
if thumbnail_bytes is None:
if not thumbnail_bytes:
return JSONResponse(
content={"success": False, "message": "Event not found"},
status_code=404,
@@ -1085,6 +1085,13 @@ async def event_thumbnail(
img_as_np = np.frombuffer(thumbnail_bytes, dtype=np.uint8)
img = cv2.imdecode(img_as_np, flags=1)
if img is None:
# thumbnail on disk is truncated or corrupt
return JSONResponse(
content={"success": False, "message": "Event not found"},
status_code=404,
)
# android notifications prefer a 2:1 ratio
if format == "android":
img = cv2.copyMakeBorder(
+11
View File
@@ -231,6 +231,17 @@ class FrigateApp:
migrate_db.close()
# a root frigate service creates these as root; wal and shm recreated
# later in the run are realigned by the per-boot /config sweep
for db_file in (
self.config.database.path,
f"{self.config.database.path}-wal",
f"{self.config.database.path}-shm",
self.config.database.path.replace("frigate.db", "backup.db"),
):
if os.path.exists(db_file):
chown_to_runtime(db_file)
def init_go2rtc(self) -> None:
for proc in psutil.process_iter(["pid", "name"]):
if proc.info["name"] == "go2rtc":
+7 -2
View File
@@ -61,6 +61,11 @@ class CameraState:
# face/LPR pipelines when using a model without built-in detection.
self.face_recognition_min_obj_area: int = 0
self.lpr_min_obj_area: int = 0
self.lp_objects = {
label
for label, attributes in self.model.attributes_map.items()
if "license_plate" in attributes
}
if (
self.camera_config.face_recognition.enabled
@@ -447,7 +452,7 @@ class CameraState:
and obj_area >= self.face_recognition_min_obj_area
and updated_obj.obj_data.get("sub_label") is None
) or (
obj_label in ("car", "motorcycle")
obj_label in self.lp_objects
and self.lpr_min_obj_area > 0
and obj_area >= self.lpr_min_obj_area
and updated_obj.obj_data.get("sub_label") is None
@@ -543,7 +548,7 @@ class CameraState:
current_best.thumbnail_data is not None
and obj.thumbnail_data is not None
and is_better_thumbnail(
object_type,
obj.thumbnail_attributes,
current_best.thumbnail_data,
obj.thumbnail_data,
self.camera_config.frame_shape,
+1
View File
@@ -430,6 +430,7 @@ class WebPushClient(Communicator):
# Don't notify if message is an update and important fields don't have an update
if (
state == "update"
and payload["before"]["severity"] == payload["after"]["severity"]
and len(payload["before"]["data"]["objects"])
== len(payload["after"]["data"]["objects"])
and len(payload["before"]["data"]["zones"])
+4
View File
@@ -53,7 +53,11 @@ DEFAULT_ATTRIBUTE_LABEL_MAP = {
"ups",
"usps",
],
"truck": ["license_plate"],
"garbage_truck": ["license_plate"],
"motorcycle": ["license_plate"],
"bus": ["license_plate"],
"school_bus": ["license_plate"],
}
ATTRIBUTE_LABEL_DISPLAY_MAP = {
"amazon": "Amazon",
@@ -1290,7 +1290,7 @@ class LicensePlateProcessingMixin:
and obj_data.get("label") != "license_plate"
):
logger.debug(
f"{camera}: Not a processing license plate for non car/motorcycle object."
f"{camera}: Not a processing license plate for {obj_data.get('label', 'unknown')}."
)
return
@@ -1367,7 +1367,7 @@ class LicensePlateProcessingMixin:
if not license_plate:
logger.debug(
f"{camera}: Detected no license plates for car/motorcycle object."
f"{camera}: Detected no license plates for {obj_data.get('label', 'unknown')} object."
)
return
+42 -36
View File
@@ -25,25 +25,31 @@ def is_arm64_platform() -> bool:
return machine in ("aarch64", "arm64", "armv8", "armv7l")
def get_ort_session_options(
is_complex_model: bool = False,
) -> ort.SessionOptions | None:
def get_ort_session_options(model_type: str | None = None) -> ort.SessionOptions | None:
"""Get ONNX Runtime session options with appropriate settings.
Args:
is_complex_model: Whether the model needs basic optimization to avoid graph fusion issues.
model_type: Model being loaded, used to pin its graph optimization level.
Returns:
SessionOptions with appropriate optimization level, or None for default settings.
SessionOptions with a pinned optimization level, or None for default settings.
"""
if is_complex_model:
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = (
ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
)
return sess_options
# Import here to avoid circular imports
from frigate.embeddings.types import EnrichmentModelTypeEnum
return None
if model_type == EnrichmentModelTypeEnum.jina_v2.value:
# below EXTENDED the CUDA EP returns an identical vector for every image,
# and ORT_ENABLE_ALL fails to build on CPU with a SimplifiedLayerNormFusion error
level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED
elif model_type == EnrichmentModelTypeEnum.jina_v1.value:
# aggressive optimizations create or expect nodes that don't exist
level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
else:
return None
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = level
return sess_options
# Import OpenVINO only when needed to avoid circular dependencies
@@ -115,21 +121,6 @@ class BaseModelRunner(ABC):
class ONNXModelRunner(BaseModelRunner):
"""Run ONNX models using ONNX Runtime."""
@staticmethod
def is_cpu_complex_model(model_type: str) -> bool:
"""Check if model needs basic optimization level to avoid graph fusion issues.
Some models (like Jina-CLIP) have issues with aggressive optimizations like
SimplifiedLayerNormFusion that create or expect nodes that don't exist.
"""
# Import here to avoid circular imports
from frigate.embeddings.types import EnrichmentModelTypeEnum
return model_type in [
EnrichmentModelTypeEnum.jina_v1.value,
EnrichmentModelTypeEnum.jina_v2.value,
]
@staticmethod
def is_migraphx_complex_model(model_type: str) -> bool:
# Import here to avoid circular imports
@@ -323,17 +314,34 @@ class OpenVINOModelRunner(BaseModelRunner):
if device in ["GPU", "AUTO", "NPU"]:
self.ov_core.set_property(device, {"PERFORMANCE_HINT": "LATENCY"})
if device == "NPU" and OpenVINOModelRunner.is_detection_model(model_type):
if device in ["GPU", "AUTO"]:
try:
self.ov_core.set_property(device, {"NPU_TURBO": "YES"})
self.ov_core.set_property("GPU", {"GPU_QUEUE_THROTTLE": "LOW"})
except Exception as e:
logger.debug(f"NPU_TURBO not supported by driver: {e}")
logger.debug(f"GPU_QUEUE_THROTTLE not supported: {e}")
# Some keys must be passed as compile-time config so that it can be caught
compile_config = {}
if device == "NPU" and OpenVINOModelRunner.is_detection_model(model_type):
compile_config["NPU_TURBO"] = "YES"
# Compile model under the shared lock
with _OPENVINO_LOCK:
self.compiled_model = self.ov_core.compile_model(
model=model_path, device_name=device
)
try:
self.compiled_model = self.ov_core.compile_model(
model=model_path, device_name=device, config=compile_config
)
except RuntimeError as e:
if not compile_config:
raise
logger.debug(
f"Failed to compile with {compile_config}, retrying without: {e}"
)
self.compiled_model = self.ov_core.compile_model(
model=model_path, device_name=device
)
# Create reusable inference request
self.infer_request = self.compiled_model.create_infer_request()
@@ -626,9 +634,7 @@ def get_optimized_runner(
return ONNXModelRunner(
ort.InferenceSession(
model_path,
sess_options=get_ort_session_options(
ONNXModelRunner.is_cpu_complex_model(model_type)
),
sess_options=get_ort_session_options(model_type),
providers=providers,
provider_options=options,
),
+2
View File
@@ -23,6 +23,7 @@ from frigate.ffmpeg_presets import (
)
from frigate.models import Previews
from frigate.util.image import copy_yuv_to_position, get_blank_yuv_frame, get_yuv_crop
from frigate.util.ownership import chown_to_runtime
logger = logging.getLogger(__name__)
@@ -185,6 +186,7 @@ class FFMpegConverter(threading.Thread):
if p.returncode == 0:
logger.debug("successfully saved preview")
chown_to_runtime(self.path)
self.requestor.send_data(
INSERT_PREVIEW,
{
+26 -1
View File
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import Any
import pytz # type: ignore[import-untyped]
from pathvalidate import sanitize_filename
from peewee import DoesNotExist
from frigate.config import FfmpegConfig, FrigateConfig
@@ -34,6 +35,7 @@ from frigate.ffmpeg_presets import (
)
from frigate.models import Export, Previews, Recordings, ReviewSegment
from frigate.util.ffmpeg import run_ffmpeg_with_progress
from frigate.util.ownership import chown_to_runtime
from frigate.util.time import is_current_hour
logger = logging.getLogger(__name__)
@@ -204,6 +206,22 @@ class PlaybackSourceEnum(str, Enum):
preview = "preview"
EXPORT_FILE_NAME_MAX_BYTES = 255
def export_video_path(name: str, export_id: str) -> str:
"""Path an export's video is stored at once the user has named it.
The id suffix keeps the path unique when two exports share a name, and
keeps the result a single path component whatever the user typed.
"""
suffix = f"_{export_id.split('_')[-1]}.mp4"
budget = EXPORT_FILE_NAME_MAX_BYTES - len(suffix.encode())
stem = sanitize_filename(name).encode()[:budget].decode(errors="ignore")
return os.path.join(EXPORT_DIR, f"{stem.strip('. ') or 'export'}{suffix}")
class RecordingExporter(threading.Thread):
"""Exports a specific set of recordings for a camera to storage as a single file."""
@@ -917,8 +935,14 @@ class RecordingExporter(threading.Thread):
"%Y%m%d_%H%M%S"
)
cleaned_export_id = self.export_id.split("_")[-1]
video_path = f"{EXPORT_DIR}/{self.camera}_{filename_start_datetime}-{filename_end_datetime}_{cleaned_export_id}.mp4"
if self.user_provided_name:
video_path = export_video_path(self.user_provided_name, self.export_id)
else:
video_path = f"{EXPORT_DIR}/{self.camera}_{filename_start_datetime}-{filename_end_datetime}_{cleaned_export_id}.mp4"
thumb_path = self.save_thumbnail(self.export_id)
if thumb_path:
chown_to_runtime(thumb_path)
export_values = {
Export.id: self.export_id,
@@ -993,6 +1017,7 @@ class RecordingExporter(threading.Thread):
Path(thumb_path).unlink(missing_ok=True)
return
else:
chown_to_runtime(video_path)
self._emit_progress("finalizing", 100.0)
Export.update({Export.in_progress: False}).where(
Export.id == self.export_id
+8
View File
@@ -43,6 +43,7 @@ from frigate.const import (
from frigate.models import Recordings, ReviewSegment
from frigate.review.types import SeverityEnum
from frigate.util.media import get_keyframe_offsets
from frigate.util.ownership import chown_to_runtime
from frigate.util.services import get_video_properties
logger = logging.getLogger(__name__)
@@ -928,6 +929,11 @@ class RecordingMaintainer(threading.Thread):
)
os.makedirs(directory, exist_ok=True)
# own every level makedirs creates so the host user can prune recordings
level = directory
while level != RECORD_DIR:
chown_to_runtime(level)
level = os.path.dirname(level)
# file will be in utc due to path_time being in utc
file_name = f"{path_time.strftime('%M.%S.mp4')}"
@@ -966,6 +972,8 @@ class RecordingMaintainer(threading.Thread):
f"Copied {file_path} in {datetime.datetime.now().timestamp() - start_frame} seconds."
)
chown_to_runtime(file_path)
try:
# get the segment size of the cache file
# file without faststart is same size
@@ -1,189 +0,0 @@
"""Tests for GET /classification/attributes."""
import os
import shutil
import unittest
from frigate.api.auth import get_allowed_cameras_for_filter
from frigate.const import CLIPS_DIR
from frigate.models import Event, Recordings, ReviewSegment
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
# "limited_user" only reaches front_door, so it never sees the values that were
# recorded on back_door.
_CONFIG = {
"mqtt": {"host": "mqtt"},
"auth": {"roles": {"limited_user": ["front_door"]}},
"classification": {
"custom": {
"delivery_service": {
"enabled": True,
"object_config": {
"objects": ["car"],
"classification_type": "attribute",
},
}
}
},
"cameras": {
"front_door": {
"ffmpeg": {
"inputs": [{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
},
"back_door": {
"ffmpeg": {
"inputs": [{"path": "rtsp://10.0.0.2:554/video", "roles": ["detect"]}]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
},
},
}
class TestClassificationAttributesAccess(BaseTestHttp):
"""The attribute list is read from the training dataset on disk, which holds
every label a model can emit regardless of which camera recorded it. Callers
without full camera access are cut back to the values on their own cameras,
so these tests pin that scoping.
"""
def setUp(self):
super().setUp([Event, ReviewSegment, Recordings])
self.minimal_config = _CONFIG
self.app = super().create_app()
self.model_dir = os.path.join(CLIPS_DIR, "delivery_service")
for category in ("DHL", "Amazon", "Hermes", "none"):
os.makedirs(
os.path.join(self.model_dir, "dataset", category), exist_ok=True
)
def tearDown(self):
shutil.rmtree(self.model_dir, ignore_errors=True)
self.app.dependency_overrides.clear()
super().tearDown()
def _insert_event(self, event_id: str, camera: str, attribute: str | None):
data = {"type": "object", "score": 0.9}
if attribute is not None:
data["delivery_service"] = attribute
Event.insert(
id=event_id,
label="car",
camera=camera,
start_time=100,
end_time=200,
top_score=0.9,
score=0.9,
false_positive=False,
zones=[],
thumbnail="",
has_clip=True,
has_snapshot=True,
region=[],
box=[],
area=0,
retain_indefinitely=False,
ratio=1.0,
plus_id=None,
model_hash="",
detector_type="cpu",
model_type="ssd",
data=data,
).execute()
def _get(self, role: str, **params):
# the base class resolves every camera by default, so drop the override
# to exercise the real role to allowed-cameras resolution
self.app.dependency_overrides.pop(get_allowed_cameras_for_filter, None)
with AuthTestClient(self.app) as client:
return client.get(
"/classification/attributes",
params=params,
headers={"remote-user": "test", "remote-role": role},
)
def _insert_split_events(self):
self._insert_event("front", "front_door", "DHL")
self._insert_event("back", "back_door", "Amazon")
def test_admin_gets_every_trained_label(self):
self._insert_split_events()
assert self._get("admin").json() == ["Amazon", "DHL", "Hermes"]
def test_viewer_gets_every_trained_label(self):
self._insert_split_events()
assert self._get("viewer").json() == ["Amazon", "DHL", "Hermes"]
def test_restricted_role_only_gets_its_own_cameras(self):
self._insert_split_events()
assert self._get("limited_user").json() == ["DHL"]
def test_restricted_role_grouped_by_model(self):
self._insert_split_events()
assert self._get("limited_user", group_by_model="true").json() == {
"delivery_service": ["DHL"]
}
def test_restricted_role_with_no_recorded_values(self):
self._insert_event("back", "back_door", "Amazon")
assert self._get("limited_user").json() == []
assert self._get("limited_user", group_by_model="true").json() == {}
def test_restricted_role_ignores_events_without_the_attribute(self):
self._insert_event("front", "front_door", None)
assert self._get("limited_user").json() == []
def test_restricted_role_with_a_dotted_model_name(self):
# model names are unrestricted config keys, and an unquoted "." in the
# json path would be read as a nested lookup and match nothing
self.app.frigate_config.classification.custom["delivery.service"] = (
self.app.frigate_config.classification.custom.pop("delivery_service")
)
self.app.frigate_config.classification.custom[
"delivery.service"
].name = "delivery.service"
os.rename(self.model_dir, os.path.join(CLIPS_DIR, "delivery.service"))
self.model_dir = os.path.join(CLIPS_DIR, "delivery.service")
data = {"type": "object", "score": 0.9, "delivery.service": "DHL"}
Event.insert(
id="front",
label="car",
camera="front_door",
start_time=100,
end_time=200,
top_score=0.9,
score=0.9,
false_positive=False,
zones=[],
thumbnail="",
has_clip=True,
has_snapshot=True,
region=[],
box=[],
area=0,
retain_indefinitely=False,
ratio=1.0,
plus_id=None,
model_hash="",
detector_type="cpu",
model_type="ssd",
data=data,
).execute()
assert self._get("limited_user").json() == ["DHL"]
def test_object_type_filters_out_unrelated_models(self):
self._insert_split_events()
assert self._get("limited_user", object_type="person").json() == []
assert self._get("limited_user", object_type="car").json() == ["DHL"]
if __name__ == "__main__":
unittest.main()
+163
View File
@@ -1,5 +1,7 @@
import io
import os
import tempfile
import zipfile
from unittest.mock import patch
from frigate.jobs.export import (
@@ -366,6 +368,91 @@ class TestHttpExport(BaseTestHttp):
assert response.status_code == 200
assert response.json() == [queued_job.to_dict()]
def test_rename_export_moves_the_file(self):
with tempfile.TemporaryDirectory() as tmpdir:
video = os.path.join(tmpdir, "front_door_20260823_020615_abc123.mp4")
thumb = os.path.join(tmpdir, "front_door_abc123.webp")
for path, data in ((video, b"video"), (thumb, b"thumb")):
with open(path, "wb") as handle:
handle.write(data)
Export.create(
id="front_door_abc123",
camera="front_door",
name="front door 2026-08-23 02:06:15 2026-08-23 02:07:34",
date=100,
video_path=video,
thumb_path=thumb,
in_progress=False,
)
with patch("frigate.record.export.EXPORT_DIR", tmpdir):
with AuthTestClient(self.app) as client:
response = client.patch(
"/export/front_door_abc123/rename",
json={"name": "Package thief"},
)
assert response.status_code == 200
renamed = Export.get(Export.id == "front_door_abc123")
assert renamed.name == "Package thief"
assert os.path.basename(renamed.video_path) == "Package thief_abc123.mp4"
assert os.path.exists(renamed.video_path)
assert not os.path.exists(video)
def test_rename_export_rejected_while_in_progress(self):
with tempfile.TemporaryDirectory() as tmpdir:
video = os.path.join(tmpdir, "front_door_abc123.mp4")
with open(video, "wb") as handle:
handle.write(b"video")
Export.create(
id="front_door_running",
camera="front_door",
name="front door export",
date=100,
video_path=video,
thumb_path=os.path.join(tmpdir, "t.webp"),
in_progress=True,
)
with AuthTestClient(self.app) as client:
response = client.patch(
"/export/front_door_running/rename",
json={"name": "Package thief"},
)
assert response.status_code == 400
assert Export.get(Export.id == "front_door_running").video_path == video
def test_rename_export_missing_file_leaves_the_row_alone(self):
with tempfile.TemporaryDirectory() as tmpdir:
video = os.path.join(tmpdir, "front_door_gone_abc123.mp4")
Export.create(
id="front_door_gone",
camera="front_door",
name="front door export",
date=100,
video_path=video,
thumb_path=os.path.join(tmpdir, "t.webp"),
in_progress=False,
)
with patch("frigate.record.export.EXPORT_DIR", tmpdir):
with AuthTestClient(self.app) as client:
response = client.patch(
"/export/front_door_gone/rename",
json={"name": "Package thief"},
)
assert response.status_code == 500
unchanged = Export.get(Export.id == "front_door_gone")
assert unchanged.name == "front door export"
assert unchanged.video_path == video
def test_reap_stale_exports_deletes_rows_with_no_file(self):
with tempfile.TemporaryDirectory() as tmpdir:
stale_video = os.path.join(tmpdir, "stale.mp4")
@@ -1431,3 +1518,79 @@ class TestHttpExport(BaseTestHttp):
)
assert response.status_code == 403
def test_download_export_case_with_multibyte_name(self):
"""A case name outside latin-1 must not break the response headers."""
case = ExportCase.create(
id="case_multibyte",
name="テスト事案",
description="",
created_at=10,
updated_at=10,
)
with tempfile.TemporaryDirectory() as tmpdir:
video_path = os.path.join(tmpdir, "現場カメラ.mp4")
with open(video_path, "wb") as handle:
handle.write(b"video")
Export.create(
id="export_multibyte",
camera="front_door",
name="現場カメラ",
date=100,
video_path=video_path,
thumb_path=os.path.join(tmpdir, "multibyte_export.webp"),
in_progress=False,
export_case=case,
)
with AuthTestClient(self.app) as client:
response = client.get(f"/cases/{case.id}/download")
assert response.status_code == 200
# RFC 5987/6266: the UTF-8 name rides in filename*, and a latin-1 safe
# fallback stays in filename for old clients.
assert response.headers["content-disposition"] == (
'attachment; filename="case_multibyte.zip"; '
"filename*=UTF-8''%E3%83%86%E3%82%B9%E3%83%88%E4%BA%8B%E6%A1%88.zip"
)
archive = zipfile.ZipFile(io.BytesIO(response.content))
assert archive.namelist() == ["現場カメラ.mp4"]
def test_download_export_case_with_ascii_name(self):
"""An ASCII case name still gets a plain, readable filename."""
case = ExportCase.create(
id="case_ascii",
name="Burglary 2026-08",
description="",
created_at=10,
updated_at=10,
)
with tempfile.TemporaryDirectory() as tmpdir:
video_path = os.path.join(tmpdir, "ascii_export.mp4")
with open(video_path, "wb") as handle:
handle.write(b"video")
Export.create(
id="export_ascii",
camera="front_door",
name="Front door",
date=100,
video_path=video_path,
thumb_path=os.path.join(tmpdir, "ascii_export.webp"),
in_progress=False,
export_case=case,
)
with AuthTestClient(self.app) as client:
response = client.get(f"/cases/{case.id}/download")
assert response.status_code == 200
assert (
response.headers["content-disposition"]
== 'attachment; filename="Burglary 2026-08.zip"; '
"filename*=UTF-8''Burglary%202026-08.zip"
)
+26
View File
@@ -0,0 +1,26 @@
"""Tests for bandwidth stats privilege handling."""
import unittest
from unittest.mock import MagicMock, patch
from frigate.util import services
class TestBandwidthStatsPrivileges(unittest.TestCase):
def setUp(self):
services._bandwidth_warning_logged = False
@patch("frigate.util.services.sp.run")
@patch("frigate.util.services.os.geteuid", return_value=1000)
def test_returns_empty_and_warns_once_without_root(self, _, sp_run):
config = MagicMock()
with self.assertLogs("frigate.util.services", level="WARNING") as logs:
assert services.get_bandwidth_stats(config) == {}
assert services.get_bandwidth_stats(config) == {}
sp_run.assert_not_called()
warnings = [m for m in logs.output if "require root" in m]
assert len(warnings) == 1
if __name__ == "__main__":
unittest.main()
+41
View File
@@ -0,0 +1,41 @@
"""Tests for ONNX Runtime session option selection."""
import unittest
import onnxruntime as ort
from frigate.detectors.detection_runners import get_ort_session_options
from frigate.detectors.detector_config import ModelTypeEnum
from frigate.embeddings.types import EnrichmentModelTypeEnum
class TestGetOrtSessionOptions(unittest.TestCase):
def test_jina_v2_uses_extended(self):
"""jina-clip-v2 returns an identical vector for every image on the CUDA
execution provider at anything below EXTENDED."""
options = get_ort_session_options(EnrichmentModelTypeEnum.jina_v2.value)
self.assertIsNotNone(options)
self.assertEqual(
options.graph_optimization_level,
ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED,
)
def test_jina_v1_uses_basic(self):
options = get_ort_session_options(EnrichmentModelTypeEnum.jina_v1.value)
self.assertIsNotNone(options)
self.assertEqual(
options.graph_optimization_level,
ort.GraphOptimizationLevel.ORT_ENABLE_BASIC,
)
def test_other_models_use_defaults(self):
for model_type in [
None,
EnrichmentModelTypeEnum.paddleocr.value,
EnrichmentModelTypeEnum.arcface.value,
ModelTypeEnum.rfdetr.value,
]:
with self.subTest(model_type=model_type):
self.assertIsNone(get_ort_session_options(model_type))
+81 -1
View File
@@ -1,6 +1,9 @@
import unittest
from pathlib import Path
from frigate.record.export import validate_ffmpeg_args
from frigate.api.export import _unique_archive_name
from frigate.models import Export
from frigate.record.export import export_video_path, validate_ffmpeg_args
class TestValidateFfmpegArgs(unittest.TestCase):
@@ -128,5 +131,82 @@ class TestValidateFfmpegArgs(unittest.TestCase):
self.assertRejected("-metadata comment=x")
class TestExportVideoPath(unittest.TestCase):
"""Tests for the file path an export takes once the user names it."""
EXPORT_ID = "front_door_abc123"
def test_uses_the_name_the_user_gave(self):
self.assertEqual(
export_video_path("Package thief", self.EXPORT_ID),
"/media/frigate/exports/Package thief_abc123.mp4",
)
def test_id_suffix_keeps_shared_names_apart(self):
self.assertNotEqual(
export_video_path("clip", "front_door_abc123"),
export_video_path("clip", "front_door_def456"),
)
def test_long_names_fit_the_filesystem_limit(self):
# Names are capped in bytes, not characters: 244 CJK characters is
# under any character cap and still 732 bytes on disk.
for name in ("A" * 256, "\u76e3" * 256, "\U0001f3a5" * 100):
file_name = Path(export_video_path(name, self.EXPORT_ID)).name
self.assertLessEqual(len(file_name.encode()), 255)
def test_truncation_keeps_the_name_decodable(self):
file_name = Path(export_video_path("\u76e3" * 256, self.EXPORT_ID)).name
self.assertTrue(file_name.endswith("_abc123.mp4"))
self.assertNotIn("\ufffd", file_name)
def test_stays_inside_the_export_dir(self):
for name in ("../../etc/passwd", "..", "a/b", "...", ""):
path = Path(export_video_path(name, self.EXPORT_ID))
self.assertEqual(str(path.parent), "/media/frigate/exports")
class TestUniqueArchiveName(unittest.TestCase):
"""Tests for zip entry names in a case download.
Entries use the on-disk file name, which is also what an individual
download produces, so the two can't drift.
"""
def build_export(self, video_path: str) -> Export:
return Export(
id="front_door_abc123",
camera="front_door",
name="whatever the display name is",
date=1756000000.0,
video_path=video_path,
thumb_path=video_path.replace(".mp4", ".webp"),
in_progress=False,
)
def test_uses_the_on_disk_file_name(self):
export = self.build_export(
"/media/frigate/exports/front_door_20260823_020615-20260823_020734_abc123.mp4"
)
self.assertEqual(
_unique_archive_name(export, set()),
"front_door_20260823_020615-20260823_020734_abc123.mp4",
)
def test_follows_a_renamed_file(self):
export = self.build_export("/media/frigate/exports/Package thief_abc123.mp4")
self.assertEqual(
_unique_archive_name(export, set()), "Package thief_abc123.mp4"
)
def test_entries_are_deduplicated(self):
export = self.build_export("/media/frigate/exports/Package thief_abc123.mp4")
used: set[str] = set()
self.assertEqual(_unique_archive_name(export, used), "Package thief_abc123.mp4")
self.assertEqual(
_unique_archive_name(export, used), "Package thief_abc123_1.mp4"
)
if __name__ == "__main__":
unittest.main()
+154
View File
@@ -0,0 +1,154 @@
"""Tests for custom ffmpeg path resolution and the root-mode guard."""
import unittest
from unittest.mock import patch
from frigate.const import DEFAULT_FFMPEG_VERSION
from frigate.util.config import (
_warn_ignored_ffmpeg_path,
frigate_service_is_granular_root,
resolve_ffmpeg_path,
)
BUNDLED = f"/usr/lib/ffmpeg/{DEFAULT_FFMPEG_VERSION}/bin/ffmpeg"
CUSTOM = "/config/custom-ffmpeg"
class TestConfigFfmpegRootGuard(unittest.TestCase):
"""A user-writable ffmpeg must not run as root under FRIGATE_ROOT_SERVICES."""
def setUp(self) -> None:
# the warning is memoized so it fires once per path, not per camera
_warn_ignored_ffmpeg_path.cache_clear()
def _resolve(self, path: str, *, euid: int, env: dict, binary: str = "ffmpeg"):
with (
patch("os.geteuid", return_value=euid),
patch.dict("os.environ", env, clear=True),
):
return resolve_ffmpeg_path(path, binary)
def test_custom_path_used_when_service_is_unprivileged(self) -> None:
self.assertEqual(
self._resolve(CUSTOM, euid=1000, env={}), f"{CUSTOM}/bin/ffmpeg"
)
def test_escape_hatch_keeps_working_exactly_as_before(self) -> None:
# FRIGATE_RUN_AS_ROOT never sweeps /config and leaves no unprivileged
# service, so a custom build there is as safe as it was pre-drop
self.assertEqual(
self._resolve(CUSTOM, euid=0, env={"FRIGATE_RUN_AS_ROOT": "true"}),
f"{CUSTOM}/bin/ffmpeg",
)
def test_custom_path_ignored_when_frigate_is_a_root_service(self) -> None:
self.assertEqual(
self._resolve(CUSTOM, euid=0, env={"FRIGATE_ROOT_SERVICES": "frigate"}),
BUNDLED,
)
def test_ffprobe_is_guarded_too(self) -> None:
self.assertEqual(
self._resolve(
CUSTOM,
euid=0,
env={"FRIGATE_ROOT_SERVICES": "frigate"},
binary="ffprobe",
),
f"/usr/lib/ffmpeg/{DEFAULT_FFMPEG_VERSION}/bin/ffprobe",
)
def test_another_root_service_does_not_trigger_the_guard(self) -> None:
# go2rtc running as root says nothing about who spawns ffmpeg
self.assertEqual(
self._resolve(CUSTOM, euid=0, env={"FRIGATE_ROOT_SERVICES": "go2rtc"}),
f"{CUSTOM}/bin/ffmpeg",
)
def test_root_services_has_no_effect_under_docker_user(self) -> None:
# docker's own user: means the service never had root to keep, which is
# also the case for get_ffmpeg_path.py in a --user container
self.assertEqual(
self._resolve(CUSTOM, euid=1000, env={"FRIGATE_ROOT_SERVICES": "frigate"}),
f"{CUSTOM}/bin/ffmpeg",
)
def test_path_outside_config_is_left_alone(self) -> None:
# only /config is runtime-user-owned; a root-owned tree stays usable
self.assertEqual(
self._resolve(
"/opt/custom-ffmpeg", euid=0, env={"FRIGATE_ROOT_SERVICES": "frigate"}
),
"/opt/custom-ffmpeg/bin/ffmpeg",
)
def test_traversal_out_of_config_does_not_evade_the_guard(self) -> None:
self.assertEqual(
self._resolve(
"/config/../config/custom-ffmpeg",
euid=0,
env={"FRIGATE_ROOT_SERVICES": "frigate"},
),
BUNDLED,
)
def test_media_tree_is_guarded_too(self) -> None:
# config.yml is uid-1000-writable, so ffmpeg.path can be pointed at any
# writable tree; /config alone would be an evasion, not a guard
self.assertEqual(
self._resolve(
"/media/frigate/evil", euid=0, env={"FRIGATE_ROOT_SERVICES": "frigate"}
),
BUNDLED,
)
def test_config_dir_itself_is_guarded(self) -> None:
self.assertEqual(
self._resolve("/config", euid=0, env={"FRIGATE_ROOT_SERVICES": "frigate"}),
BUNDLED,
)
def test_default_alias_is_unaffected(self) -> None:
self.assertEqual(
self._resolve("default", euid=0, env={"FRIGATE_ROOT_SERVICES": "frigate"}),
BUNDLED,
)
class TestFrigateServiceIsGranularRoot(unittest.TestCase):
"""Root via FRIGATE_ROOT_SERVICES only, never via the escape hatch."""
def _check(self, *, euid: int, env: dict) -> bool:
with (
patch("os.geteuid", return_value=euid),
patch.dict("os.environ", env, clear=True),
):
return frigate_service_is_granular_root()
def test_false_without_any_root_signal(self) -> None:
self.assertFalse(self._check(euid=0, env={}))
def test_escape_hatch_is_not_granular_root(self) -> None:
# the escape hatch restores old behavior wholesale, sweep included
self.assertFalse(self._check(euid=0, env={"FRIGATE_RUN_AS_ROOT": "true"}))
self.assertFalse(
self._check(
euid=0,
env={"FRIGATE_RUN_AS_ROOT": "true", "FRIGATE_ROOT_SERVICES": "frigate"},
)
)
def test_membership_ignores_whitespace_and_other_entries(self) -> None:
self.assertTrue(
self._check(euid=0, env={"FRIGATE_ROOT_SERVICES": "go2rtc, frigate"})
)
self.assertFalse(
self._check(euid=0, env={"FRIGATE_ROOT_SERVICES": "go2rtc,nginx"})
)
def test_substring_of_a_service_name_does_not_match(self) -> None:
self.assertFalse(self._check(euid=0, env={"FRIGATE_ROOT_SERVICES": "frigatee"}))
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -70,3 +70,19 @@ class TestFileUtils(TestCase):
assert rendered_image is not None
assert rendered_image.shape[0] == 40
assert rendered_image.max() > 0
def test_get_event_thumbnail_bytes_ignores_empty_file(self):
"""Verify empty thumbnail files are treated as missing."""
event = SimpleNamespace(id="empty-thumb", camera="front_door", thumbnail=None)
with (
tempfile.TemporaryDirectory() as thumb_dir,
patch.object(file_util, "THUMB_DIR", thumb_dir),
):
camera_dir = os.path.join(thumb_dir, event.camera)
os.makedirs(camera_dir)
with open(os.path.join(camera_dir, f"{event.id}.webp"), "wb"):
pass
assert file_util.get_event_thumbnail_bytes(event) is None
+225
View File
@@ -0,0 +1,225 @@
"""Tests for the hardware decoding recommendation."""
import os
import tempfile
import unittest
from unittest.mock import patch
from frigate.detectors.hardware import DetectionHardware
from frigate.util import hwaccel
def found(key: str) -> DetectionHardware:
"""A probe result carrying only the fields the recommendation reads."""
return DetectionHardware(
key=key,
detector=key.partition(":")[0],
name=key,
units=[],
count=0,
unlimited=True,
)
class HwaccelRecommendationTestCase(unittest.TestCase):
"""Points every read at an empty fixture tree, so nothing is found by default."""
def setUp(self):
self.root = tempfile.TemporaryDirectory()
self.addCleanup(self.root.cleanup)
self.proc_root = os.path.join(self.root.name, "proc")
os.makedirs(self.proc_root)
patcher = patch.object(hwaccel, "PROC_ROOT", self.proc_root)
patcher.start()
self.addCleanup(patcher.stop)
drm = patch.object(hwaccel, "enumerate_drm_devices", return_value={})
self.drm = drm.start()
self.addCleanup(drm.stop)
def options(self, keys=(), detector_key=None, codecs=None):
"""Run the recommendation against a fixed set of hardware keys."""
with patch.object(
hwaccel.hardware_prober,
"probe",
return_value=[found(key) for key in keys],
):
return hwaccel.hwaccel_options(detector_key, codecs)
def recommend(self, keys=(), detector_key=None, codecs=None) -> str:
"""The recommended family key."""
return self.options(keys, detector_key, codecs)[0]
def available(self, keys=(), detector_key=None, codecs=None) -> list[str]:
"""The keys of the usable families, best first."""
return [family.key for family in self.options(keys, detector_key, codecs)[1]]
def presets(self, keys=(), detector_key=None, codecs=None) -> dict:
"""The presets each usable family provides."""
return {
family.key: family.presets
for family in self.options(keys, detector_key, codecs)[1]
}
def write_cpuinfo(self, model_name: str) -> None:
with open(os.path.join(self.proc_root, "cpuinfo"), "w") as f:
f.write(f"processor\t: 0\nmodel name\t: {model_name}\n")
def write_device_tree(self) -> None:
os.makedirs(os.path.join(self.proc_root, "device-tree"), exist_ok=True)
with open(os.path.join(self.proc_root, "device-tree", "compatible"), "w") as f:
f.write("raspberrypi,5-model-b\x00brcm,bcm2712\x00")
class TestPriority(HwaccelRecommendationTestCase):
def test_nothing_found_recommends_nothing(self):
self.assertEqual(self.recommend(), "")
def test_nvidia_wins_over_intel(self):
self.assertEqual(self.recommend(["onnx:nvidia", "openvino:GPU"]), "nvidia")
def test_a_jetson_uses_its_own_family(self):
self.assertEqual(self.recommend(["tensorrt"]), "jetson")
def test_a_rockchip_uses_rkmpp(self):
self.assertEqual(self.recommend(["rknn"]), "rkmpp")
def test_an_amd_gpu_uses_vaapi(self):
self.assertEqual(self.recommend(["onnx:amd"]), "vaapi")
class TestDetectorBias(HwaccelRecommendationTestCase):
def test_a_chosen_intel_gpu_beats_a_present_nvidia(self):
self.assertEqual(
self.recommend(["onnx:nvidia", "openvino:GPU"], "openvino:GPU"), "vaapi"
)
def test_a_chosen_npu_decodes_through_the_igpu(self):
self.assertEqual(
self.recommend(["openvino:NPU", "openvino:GPU"], "openvino:NPU"), "vaapi"
)
def test_an_npu_without_an_igpu_falls_through(self):
self.assertEqual(self.recommend(["openvino:NPU"], "openvino:NPU"), "")
def test_a_cpu_choice_still_recommends_the_present_gpu(self):
self.assertEqual(self.recommend(["cpu", "openvino:GPU"], "cpu"), "vaapi")
class TestIntelGeneration(HwaccelRecommendationTestCase):
def test_the_xe_driver_prefers_qsv(self):
self.drm.return_value = {"0000:00:02.0": "xe"}
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "intel-qsv")
def test_gen13_prefers_qsv(self):
self.write_cpuinfo("13th Gen Intel(R) Core(TM) i5-13500")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "intel-qsv")
def test_a_core_ultra_prefers_qsv(self):
self.write_cpuinfo("Intel(R) Core(TM) Ultra 7 155H")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "intel-qsv")
def test_gen13_prefers_qsv_for_mixed_codecs(self):
# each camera resolves the family to its own codec
self.write_cpuinfo("13th Gen Intel(R) Core(TM) i5-13500")
self.assertEqual(
self.recommend(["openvino:GPU"], codecs={"h264", "h265"}), "intel-qsv"
)
def test_gen12_prefers_vaapi(self):
self.write_cpuinfo("12th Gen Intel(R) Core(TM) i5-12400")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "vaapi")
def test_gen12_still_offers_qsv(self):
self.write_cpuinfo("12th Gen Intel(R) Core(TM) i5-12400")
self.assertEqual(self.available(["openvino:GPU"]), ["vaapi", "intel-qsv"])
def test_an_older_model_string_prefers_vaapi(self):
self.write_cpuinfo("Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "vaapi")
def test_missing_cpuinfo_prefers_vaapi(self):
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "vaapi")
def test_qsv_is_not_offered_before_gen8(self):
self.write_cpuinfo("7th Gen Intel(R) Core(TM) i5-7500")
self.assertEqual(self.available(["openvino:GPU"]), ["vaapi"])
class TestUnknownCodecs(HwaccelRecommendationTestCase):
def test_a_codec_agnostic_family_wins_when_no_codec_is_known(self):
# a qsv preset would have to guess a codec for cameras added later
self.drm.return_value = {"0000:00:02.0": "xe"}
self.assertEqual(self.recommend(["openvino:GPU"]), "vaapi")
def test_hardware_with_no_agnostic_family_still_recommends(self):
self.assertEqual(self.recommend(["tensorrt"]), "jetson")
class TestAvailableFamilies(HwaccelRecommendationTestCase):
def test_nothing_found_offers_nothing(self):
self.assertEqual(self.available(), [])
def test_only_families_the_hardware_can_use_are_offered(self):
self.assertEqual(self.available(["onnx:nvidia"]), ["nvidia"])
def test_a_pi_does_not_offer_desktop_gpu_families(self):
self.write_device_tree()
self.assertEqual(self.available(), ["rpi"])
def test_an_intel_system_does_not_offer_the_pi_family(self):
offered = self.available(["openvino:GPU"])
self.assertIn("vaapi", offered)
self.assertNotIn("rpi", offered)
self.assertNotIn("nvidia", offered)
def test_every_gpu_present_is_offered(self):
offered = self.available(["onnx:nvidia", "openvino:GPU"])
self.assertEqual(offered[0], "nvidia")
self.assertIn("vaapi", offered)
def test_a_gpu_wins_over_the_pi_fallback(self):
self.write_device_tree()
self.assertEqual(self.recommend(["onnx:nvidia"]), "nvidia")
def test_the_recommendation_is_always_offered(self):
recommended, families = self.options(["openvino:GPU"], codecs={"h264"})
self.assertIn(recommended, [family.key for family in families])
class TestCodecCoverage(HwaccelRecommendationTestCase):
def test_a_family_carries_a_preset_per_codec(self):
self.assertEqual(
self.presets(["tensorrt"])["jetson"],
{"h264": "preset-jetson-h264", "h265": "preset-jetson-h265"},
)
def test_a_codec_agnostic_family_carries_one_preset(self):
self.assertEqual(
self.presets(["onnx:nvidia"])["nvidia"], {"any": "preset-nvidia"}
)
def test_hevc_is_treated_as_h265(self):
self.assertEqual(self.available(["tensorrt"], codecs={"hevc"}), ["jetson"])
def test_a_family_that_cannot_decode_a_codec_is_dropped(self):
# a jetson decodes h264 and h265 only, so an mjpeg camera rules it out
self.assertEqual(self.available(["tensorrt"], codecs={"mjpeg"}), [])
def test_codec_agnostic_families_survive_any_codec(self):
self.assertEqual(
self.available(["onnx:nvidia"], codecs={"mjpeg", "h265"}), ["nvidia"]
)
def test_a_dropped_family_hands_off_to_the_next_hardware(self):
self.assertEqual(
self.recommend(["tensorrt", "onnx:nvidia"], codecs={"mjpeg"}), "nvidia"
)
if __name__ == "__main__":
unittest.main()
+18
View File
@@ -14,6 +14,11 @@ class FakePwEntry:
# The devcontainer image exports FRIGATE_RUN_AS_ROOT, so any test that has to
# reach past the escape-hatch check pins the variable instead of inheriting it.
class TestGetRuntimeIds(unittest.TestCase):
def setUp(self) -> None:
ownership.get_runtime_ids.cache_clear()
# a value cached under this test's patches must not leak into later modules
self.addCleanup(ownership.get_runtime_ids.cache_clear)
@patch("frigate.util.ownership.os.geteuid", return_value=1000)
def test_returns_none_when_not_root(self, _):
assert ownership.get_runtime_ids() is None
@@ -35,8 +40,21 @@ class TestGetRuntimeIds(unittest.TestCase):
def test_returns_frigate_ids_as_root(self, *_):
assert ownership.get_runtime_ids() == (1500, 1500)
@patch.dict("os.environ", {"FRIGATE_RUN_AS_ROOT": "false"})
@patch("frigate.util.ownership.pwd.getpwnam", return_value=FakePwEntry())
@patch("frigate.util.ownership.os.geteuid", return_value=0)
def test_caches_lookup(self, _geteuid, getpwnam):
assert ownership.get_runtime_ids() == (1500, 1500)
assert ownership.get_runtime_ids() == (1500, 1500)
getpwnam.assert_called_once()
class TestChownToRuntime(unittest.TestCase):
def setUp(self) -> None:
ownership.get_runtime_ids.cache_clear()
# a value cached under this test's patches must not leak into later modules
self.addCleanup(ownership.get_runtime_ids.cache_clear)
@patch("frigate.util.ownership.os.chown")
@patch("frigate.util.ownership.get_runtime_ids", return_value=None)
def test_noop_when_no_runtime_ids(self, _, chown):
@@ -442,6 +442,71 @@ class TestSegmentPathTime(unittest.IsolatedAsyncioTestCase):
self.assertTrue(paths[1].endswith("30.23.mp4"), paths[1])
class TestMoveSegmentOwnership(unittest.IsolatedAsyncioTestCase):
"""Every directory level makedirs creates must be handed to the runtime user."""
def _build_maintainer(self) -> RecordingMaintainer:
camera_config = MagicMock()
camera_config.record.enabled = True
camera_config.record.continuous.days = 1
camera_config.record.motion.days = 0
config = MagicMock()
config.cameras = {"test_cam": camera_config}
maintainer = RecordingMaintainer.__new__(RecordingMaintainer)
maintainer.config = config
maintainer.end_time_cache = {}
maintainer.object_recordings_info = defaultdict(list)
maintainer.audio_recordings_info = defaultdict(list)
maintainer.recordings_publisher = MagicMock()
maintainer.last_segment_end = {("test_cam", "main"): 0.0}
return maintainer
async def test_move_segment_chowns_all_created_levels(self):
maintainer = self._build_maintainer()
maintainer.config.ffmpeg.ffmpeg_path = "ffmpeg"
start_time = datetime.datetime(2026, 6, 10, 14, 30, 22, tzinfo=datetime.UTC)
proc = MagicMock()
proc.returncode = 0
proc.wait = AsyncMock(return_value=0)
chown = MagicMock()
with tempfile.TemporaryDirectory() as tmpdir:
record_dir = os.path.join(tmpdir, "recordings")
cache_path = os.path.join(tmpdir, "test_cam@20260610143022+0000.mp4")
with open(cache_path, "wb") as f:
f.write(b"\x00" * 16)
with (
patch("frigate.record.maintainer.RECORD_DIR", record_dir),
patch(
"frigate.record.maintainer.asyncio.create_subprocess_exec",
AsyncMock(return_value=proc),
),
patch("frigate.record.maintainer.chown_to_runtime", chown),
):
result = await maintainer.move_segment(
"test_cam",
"main",
start_time,
start_time + datetime.timedelta(seconds=10),
10.0,
cache_path,
SegmentInfo(0, 0, 0, 0),
)
self.assertIsNotNone(result)
camera_dir = os.path.join(record_dir, "2026-06-10", "14", "test_cam")
hour_dir = os.path.dirname(camera_dir)
date_dir = os.path.dirname(hour_dir)
file_path = os.path.join(camera_dir, "30.22.mp4")
chowned = [call.args[0] for call in chown.call_args_list]
self.assertEqual(chowned, [camera_dir, hour_dir, date_dir, file_path])
class TestSegmentStartChaining(unittest.IsolatedAsyncioTestCase):
"""Contiguous segments must chain start times across filename truncation.
+6 -1
View File
@@ -54,6 +54,11 @@ class TrackedObject:
self.obj_data = obj_data
self.colormap = model_config.colormap
self.logos = model_config.all_attribute_logos
self.thumbnail_attributes = [
attr
for attr in model_config.attributes_map.get(obj_data["label"], [])
if attr in model_config.non_logo_attributes
]
self.camera_config = camera_config
self.ui_config = ui_config
self.frame_cache = frame_cache
@@ -149,7 +154,7 @@ class TrackedObject:
if not self.false_positive and has_valid_frame:
# determine if this frame is a better thumbnail
if self.thumbnail_data is None or is_better_thumbnail(
self.obj_data["label"],
self.thumbnail_attributes,
self.thumbnail_data,
obj_data,
self.camera_config.frame_shape,
+64 -4
View File
@@ -4,11 +4,14 @@ import asyncio
import logging
import os
import shutil
from functools import cache
from typing import Any
from ruamel.yaml import YAML
from frigate.const import (
BASE_DIR,
CACHE_DIR,
CONFIG_DIR,
DEFAULT_FFMPEG_VERSION,
EXPORT_DIR,
@@ -43,13 +46,56 @@ DROPPED_DETECTOR_OPTIONS = {
}
# Trees the unprivileged runtime user can write. A root frigate service must
# not execute a binary from any of them; a compromised uid-1000 process could
# plant one and be root after the next restart.
RUNTIME_USER_WRITABLE_DIRS = (CONFIG_DIR, BASE_DIR, CACHE_DIR, "/dev/shm", "/tmp")
def frigate_service_is_granular_root() -> bool:
"""Report whether FRIGATE_ROOT_SERVICES runs frigate as root.
The escape hatch is excluded: it never sweeps /config and leaves no
unprivileged service running, so custom binaries stay as safe as they
were before the privilege drop.
"""
if os.geteuid() != 0:
return False
if os.environ.get("FRIGATE_RUN_AS_ROOT", "false") == "true":
return False
entries = os.environ.get("FRIGATE_ROOT_SERVICES", "").split(",")
return any("".join(entry.split()) == "frigate" for entry in entries)
def _is_runtime_user_writable(path: str) -> bool:
"""Report whether a path resolves inside a runtime-user-writable tree."""
resolved = os.path.realpath(path)
return any(
resolved == root or resolved.startswith(f"{root}{os.sep}")
for root in RUNTIME_USER_WRITABLE_DIRS
)
@cache
def _warn_ignored_ffmpeg_path(path: str) -> None:
"""Warn once per path; resolution runs per camera and per binary."""
logger.warning(
"Ignoring ffmpeg.path %s because FRIGATE_ROOT_SERVICES runs frigate as root and that location is writable by the unprivileged user; using the bundled build",
path,
)
def resolve_ffmpeg_path(path: str, binary: str = "ffmpeg") -> str:
"""Resolve an ffmpeg version alias or custom path to a binary path.
A bare version alias that is no longer bundled (for example one that was
dropped when the default version changed) falls back to the default
bundled version so existing configs keep working across an upgrade or a
revert. Custom install paths (anything absolute) are used as-is.
revert. Custom install paths (anything absolute) are used as-is, except
one in a runtime-user-writable tree while FRIGATE_ROOT_SERVICES makes
frigate root; see RUNTIME_USER_WRITABLE_DIRS.
"""
if path == "default" or (
not path.startswith("/") and path not in INCLUDED_FFMPEG_VERSIONS
@@ -58,7 +104,11 @@ def resolve_ffmpeg_path(path: str, binary: str = "ffmpeg") -> str:
elif path in INCLUDED_FFMPEG_VERSIONS:
version = path
else:
return f"{path}/bin/{binary}"
if not (frigate_service_is_granular_root() and _is_runtime_user_writable(path)):
return f"{path}/bin/{binary}"
_warn_ignored_ffmpeg_path(path)
version = DEFAULT_FFMPEG_VERSION
return f"/usr/lib/ffmpeg/{version}/bin/{binary}"
@@ -79,10 +129,20 @@ def redact_credential(obj: dict[str, Any], key: str) -> None:
def find_config_file() -> str:
"""Return the path of the config file to use.
Both .yml and .yaml are supported, so fall back to the other extension when
the configured path does not exist. If neither exists the configured path is
returned so a new config is created with the default .yml extension.
"""
config_path = os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE)
if not os.path.isfile(config_path):
config_path = config_path.replace("yml", "yaml")
base, ext = os.path.splitext(config_path)
alternate = f"{base}.yaml" if ext == ".yml" else f"{base}.yml"
if os.path.isfile(alternate):
return alternate
return config_path
@@ -592,7 +652,7 @@ def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]
genai = new_config.get("genai")
if genai and genai.get("provider"):
genai["roles"] = ["embeddings", "descriptions", "chat"]
genai["roles"] = ["descriptions", "chat"]
new_config["genai"] = {"default": genai}
# Remove deprecated sync_recordings from global record config
+3 -2
View File
@@ -20,14 +20,15 @@ logger = logging.getLogger(__name__)
def get_event_thumbnail_bytes(event: Event) -> bytes | None:
# callers treat empty bytes as a valid image, so normalize them to None
if event.thumbnail:
return base64.b64decode(event.thumbnail)
return base64.b64decode(event.thumbnail) or None
else:
try:
with open(
os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp"), "rb"
) as f:
return f.read()
return f.read() or None
except Exception:
return None
+273
View File
@@ -0,0 +1,273 @@
"""Recommendation of ffmpeg hwaccel presets from the hardware on the system.
Every check is a filesystem read, like the detection hardware probes, so this
is cheap enough to serve from the API process.
Presets are grouped into families because some of them only decode the codec
they name. A family hides that: callers pick the family their hardware needs
and resolve it per camera against that camera's detect stream.
"""
import logging
import re
from pydantic import BaseModel, Field
from frigate.const import (
FFMPEG_HWACCEL_NVIDIA,
FFMPEG_HWACCEL_RKMPP,
FFMPEG_HWACCEL_VAAPI,
)
from frigate.detectors.hardware import hardware_prober
from frigate.util.services import enumerate_drm_devices
logger = logging.getLogger(__name__)
# root the /proc reads use, so tests can point them at a fixture tree
PROC_ROOT = "/proc"
ANY_CODEC = "any"
# a Raspberry Pi has no detection hardware of its own, so it gets a key here
RASPBERRY_PI = "raspberrypi"
# ffprobe names h265 streams hevc
CODEC_ALIASES = {"hevc": "h265"}
# e.g. "13th Gen Intel(R) Core(TM) i5-13500"
INTEL_GEN_PATTERN = re.compile(r"(\d+)th Gen")
# Core Ultra dropped the generation prefix and is newer than all of them
INTEL_ULTRA_PATTERN = re.compile(r"Core\(TM\) Ultra")
INTEL_GEN_LATEST = 99
# per the hwaccel docs, gen13+ and Arc prefer qsv while older is safest on
# vaapi, and qsv is not supported at all before gen8
INTEL_QSV_MIN_GEN = 13
INTEL_QSV_SUPPORTED_GEN = 8
# decode capable detection hardware, in recommendation priority order
DECODE_HARDWARE = (
"onnx:nvidia",
"tensorrt",
"rknn",
"openvino:GPU",
"onnx:amd",
RASPBERRY_PI,
)
class HwaccelFamily(BaseModel):
"""A kind of hardware decoding, and the presets that drive it."""
key: str = Field(
title="Family key",
description="Stable identifier for this kind of hardware decoding.",
)
presets: dict[str, str] = Field(
title="Presets",
description="The ffmpeg preset for each codec this family decodes, or a single 'any' preset when it decodes every codec.",
)
class HwaccelRecommendation(BaseModel):
"""The hardware decoding this system can do."""
recommended: str = Field(
title="Recommended family",
description="Key of the family that fits this system best, or an empty string when none does.",
)
available: list[HwaccelFamily] = Field(
default_factory=list,
title="Available families",
description="Every family this system's hardware can use, best first.",
)
FAMILY_NVIDIA = HwaccelFamily(key="nvidia", presets={ANY_CODEC: FFMPEG_HWACCEL_NVIDIA})
FAMILY_VAAPI = HwaccelFamily(key="vaapi", presets={ANY_CODEC: FFMPEG_HWACCEL_VAAPI})
FAMILY_RKMPP = HwaccelFamily(key="rkmpp", presets={ANY_CODEC: FFMPEG_HWACCEL_RKMPP})
FAMILY_QSV = HwaccelFamily(
key="intel-qsv",
presets={"h264": "preset-intel-qsv-h264", "h265": "preset-intel-qsv-h265"},
)
FAMILY_JETSON = HwaccelFamily(
key="jetson",
presets={"h264": "preset-jetson-h264", "h265": "preset-jetson-h265"},
)
FAMILY_RPI = HwaccelFamily(
key="rpi",
presets={"h264": "preset-rpi-64-h264", "h265": "preset-rpi-64-h265"},
)
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 _intel_generation() -> int | None:
"""The Intel platform generation, or None when it cannot be determined."""
# the xe driver only binds to the newest platforms (Arc and later iGPUs)
if "xe" in enumerate_drm_devices().values():
return INTEL_GEN_LATEST
cpuinfo = _read(f"{PROC_ROOT}/cpuinfo") or ""
for line in cpuinfo.splitlines():
if not line.startswith("model name"):
continue
match = INTEL_GEN_PATTERN.search(line)
if match:
return int(match.group(1))
if INTEL_ULTRA_PATTERN.search(line):
return INTEL_GEN_LATEST
break
return None
def _is_raspberry_pi() -> bool:
compatible = _read(f"{PROC_ROOT}/device-tree/compatible") or ""
return "raspberrypi" in compatible
def _intel_families(generation: int | None) -> list[HwaccelFamily]:
"""vaapi drives every Intel GPU, qsv only those from gen8 on."""
if generation is not None and generation < INTEL_QSV_SUPPORTED_GEN:
return [FAMILY_VAAPI]
if generation is not None and generation >= INTEL_QSV_MIN_GEN:
return [FAMILY_QSV, FAMILY_VAAPI]
return [FAMILY_VAAPI, FAMILY_QSV]
def _families(key: str, generation: int | None) -> list[HwaccelFamily]:
"""Every family that can decode on this hardware, best first."""
if key == "onnx:nvidia":
return [FAMILY_NVIDIA]
if key == "tensorrt":
return [FAMILY_JETSON]
if key == "rknn":
return [FAMILY_RKMPP]
if key == "onnx:amd":
return [FAMILY_VAAPI]
if key == RASPBERRY_PI:
return [FAMILY_RPI]
if key == "openvino:GPU":
return _intel_families(generation)
return []
def _decodes(family: HwaccelFamily, codecs: set[str]) -> bool:
"""Whether a family can decode every codec that is in use."""
if ANY_CODEC in family.presets:
return True
return all(codec in family.presets for codec in codecs)
def _decode_hardware(detector_key: str | None) -> list[str]:
"""Decode capable hardware on this system, best first.
Args:
detector_key: Hardware key of the detection hardware in use, whose GPU
is preferred over any other
Returns:
The hardware keys that can decode video, in recommendation order
"""
present = {found.key for found in hardware_prober.probe()}
if _is_raspberry_pi():
present.add(RASPBERRY_PI)
# an Intel NPU decodes through the iGPU next to it
if detector_key == "openvino:NPU":
detector_key = "openvino:GPU"
ordered = [key for key in DECODE_HARDWARE if key in present]
if detector_key in ordered:
ordered.remove(detector_key)
ordered.insert(0, detector_key)
return ordered
def hwaccel_options(
detector_key: str | None = None, codecs: set[str] | None = None
) -> tuple[str, list[HwaccelFamily]]:
"""Get the hardware decoding this system can do.
Args:
detector_key: Hardware key of the detection hardware in use, which
biases the recommendation toward that hardware's GPU
codecs: Codecs of the streams that will be decoded, used to drop
families that cannot decode one of them
Returns:
The recommended family key (empty when none fits) and every usable
family, best first
"""
wanted = {CODEC_ALIASES.get(codec, codec) for codec in codecs or set()}
hardware = _decode_hardware(detector_key)
generation = _intel_generation() if "openvino:GPU" in hardware else None
available: list[HwaccelFamily] = []
recommended = ""
for key in hardware:
usable = [
family for family in _families(key, generation) if _decodes(family, wanted)
]
if usable and not recommended:
recommended = _recommend(usable, bool(wanted))
for family in usable:
if family.key not in {entry.key for entry in available}:
available.append(family)
return recommended, available
def _recommend(families: list[HwaccelFamily], codecs_known: bool) -> str:
"""Pick the family to default to out of the ones this hardware can use."""
if not codecs_known:
# a codec specific family would have to guess a codec for cameras
# that do not exist yet
for family in families:
if ANY_CODEC in family.presets:
return family.key
return families[0].key
def recommend_hwaccel(
detector_key: str | None = None, codecs: set[str] | None = None
) -> str:
"""Recommend a hardware decoding family for this system.
Args:
detector_key: Hardware key of the detection hardware in use
codecs: Codecs of the streams that will be decoded
Returns:
The key of the family that fits, or an empty string when none does
"""
return hwaccel_options(detector_key, codecs)[0]
+5 -13
View File
@@ -67,7 +67,7 @@ def has_better_attr(current_thumb, new_obj, attr_label) -> bool:
def is_better_thumbnail(
label: str,
label_attributes: list[str],
current_thumb: dict[str, Any],
new_obj: dict[str, Any],
frame_shape: tuple[int, int],
@@ -76,20 +76,12 @@ def is_better_thumbnail(
# cutoff images are less ideal, but they should also be smaller?
# better scores are obviously better too
# check face on person
if label == "person":
if has_better_attr(current_thumb, new_obj, "face"):
for attr_label in label_attributes:
if has_better_attr(current_thumb, new_obj, attr_label):
return True
# if the current thumb has a face attr, dont update unless it gets better
if any([a["label"] == "face" for a in current_thumb["attributes"]]):
return False
# check license_plate on car
if label in ["car", "motorcycle"]:
if has_better_attr(current_thumb, new_obj, "license_plate"):
return True
# if the current thumb has a license_plate attr, dont update unless it gets better
if any([a["label"] == "license_plate" for a in current_thumb["attributes"]]):
# if the current thumb has the attr, dont update unless it gets better
if any([a["label"] == attr_label for a in current_thumb["attributes"]]):
return False
# if the new_thumb is on an edge, and the current thumb is not
+4
View File
@@ -1,5 +1,6 @@
"""Helpers for aligning created files with the non-root runtime user."""
import functools
import logging
import os
import pwd
@@ -9,12 +10,15 @@ logger = logging.getLogger(__name__)
RUNTIME_USER = "frigate"
@functools.lru_cache(maxsize=1)
def get_runtime_ids() -> tuple[int, int] | None:
"""Return (uid, gid) that services run as, or None when chown is not applicable.
None when: not root (docker --user, so the host already mapped us),
FRIGATE_RUN_AS_ROOT=true (escape hatch must not mutate ownership),
or outside the Frigate container image (no frigate user).
The result is cached for the process lifetime because the runtime user
cannot change after boot.
"""
if os.geteuid() != 0:
return None
+15
View File
@@ -187,8 +187,23 @@ def get_physical_interfaces(interfaces) -> list:
return physical_interfaces
_bandwidth_warning_logged = False
def get_bandwidth_stats(config) -> dict[str, dict]:
"""Get bandwidth usages for each ffmpeg process id"""
global _bandwidth_warning_logged
if os.geteuid() != 0:
if not _bandwidth_warning_logged:
logger.warning(
"Network bandwidth stats require root (nethogs needs CAP_NET_ADMIN/CAP_NET_RAW) "
"and are disabled; set FRIGATE_ROOT_SERVICES=frigate (or FRIGATE_RUN_AS_ROOT=true) "
"or disable telemetry.stats.network_bandwidth to silence this warning"
)
_bandwidth_warning_logged = True
return {}
usages = {}
top_command = ["nethogs", "-t", "-v0", "-c5", "-d1"] + get_physical_interfaces(
config.telemetry.network_interfaces
+4 -14
View File
@@ -216,20 +216,10 @@ def process_frames(
# remove license_plate from attributes if this camera is a dedicated LPR cam
if camera_config.type == CameraTypeEnum.lpr:
modified_attributes_map = model_config.attributes_map.copy()
if (
"car" in modified_attributes_map
and "license_plate" in modified_attributes_map["car"]
):
modified_attributes_map["car"] = [
attr
for attr in modified_attributes_map["car"]
if attr != "license_plate"
]
attributes_map = modified_attributes_map
attributes_map = {
label: [attr for attr in attributes if attr != "license_plate"]
for label, attributes in model_config.attributes_map.items()
}
all_attributes = [
attr for attr in model_config.all_attributes if attr != "license_plate"
]
+26
View File
@@ -43,6 +43,11 @@ export interface ApiMockOverrides {
configRaw?: string;
configSchema?: Record<string, unknown>;
hardware?: unknown[];
hwaccel?: {
recommended: string;
available?: { key: string; presets: Record<string, string> }[];
};
users?: { username: string; role: string }[];
}
export class ApiMocker {
@@ -185,6 +190,27 @@ export class ApiMocker {
route.fulfill({ json: overrides?.hardware ?? DETECTION_HARDWARE }),
);
// Hwaccel preset recommendation
await this.page.route("**/api/hardware/hwaccel**", (route) =>
route.fulfill({
json: {
recommended: "",
available: [],
...(overrides?.hwaccel ?? {}),
},
}),
);
// Users. GET lists them; POST/PUT (create, password) just succeed, so
// tests assert on the intercepted request body instead of a response.
await this.page.route("**/api/users**", (route) =>
route.request().method() === "GET"
? route.fulfill({
json: overrides?.users ?? [{ username: "admin", role: "admin" }],
})
: route.fulfill({ json: { message: "ok" } }),
);
// Go2RTC streams
await this.page.route("**/api/go2rtc/streams**", (route) =>
route.fulfill({ json: {} }),
+51
View File
@@ -0,0 +1,51 @@
/**
* Shared setup-wizard e2e helpers.
*
* The wizard shows when config has no cameras, so a first run is mocked by
* serving a camera-less config until the returned callback is fired. Firing
* it is only needed by tests that care what the rest of the app sees; the
* wizard itself tracks added cameras from the camera dialog's own callback.
*/
import type { Page } from "@playwright/test";
import { expect } from "../fixtures/frigate-test";
import { configFactory } from "../fixtures/mock-data/config";
import type { ApiMockOverrides } from "./api-mocker";
export async function installFirstRun(
frigateApp: { installDefaults: (o?: ApiMockOverrides) => Promise<void> },
page: Page,
overrides?: ApiMockOverrides,
): Promise<() => void> {
await frigateApp.installDefaults(overrides);
const full = configFactory(overrides?.config);
let cameras: unknown = {};
await page.route("**/api/config", (route) => {
if (route.request().method() === "GET") {
return route.fulfill({ json: { ...full, cameras } });
}
return route.fulfill({ json: { success: true } });
});
return () => {
cameras = full.cameras;
};
}
export async function gotoDetectorStep(page: Page) {
await page.getByRole("button", { name: "Get Started" }).click();
// the account step sits between welcome and camera whenever auth is on,
// which the default mock config has it
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Object Detection")).toBeVisible();
}
@@ -0,0 +1,353 @@
/**
* Add-camera wizard - Apple/HEVC compatibility switch on Step 3.
*
* It writes the camera-level `ffmpeg.apple_compatibility` and starts on for
* Apple browsers. That default is user-agent driven, so the second describe
* pins an explicit Safari and Chrome UA instead of relying on the project's
* own.
*
* The save tests drive Step 4, which registers go2rtc streams and renders MSE
* previews; they mock those and assert only the captured config/set body.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page, Locator } from "@playwright/test";
const MAIN_URI = "rtsp://admin:pw@192.168.1.100:554/stream1";
const SUB_URI = "rtsp://admin:pw@192.168.1.100:554/stream2";
const SAFARI_UA =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15";
const CHROME_UA =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const APPLE_TITLE = "Improve playback on Apple devices";
const PROBE = {
success: true,
host: "192.168.1.100",
port: 80,
manufacturer: "Acme",
model: "Cam-1",
firmware_version: "1.0",
profiles_count: 2,
ptz_supported: false,
pan_tilt_supported: false,
presets_count: 0,
autotrack_supported: false,
rtsp_candidates: [
{ source: "GetStreamUri", profile_token: "profile_1", uri: MAIN_URI },
{ source: "GetStreamUri", profile_token: "profile_2", uri: SUB_URI },
],
};
function ffprobeJson(codec: string) {
return [
{
return_code: 0,
stderr: [],
stdout: {
streams: [
{
codec_type: "video",
codec_name: codec,
width: 1920,
height: 1080,
avg_frame_rate: "15/1",
},
{ codec_type: "audio", codec_name: "aac" },
],
},
},
];
}
/** Mock ffprobe per stream URL; a null codec makes that probe fail. */
async function mockFfprobe(
page: Page,
codecByUri: Record<string, string | null>,
) {
await page.route("**/api/ffprobe**", (route) => {
const paths = new URL(route.request().url()).searchParams.get("paths");
const match = Object.keys(codecByUri).find((uri) => paths?.includes(uri));
const codec = match ? codecByUri[match] : null;
return route.fulfill({
json: codec
? ffprobeJson(codec)
: [{ return_code: 1, stderr: ["probe failed"], stdout: "" }],
});
});
}
/** Open the wizard and drive Step 1 -> Step 2 -> Step 3. */
async function gotoStep3(page: Page) {
await page.route("**/api/onvif/probe**", (route) =>
route.fulfill({ json: PROBE }),
);
await page.getByRole("button", { name: /Add New Camera/i }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
await dialog.getByPlaceholder(/front_door/i).fill("hevc_test_camera");
await dialog.getByPlaceholder("192.168.1.100").fill("192.168.1.100");
await dialog.getByRole("button", { name: /^Continue$/i }).click();
const next = dialog.getByRole("button", { name: /^Next$/i });
await expect(next).toBeEnabled({ timeout: 10_000 });
await next.click();
await expect(
dialog.getByRole("button", { name: /Add Another Stream/i }),
).toBeVisible();
return dialog;
}
/** The role toggle for `role` on the nth stream card (0-based). */
function roleSwitch(dialog: Locator, role: string, streamIndex = 0) {
return dialog
.locator("span.capitalize", { hasText: new RegExp(`^${role}$`) })
.nth(streamIndex)
.locator("xpath=..")
.getByRole("switch");
}
/** Run "Test Connection" on the nth stream card and wait for the result. */
async function testStream(dialog: Locator, streamIndex = 0) {
await dialog
.getByRole("button", { name: /Test Connection/i })
.nth(streamIndex)
.click();
await expect(
dialog.getByText("Connected", { exact: true }).nth(streamIndex),
).toBeVisible();
}
/** Run "Test Connection" on the nth stream card and wait for it to fail. */
async function failStream(dialog: Locator, streamIndex: number) {
await dialog
.getByRole("button", { name: /Test Connection/i })
.nth(streamIndex)
.click();
await expect(dialog.getByText("Test Failed", { exact: true })).toBeVisible();
}
function appleSwitch(dialog: Locator) {
return dialog
.locator("div.items-start.justify-between", { hasText: APPLE_TITLE })
.getByRole("switch");
}
async function openCameraManagement(frigateApp: {
page: Page;
goto: (path: string) => Promise<void>;
}) {
// not in the default mock; unmocked it 500s and trips the error collector
await frigateApp.page.route("**/api/config/raw_paths", (route) =>
route.fulfill({ json: {} }),
);
await frigateApp.goto("/settings?page=cameraManagement");
await expect(
frigateApp.page.getByRole("heading", { name: /Manage Cameras/i }),
).toBeVisible();
}
test.describe("Camera wizard Apple compatibility @medium @mobile", () => {
test.beforeEach(async ({ frigateApp }) => {
await openCameraManagement(frigateApp);
});
test("appears only once the record stream is probed as H.265", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "hevc" });
const dialog = await gotoStep3(frigateApp.page);
// the probe leaves the stream untested, so the codec is unknown
await roleSwitch(dialog, "record").click();
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(0);
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toBeVisible();
});
test("stays hidden for an H.264 record stream", async ({ frigateApp }) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "h264" });
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(0);
});
test("stays hidden for an H.265 stream with no recording role", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "hevc" });
const dialog = await gotoStep3(frigateApp.page);
// detect is assigned by default; no record or record_sub role
await testStream(dialog);
await expect(roleSwitch(dialog, "detect")).toBeChecked();
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(0);
});
test("appears for an H.265 record_sub stream", async ({ frigateApp }) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "hevc" });
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record_sub").click();
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toBeVisible();
});
test("renders once when only one recording stream is H.265", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, {
[MAIN_URI]: "hevc",
[SUB_URI]: "h264",
});
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await dialog.getByRole("button", { name: /Add Another Stream/i }).click();
await roleSwitch(dialog, "record_sub", 1).click();
await testStream(dialog, 1);
// ffmpeg drops the tag on the H.264 output, so the H.265 one still wins
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(1);
});
test("stays visible when another recording stream fails to probe", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, {
[MAIN_URI]: "hevc",
[SUB_URI]: null,
});
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toBeVisible();
await dialog.getByRole("button", { name: /Add Another Stream/i }).click();
await roleSwitch(dialog, "record_sub", 1).click();
await failStream(dialog, 1);
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(1);
});
});
test.describe("Camera wizard Apple compatibility default @medium @mobile", () => {
test.describe("on an Apple browser", () => {
test.use({ userAgent: SAFARI_UA });
test.beforeEach(async ({ frigateApp }) => {
await openCameraManagement(frigateApp);
});
test("starts on for an H.265 record stream and is saved", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: true,
toggle: false,
});
expect(ffmpeg.apple_compatibility).toBe(true);
});
test("can still be turned off, which omits it from the save", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: true,
toggle: true,
});
expect(ffmpeg).not.toHaveProperty("apple_compatibility");
});
});
test.describe("on a non-Apple browser", () => {
test.use({ userAgent: CHROME_UA });
test.beforeEach(async ({ frigateApp }) => {
await openCameraManagement(frigateApp);
});
test("starts off and is omitted so the global applies", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: false,
toggle: false,
});
expect(ffmpeg).not.toHaveProperty("apple_compatibility");
});
test("can be turned on, which writes it at camera level", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: false,
toggle: true,
});
expect(ffmpeg.apple_compatibility).toBe(true);
});
});
});
/**
* Drive the whole wizard for an H.265 record stream, asserting the switch's
* starting state and optionally toggling it, then return the `ffmpeg` section
* of the camera that config/set received.
*/
async function saveHevcCamera(
page: Page,
{ startsOn, toggle }: { startsOn: boolean; toggle: boolean },
) {
await mockFfprobe(page, { [MAIN_URI]: "hevc" });
const saved: Record<string, unknown>[] = [];
await page.route("**/api/config/set", (route) => {
saved.push(route.request().postDataJSON());
return route.fulfill({ json: { success: true, require_restart: false } });
});
const dialog = await gotoStep3(page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await expect(appleSwitch(dialog)).toBeChecked({ checked: startsOn });
if (toggle) {
await appleSwitch(dialog).click();
await expect(appleSwitch(dialog)).toBeChecked({ checked: !startsOn });
}
await dialog.getByRole("button", { name: /^Next$/i }).click();
const save = dialog.getByRole("button", { name: /Save New Camera/i });
await expect(save).toBeEnabled({ timeout: 15_000 });
await save.click();
// the camera PUT is the one carrying update_topic; go2rtc follows without it
await expect
.poll(() => saved.some((body) => "update_topic" in body), {
timeout: 15_000,
})
.toBe(true);
const cameraSave = saved.find((body) => "update_topic" in body) as {
update_topic: string;
config_data: {
cameras: Record<string, { ffmpeg: { apple_compatibility?: boolean } }>;
};
};
expect(cameraSave.update_topic).toBe("config/cameras/hevc_test_camera/add");
return cameraSave.config_data.cameras.hevc_test_camera.ffmpeg;
}
+196
View File
@@ -0,0 +1,196 @@
/**
* Setup wizard account step -- HIGH tier.
*
* Covers the step's placement and gating, the password and user payloads it
* sends, the copy it shows when nobody is signed in (the internal port), and
* that skipping it writes nothing.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page } from "@playwright/test";
import { installFirstRun } from "../../helpers/setup-wizard";
type Sent = {
method: string;
url: string;
body: Record<string, unknown> | null;
};
async function captureUserCalls(page: Page): Promise<Sent[]> {
const sent: Sent[] = [];
await page.route("**/api/users**", (route) => {
const request = route.request();
if (request.method() === "GET") {
return route.fulfill({ json: [{ username: "admin", role: "admin" }] });
}
sent.push({
method: request.method(),
url: request.url(),
body: request.postDataJSON(),
});
return route.fulfill({ json: { message: "ok" } });
});
return sent;
}
async function gotoAccountStep(page: Page) {
await page.getByRole("button", { name: "Get Started" }).click();
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeVisible();
}
test.describe("setup wizard account @high @mobile", () => {
test("sets the admin password without an old password", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Change password" }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
// the dialog is in set-password mode, so it asks for no current password
await expect(
dialog.getByPlaceholder("Enter your current password"),
).toBeHidden();
await dialog
.getByPlaceholder("Enter new password", { exact: true })
.fill("a-long-enough-password");
await dialog
.getByPlaceholder("Re-enter new password")
.fill("a-long-enough-password");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Password set")).toBeVisible();
const passwordCall = sent.find((call) => call.method === "PUT");
expect(passwordCall?.url).toContain("/users/admin/password");
// admins are exempt from the current-password check, so it must not be sent
expect(passwordCall?.body).toEqual({ password: "a-long-enough-password" });
});
test("creates a user with a role", async ({ frigateApp, page }) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Add user" }).click();
await page.getByPlaceholder("Enter username").fill("family");
await page
.getByPlaceholder("Enter password")
.fill("a-long-enough-password");
await page
.getByPlaceholder("Confirm Password")
.fill("a-long-enough-password");
await page.getByRole("button", { name: "Save" }).click();
const createCall = sent.find((call) => call.method === "POST");
expect(createCall?.body).toEqual({
username: "family",
password: "a-long-enough-password",
role: "viewer",
});
});
test("shows anonymous copy when nobody is signed in", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
profile: { username: "anonymous", role: "admin", allowed_cameras: null },
});
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await expect(page.getByText("doesn't require a login")).toBeVisible();
await expect(page.getByText("You're signed in as")).toBeHidden();
});
test("is absent when native auth is disabled", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
config: { auth: { enabled: false } } as never,
});
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await page.getByRole("button", { name: "Get Started" }).click();
// straight from welcome to the camera step, with no gap in the indicator
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeHidden();
});
test("skipping sends nothing", async ({ frigateApp, page }) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
expect(sent).toHaveLength(0);
});
test("an account change alone needs no restart", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Change password" }).click();
const dialog = page.getByRole("dialog");
await dialog
.getByPlaceholder("Enter new password", { exact: true })
.fill("a-long-enough-password");
await dialog
.getByPlaceholder("Re-enter new password")
.fill("a-long-enough-password");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Password set")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
// every remaining step is passed without writing config: Skip on the
// detector, then Auto on hwaccel, which has nothing to derive and so
// saves nothing, then Skip on recording
await expect(page.getByText("Object Detection")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByRole("button", { name: "Go to Live View" }),
).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeHidden();
});
});
+255
View File
@@ -0,0 +1,255 @@
/**
* Setup wizard hardware tests -- HIGH tier.
*
* Covers the detector step's probed radio list and the models: payload it
* writes, the model-required deferral for onnx hardware, the hwaccel step's
* Auto option writing the preset derived from the chosen hardware, and the
* completion screen only restarting when a saved step requires it.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page } from "@playwright/test";
import { gotoDetectorStep, installFirstRun } from "../../helpers/setup-wizard";
const NVIDIA_HARDWARE = [
{
key: "onnx:nvidia",
detector: "onnx",
name: "NVIDIA GeForce RTX 3060",
units: [{ device: "onnx:0", label: "NVIDIA GeForce RTX 3060" }],
count: 1,
unlimited: true,
},
{
key: "cpu",
detector: "cpu",
name: "CPU",
units: [{ device: "cpu", label: "CPU" }],
count: 1,
unlimited: true,
},
];
type SavedConfig = {
config_data?: {
models?: { devices: string[]; path?: string }[];
detect?: { enabled?: boolean };
ffmpeg?: { hwaccel_args?: string | string[] };
};
};
async function captureSaves(page: Page): Promise<SavedConfig[]> {
const saves: SavedConfig[] = [];
await page.route("**/api/config/set**", (route) => {
saves.push(route.request().postDataJSON() as SavedConfig);
return route.fulfill({ json: { success: true, require_restart: true } });
});
return saves;
}
async function captureRestarts(page: Page): Promise<string[]> {
const calls: string[] = [];
await page.route("**/api/restart", (route) => {
calls.push(route.request().url());
return route.fulfill({ json: { success: true, message: "Restarting" } });
});
return calls;
}
test.describe("setup wizard hardware @high @mobile", () => {
test("lists probed hardware and writes a models config", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hwaccel: {
recommended: "vaapi",
available: [
{ key: "vaapi", presets: { any: "preset-vaapi" } },
{
key: "intel-qsv",
presets: {
h264: "preset-intel-qsv-h264",
h265: "preset-intel-qsv-h265",
},
},
],
},
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
// the default hardware mock reports two Corals, an Intel GPU, and the CPU
await expect(
page.getByRole("radio", { name: /Coral EdgeTPU \(PCIe\) \(2\)/ }),
).toBeChecked();
await expect(page.getByText("Recommended")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
const detectorSave = saves.find((save) => save.config_data?.models);
expect(detectorSave?.config_data?.models).toEqual([
{ devices: ["edgetpu:pci:0"] },
]);
expect(detectorSave?.config_data?.detect).toEqual({ enabled: true });
// VAAPI decodes any codec, so one global value covers every camera
await expect(page.getByText("Will use VAAPI (Intel/AMD)")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
const hwaccelSave = saves.find((save) => save.config_data?.ffmpeg);
expect(hwaccelSave?.config_data?.ffmpeg).toEqual({
hwaccel_args: "preset-vaapi",
});
// the saved steps only take effect after a restart
const restarts = await captureRestarts(page);
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeVisible();
await page.getByRole("button", { name: "Apply & Restart" }).click();
await expect(page.getByText("Starting Frigate...")).toBeVisible();
expect(restarts).toHaveLength(1);
});
test("defers model setup for onnx hardware without Frigate+", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hardware: NVIDIA_HARDWARE,
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await expect(
page.getByRole("radio", { name: /NVIDIA GeForce RTX 3060/ }),
).toBeChecked();
await page
.getByRole("button", { name: "Continue without detection" })
.click();
// advances without touching the config
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
expect(saves.filter((save) => save.config_data?.models)).toHaveLength(0);
// nothing derived and nothing saved, so finishing needs no restart
const restarts = await captureRestarts(page);
await expect(page.getByText("No supported video card found")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeHidden();
await page.getByRole("button", { name: "Go to Live View" }).click();
// hands off without restarting, and the wizard does not come back
await expect(page.getByText("Welcome to Frigate")).toBeHidden();
expect(restarts).toHaveLength(0);
});
test("offers only the presets the hardware supports", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hardware: NVIDIA_HARDWARE,
hwaccel: {
recommended: "nvidia",
available: [{ key: "nvidia", presets: { any: "preset-nvidia" } }],
},
});
await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await page
.getByRole("button", { name: "Continue without detection" })
.click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
// an NVIDIA box has no business being offered Rockchip or Pi decoding
await expect(
page.getByRole("radio", { name: "CUDA (NVIDIA)" }),
).toBeVisible();
await expect(
page.getByRole("radio", { name: /Raspberry Pi/ }),
).toBeHidden();
await expect(page.getByRole("radio", { name: /Rockchip/ })).toBeHidden();
// Auto and None are always available
await expect(page.getByRole("radio", { name: "Auto" })).toBeVisible();
await expect(
page.getByRole("radio", { name: "None (software decoding)" }),
).toBeVisible();
});
test("a codec specific family falls back to h264 with no cameras", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hwaccel: {
recommended: "jetson",
available: [
{
key: "jetson",
presets: {
h264: "preset-jetson-h264",
h265: "preset-jetson-h265",
},
},
],
},
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await expect(
page.getByRole("radio", { name: "NVIDIA Jetson" }),
).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
// no camera was added, so there is no codec to match
const hwaccelSave = saves.find((save) => save.config_data?.ffmpeg);
expect(hwaccelSave?.config_data?.ffmpeg).toEqual({
hwaccel_args: "preset-jetson-h264",
});
});
test("None writes an explicit empty hwaccel list", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await page.getByRole("radio", { name: "None (software decoding)" }).click();
await page.getByRole("button", { name: "Next" }).click();
const hwaccelSave = saves.find((save) => save.config_data?.ffmpeg);
expect(hwaccelSave?.config_data?.ffmpeg).toEqual({ hwaccel_args: [] });
});
});
+5 -1
View File
@@ -427,6 +427,10 @@
"notConnected": "Not Connected",
"featuresTitle": "Features",
"go2rtc": "Reduce connections to camera",
"appleCompatibility": {
"title": "Improve playback on Apple devices",
"description": "Turn this on if you watch recordings in Safari or on an iPhone, iPad, or Mac."
},
"detectRoleWarning": "At least one stream must have the \"detect\" role to proceed.",
"rolesPopover": {
"title": "Stream Roles",
@@ -1973,7 +1977,7 @@
},
"lpr": {
"globalDisabled": "The license plate recognition enrichment must be enabled for LPR features to function on this camera.",
"vehicleNotTracked": "License plate recognition requires 'car' or 'motorcycle' to be tracked. Enable 'car' or 'motorcycle' in Objects for this camera.",
"vehicleNotTracked": "License plate recognition requires a vehicle to be tracked. Enable 'car' or another vehicle type in Objects for this camera.",
"modelSizeLarge": "The 'large' model is optimized for multi-line license plates. The 'small' model provides better performance over 'large' and should be used unless your region uses multi-line plate formats."
},
"record": {
+114
View File
@@ -0,0 +1,114 @@
{
"setupWizard": {
"steps": {
"welcome": "Welcome",
"account": "Account",
"camera": "Add Camera",
"hwaccel": "Acceleration",
"detector": "Detection",
"recording": "Recording",
"complete": "Done"
},
"welcome": {
"title": "Welcome to Frigate",
"description": "Let's get your security cameras set up. We'll walk through camera connection, hardware settings, and recording.",
"getStarted": "Get Started",
"skipSetup": "Skip setup and configure manually"
},
"account": {
"title": "Secure your account",
"descriptionSignedIn": "You're signed in as {{username}} using the temporary password from the Frigate logs. Set one you'll remember.",
"descriptionAnonymous": "You're accessing Frigate on a port that doesn't require a login. Set a password for the admin account so you can sign in on the secured port.",
"passwordSet": "Password set",
"changePassword": "Change password",
"addUser": "Add user",
"usersFailed": "Could not load the user list. You can still set the admin password.",
"userFailed": "Failed to add the user. Please try again."
},
"camera": {
"title": "Add Your First Camera",
"description": "Connect a camera to start monitoring. You can also add more cameras later in Settings.",
"addCamera": "Add Camera",
"addAnother": "Add Another Camera",
"cameraAdded": "Camera added successfully",
"retry": "Try Again"
},
"hwaccel": {
"title": "Hardware Acceleration",
"description": "Speed up video decoding with your GPU.",
"detecting": "Checking your hardware...",
"auto": "Auto",
"autoResolved": "Will use {{family}} for your cameras.",
"autoNone": "No supported video card found. Frigate will decide at startup.",
"recommendFailed": "Hardware detection is unavailable. Frigate will decide at startup.",
"families": {
"nvidia": "CUDA (NVIDIA)",
"vaapi": "VAAPI (Intel/AMD)",
"intel-qsv": "QuickSync (Intel)",
"rkmpp": "RKMPP (Rockchip)",
"jetson": "NVIDIA Jetson",
"rpi": "V4L2 (Raspberry Pi)",
"none": "None (software decoding)"
}
},
"detector": {
"title": "Object Detection",
"description": "Choose the hardware Frigate uses to detect people and objects.",
"detecting": "Checking for detection hardware...",
"probeFailed": "Hardware detection is unavailable. You can configure detection later in Settings.",
"recommended": "Recommended",
"modelRequired": "{{name}} needs a detection model before it can run. Pick a Frigate+ model, or finish setup and add one under Settings > Detection models.",
"plusModelPlaceholder": "Select a Frigate+ model",
"continueWithout": "Continue without detection"
},
"recording": {
"title": "Recordings",
"description": "Save video from your cameras so you can watch it later.",
"enableRecording": "Enable recordings",
"retentionDays": "Keep recordings for (days)",
"storageEstimate": "With {{free}} GB free, {{cameras}} camera(s) recording around the clock fills the disk in roughly {{days}} days.",
"noCameras": "You haven't added cameras yet. Recording will apply when you add cameras in Settings.",
"modeLabel": "What to record",
"modes": {
"events": {
"label": "Only when something is detected",
"description": "Saves video around people, cars, and other objects Frigate detects. Uses far less disk space."
},
"continuous": {
"label": "All the time",
"description": "Saves video around the clock, so you can go back to any moment. Uses much more disk space."
}
},
"retentionHint": {
"events": "Video of anything Frigate detects is kept this long, then deleted automatically.",
"continuous": "All video is kept this long, then deleted automatically."
}
},
"complete": {
"title": "You're done!",
"description": "Your Frigate system is configured. Here's what we set up:",
"configured": "Configured",
"notConfigured": "Not configured",
"configureInSettings": "Configure in Settings",
"camera": "Camera",
"hwaccel": "Hardware Acceleration",
"detector": "Object Detection",
"recording": "Recording",
"goToLiveView": "Go to Live View",
"applyAndRestart": "Apply & Restart",
"restartNotice": "Frigate needs to restart to apply your settings. This takes about 30 seconds.",
"nextSteps": "Next steps: Set up motion masks, zones, and notifications in Settings.",
"restarting": "Starting Frigate...",
"restartingDescription": "This takes about 30 seconds."
},
"actions": {
"next": "Next",
"back": "Back",
"skip": "Skip",
"saving": "Saving..."
},
"errors": {
"saveFailed": "Failed to save configuration. Please try again."
}
}
}
+38 -1
View File
@@ -6,7 +6,7 @@ import Sidebar from "@/components/navigation/Sidebar";
import { isDesktop, isMobile } from "react-device-detect";
import Statusbar from "./components/Statusbar";
import Bottombar from "./components/navigation/Bottombar";
import { Suspense, lazy } from "react";
import { Suspense, lazy, useContext, useEffect, useState } from "react";
import { Redirect } from "./components/navigation/Redirect";
import { cn } from "./lib/utils";
import { isPWA } from "./utils/isPWA";
@@ -15,6 +15,9 @@ import useSWR from "swr";
import { FrigateConfig } from "./types/frigateConfig";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { isRedirectingToLogin } from "@/api/auth-redirect";
import { AuthContext } from "@/context/auth-context";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { isSetupDismissed } from "@/utils/setupWizard";
const Live = lazy(() => import("@/pages/Live"));
const Events = lazy(() => import("@/pages/Events"));
@@ -30,6 +33,7 @@ const Chat = lazy(() => import("@/pages/Chat"));
const Logs = lazy(() => import("@/pages/Logs"));
const AccessDenied = lazy(() => import("@/pages/AccessDenied"));
const Replay = lazy(() => import("@/pages/Replay"));
const SetupWizard = lazy(() => import("@/pages/SetupWizard"));
function App() {
const { data: config } = useSWR<FrigateConfig>("config", {
@@ -52,6 +56,24 @@ function DefaultAppView() {
revalidateOnFocus: false,
});
// decided once per load: adding the first camera part way through the
// wizard must not pull the wizard out from under the user
const [showWizard, setShowWizard] = useState<boolean>();
const { auth } = useContext(AuthContext);
const isAdmin = useIsAdmin();
useEffect(() => {
// every step writes through admin only endpoints, and the role isn't
// known until the profile resolves
if (config && !auth.isLoading && showWizard === undefined) {
setShowWizard(
isAdmin &&
Object.keys(config.cameras ?? {}).length === 0 &&
!isSetupDismissed(),
);
}
}, [config, auth.isLoading, isAdmin, showWizard]);
// Compute required roles for main routes, ensuring we have config first
// to prevent race condition where custom roles are temporarily unavailable
const mainRouteRoles = config?.auth?.roles
@@ -68,6 +90,21 @@ function DefaultAppView() {
);
}
// Show setup wizard for first-time users
if (showWizard) {
return (
<div className="size-full overflow-hidden">
<Suspense
fallback={
<ActivityIndicator className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" />
}
>
<SetupWizard />
</Suspense>
</div>
);
}
return (
<div className="size-full overflow-hidden">
{isDesktop && <Sidebar />}
@@ -1,3 +1,4 @@
import { getModelForCamera } from "@/utils/modelUtil";
import type { SectionConfigOverrides } from "./types";
const lpr: SectionConfigOverrides = {
@@ -21,7 +22,10 @@ const lpr: SectionConfigOverrides = {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
if (ctx.fullCameraConfig.type === "lpr") return false;
const tracked = ctx.fullCameraConfig.objects?.track ?? [];
return !tracked.some((o) => ["car", "motorcycle"].includes(o));
const model = getModelForCamera(ctx.fullConfig, ctx.cameraName);
return !tracked.some((o) =>
model?.attributes_map?.[o]?.includes("license_plate"),
);
},
},
],
@@ -32,8 +32,8 @@ export function GenericVideoPlayer({
const checkSourceExists = async (url: string) => {
try {
const response = await fetch(url, { method: "HEAD" });
// nginx vod module returns 502 for non existent media
// https://github.com/kaltura/nginx-vod-module/issues/468
// missing media is a 404; 502 still covers a failed or
// unreachable mapping request, which is equally unplayable
setSourceExists(response.status !== 502 && response.status !== 404);
} catch (error) {
setSourceExists(false);
@@ -23,6 +23,7 @@ import type {
import {
processCameraName,
calculateDetectDimensions,
hevcRecordingStreamId,
} from "@/utils/cameraUtil";
import { cn } from "@/lib/utils";
@@ -74,11 +75,14 @@ const STEPS = [
type CameraWizardDialogProps = {
open: boolean;
onClose: () => void;
// lets callers reuse what was probed here instead of probing again
onCameraAdded?: (camera: { name: string; detectCodec?: string }) => void;
};
export default function CameraWizardDialog({
open,
onClose,
onCameraAdded,
}: CameraWizardDialogProps) {
const { t } = useTranslation(["views/settings"]);
const { mutate: updateConfig } = useSWR("config");
@@ -182,6 +186,11 @@ export default function CameraWizardDialog({
wizardData.cameraName,
);
// re-checked here: roles and codecs may have changed since it was set
const appleCompatibility =
!!wizardData.appleCompatibility &&
!!hevcRecordingStreamId(wizardData.streams);
// Convert wizard data to Frigate config format
const configData: CameraConfigData = {
cameras: {
@@ -189,6 +198,7 @@ export default function CameraWizardDialog({
enabled: true,
...(friendlyName && { friendly_name: friendlyName }),
ffmpeg: {
...(appleCompatibility && { apple_compatibility: true }),
inputs: wizardData.streams.map((stream, index) => {
if (stream.restream) {
const go2rtcStreamName =
@@ -271,6 +281,13 @@ export default function CameraWizardDialog({
.put("config/set", requestBody)
.then((response) => {
if (response.status === 200) {
onCameraAdded?.({
name: finalCameraName,
detectCodec: wizardData.streams?.find((stream) =>
stream.roles.includes("detect"),
)?.testResult?.videoCodec,
});
// Configure go2rtc streams for all streams
if (wizardData.streams && wizardData.streams.length > 0) {
const go2rtcStreams: Record<string, string[]> = {};
@@ -393,7 +410,7 @@ export default function CameraWizardDialog({
setIsLoading(false);
});
},
[updateConfig, t, onClose],
[updateConfig, t, onClose, onCameraAdded],
);
return (
@@ -26,7 +26,7 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { Drawer, DrawerContent, DrawerTrigger } from "@/components/ui/drawer";
import { isMobile } from "react-device-detect";
import { isIOS, isMobile, isSafari } from "react-device-detect";
import {
LuInfo,
LuExternalLink,
@@ -53,6 +53,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { hevcRecordingStreamId } from "@/utils/cameraUtil";
// Recording the sub stream from the same stream as record would just
// re-record the main stream, so the two roles are mutually exclusive.
@@ -389,6 +390,22 @@ export default function Step3StreamConfig({
const hasDetectRole = streams.some((s) => s.roles.includes("detect"));
const appleCompatibilityStreamId = useMemo(
() => hevcRecordingStreamId(streams),
[streams],
);
useEffect(() => {
// undefined, not false: a deliberate toggle-off must not be re-seeded
if (
(isSafari || isIOS) &&
appleCompatibilityStreamId &&
wizardData.appleCompatibility === undefined
) {
onUpdate({ appleCompatibility: true });
}
}, [appleCompatibilityStreamId, wizardData.appleCompatibility, onUpdate]);
return (
<div className="space-y-6">
<div className="text-sm text-secondary-foreground">
@@ -778,7 +795,7 @@ export default function Step3StreamConfig({
</PopoverContent>
</Popover>
</div>
<div className="rounded-lg bg-background p-3">
<div className="space-y-3 rounded-lg bg-background p-3">
<div className="flex items-center justify-between">
<span className="text-sm">
{t("cameraWizard.step3.go2rtc")}
@@ -788,6 +805,27 @@ export default function Step3StreamConfig({
onCheckedChange={() => setRestream(stream.id)}
/>
</div>
{appleCompatibilityStreamId === stream.id && (
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<div className="text-sm">
{t("cameraWizard.step3.appleCompatibility.title")}
</div>
<p className="text-xs text-muted-foreground">
{t(
"cameraWizard.step3.appleCompatibility.description",
)}
</p>
</div>
<Switch
checked={wizardData.appleCompatibility ?? false}
onCheckedChange={(checked) =>
onUpdate({ appleCompatibility: checked })
}
/>
</div>
)}
</div>
</div>
</CardContent>
@@ -268,6 +268,7 @@ export default function Step4Validation({
customUrl: wizardData.customUrl,
streams: wizardData.streams,
hasBackchannel: wizardData.hasBackchannel,
appleCompatibility: wizardData.appleCompatibility,
onvif: wizardData.onvif,
};
+194
View File
@@ -0,0 +1,194 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import CreateUserDialog from "@/components/overlay/CreateUserDialog";
import SetPasswordDialog from "@/components/overlay/SetPasswordDialog";
import { Button } from "@/components/ui/button";
import { AuthContext } from "@/context/auth-context";
import axios from "axios";
import { useCallback, useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import { FaCircleCheck } from "react-icons/fa6";
import { toast } from "sonner";
import useSWR from "swr";
type User = {
username: string;
role: string;
};
type SetupAccountProps = {
onNext: () => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupAccount({
onNext,
onBack,
onSkip,
}: SetupAccountProps) {
const { t } = useTranslation(["views/setup"]);
const { auth } = useContext(AuthContext);
const {
data: users,
isLoading,
error: usersError,
mutate: mutateUsers,
} = useSWR<User[]>("users", { revalidateOnFocus: false });
// the internal port has no signed in user, so the built-in admin is the
// account being secured
const adminUsername = auth.isAuthenticated
? (auth.user?.username ?? "admin")
: "admin";
const [showPassword, setShowPassword] = useState(false);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [passwordSaving, setPasswordSaving] = useState(false);
const [passwordSet, setPasswordSet] = useState(false);
const [showCreate, setShowCreate] = useState(false);
const handleSavePassword = useCallback(
(password: string) => {
setPasswordSaving(true);
axios
.put(`users/${adminUsername}/password`, { password })
.then(() => {
setShowPassword(false);
setPasswordError(null);
setPasswordSet(true);
})
.catch((error) => {
setPasswordError(
error.response?.data?.message ||
error.response?.data?.detail ||
t("setupWizard.errors.saveFailed"),
);
})
.finally(() => setPasswordSaving(false));
},
[adminUsername, t],
);
const handleCreateUser = useCallback(
(username: string, password: string, role: string) =>
axios
.post("users", { username, password, role })
.then(() => {
setShowCreate(false);
mutateUsers();
})
.catch((error) => {
toast.error(
error.response?.data?.message ||
error.response?.data?.detail ||
t("setupWizard.account.userFailed"),
);
}),
[mutateUsers, t],
);
const otherUsers = (users ?? []).filter(
(user) => user.username !== adminUsername,
);
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.account.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{auth.isAuthenticated
? t("setupWizard.account.descriptionSignedIn", {
username: adminUsername,
})
: t("setupWizard.account.descriptionAnonymous")}
</p>
</div>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between rounded-md border p-3">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">{adminUsername}</span>
{passwordSet && (
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<FaCircleCheck className="size-3 text-success" />
{t("setupWizard.account.passwordSet")}
</span>
)}
</div>
<Button
type="button"
variant="outline"
onClick={() => setShowPassword(true)}
>
{t("setupWizard.account.changePassword")}
</Button>
</div>
{otherUsers.map((user) => (
<div
key={user.username}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{user.username}</span>
<span className="text-xs text-muted-foreground">{user.role}</span>
</div>
))}
</div>
{isLoading && <ActivityIndicator />}
{usersError && (
<p className="rounded-md bg-muted p-3 text-xs text-muted-foreground">
{t("setupWizard.account.usersFailed")}
</p>
)}
<div className="flex flex-col items-center gap-3 py-4">
<Button
variant="select"
className="w-full"
onClick={() => setShowCreate(true)}
>
{t("setupWizard.account.addUser")}
</Button>
</div>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button type="button" variant="select" onClick={onNext}>
{t("setupWizard.actions.next")}
</Button>
</div>
</div>
{/* no username prop: passing one puts the dialog in current-password
mode, which the admin is exempt from and an anonymous internal port
user has no way to satisfy */}
<SetPasswordDialog
show={showPassword}
initialError={passwordError}
isLoading={passwordSaving}
onSave={handleSavePassword}
onCancel={() => {
setShowPassword(false);
setPasswordError(null);
}}
/>
<CreateUserDialog
show={showCreate}
onCreate={handleCreateUser}
onCancel={() => setShowCreate(false)}
/>
</div>
);
}
+109
View File
@@ -0,0 +1,109 @@
import CameraWizardDialog from "@/components/settings/CameraWizardDialog";
import { Button } from "@/components/ui/button";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { FaCircleCheck } from "react-icons/fa6";
type SetupCameraProps = {
onNext: (
cameraNames?: string[],
detectCodecs?: Record<string, string>,
) => void;
onBack: () => void;
};
export default function SetupCamera({ onNext, onBack }: SetupCameraProps) {
const { t } = useTranslation(["views/setup"]);
const [showWizard, setShowWizard] = useState(false);
const [addedCameras, setAddedCameras] = useState<string[]>([]);
const [detectCodecs, setDetectCodecs] = useState<Record<string, string>>({});
const handleClose = useCallback(() => {
setShowWizard(false);
}, []);
// the dialog fires this once its config write has succeeded, which is the
// only reliable signal that a camera was added
const handleCameraAdded = useCallback(
({ name, detectCodec }: { name: string; detectCodec?: string }) => {
setAddedCameras((previous) =>
previous.includes(name) ? previous : [...previous, name],
);
if (detectCodec) {
setDetectCodecs((previous) => ({ ...previous, [name]: detectCodec }));
}
},
[],
);
const handleNext = useCallback(() => {
onNext(addedCameras, detectCodecs);
}, [onNext, addedCameras, detectCodecs]);
const handleSkip = useCallback(() => {
onNext();
}, [onNext]);
return (
<>
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.camera.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.camera.description")}
</p>
</div>
{addedCameras.length > 0 && (
<div className="flex flex-col gap-2">
{addedCameras.map((name) => (
<div
key={name}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{name}</span>
<FaCircleCheck className="size-4 text-success" />
</div>
))}
</div>
)}
<div className="flex flex-col items-center gap-3 py-4">
<Button
variant="select"
className="w-full"
onClick={() => setShowWizard(true)}
>
{addedCameras.length > 0
? t("setupWizard.camera.addAnother")
: t("setupWizard.camera.addCamera")}
</Button>
</div>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
{addedCameras.length > 0 ? (
<Button type="button" variant="select" onClick={handleNext}>
{t("setupWizard.actions.next")}
</Button>
) : (
<Button type="button" variant="outline" onClick={handleSkip}>
{t("setupWizard.actions.skip")}
</Button>
)}
</div>
</div>
</div>
<CameraWizardDialog
open={showWizard}
onClose={handleClose}
onCameraAdded={handleCameraAdded}
/>
</>
);
}
+209
View File
@@ -0,0 +1,209 @@
import Logo from "@/components/Logo";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { Button } from "@/components/ui/button";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import axios from "axios";
import { FaCircleCheck } from "react-icons/fa6";
import { dismissSetup } from "@/utils/setupWizard";
type ConfiguredItem = {
key: string;
label: string;
value: string | null;
};
type SetupCompleteProps = {
cameraNames: string[];
configuredSteps: {
camera: boolean;
hwaccel: boolean;
detector: boolean;
recording: boolean;
};
restartRequired: boolean;
onBack: () => void;
};
export default function SetupComplete({
cameraNames,
configuredSteps,
restartRequired,
onBack,
}: SetupCompleteProps) {
const { t } = useTranslation(["views/setup"]);
const [restarting, setRestarting] = useState(false);
const [finishing, setFinishing] = useState(false);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const cameraItems: ConfiguredItem[] =
configuredSteps.camera && cameraNames.length > 0
? cameraNames.map((name) => ({
key: `camera-${name}`,
label: t("setupWizard.complete.camera"),
value: name,
}))
: [
{
key: "camera",
label: t("setupWizard.complete.camera"),
value: null,
},
];
const items: ConfiguredItem[] = [
...cameraItems,
{
key: "hwaccel",
label: t("setupWizard.complete.hwaccel"),
value: configuredSteps.hwaccel
? t("setupWizard.complete.configured")
: null,
},
{
key: "detector",
label: t("setupWizard.complete.detector"),
value: configuredSteps.detector
? t("setupWizard.complete.configured")
: null,
},
{
key: "recording",
label: t("setupWizard.complete.recording"),
value: configuredSteps.recording
? t("setupWizard.complete.configured")
: null,
},
];
useEffect(() => {
return () => {
if (pollRef.current) {
clearInterval(pollRef.current);
}
};
}, []);
const handleFinish = useCallback(async () => {
setFinishing(true);
dismissSetup();
try {
// camera adds were applied live, so nothing is waiting on a restart
if (!restartRequired) {
window.location.href = window.baseUrl || "/";
return;
}
setRestarting(true);
await axios.post("restart");
let retries = 0;
const maxRetries = 60; // 2 minutes max
pollRef.current = setInterval(async () => {
retries++;
if (retries > maxRetries) {
if (pollRef.current) {
clearInterval(pollRef.current);
}
window.location.href = window.baseUrl || "/";
return;
}
try {
const resp = await axios.get("version", { timeout: 2000 });
if (resp.status === 200) {
if (pollRef.current) {
clearInterval(pollRef.current);
}
window.location.href = window.baseUrl || "/";
}
} catch {
// not back yet
}
}, 2000);
} catch {
setRestarting(false);
setFinishing(false);
toast.error(t("setupWizard.errors.saveFailed"));
}
}, [restartRequired, t]);
if (restarting) {
return (
<div className="flex flex-col items-center gap-6 py-12">
<Logo className="h-12 w-12" />
<ActivityIndicator />
<div className="text-center">
<p className="font-semibold">
{t("setupWizard.complete.restarting")}
</p>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.complete.restartingDescription")}
</p>
</div>
</div>
);
}
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.complete.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.complete.description")}
</p>
</div>
<div className="flex flex-col gap-2">
{items.map((item) => (
<div
key={item.key}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{item.label}</span>
<div className="flex items-center gap-2">
{item.value && <FaCircleCheck className="size-4 text-success" />}
<span
className={`text-sm ${item.value ? "" : "text-muted-foreground"}`}
>
{item.value ?? t("setupWizard.complete.notConfigured")}
</span>
</div>
</div>
))}
</div>
<p className="text-sm text-muted-foreground">
{t("setupWizard.complete.nextSteps")}
</p>
{restartRequired && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.complete.restartNotice")}
</p>
)}
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end">
<Button
type="button"
variant="select"
onClick={handleFinish}
disabled={finishing}
>
{restartRequired
? t("setupWizard.complete.applyAndRestart")
: t("setupWizard.complete.goToLiveView")}
</Button>
</div>
</div>
</div>
);
}
+273
View File
@@ -0,0 +1,273 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import type { FrigatePlusModel } from "@/components/config-form/theme/fields/ModelSourcePicker";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useDocDomain } from "@/hooks/use-doc-domain";
import type { FrigateConfig } from "@/types/frigateConfig";
import type { DetectionHardware } from "@/types/hardware";
import { recommendedDetectorCount } from "@/utils/detectionHardware";
import axios from "axios";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { LuExternalLink } from "react-icons/lu";
import { toast } from "sonner";
import useSWR from "swr";
// these ship no default model, so configuring one without a model leaves the
// detector unable to start
const MODEL_REQUIRED_DETECTORS = ["onnx", "tensorrt"];
const CPU_FALLBACK: DetectionHardware[] = [
{
key: "cpu",
detector: "cpu",
name: "CPU",
units: [{ device: "cpu", label: "CPU" }],
count: 1,
unlimited: true,
},
];
type SetupDetectorProps = {
cameraCount: number;
onNext: (hardwareKey: string) => void;
onBack: () => void;
onSkip: (hardwareKey?: string) => void;
};
export default function SetupDetector({
cameraCount,
onNext,
onBack,
onSkip,
}: SetupDetectorProps) {
const { t } = useTranslation(["views/setup", "common"]);
const { getLocaleDocUrl } = useDocDomain();
const {
data: hardware,
isLoading,
error: probeError,
} = useSWR<DetectionHardware[]>("hardware/probe", {
revalidateOnFocus: false,
});
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
const plusEnabled = Boolean(config?.plus?.enabled);
// the cpu is always probed, so an empty list means the probe failed
const options = useMemo(
() => (hardware && hardware.length > 0 ? hardware : CPU_FALLBACK),
[hardware],
);
// the prober orders accelerators ahead of the cpu
const recommendedKey = options[0].key;
const [selectedKey, setSelectedKey] = useState<string>();
const selected =
options.find((entry) => entry.key === (selectedKey ?? recommendedKey)) ??
options[0];
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
plusEnabled && needsModel ? "/plus/models" : null,
{
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data;
},
},
);
const [plusModelId, setPlusModelId] = useState("");
const compatiblePlusModels = useMemo(
() =>
(plusModels ?? []).filter((model) =>
model.supportedDetectors.includes(selected.detector),
),
[plusModels, selected.detector],
);
const [saving, setSaving] = useState(false);
const buildDevices = useCallback(
(entry: DetectionHardware): string[] => {
const first = entry.units[0]?.device;
if (!first) {
return [];
}
if (!entry.unlimited) {
return [first];
}
// repeating a device runs an extra inference process on it
const count = recommendedDetectorCount(Math.max(cameraCount, 1));
return Array.from({ length: count }, () => first);
},
[cameraCount],
);
const handleSave = useCallback(async () => {
if (needsModel && !plusModelId) {
onSkip(selected.key);
return;
}
setSaving(true);
try {
const model: Record<string, unknown> = {
devices: buildDevices(selected),
};
if (needsModel) {
model.path = `plus://${plusModelId}`;
}
await axios.put("config/set", {
config_data: {
models: [model],
detect: { enabled: true },
},
requires_restart: 1,
});
onNext(selected.key);
} catch {
toast.error(t("setupWizard.errors.saveFailed"));
} finally {
setSaving(false);
}
}, [needsModel, plusModelId, selected, buildDevices, onNext, onSkip, t]);
if (isLoading) {
return (
<div className="flex flex-col items-center gap-4 py-12">
<ActivityIndicator />
<p className="text-sm text-muted-foreground">
{t("setupWizard.detector.detecting")}
</p>
</div>
);
}
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.detector.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.detector.description")}
</p>
</div>
{probeError && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.detector.probeFailed")}
</p>
)}
<RadioGroup
value={selected.key}
onValueChange={(value) => {
setSelectedKey(value);
setPlusModelId("");
}}
>
{options.map((entry) => (
<div key={entry.key} className="flex items-center space-x-2">
<RadioGroupItem
value={entry.key}
id={`detector-${entry.key}`}
className={
selected.key === entry.key
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
/>
<label
htmlFor={`detector-${entry.key}`}
className="cursor-pointer text-sm font-medium"
>
{entry.name}
{entry.count > 1 ? ` (${entry.count})` : ""}
{entry.key === recommendedKey && entry.key !== "cpu" && (
<span className="ml-2 text-xs text-selected">
{t("setupWizard.detector.recommended")}
</span>
)}
</label>
</div>
))}
</RadioGroup>
{needsModel && (
<div className="flex flex-col gap-3 rounded-md bg-muted p-3 text-sm">
<p>
{t("setupWizard.detector.modelRequired", { name: selected.name })}
</p>
{plusEnabled ? (
<Select value={plusModelId} onValueChange={setPlusModelId}>
<SelectTrigger className="max-w-xs">
<SelectValue
placeholder={t("setupWizard.detector.plusModelPlaceholder")}
/>
</SelectTrigger>
<SelectContent>
{compatiblePlusModels.map((model) => (
<SelectItem key={model.id} value={model.id}>
{`${model.name} (${model.width}x${model.height})`}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<a
href={getLocaleDocUrl("configuration/object_detectors")}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center text-primary"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 size-3" />
</a>
)}
</div>
)}
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={() => onSkip(selected.key)}>
{t("setupWizard.actions.skip")}
</Button>
<Button
type="button"
variant="select"
onClick={handleSave}
disabled={saving}
>
{saving
? t("setupWizard.actions.saving")
: needsModel && !plusModelId
? t("setupWizard.detector.continueWithout")
: t("setupWizard.actions.next")}
</Button>
</div>
</div>
</div>
);
}
+258
View File
@@ -0,0 +1,258 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import type { HwaccelFamily, HwaccelRecommendation } from "@/types/hardware";
import axios from "axios";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import useSWR from "swr";
const AUTO = "auto";
const NONE = "none";
const ANY_CODEC = "any";
// ffprobe names h265 streams hevc
const CODEC_ALIASES: Record<string, string> = { hevc: "h265" };
function normalizeCodec(codec: string): string {
const lower = codec.toLowerCase();
return CODEC_ALIASES[lower] ?? lower;
}
type SetupHwAccelProps = {
detectorHardwareKey?: string;
// camera name -> detect stream codec, the only stream hwaccel applies to
detectCodecs: Record<string, string>;
// saved tells the wizard whether finishing needs a restart
onNext: (saved: boolean) => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupHwAccel({
detectorHardwareKey,
detectCodecs,
onNext,
onBack,
onSkip,
}: SetupHwAccelProps) {
const { t } = useTranslation(["views/setup"]);
const cameraCodecs = useMemo(
() =>
Object.entries(detectCodecs).map(([camera, codec]) => ({
camera,
codec: normalizeCodec(codec),
})),
[detectCodecs],
);
const query = useMemo(() => {
const params = new URLSearchParams();
if (detectorHardwareKey) {
params.set("detector", detectorHardwareKey);
}
const codecs = [...new Set(cameraCodecs.map((entry) => entry.codec))];
if (codecs.length > 0) {
params.set("codecs", codecs.join(","));
}
return params.toString();
}, [detectorHardwareKey, cameraCodecs]);
const {
data: recommendation,
isLoading,
error: recommendError,
} = useSWR<HwaccelRecommendation>(
query ? `hardware/hwaccel?${query}` : "hardware/hwaccel",
{ revalidateOnFocus: false },
);
const [selected, setSelected] = useState<string>(AUTO);
const [saving, setSaving] = useState(false);
const families = useMemo(
() => recommendation?.available ?? [],
[recommendation],
);
const derived = recommendation?.recommended ?? "";
/** The config a family should be saved as, or null when it writes nothing. */
const configFor = useCallback(
(family: HwaccelFamily | undefined): Record<string, unknown> | null => {
if (!family) {
return null;
}
const shared = family.presets[ANY_CODEC];
if (shared) {
return { ffmpeg: { hwaccel_args: shared } };
}
const perCamera = cameraCodecs
.map((entry) => ({ ...entry, preset: family.presets[entry.codec] }))
.filter((entry) => entry.preset);
if (perCamera.length === 0) {
const fallback = Object.values(family.presets)[0];
return fallback ? { ffmpeg: { hwaccel_args: fallback } } : null;
}
const presets = new Set(perCamera.map((entry) => entry.preset));
if (presets.size === 1 && perCamera.length === cameraCodecs.length) {
return { ffmpeg: { hwaccel_args: [...presets][0] } };
}
// the global stays on auto so cameras added later resolve at startup
// instead of inheriting one camera's codec
return {
cameras: Object.fromEntries(
perCamera.map((entry) => [
entry.camera,
{ ffmpeg: { hwaccel_args: entry.preset } },
]),
),
};
},
[cameraCodecs],
);
const handleSave = useCallback(async () => {
const key = selected === AUTO ? derived : selected;
const configData =
selected === NONE
? // an empty string would make config/set delete the key, reviving
// the "auto" default
{ ffmpeg: { hwaccel_args: [] } }
: configFor(families.find((family) => family.key === key));
// nothing to write leaves the config default of "auto" in place
if (!configData) {
onNext(false);
return;
}
setSaving(true);
try {
await axios.put("config/set", {
config_data: configData,
requires_restart: 1,
});
onNext(true);
} catch {
toast.error(t("setupWizard.errors.saveFailed"));
} finally {
setSaving(false);
}
}, [selected, derived, families, configFor, onNext, t]);
if (isLoading) {
return (
<div className="flex flex-col items-center gap-4 py-12">
<ActivityIndicator />
<p className="text-sm text-muted-foreground">
{t("setupWizard.hwaccel.detecting")}
</p>
</div>
);
}
const radioClass = (value: string) =>
selected === value
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary";
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.hwaccel.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.hwaccel.description")}
</p>
</div>
<RadioGroup value={selected} onValueChange={setSelected}>
<div className="flex flex-col gap-0.5">
<div className="flex items-center space-x-2">
<RadioGroupItem
value={AUTO}
id="hwaccel-auto"
className={radioClass(AUTO)}
/>
<label htmlFor="hwaccel-auto" className="cursor-pointer text-sm">
{t("setupWizard.hwaccel.auto")}
</label>
</div>
<p className="ml-6 text-xs text-muted-foreground">
{derived
? t("setupWizard.hwaccel.autoResolved", {
family: t(`setupWizard.hwaccel.families.${derived}`),
})
: recommendError
? t("setupWizard.hwaccel.recommendFailed")
: t("setupWizard.hwaccel.autoNone")}
</p>
</div>
{families.map((family) => (
<div key={family.key} className="flex items-center space-x-2">
<RadioGroupItem
value={family.key}
id={`hwaccel-${family.key}`}
className={radioClass(family.key)}
/>
<label
htmlFor={`hwaccel-${family.key}`}
className="cursor-pointer text-sm"
>
{t(`setupWizard.hwaccel.families.${family.key}`)}
</label>
</div>
))}
<div className="flex items-center space-x-2">
<RadioGroupItem
value={NONE}
id="hwaccel-none"
className={radioClass(NONE)}
/>
<label htmlFor="hwaccel-none" className="cursor-pointer text-sm">
{t("setupWizard.hwaccel.families.none")}
</label>
</div>
</RadioGroup>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button
type="button"
variant="select"
onClick={handleSave}
disabled={saving}
>
{saving
? t("setupWizard.actions.saving")
: t("setupWizard.actions.next")}
</Button>
</div>
</div>
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import axios from "axios";
import useSWR from "swr";
const EVENTS = "events";
const CONTINUOUS = "continuous";
const MODES = [EVENTS, CONTINUOUS] as const;
type SetupRecordingProps = {
cameraNames: string[];
onNext: () => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupRecording({
cameraNames,
onNext,
onBack,
onSkip,
}: SetupRecordingProps) {
const { t } = useTranslation(["views/setup"]);
const [enabled, setEnabled] = useState(true);
const [mode, setMode] = useState<string>(EVENTS);
const [retentionDays, setRetentionDays] = useState(10);
const [saving, setSaving] = useState(false);
const { data: stats } = useSWR("stats", { revalidateOnFocus: false });
const storageInfo = stats?.service?.storage?.["/tmp/frigate/recordings"];
const freeGb = storageInfo ? Math.round(storageInfo.free / 1024) : null;
const cameraCount = cameraNames.length;
// Rough estimate: ~2 Mbps per camera continuous recording
const estimatedDays =
freeGb && cameraCount > 0
? Math.round((freeGb * 1024) / ((2 * 0.125 * 86400) / 1024) / cameraCount)
: null;
const handleSave = useCallback(async () => {
setSaving(true);
try {
const record: Record<string, unknown> = { enabled };
if (enabled) {
record.alerts = { retain: { days: retentionDays } };
record.detections = { retain: { days: retentionDays } };
// written even when off, so switching modes back turns it off again
record.continuous = { days: mode === CONTINUOUS ? retentionDays : 0 };
}
await axios.put("config/set", {
config_data: { record },
requires_restart: 1,
});
onNext();
} catch {
toast.error(t("setupWizard.errors.saveFailed"));
} finally {
setSaving(false);
}
}, [enabled, mode, retentionDays, onNext, t]);
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.recording.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.recording.description")}
</p>
</div>
{cameraCount === 0 && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.recording.noCameras")}
</p>
)}
<div className="flex items-center justify-between rounded-md border p-4">
<Label htmlFor="recording-toggle" className="font-medium">
{t("setupWizard.recording.enableRecording")}
</Label>
<Switch
id="recording-toggle"
checked={enabled}
onCheckedChange={setEnabled}
/>
</div>
{enabled && (
<>
<div className="flex flex-col gap-2">
<Label>{t("setupWizard.recording.modeLabel")}</Label>
<RadioGroup value={mode} onValueChange={setMode}>
{MODES.map((option) => (
<div key={option} className="flex flex-col gap-0.5">
<div className="flex items-center space-x-2">
<RadioGroupItem
value={option}
id={`recording-mode-${option}`}
className={
mode === option
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
/>
<label
htmlFor={`recording-mode-${option}`}
className="cursor-pointer text-sm font-medium"
>
{t(`setupWizard.recording.modes.${option}.label`)}
</label>
</div>
<p className="ml-6 text-xs text-muted-foreground">
{t(`setupWizard.recording.modes.${option}.description`)}
</p>
</div>
))}
</RadioGroup>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="retention-days">
{t("setupWizard.recording.retentionDays")}
</Label>
<Input
id="retention-days"
type="number"
min={1}
max={365}
value={retentionDays}
// drop the spinner arrows; typing and arrow keys still work
className="[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
onChange={(e) =>
setRetentionDays(Math.max(1, parseInt(e.target.value) || 1))
}
/>
<p className="text-xs text-muted-foreground">
{t(`setupWizard.recording.retentionHint.${mode}`)}
</p>
</div>
{mode === CONTINUOUS &&
freeGb !== null &&
estimatedDays !== null &&
cameraCount > 0 && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.recording.storageEstimate", {
free: freeGb,
days: estimatedDays,
cameras: cameraCount,
})}
</p>
)}
</>
)}
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button
type="button"
variant="select"
onClick={handleSave}
disabled={saving}
>
{saving
? t("setupWizard.actions.saving")
: t("setupWizard.actions.next")}
</Button>
</div>
</div>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
import Logo from "@/components/Logo";
import { Button } from "@/components/ui/button";
import { useTranslation } from "react-i18next";
type SetupWelcomeProps = {
onNext: () => void;
onSkip: () => void;
};
export default function SetupWelcome({ onNext, onSkip }: SetupWelcomeProps) {
const { t } = useTranslation(["views/setup"]);
return (
<div className="flex flex-col items-center gap-6 py-4">
<Logo className="h-16 w-16" />
<div className="text-center">
<h2 className="text-2xl font-semibold">
{t("setupWizard.welcome.title")}
</h2>
<p className="mt-2 text-muted-foreground">
{t("setupWizard.welcome.description")}
</p>
</div>
<div className="flex w-full flex-col gap-3 pt-4">
<Button variant="select" className="w-full" onClick={onNext}>
{t("setupWizard.welcome.getStarted")}
</Button>
<button
className="text-sm text-muted-foreground hover:text-primary"
onClick={onSkip}
>
{t("setupWizard.welcome.skipSetup")}
</button>
</div>
</div>
);
}
+284
View File
@@ -0,0 +1,284 @@
import StepIndicator from "@/components/indicators/StepIndicator";
import SetupAccount from "@/components/setup/SetupAccount";
import SetupCamera from "@/components/setup/SetupCamera";
import SetupComplete from "@/components/setup/SetupComplete";
import SetupDetector from "@/components/setup/SetupDetector";
import SetupHwAccel from "@/components/setup/SetupHwAccel";
import SetupRecording from "@/components/setup/SetupRecording";
import SetupWelcome from "@/components/setup/SetupWelcome";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { useTheme } from "@/context/theme-provider";
import { FrigateConfig } from "@/types/frigateConfig";
import { dismissSetup } from "@/utils/setupWizard";
import { useCallback, useMemo, useReducer } from "react";
import { useTranslation } from "react-i18next";
import { LuMoon, LuSun } from "react-icons/lu";
import useSWR from "swr";
type StepKey =
| "welcome"
| "account"
| "camera"
| "detector"
| "hwaccel"
| "recording"
| "complete";
const STEP_KEYS: StepKey[] = [
"welcome",
"account",
"camera",
"detector",
"hwaccel",
"recording",
"complete",
];
type WizardState = {
currentStep: number;
cameraNames: string[];
detectorHardwareKey?: string;
// camera name -> detect stream codec
detectCodecs: Record<string, string>;
// camera adds apply live, so they don't count toward needing a restart
restartRequired: boolean;
configuredSteps: {
camera: boolean;
hwaccel: boolean;
detector: boolean;
recording: boolean;
};
};
type WizardAction =
| { type: "NEXT_STEP" }
| { type: "PREV_STEP" }
| {
type: "CAMERAS_ADDED";
cameraNames: string[];
detectCodecs: Record<string, string>;
}
| {
type: "STEP_CONFIGURED";
step: keyof WizardState["configuredSteps"];
savedConfig: boolean;
}
| { type: "DETECTOR_DONE"; configured: boolean; hardwareKey?: string }
| { type: "SKIP_STEP" };
const initialState: WizardState = {
currentStep: 0,
cameraNames: [],
detectCodecs: {},
restartRequired: false,
configuredSteps: {
camera: false,
hwaccel: false,
detector: false,
recording: false,
},
};
function wizardReducer(state: WizardState, action: WizardAction): WizardState {
switch (action.type) {
case "NEXT_STEP":
return { ...state, currentStep: state.currentStep + 1 };
case "PREV_STEP":
return {
...state,
currentStep: Math.max(0, state.currentStep - 1),
};
case "CAMERAS_ADDED":
return {
...state,
currentStep: state.currentStep + 1,
cameraNames: action.cameraNames,
detectCodecs: action.detectCodecs,
configuredSteps: { ...state.configuredSteps, camera: true },
};
case "STEP_CONFIGURED":
return {
...state,
currentStep: state.currentStep + 1,
restartRequired: state.restartRequired || action.savedConfig,
configuredSteps: { ...state.configuredSteps, [action.step]: true },
};
case "DETECTOR_DONE":
return {
...state,
currentStep: state.currentStep + 1,
detectorHardwareKey: action.hardwareKey ?? state.detectorHardwareKey,
restartRequired: state.restartRequired || action.configured,
configuredSteps: {
...state.configuredSteps,
detector: state.configuredSteps.detector || action.configured,
},
};
case "SKIP_STEP":
return { ...state, currentStep: state.currentStep + 1 };
default:
return state;
}
}
export default function SetupWizard() {
const { t } = useTranslation(["views/setup", "common"]);
const [state, dispatch] = useReducer(wizardReducer, initialState);
const { theme, systemTheme, setTheme } = useTheme();
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
// with native auth off there are no users to manage, so the step would lie
const steps = useMemo(
() =>
config?.auth?.enabled === false
? STEP_KEYS.filter((key) => key !== "account")
: STEP_KEYS,
[config],
);
const stepLabels = useMemo(
() => steps.map((key) => `setupWizard.steps.${key}`),
[steps],
);
const isDark = (theme === "system" ? systemTheme : theme) === "dark";
const handleSkipSetup = useCallback(() => {
dismissSetup();
window.location.href = window.baseUrl || "/";
}, []);
const handleCameraNext = useCallback(
(cameraNames?: string[], detectCodecs?: Record<string, string>) => {
if (cameraNames && cameraNames.length > 0) {
dispatch({
type: "CAMERAS_ADDED",
cameraNames,
detectCodecs: detectCodecs ?? {},
});
} else {
dispatch({ type: "SKIP_STEP" });
}
},
[],
);
const handleHwAccelNext = useCallback((saved: boolean) => {
dispatch({ type: "STEP_CONFIGURED", step: "hwaccel", savedConfig: saved });
}, []);
const handleDetectorNext = useCallback((hardwareKey: string) => {
dispatch({ type: "DETECTOR_DONE", configured: true, hardwareKey });
}, []);
const handleDetectorSkip = useCallback((hardwareKey?: string) => {
dispatch({ type: "DETECTOR_DONE", configured: false, hardwareKey });
}, []);
const handleRecordingNext = useCallback(() => {
dispatch({ type: "STEP_CONFIGURED", step: "recording", savedConfig: true });
}, []);
const handleBack = useCallback(() => {
dispatch({ type: "PREV_STEP" });
}, []);
const handleSkipStep = useCallback(() => {
dispatch({ type: "SKIP_STEP" });
}, []);
const renderStep = () => {
switch (steps[state.currentStep]) {
case "welcome":
return (
<SetupWelcome
onNext={() => dispatch({ type: "NEXT_STEP" })}
onSkip={handleSkipSetup}
/>
);
case "account":
return (
<SetupAccount
onNext={handleSkipStep}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "camera":
return <SetupCamera onNext={handleCameraNext} onBack={handleBack} />;
case "detector":
return (
<SetupDetector
cameraCount={state.cameraNames.length}
onNext={handleDetectorNext}
onBack={handleBack}
onSkip={handleDetectorSkip}
/>
);
case "hwaccel":
return (
<SetupHwAccel
detectorHardwareKey={state.detectorHardwareKey}
detectCodecs={state.detectCodecs}
onNext={handleHwAccelNext}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "recording":
return (
<SetupRecording
cameraNames={state.cameraNames}
onNext={handleRecordingNext}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "complete":
return (
<SetupComplete
cameraNames={state.cameraNames}
configuredSteps={state.configuredSteps}
restartRequired={state.restartRequired}
onBack={handleBack}
/>
);
default:
return null;
}
};
return (
<div className="flex min-h-dvh items-center justify-center bg-background p-4">
<Button
type="button"
variant="ghost"
size="icon"
className="fixed right-4 top-4 text-muted-foreground hover:text-primary"
aria-label={t(isDark ? "menu.darkMode.light" : "menu.darkMode.dark", {
ns: "common",
})}
onClick={() => setTheme(isDark ? "light" : "dark")}
>
{isDark ? <LuSun className="size-4" /> : <LuMoon className="size-4" />}
</Button>
<Card className="w-full max-w-lg bg-background_alt">
<CardContent className="p-6">
<StepIndicator
steps={stepLabels}
currentStep={state.currentStep}
variant="dots"
translationNameSpace="views/setup"
className="mb-4 justify-start"
/>
<div className="fade-in">{renderStep()}</div>
</CardContent>
</Card>
</div>
);
}
+2
View File
@@ -119,6 +119,7 @@ export type WizardFormData = {
probeCandidates?: string[]; // candidate URLs from probe
candidateTests?: CandidateTestMap; // test results for candidates
hasBackchannel?: boolean; // true if camera supports backchannel audio
appleCompatibility?: boolean; // camera level, covers both recording outputs
onvif?: {
enabled: boolean;
host: string;
@@ -163,6 +164,7 @@ export type CameraConfigData = {
enabled: boolean;
friendly_name?: string;
ffmpeg: {
apple_compatibility?: boolean;
inputs: {
path: string;
roles: string[];
+11
View File
@@ -11,3 +11,14 @@ export type DetectionHardware = {
count: number;
unlimited: boolean;
};
export type HwaccelFamily = {
key: string;
// keyed by codec, or a single "any" preset when it decodes every codec
presets: Record<string, string>;
};
export type HwaccelRecommendation = {
recommended: string;
available: HwaccelFamily[];
};
+23
View File
@@ -1,6 +1,7 @@
import { baseUrl } from "@/api/baseUrl";
import { generateFixedHash, isValidId } from "./stringUtil";
import type { LiveStreamMetadata } from "@/types/live";
import type { StreamConfig } from "@/types/cameraWizard";
/**
* Processes a user-entered camera name and returns both the final camera name
@@ -205,3 +206,25 @@ const REPLAY_CAMERA_PREFIX = "_replay_";
export function isReplayCamera(name: string): boolean {
return name.startsWith(REPLAY_CAMERA_PREFIX);
}
const HEVC_CODEC_NAMES = ["hevc", "h265"];
function isHevcCodec(codec?: string): boolean {
return HEVC_CODEC_NAMES.includes((codec ?? "").trim().toLowerCase());
}
function isRecordingStream(stream: StreamConfig): boolean {
return stream.roles.includes("record") || stream.roles.includes("record_sub");
}
/**
* First recording stream probed as H.265. The other record output's codec
* doesn't matter: ffmpeg drops `-tag:v hvc1` on anything that isn't HEVC.
*/
export function hevcRecordingStreamId(
streams: StreamConfig[],
): string | undefined {
return streams.find(
(s) => isRecordingStream(s) && isHevcCodec(s.testResult?.videoCodec),
)?.id;
}
+19
View File
@@ -0,0 +1,19 @@
// dismissing the setup wizard is per-device UI state, so it lives in the
// browser rather than in the config the wizard exists to write
const DISMISSED_KEY = "frigate-setup-dismissed";
export function isSetupDismissed(): boolean {
try {
return localStorage.getItem(DISMISSED_KEY) === "true";
} catch {
return false;
}
}
export function dismissSetup(): void {
try {
localStorage.setItem(DISMISSED_KEY, "true");
} catch {
// storage can be unavailable; showing the wizard again beats failing here
}
}