Compare commits

..
Author SHA1 Message Date
Josh Hawkins 40f6b5f545 run recording deletion off the event loop 2026-11-23 14:57:02 -06:00
Josh Hawkins 3a1f4eca4c keep password hashing on the event loop 2026-11-23 13:37:29 -06:00
Josh Hawkins 3ad3802988 bound per-request work in recordings, image, password and motion search endpoints
- /recordings/unavailable walked the requested span one scale bucket at a time on the event loop, so a huge or non-finite range hung the whole API, including /auth. It now walks the gaps between recordings and rejects non-finite bounds.
- latest, mjpeg, event snapshot and recording snapshot heights are capped at the source frame height, and recording frame grabs time out after 30 s.
- Password verify and hash run in a worker thread, so a password change no longer freezes the API while PBKDF2 runs.
- Motion search collected every decoded frame of a run before detecting, up to about 190 MB per run. Frames now stream through detection, and keyframe mode stops reading at the probed keyframe count before falling back to cadence.
2026-11-23 12:55:03 -06:00
177 changed files with 2552 additions and 4891 deletions
+4 -3
View File
@@ -23,7 +23,7 @@ runs:
# from root and temp-reserve-mb is what actually stays free on root. Keep 4G # from root and temp-reserve-mb is what actually stays free on root. Keep 4G
# there for setup-qemu/buildx caches in ~/.docker and the tool cache # there for setup-qemu/buildx caches in ~/.docker and the tool cache
- name: Maximize build space - name: Maximize build space
uses: easimon/maximize-build-space@fc881a613ad2a34aca9c9624518214ebc21dfc0c # v10 uses: easimon/maximize-build-space@master
with: with:
root-reserve-mb: 8192 root-reserve-mb: 8192
temp-reserve-mb: 4096 temp-reserve-mb: 4096
@@ -36,8 +36,9 @@ runs:
run: sudo systemctl start docker run: sudo systemctl start docker
shell: bash shell: bash
- id: lowercaseRepo - id: lowercaseRepo
run: echo "lowercase=${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT uses: ASzc/change-string-case-action@v8
shell: bash with:
string: ${{ github.repository }}
- name: Set up QEMU - name: Set up QEMU
uses: docker/setup-qemu-action@v4 uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx - name: Set up Docker Buildx
+3
View File
@@ -133,6 +133,9 @@ updates:
# monaco-worker-manager releases its PR 4 # monaco-worker-manager releases its PR 4
- dependency-name: "monaco-editor" - dependency-name: "monaco-editor"
versions: [">=0.54.0"] versions: [">=0.54.0"]
# Later versions need Node 22 and extract false keys
- dependency-name: "i18next-cli"
versions: [">1.5.11"]
- package-ecosystem: "npm" - package-ecosystem: "npm"
directory: "/docs" directory: "/docs"
+4 -34
View File
@@ -14,9 +14,6 @@ concurrency:
group: ${{ github.ref }} group: ${{ github.ref }}
cancel-in-progress: true cancel-in-progress: true
permissions:
contents: read
env: env:
PYTHON_VERSION: 3.11 PYTHON_VERSION: 3.11
@@ -24,9 +21,6 @@ jobs:
amd64_build: amd64_build:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
name: AMD64 Build name: AMD64 Build
permissions:
contents: read
packages: write
steps: steps:
- name: Check out code - name: Check out code
uses: actions/checkout@v7 uses: actions/checkout@v7
@@ -51,9 +45,6 @@ jobs:
smoke_test: smoke_test:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
name: AMD64 Smoke Test name: AMD64 Smoke Test
permissions:
contents: read
packages: read
needs: needs:
- amd64_build - amd64_build
steps: steps:
@@ -165,16 +156,8 @@ jobs:
# the usb tree gets recursive grants plus a default ACL that # the usb tree gets recursive grants plus a default ACL that
# newly created nodes inherit (the Coral re-enumeration path) # 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 sh -c 'mkdir -p /dev/bus/usb/001 && mknod /dev/bus/usb/001/002 c 189 1'
docker exec frigate sh -c 'mkdir -p /opt/link-target && ln -s /opt/link-target /dev/bus/usb/001/link'
docker exec frigate sh -c 'export PATH=/command:$PATH; exec /etc/s6-overlay/s6-rc.d/init-devices/run' docker exec frigate sh -c 'export PATH=/command:$PATH; exec /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 getfacl -p /dev/bus/usb/001 | grep -q "user:frigate:rwx"
# a symlink in the usb tree is never followed
target_acl=$(docker exec frigate getfacl -p /opt/link-target)
if grep -q "user:frigate" <<< "$target_acl"; then
echo "init-devices followed a symlink under /dev/bus/usb"; exit 1
fi
# a fifo at the sentinel path is rejected at once instead of hanging the boot
docker exec frigate sh -c 'mkfifo /tmp/sentinel-fifo && timeout 5 /usr/local/bin/safe-sentinel read /tmp/sentinel-fifo; test $? -eq 1'
docker exec frigate sh -c 'mknod /dev/bus/usb/001/099 c 189 98 && chmod 664 /dev/bus/usb/001/099' 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) inherited=$(docker exec frigate getfacl -p /dev/bus/usb/001/099)
echo "$inherited" echo "$inherited"
@@ -261,9 +244,6 @@ jobs:
done done
if [ "$up" -ne 1 ]; then echo "granular container never came back after restart"; docker logs frigate-granular; exit 1; fi 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 exec frigate-granular stat -c %u /media/frigate/clips/straggler.webp | grep -qx 1000
# the per-boot /config sweep leaves the sentinel root-owned, so the restart skips the full sweep
docker exec frigate-granular stat -c %u /config/.permissions_version | grep -qx 0
docker logs frigate-granular 2>&1 | grep -q "already applied, skipping"
docker rm -f frigate-granular docker rm -f frigate-granular
- name: Assert unknown root service fails fast - name: Assert unknown root service fails fast
run: | run: |
@@ -314,18 +294,6 @@ jobs:
sleep 2 sleep 2
done done
if [ "$ok" -ne 1 ]; then echo "sentinel skip never logged"; docker logs frigate-puid; exit 1; fi if [ "$ok" -ne 1 ]; then echo "sentinel skip never logged"; docker logs frigate-puid; exit 1; fi
# a replaced media volume re-sweeps despite the sentinel
docker stop frigate-puid
sudo rm -rf /tmp/frigate-media-puid
sudo mkdir /tmp/frigate-media-puid
docker start frigate-puid
up=0
for i in $(seq 1 60); do
docker exec frigate-puid curl -fs http://127.0.0.1:5000/api/version && up=1 && break
sleep 5
done
if [ "$up" -ne 1 ]; then echo "replaced media volume was not swept"; docker logs frigate-puid; exit 1; fi
docker exec frigate-puid stat -c %u:%g /media/frigate | grep -qx 1500:1500
docker rm -f frigate-puid docker rm -f frigate-puid
- name: Assert read-only rootfs with --user works - name: Assert read-only rootfs with --user works
run: | run: |
@@ -696,7 +664,9 @@ jobs:
- arm64_build - arm64_build
steps: steps:
- id: lowercaseRepo - id: lowercaseRepo
run: echo "lowercase=${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT uses: ASzc/change-string-case-action@v8
with:
string: ${{ github.repository }}
- name: Log in to the Container registry - name: Log in to the Container registry
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
with: with:
@@ -705,7 +675,7 @@ jobs:
password: ${{ secrets.GITHUB_TOKEN }} password: ${{ secrets.GITHUB_TOKEN }}
- name: Create short sha - name: Create short sha
run: echo "SHORT_SHA=${GITHUB_SHA::7}" >> $GITHUB_ENV run: echo "SHORT_SHA=${GITHUB_SHA::7}" >> $GITHUB_ENV
- uses: int128/docker-manifest-create-action@3017ee3111145ac278bd27bf53b934f73def55af # v2.31.0 - uses: int128/docker-manifest-create-action@v2
id: manifest id: manifest
with: with:
tags: ghcr.io/${{ steps.lowercaseRepo.outputs.lowercase }}:${{ env.SHORT_SHA }} tags: ghcr.io/${{ steps.lowercaseRepo.outputs.lowercase }}:${{ env.SHORT_SHA }}
-3
View File
@@ -8,9 +8,6 @@ on:
- ".github/DISCUSSION_TEMPLATE/**" - ".github/DISCUSSION_TEMPLATE/**"
- ".github/ISSUE_TEMPLATE/**" - ".github/ISSUE_TEMPLATE/**"
permissions:
contents: read
env: env:
DEFAULT_PYTHON: 3.11 DEFAULT_PYTHON: 3.11
+7 -11
View File
@@ -5,10 +5,6 @@ on:
release: release:
types: [published] types: [published]
permissions:
contents: read
packages: write
jobs: jobs:
release: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -18,7 +14,9 @@ jobs:
with: with:
persist-credentials: false persist-credentials: false
- id: lowercaseRepo - id: lowercaseRepo
run: echo "lowercase=${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT uses: ASzc/change-string-case-action@v8
with:
string: ${{ github.repository }}
- name: Log in to the Container registry - name: Log in to the Container registry
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550
with: with:
@@ -36,21 +34,19 @@ jobs:
echo "BUILD_TAG=${GITHUB_SHA::7}" >> $GITHUB_ENV echo "BUILD_TAG=${GITHUB_SHA::7}" >> $GITHUB_ENV
echo "CLEAN_VERSION=$(echo ${GITHUB_REF##*/} | tr '[:upper:]' '[:lower:]' | sed 's/^[v]//')" >> $GITHUB_ENV echo "CLEAN_VERSION=$(echo ${GITHUB_REF##*/} | tr '[:upper:]' '[:lower:]' | sed 's/^[v]//')" >> $GITHUB_ENV
- name: Tag and push the main image - name: Tag and push the main image
env:
SKOPEO: quay.io/skopeo/stable:v1.24.1-immutable@sha256:81a8d4265c339539cba229459fdc4cb3580e1d2c2cb4285271c75adaa0fcb9b5
run: | run: |
VERSION_TAG=${BASE}:${CLEAN_VERSION} VERSION_TAG=${BASE}:${CLEAN_VERSION}
STABLE_TAG=${BASE}:stable STABLE_TAG=${BASE}:stable
PULL_TAG=${BASE}:${BUILD_TAG} PULL_TAG=${BASE}:${BUILD_TAG}
docker run --rm -v $HOME/.docker/config.json:/config.json ${SKOPEO} copy --authfile /config.json --multi-arch all docker://${PULL_TAG} docker://${VERSION_TAG} docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG} docker://${VERSION_TAG}
for variant in standard-arm64 tensorrt tensorrt-jp6 rk rocm synaptics; do for variant in standard-arm64 tensorrt tensorrt-jp6 rk rocm synaptics; do
docker run --rm -v $HOME/.docker/config.json:/config.json ${SKOPEO} copy --authfile /config.json --multi-arch all docker://${PULL_TAG}-${variant} docker://${VERSION_TAG}-${variant} docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG}-${variant} docker://${VERSION_TAG}-${variant}
done done
# stable tag # stable tag
if [[ "${BUILD_TYPE}" == "stable" ]]; then if [[ "${BUILD_TYPE}" == "stable" ]]; then
docker run --rm -v $HOME/.docker/config.json:/config.json ${SKOPEO} copy --authfile /config.json --multi-arch all docker://${PULL_TAG} docker://${STABLE_TAG} docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG} docker://${STABLE_TAG}
for variant in standard-arm64 tensorrt tensorrt-jp6 rk rocm synaptics; do for variant in standard-arm64 tensorrt tensorrt-jp6 rk rocm synaptics; do
docker run --rm -v $HOME/.docker/config.json:/config.json ${SKOPEO} copy --authfile /config.json --multi-arch all docker://${PULL_TAG}-${variant} docker://${STABLE_TAG}-${variant} docker run --rm -v $HOME/.docker/config.json:/config.json quay.io/skopeo/stable:latest copy --authfile /config.json --multi-arch all docker://${PULL_TAG}-${variant} docker://${STABLE_TAG}-${variant}
done done
fi fi
+1 -6
View File
@@ -7,16 +7,11 @@ on:
schedule: schedule:
- cron: "0 0 * * *" # run stalebot once a day - cron: "0 0 * * *" # run stalebot once a day
permissions:
actions: write
issues: write
pull-requests: write
jobs: jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 - uses: actions/stale@main
id: stale id: stale
with: with:
stale-issue-message: "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions." stale-issue-message: "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions."
-4
View File
@@ -11,10 +11,6 @@ Frigate NVR is a realtime object detection system for IP cameras that uses:
- **Architecture**: Multiprocessing design with ZMQ and MQTT communication - **Architecture**: Multiprocessing design with ZMQ and MQTT communication
- **Focus**: Minimal resource usage with maximum performance - **Focus**: Minimal resource usage with maximum performance
## Before Starting Work
Before starting work on a large change or a new feature, let the user know that a [GitHub discussion](https://github.com/blakeblackshear/frigate/discussions/new) should be opened first to align with the maintainers on scope and approach. This applies even to features that are self-contained and don't touch existing code, since every feature adds long-term maintenance cost. PRs for large changes without a prior discussion are unlikely to be merged. See [CONTRIBUTING.md](CONTRIBUTING.md). This can be skipped if the user has said they are a Frigate maintainer.
## Code Review Guidelines ## Code Review Guidelines
When reviewing code, do NOT comment on: When reviewing code, do NOT comment on:
+7 -10
View File
@@ -2,21 +2,18 @@
set -euxo pipefail set -euxo pipefail
go2rtc_version="1.10.0" go2rtc_version="1.9.14"
# sha256 digests of the release archives; update when bumping go2rtc_version. # sha256 digests of the release binaries; update when bumping go2rtc_version.
declare -A go2rtc_checksums=( declare -A go2rtc_checksums=(
["amd64"]="345d02a82ccd36028d98ef821cdc50cedabe919710c0d7506a86ed0e397d179b" ["amd64"]="32d616af226bd731678ffde328b94cfb94e30339bfefc469cfb76323144615a6"
["arm64"]="8951fda217fd637969b9936c8fc49ab2392e87fea6979b2ee99b755a70a8399d" ["arm64"]="359fabade8a7a51e81a55fe6df6b0ef81764a5e1d63179577534eaaa71904b50"
) )
dest_dir="/rootfs/usr/local/go2rtc/bin" dest_dir="/rootfs/usr/local/go2rtc/bin"
tarball="/tmp/go2rtc_linux_${TARGETARCH}.tar.gz"
mkdir -p "${dest_dir}" mkdir -p "${dest_dir}"
wget -qO "${tarball}" \ wget -qO "${dest_dir}/go2rtc" \
"https://github.com/AlexxIT/go2rtc/releases/download/v${go2rtc_version}/go2rtc_linux_${TARGETARCH}.tar.gz" "https://github.com/AlexxIT/go2rtc/releases/download/v${go2rtc_version}/go2rtc_linux_${TARGETARCH}"
echo "${go2rtc_checksums[${TARGETARCH}]} ${tarball}" | sha256sum -c - echo "${go2rtc_checksums[${TARGETARCH}]} ${dest_dir}/go2rtc" | sha256sum -c -
tar -xzOf "${tarball}" "go2rtc_linux_${TARGETARCH}" > "${dest_dir}/go2rtc"
rm -f "${tarball}"
chmod 755 "${dest_dir}/go2rtc" chmod 755 "${dest_dir}/go2rtc"
+1 -1
View File
@@ -1,4 +1,4 @@
ruff == 0.17.6 ruff == 0.17.5
# types # types
types-peewee == 4.0.* types-peewee == 4.0.*
+5 -5
View File
@@ -21,7 +21,7 @@ onvif-zeep-async == 4.3.*
paho-mqtt == 2.2.* paho-mqtt == 2.2.*
pandas == 3.0.* pandas == 3.0.*
peewee == 4.5.* peewee == 4.5.*
peewee_migrate == 2.5.* peewee_migrate == 2.3.*
psutil == 7.2.* psutil == 7.2.*
pydantic == 2.14.* pydantic == 2.14.*
git+https://github.com/fbcotter/py3nvml#egg=py3nvml git+https://github.com/fbcotter/py3nvml#egg=py3nvml
@@ -45,11 +45,11 @@ scipy == 1.17.*
openvino == 2026.4.* openvino == 2026.4.*
onnxruntime == 1.32.* onnxruntime == 1.32.*
# Embeddings # Embeddings
transformers == 5.24.* transformers == 5.22.*
# Generative AI # Generative AI
google-genai == 3.6.* google-genai == 3.6.*
ollama == 0.6.* ollama == 0.6.*
openai == 3.60.* openai == 3.55.*
# push notifications # push notifications
py-vapid == 1.9.6 py-vapid == 1.9.6
pywebpush == 2.5.* pywebpush == 2.5.*
@@ -58,7 +58,7 @@ pyclipper == 1.4.*
shapely == 2.2.* shapely == 2.2.*
rapidfuzz==3.14.* rapidfuzz==3.14.*
# HailoRT # HailoRT
argcomplete==3.8.* argcomplete==3.7.*
contextlib2==21.6.* contextlib2==21.6.*
future==1.0.* future==1.0.*
netaddr==1.3.* netaddr==1.3.*
@@ -73,4 +73,4 @@ faster-whisper==1.2.*
librosa==0.11.* librosa==0.11.*
soundfile==0.14.* soundfile==0.14.*
# Memory profiling # Memory profiling
memray == 1.21.* memray == 1.20.*
@@ -12,7 +12,7 @@ echo "[INFO] Starting go2rtc healthcheck service..."
while sleep 30s; do while sleep 30s; do
# Check if the service is running # Check if the service is running
if ! curl --connect-timeout 10 --max-time 15 --fail --silent --show-error --output /dev/null http://127.0.0.1:1984/api/streams 2>&1; then if ! curl --connect-timeout 10 --fail --silent --show-error --output /dev/null http://127.0.0.1:1984/api/streams 2>&1; then
echo "[ERROR] The go2rtc service is not responding to ping, restarting..." echo "[ERROR] The go2rtc service is not responding to ping, restarting..."
# We can also use -r instead of -t to send kill signal rather than term # We can also use -r instead of -t to send kill signal rather than term
s6-svc -t /var/run/service/go2rtc 2>&1 s6-svc -t /var/run/service/go2rtc 2>&1
@@ -105,14 +105,12 @@ done
# node), so the directories also get a default ACL new nodes inherit. The # 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 # 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. # udev hosts (0664) and nothing on raw devtmpfs (0600); hardware-verified.
# The tree may be a host devtmpfs bind mount the runtime users can write, so
# only real directories and device nodes are granted and links are never followed
if [[ -d /dev/bus/usb ]]; then if [[ -d /dev/bus/usb ]]; then
while IFS= read -r -d '' node; do while IFS= read -r -d '' node; do
grant "$node" grant "$node"
done < <(find /dev/bus/usb -mindepth 1 \( -type c -o -type d \) -print0) done < <(find /dev/bus/usb -mindepth 1 -print0)
while IFS= read -r -d '' dir; do while IFS= read -r -d '' dir; do
setfacl -P -d -m "u:frigate:rw,u:go2rtc:rw" "$dir" 2>/dev/null || \ 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" 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) done < <(find /dev/bus/usb -type d -print0)
fi fi
@@ -152,24 +152,13 @@ if [[ "$(id -u)" -eq 0 && "$runs_as_root" -eq 0 ]]; then
# nginx reopens /dev/stdout by path for its logs, and s6 made the pipe # 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 # root-owned 0600; without this the non-root master exits EACCES
chown frigate /dev/stdout chown frigate /dev/stdout
# Only mounted certs need handing over; the self-signed pair is already
# owned by the runtime user that generated it. Never chown the /config copy:
# chown follows symlinks, so it would retarget onto any root file the
# runtime user pointed it at. Tolerant because mounted certs may be :ro.
if [ "$cert_path" = "$letsencrypt_path" ] && [ -f "$cert_path/privkey.pem" ]; then
chown frigate:frigate "$cert_path/privkey.pem" "$cert_path/fullchain.pem" 2>/dev/null || true
fi fi
# Mounted certs are never chowned: chown follows symlinks, and the runtime user
# may control the mounted folder. The key's group and group read survive certbot
# renewals, so the host grants access once.
if [[ "$cert_path" == "$letsencrypt_path" && "$runs_as_root" -eq 0 ]] &&
[[ "$(echo "$nginx_settings" | jq -r .tls.enabled)" == "true" ]]; then
as_runtime=()
if [[ "$(id -u)" -eq 0 ]]; then
as_runtime=(s6-setuidgid frigate)
fi
for file in privkey.pem fullchain.pem; do
if ! "${as_runtime[@]}" test -r "$cert_path/$file"; then
runtime_gid=$("${as_runtime[@]}" id -g)
echo "[ERROR] The mounted ${file} is not readable by the runtime user; on the host, give it group ${runtime_gid} with read access and let that group enter the folders above it" >&2
fi
done
fi fi
# Replace the bash process with the NGINX process, redirecting stderr to stdout # Replace the bash process with the NGINX process, redirecting stderr to stdout
+19 -31
View File
@@ -70,6 +70,16 @@ if [[ -n "$mode" ]]; then
sentinel_content="${sentinel_content}:${mode}" sentinel_content="${sentinel_content}:${mode}"
fi 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: # A sweep that could not chown everything must not be recorded as complete:
# the sentinel would make every later boot skip it and the entries would stay # the sentinel would make every later boot skip it and the entries would stay
# unreachable once services run unprivileged. # unreachable once services run unprivileged.
@@ -78,36 +88,21 @@ swept_clean=1
# Entries another mechanism deliberately owns. Chowning them undoes that work # Entries another mechanism deliberately owns. Chowning them undoes that work
# and leaves the same "mismatch" waiting for the next boot, so /config could # 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 # never report itself clean: /config is chgrp'd to frigate-data below so go2rtc
# can traverse it, the HomeKit file is handed to the go2rtc user by the go2rtc # can traverse it, and the HomeKit file is handed to the go2rtc user by the
# service, and safe-sentinel only trusts a root-owned sentinel. The sentinel is # go2rtc service. Only the GROUP on /config is exempt; a root-owned /config
# excluded on every call, including the granular per-boot /config sweep that # must still be chowned or the runtime user cannot write there at all.
# runs without --sentinel. 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. # Shared by the counting and the chowning walk so the two cannot disagree.
mismatch_expr=( mismatch_expr=(
"(" -not -uid "$target_uid" "(" -not -uid "$target_uid"
-o "(" -not -gid "$target_gid" -a ! -path /config ")" -o "(" -not -gid "$target_gid" -a ! -path /config ")"
")" ")"
-a ! -path /config/go2rtc_homekit.yml -a ! -path /config/go2rtc_homekit.yml
-a ! -path /config/.permissions_version
) )
if [[ -n "$sentinel" ]]; then
first_mismatched_root() { # safe-sentinel keeps the sentinel root-owned on purpose and rejects one
find "$@" -maxdepth 0 "${mismatch_expr[@]}" -print -quit 2>/dev/null || true # 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")
# safe-sentinel reports only a root-owned regular file, so a forged or
# symlinked sentinel in the runtime-user-owned /config can't suppress the sweep.
# A mismatched volume root means the volume was replaced or wiped since the
# sweep (Docker recreates a missing bind source as root), so it sweeps again,
# unless the sentinel records a filesystem that ignores chown.
if [[ "$dry_run" -eq 0 && -n "$sentinel" ]]; then
if existing=$(/usr/local/bin/safe-sentinel read "$sentinel" 2>/dev/null) && \
{ [[ "$existing" == "${sentinel_content}:unmanaged" ]] || \
{ [[ "$existing" == "$sentinel_content" ]] && [[ -z "$(first_mismatched_root "$@")" ]]; }; }; then
echo "[INFO] fix-ownership: ${target_uid}:${target_gid} (schema ${schema}) already applied, skipping"
exit 0
fi
fi fi
exec 3>&1 exec 3>&1
@@ -197,7 +192,7 @@ done
# go2rtc (separate user) must be able to REACH its HomeKit state in /config. # go2rtc (separate user) must be able to REACH its HomeKit state in /config.
# Write access is per-file, not per-directory: go2rtc's PatchConfig rewrites # Write access is per-file, not per-directory: go2rtc's PatchConfig rewrites
# the first -config file via os.WriteFile (in-place truncate, no rename, # the first -config file via os.WriteFile (in-place truncate, no rename,
# verified against go2rtc v1.10.0 internal/app/config.go), and the file is # verified against go2rtc v1.9.14 internal/app/config.go), and the file is
# always pre-created by setup_homekit_config before go2rtc starts, so # always pre-created by setup_homekit_config before go2rtc starts, so
# O_CREATE never needs directory write. See header comment for why g+w is # O_CREATE never needs directory write. See header comment for why g+w is
# forbidden here. # forbidden here.
@@ -207,13 +202,6 @@ if [[ "$dry_run" -eq 0 && -d /config ]]; then
fi fi
if [[ "$dry_run" -eq 0 && -n "$sentinel" && "$swept_clean" -eq 1 ]]; then if [[ "$dry_run" -eq 0 && -n "$sentinel" && "$swept_clean" -eq 1 ]]; then
# CIFS without the setuids option accepts chown and changes nothing, so
# the root can never match. Without this every boot would sweep again.
unmanaged_root=$(first_mismatched_root "$@")
if [[ -n "$unmanaged_root" ]]; then
echo "[WARN] fix-ownership: ${unmanaged_root} kept its owner after chown; its filesystem ignores ownership changes, so set the owner through its mount options"
sentinel_content="${sentinel_content}:unmanaged"
fi
/usr/local/bin/safe-sentinel write "$sentinel" "$sentinel_content" || \ /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" echo "[WARN] fix-ownership: could not write ${sentinel}; the sweep will run again on next boot"
fi fi
@@ -20,8 +20,7 @@ MODE = 0o644
def do_read(path: str) -> int: def do_read(path: str) -> int:
try: try:
# O_NONBLOCK so a fifo opens at once and fails the regular-file check fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
except OSError: except OSError:
return 1 return 1
try: try:
@@ -183,7 +183,7 @@ http {
} }
expires 7d; expires 7d;
add_header Cache-Control "private"; add_header Cache-Control "public";
autoindex on; autoindex on;
root /media/frigate; root /media/frigate;
@@ -205,7 +205,6 @@ http {
video/mp4 mp4; video/mp4 mp4;
} }
add_header Cache-Control "private";
autoindex on; autoindex on;
autoindex_format json; autoindex_format json;
root /media/frigate; root /media/frigate;
@@ -217,7 +216,6 @@ http {
video/mp4 mp4; video/mp4 mp4;
} }
add_header Cache-Control "private";
autoindex on; autoindex on;
autoindex_format json; autoindex_format json;
root /media/frigate; root /media/frigate;
@@ -8,11 +8,7 @@ from typing import Any
from ruamel.yaml import YAML from ruamel.yaml import YAML
sys.path.insert(0, "/opt/frigate") sys.path.insert(0, "/opt/frigate")
from frigate.util.config import ( from frigate.util.config import find_config_file, parse_listen_address
find_config_file,
ipv6_listen_address,
parse_listen_address,
)
sys.path.remove("/opt/frigate") sys.path.remove("/opt/frigate")
@@ -55,9 +51,6 @@ for key, default in (("internal", 5000), ("external", 8971)):
listen_config[key] = value listen_config[key] = value
listen_config[f"{key}_port"] = port listen_config[f"{key}_port"] = port
listen_config[f"{key}_ipv6"] = (
ipv6_listen_address(value, port) if ipv6_config["enabled"] else None
)
if listen_config["internal_port"] == listen_config["external_port"]: if listen_config["internal_port"] == listen_config["external_port"]:
print( print(
@@ -1,12 +1,12 @@
# Internal; a wildcard address also listens on [::] when IPv6 is enabled # Internal (IPv4 always; IPv6 optional)
listen {{ .listen.internal }}; listen {{ .listen.internal }};
{{ if .listen.internal_ipv6 }}listen {{ .listen.internal_ipv6 }};{{ end }} {{ if .ipv6.enabled }}listen [::]:{{ .listen.internal_port }};{{ end }}
# intended for external traffic, protected by auth # intended for external traffic, protected by auth
{{ if .tls.enabled }} {{ if .tls.enabled }}
# external HTTPS # external HTTPS (IPv4 always; IPv6 optional)
listen {{ .listen.external }} ssl; listen {{ .listen.external }} ssl;
{{ if .listen.external_ipv6 }}listen {{ .listen.external_ipv6 }} ssl;{{ end }} {{ if .ipv6.enabled }}listen [::]:{{ .listen.external_port }} ssl;{{ end }}
ssl_certificate {{ .tls.cert_path }}/fullchain.pem; ssl_certificate {{ .tls.cert_path }}/fullchain.pem;
ssl_certificate_key {{ .tls.cert_path }}/privkey.pem; ssl_certificate_key {{ .tls.cert_path }}/privkey.pem;
@@ -30,7 +30,7 @@ listen {{ .listen.internal }};
root /etc/letsencrypt/www; root /etc/letsencrypt/www;
} }
{{ else }} {{ else }}
# (No tls) default to HTTP # (No tls) default to HTTP (IPv4 always; IPv6 optional)
listen {{ .listen.external }}; listen {{ .listen.external }};
{{ if .listen.external_ipv6 }}listen {{ .listen.external_ipv6 }};{{ end }} {{ if .ipv6.enabled }}listen [::]:{{ .listen.external_port }};{{ end }}
{{ end }} {{ end }}
@@ -102,7 +102,7 @@ proxy:
# Optional: Auth secret that is checked against the X-Proxy-Secret header sent from # Optional: Auth secret that is checked against the X-Proxy-Secret header sent from
# the proxy. If not set, all requests are trusted regardless of origin. # the proxy. If not set, all requests are trusted regardless of origin.
auth_secret: None auth_secret: None
# Optional: The default role to use for proxy auth. Must be "admin", "viewer", a custom role, or "none" to deny # Optional: The default role to use for proxy auth. Must be "admin" or "viewer"
default_role: viewer default_role: viewer
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below) # Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
separator: "," separator: ","
@@ -895,7 +895,7 @@ classification:
interval: None interval: None
# Optional: Restream configuration # Optional: Restream configuration
# Uses https://github.com/AlexxIT/go2rtc (v1.10.0) # Uses https://github.com/AlexxIT/go2rtc (v1.9.14)
# NOTE: The default go2rtc API port (1984) must be used, # NOTE: The default go2rtc API port (1984) must be used,
# changing this port for the integrated go2rtc instance is not supported. # changing this port for the integrated go2rtc instance is not supported.
go2rtc: go2rtc:
+2 -2
View File
@@ -287,7 +287,7 @@ Frigate exposes a few networking options. IPv6 and the listen ports are set in t
### Enabling IPv6 ### Enabling IPv6
By default Frigate listens on IPv4 only. To also listen on IPv6 (on port `5000`, and on `8971` when TLS is configured), enable it in the `networking` configuration. A listen port bound to a specific address stays on that address only. By default Frigate listens on IPv4 only. To also listen on IPv6 (on port `5000`, and on `8971` when TLS is configured), enable it in the `networking` configuration.
<ConfigTabs> <ConfigTabs>
<TabItem value="ui"> <TabItem value="ui">
@@ -413,7 +413,7 @@ There is one exception, and it only affects [`FRIGATE_ROOT_SERVICES`](/configura
### Custom go2rtc version ### Custom go2rtc version
Frigate currently includes go2rtc v1.10.0, there may be certain cases where you want to run a different version of go2rtc. Frigate currently includes go2rtc v1.9.14, there may be certain cases where you want to run a different version of go2rtc.
To do this: To do this:
+1 -4
View File
@@ -234,8 +234,6 @@ proxy:
Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in. Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in.
A `default_role` that does not name a configured role is treated as `none`.
```yaml ```yaml
proxy: proxy:
... ...
@@ -268,8 +266,7 @@ In this example:
- If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role. - If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role.
- If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role. - If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role.
- If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`. - If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`.
- If a group matches but its mapped role no longer exists (for example, a deleted custom role), access is denied. - If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name, matched without regard to case.
**Note on matching semantics:** **Note on matching semantics:**
+1 -1
View File
@@ -264,7 +264,7 @@ go2rtc:
- rtspx://192.168.1.1:7441/abcdefghijk - rtspx://192.168.1.1:7441/abcdefghijk
``` ```
[See the go2rtc docs for more information](https://github.com/AlexxIT/go2rtc/tree/v1.10.0#source-rtsp) [See the go2rtc docs for more information](https://github.com/AlexxIT/go2rtc/tree/v1.9.14#source-rtsp)
In the Unifi 2.0 update Unifi Protect Cameras had a change in audio sample rate which causes issues for ffmpeg. The input rate needs to be set for record if used directly with unifi protect. In the Unifi 2.0 update Unifi Protect Cameras had a change in audio sample rate which causes issues for ffmpeg. The input rate needs to be set for record if used directly with unifi protect.
+1 -3
View File
@@ -84,7 +84,7 @@ A camera is enabled by default but can be disabled by using `enabled: False`. Ca
Each role can only be assigned to one input per camera. The options for roles are as follows: Each role can only be assigned to one input per camera. The options for roles are as follows:
| Role | Description | | Role | Description |
| ------------ | --------------------------------------------------------------------------------------------------------------- | | ------------ | ------------------------------------------------------------------------------------------------------------ |
| `detect` | Main feed for object detection. [docs](object_detectors.md) | | `detect` | Main feed for object detection. [docs](object_detectors.md) |
| `record` | Saves segments of the video feed based on configuration settings. [docs](record.md) | | `record` | Saves segments of the video feed based on configuration settings. [docs](record.md) |
| `record_sub` | Saves segments of a second, lower quality stream with its own retention. [docs](record.md#sub-stream-recording) | | `record_sub` | Saves segments of a second, lower quality stream with its own retention. [docs](record.md#sub-stream-recording) |
@@ -160,8 +160,6 @@ If you only define one stream in your `inputs` and do not assign a `detect` role
If you plan to use Frigate for recording only, it is still recommended to define a `detect` role for a low resolution stream to minimize resource usage from the required stream decoding. If you plan to use Frigate for recording only, it is still recommended to define a `detect` role for a low resolution stream to minimize resource usage from the required stream decoding.
Setting the `detect` `width` and `height` explicitly is recommended. When they are unset, Frigate probes the detect stream at every startup, which can add several seconds per camera. Cameras added with the [Add Camera Wizard](#adding-a-camera-with-the-add-camera-wizard) have them set automatically.
::: :::
For camera model specific settings check the [camera specific](camera_specific.md) infos. For camera model specific settings check the [camera specific](camera_specific.md) infos.
+1 -1
View File
@@ -25,7 +25,7 @@ This guide is mainly useful if you are **upgrading from an older version and hav
If you added your cameras with the wizard, go2rtc is already configured. You can skip straight to [troubleshooting](/troubleshooting/go2rtc). The steps below are for upgrading users with existing cameras that aren't using go2rtc yet, or for anyone who prefers to configure a stream by hand. If you added your cameras with the wizard, go2rtc is already configured. You can skip straight to [troubleshooting](/troubleshooting/go2rtc). The steps below are for upgrading users with existing cameras that aren't using go2rtc yet, or for anyone who prefers to configure a stream by hand.
Configure go2rtc to connect to your camera by adding the stream you want to use for live view. Avoid changing any other parts of your config at this step. Note that go2rtc supports [many different stream types](https://github.com/AlexxIT/go2rtc/tree/v1.10.0#module-streams), not just rtsp. Configure go2rtc to connect to your camera by adding the stream you want to use for live view. Avoid changing any other parts of your config at this step. Note that go2rtc supports [many different stream types](https://github.com/AlexxIT/go2rtc/tree/v1.9.14#module-streams), not just rtsp.
:::tip :::tip
+1 -1
View File
@@ -245,7 +245,7 @@ services:
::: :::
See [go2rtc WebRTC docs](https://github.com/AlexxIT/go2rtc/tree/v1.10.0#module-webrtc) for more information about this. See [go2rtc WebRTC docs](https://github.com/AlexxIT/go2rtc/tree/v1.9.14#module-webrtc) for more information about this.
### Two way talk ### Two way talk
+1 -1
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
# Metrics # Metrics
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance. On the authenticated port (8971), the endpoint requires an admin user, so point scrapers at the internal port (5000) as shown below. Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance.
## Enabling Telemetry ## Enabling Telemetry
+2 -12
View File
@@ -86,16 +86,6 @@ Once the volumes are aligned, start Frigate normally. A file at `/config/.permis
If something under your volumes can't be chowned, a read-only btrfs snapshot directory for example, the sweep warns and names the path and doesn't record the migration as finished. It retries on the next boot instead. Either move those paths outside `/media/frigate` or expect the scan to repeat. If something under your volumes can't be chowned, a read-only btrfs snapshot directory for example, the sweep warns and names the path and doesn't record the migration as finished. It retries on the next boot instead. Either move those paths outside `/media/frigate` or expect the scan to repeat.
### Custom database location
The sweep only covers `/config` and `/media/frigate`. If `database.path` points somewhere else, such as a separate volume, align that directory yourself before upgrading, and again after running with `FRIGATE_RUN_AS_ROOT=true`:
```bash
chown -R 1000:1000 /path/to/your/database/dir
```
Use your `PUID` and `PGID` if you've changed them. Until the directory and its files are writable, Frigate stops at startup with an error naming the path it can't write.
### Network storage ### Network storage
Recordings on a NAS behave differently, so check what you have before migrating: Recordings on a NAS behave differently, so check what you have before migrating:
@@ -104,7 +94,7 @@ Recordings on a NAS behave differently, so check what you have before migrating:
findmnt -T /path/to/your/storage -o TARGET,FSTYPE,OPTIONS 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` has no effect and isn't needed. Mount the share as the uid and gid Frigate runs as, and every file already looks correct to the sweep: **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 //nas/frigate /media/frigate cifs credentials=/root/.smb,uid=1000,gid=1000,file_mode=0664,dir_mode=0775 0 0
@@ -399,7 +389,7 @@ Rockchip NPU and GPU usage come from `/sys/kernel/debug`, which the kernel makes
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. 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 key and the certificate have to be readable by the runtime user, which runs nginx, and that user has to be able to enter the folders above them. Frigate doesn't change ownership of mounted certificates, so give the key to the runtime user's group (gid 1000, your `PGID`, or the group in Docker's `user:`) with group read on the host. certbot keeps the key's group and group read on renewal, so this is a one-time step. 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: If you're debugging nginx, run the config check as the runtime user with stdout discarded:
+2 -2
View File
@@ -11,7 +11,7 @@ import NavPath from "@site/src/components/NavPath";
Frigate can restream your video feed as an RTSP feed for other applications such as Home Assistant to utilize it at `rtsp://<frigate_host>:8554/<camera_name>`. Port 8554 must be open. [This allows you to use a video feed for detection in Frigate and Home Assistant live view at the same time without having to make two separate connections to the camera](#reduce-connections-to-camera). The video feed is copied from the original video feed directly to avoid re-encoding. This feed does not include any annotation by Frigate. Frigate can restream your video feed as an RTSP feed for other applications such as Home Assistant to utilize it at `rtsp://<frigate_host>:8554/<camera_name>`. Port 8554 must be open. [This allows you to use a video feed for detection in Frigate and Home Assistant live view at the same time without having to make two separate connections to the camera](#reduce-connections-to-camera). The video feed is copied from the original video feed directly to avoid re-encoding. This feed does not include any annotation by Frigate.
Frigate uses [go2rtc](https://github.com/AlexxIT/go2rtc/tree/v1.10.0) to provide its restream and MSE/WebRTC capabilities. The go2rtc config is hosted at the `go2rtc` in the config, see [go2rtc docs](https://github.com/AlexxIT/go2rtc/tree/v1.10.0#configuration) for more advanced configurations and features. Frigate uses [go2rtc](https://github.com/AlexxIT/go2rtc/tree/v1.9.14) to provide its restream and MSE/WebRTC capabilities. The go2rtc config is hosted at the `go2rtc` in the config, see [go2rtc docs](https://github.com/AlexxIT/go2rtc/tree/v1.9.14#configuration) for more advanced configurations and features.
:::note :::note
@@ -240,7 +240,7 @@ Enabling arbitrary exec sources allows execution of arbitrary commands through g
## Advanced Restream Configurations ## Advanced Restream Configurations
The [exec](https://github.com/AlexxIT/go2rtc/tree/v1.10.0#source-exec) source in go2rtc can be used for custom ffmpeg commands and other applications. An example is below: The [exec](https://github.com/AlexxIT/go2rtc/tree/v1.9.14#source-exec) source in go2rtc can be used for custom ffmpeg commands and other applications. An example is below:
:::warning :::warning
+1 -1
View File
@@ -47,7 +47,7 @@ frigate:
Within the folder, the private key is expected to be named `privkey.pem` and the certificate is expected to be named `fullchain.pem`. Mounted certificates take precedence over the self signed pair in `/config/tls`. Within the folder, the private key is expected to be named `privkey.pem` and the certificate is expected to be named `fullchain.pem`. Mounted certificates take precedence over the self signed pair in `/config/tls`.
`privkey.pem` and `fullchain.pem` must be readable by the runtime user that runs NGINX, and that user must be able to enter the folders above them. Frigate doesn't change ownership of mounted certificates, so give the key to the runtime user's group (gid 1000, your `PGID`, or the group in Docker's `user:`) with group read on the host, for example `chgrp 1000 privkey.pem && chmod g+r privkey.pem`. certbot keeps the key's group and group read on renewal, so this is a one-time step. See [Running as a non-root user](/configuration/non_root). `privkey.pem` must be readable by the runtime user that runs NGINX. Frigate hands it over at startup when the mount is writable; on a `:ro` mount, make it readable by uid 1000 (or your `PUID`) yourself. See [Running as a non-root user](/configuration/non_root).
Note that certbot uses symlinks, and those can't be followed by the container unless it has access to the targets as well, so if using certbot you'll also have to mount the `archive` folder for your domain, e.g.: Note that certbot uses symlinks, and those can't be followed by the container unless it has access to the targets as well, so if using certbot you'll also have to mount the `archive` folder for your domain, e.g.:
-17
View File
@@ -112,20 +112,3 @@ This metric scales with how many detections per second Frigate runs and how expe
- **Tune stationary object behavior.** Objects that never settle into a stationary state are re-detected continuously. Raising `detect -> stationary -> interval` reduces how often detection runs on objects that are already parked. See [stationary objects](../configuration/stationary_objects). - **Tune stationary object behavior.** Objects that never settle into a stationary state are re-detected continuously. Raising `detect -> stationary -> interval` reduces how often detection runs on objects that are already parked. See [stationary objects](../configuration/stationary_objects).
Adding [more detector instances](#multiple-detector-instances) spreads this work across more CPU cores, but does not reduce the total CPU used. Adding [more detector instances](#multiple-detector-instances) spreads this work across more CPU cores, but does not reduce the total CPU used.
## Tracked object processing could not keep up {#tracked-object-processing-behind}
After detection, Frigate hands each camera's frames to a single tracked object processor in the main Frigate process. It handles zones, loitering, snapshots, and event and MQTT updates for all cameras. When the processor falls more than about a second behind, Frigate drops new frames instead of waiting for it. Frigate raises this notice in the UI's Notices pane when it drops at least 5% of a camera's frames for more than a minute.
This is different from "Detection could not keep up", which means the [object detector](#2-detector-selection-and-configuration) is too slow. Dropped frames mean the system itself is short on CPU or stalling.
The notice stays until you acknowledge or mute it, and is raised again only after drops stop and later start again. `/api/stats` reports each camera's current `dropped_pct`.
Detection, tracking, and recording continue while frames are dropped. Zone [inertia](../configuration/zones.md#zone-inertia) and [loitering time](../configuration/zones.md#zone-loitering) count fewer frames, so a fast object can miss a small zone and loitering triggers late. Snapshots are picked from fewer frames, and events, MQTT messages, and notifications are delayed until the processor catches up.
To reduce dropped frames:
- Check CPU use and any CPU limits on the container or VM (`cpus`, `cpuset`, or the cores assigned to a VM or LXC container). A rising `nr_throttled` in `/sys/fs/cgroup/cpu.stat` means a limit is throttling Frigate.
- Use a detect fps of 5, and no more than 10. See [choosing a detect frame rate](../frigate/camera_setup.md#choosing-a-detect-frame-rate).
- Lower the detect resolution. The snapshot saved when an object ends is encoded from the full detect frame.
- Keep `/media/frigate` on local storage, since the processor writes snapshots and thumbnails itself.
+1 -1
View File
@@ -222,7 +222,7 @@ go2rtc:
`/dev/dri/renderD128` is the usual render node; on a system with more than one GPU you may need `renderD129` (or higher), and the device must be passed into the container (e.g. `devices: - /dev/dri:/dev/dri` in Docker Compose). `/dev/dri/renderD128` is the usual render node; on a system with more than one GPU you may need `renderD129` (or higher), and the device must be passed into the container (e.g. `devices: - /dev/dri:/dev/dri` in Docker Compose).
If you use a **different hardware acceleration backend**, you will likely need to specify its device in the same way, using the option that matches that backend instead of `-vaapi_device`. See the [go2rtc FFmpeg source documentation](https://github.com/AlexxIT/go2rtc/tree/v1.10.0#source-ffmpeg) and the upstream report ([go2rtc issue #1984](https://github.com/AlexxIT/go2rtc/issues/1984)) for background and other examples. If you use a **different hardware acceleration backend**, you will likely need to specify its device in the same way, using the option that matches that backend instead of `-vaapi_device`. See the [go2rtc FFmpeg source documentation](https://github.com/AlexxIT/go2rtc/tree/v1.9.14#source-ffmpeg) and the upstream report ([go2rtc issue #1984](https://github.com/AlexxIT/go2rtc/issues/1984)) for background and other examples.
:::tip :::tip
+1 -1
View File
@@ -135,7 +135,7 @@ const sidebars: SidebarsConfig = {
{ {
type: "link", type: "link",
label: "Go2RTC Configuration Reference", label: "Go2RTC Configuration Reference",
href: "https://github.com/AlexxIT/go2rtc/tree/v1.10.0#configuration", href: "https://github.com/AlexxIT/go2rtc/tree/v1.9.14#configuration",
} as PropSidebarItemLink, } as PropSidebarItemLink,
], ],
}, },
+92 -17
View File
@@ -2064,12 +2064,6 @@ paths:
schema: schema:
type: number type: number
title: After title: After
- name: sort
in: query
required: false
schema:
type: string
title: Sort
responses: responses:
'200': '200':
description: Successful Response description: Successful Response
@@ -2317,8 +2311,8 @@ paths:
$ref: '#/components/schemas/HTTPValidationError' $ref: '#/components/schemas/HTTPValidationError'
security: security:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: any x-required-role: camera
description: '**Access:** Any authenticated user.' description: '**Access:** Authenticated user with access to the referenced camera.'
/review/{review_id}: /review/{review_id}:
get: get:
tags: tags:
@@ -2552,7 +2546,7 @@ paths:
- App - App
summary: Metrics summary: Metrics
description: |- description: |-
**Access:** Admin role required. **Access:** Any authenticated user.
Expose Prometheus metrics endpoint and update metrics with latest stats Expose Prometheus metrics endpoint and update metrics with latest stats
operationId: metrics_metrics_get operationId: metrics_metrics_get
@@ -2563,8 +2557,8 @@ paths:
application/json: application/json:
schema: {} schema: {}
security: security:
- frigateAdminAuth: [] - frigateUserAuth: []
x-required-role: admin x-required-role: any
/genai/models: /genai/models:
get: get:
tags: tags:
@@ -4614,6 +4608,14 @@ paths:
- type: 'null' - type: 'null'
default: 1 default: 1
title: Include Thumbnails title: Include Thumbnails
- name: favorites
in: query
required: false
schema:
anyOf:
- type: integer
- type: 'null'
title: Favorites
- name: min_score - name: min_score
in: query in: query
required: false required: false
@@ -5144,6 +5146,75 @@ paths:
security: security:
- frigateAdminAuth: [] - frigateAdminAuth: []
x-required-role: admin x-required-role: admin
/events/{event_id}/retain:
post:
tags:
- Events
summary: Set event retain indefinitely.
description: |-
**Access:** Admin role required.
Sets an event to retain indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
operationId: set_retain_events__event_id__retain_post
parameters:
- name: event_id
in: path
required: true
schema:
type: string
title: Event Id
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/GenericResponse'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
delete:
tags:
- Events
summary: Stop event from being retained indefinitely
description: |-
**Access:** Admin role required.
Stops an event from being retained indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
operationId: delete_retain_events__event_id__retain_delete
parameters:
- name: event_id
in: path
required: true
schema:
type: string
title: Event Id
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/GenericResponse'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
/events/{event_id}/plus: /events/{event_id}/plus:
post: post:
tags: tags:
@@ -6081,7 +6152,9 @@ paths:
in: path in: path
required: true required: true
schema: schema:
type: string anyOf:
- type: string
- type: 'null'
title: Camera Name title: Camera Name
- name: frame_time - name: frame_time
in: path in: path
@@ -6102,9 +6175,9 @@ paths:
schema: schema:
$ref: '#/components/schemas/HTTPValidationError' $ref: '#/components/schemas/HTTPValidationError'
security: security:
- frigateAdminAuth: [] - frigateUserAuth: []
x-required-role: admin x-required-role: camera
description: '**Access:** Admin role required.' description: '**Access:** Authenticated user with access to the referenced camera.'
/{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4: /{camera_name}/start/{start_ts}/end/{end_ts}/clip.mp4:
get: get:
tags: tags:
@@ -8382,6 +8455,9 @@ components:
has_snapshot: has_snapshot:
type: boolean type: boolean
title: Has Snapshot title: Has Snapshot
retain_indefinitely:
type: boolean
title: Retain Indefinitely
plus_id: plus_id:
anyOf: anyOf:
- type: string - type: string
@@ -8419,6 +8495,7 @@ components:
- thumbnail - thumbnail
- has_clip - has_clip
- has_snapshot - has_snapshot
- retain_indefinitely
- plus_id - plus_id
- model_hash - model_hash
- detector_type - detector_type
@@ -9553,8 +9630,6 @@ components:
title: Condition title: Condition
max_duration_minutes: max_duration_minutes:
type: integer type: integer
maximum: 1440.0
minimum: 1.0
title: Max Duration Minutes title: Max Duration Minutes
default: 60 default: 60
labels: labels:
+55 -91
View File
@@ -40,7 +40,6 @@ from frigate.api.defs.request.app_body import (
MediaSyncBody, MediaSyncBody,
) )
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.api.plus_util import plus_rate_limited_response
from frigate.config import FrigateConfig, GenAIConfig, GenAIProviderEnum from frigate.config import FrigateConfig, GenAIConfig, GenAIProviderEnum
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
@@ -55,7 +54,7 @@ from frigate.jobs.media_sync import (
start_media_sync_job, start_media_sync_job,
) )
from frigate.models import Event, Timeline from frigate.models import Event, Timeline
from frigate.plus import PlusKeyStatus, PlusRateLimitError, load_plus_model_info from frigate.plus import PlusKeyStatus, load_plus_model_info
from frigate.stats.prometheus import get_metrics, update_metrics from frigate.stats.prometheus import get_metrics, update_metrics
from frigate.types import JobStatusTypesEnum from frigate.types import JobStatusTypesEnum
from frigate.util.builtin import ( from frigate.util.builtin import (
@@ -65,7 +64,6 @@ from frigate.util.builtin import (
is_masked_camera_path, is_masked_camera_path,
load_labels, load_labels,
process_config_query_string, process_config_query_string,
scope_stats_for_non_admin,
split_config_key_path, split_config_key_path,
update_yaml_file_bulk, update_yaml_file_bulk,
) )
@@ -74,7 +72,7 @@ from frigate.util.config import (
find_config_file, find_config_file,
redact_credential, redact_credential,
) )
from frigate.util.env import candidate_env_vars, substitute_frigate_vars from frigate.util.env import substitute_frigate_vars
from frigate.util.live_streams import ( from frigate.util.live_streams import (
generated_transcode_streams, generated_transcode_streams,
sync_transcode_streams, sync_transcode_streams,
@@ -133,12 +131,37 @@ def stats(
): ):
stats_data = request.app.stats_emitter.get_latest_stats() stats_data = request.app.stats_emitter.get_latest_stats()
# Admins see the full snapshot
if request.headers.get("remote-role") == "admin": if request.headers.get("remote-role") == "admin":
return JSONResponse(content=stats_data) return JSONResponse(content=stats_data)
return JSONResponse( allowed_set = set(allowed_cameras)
content=scope_stats_for_non_admin(stats_data, set(allowed_cameras))
) # Shallow-copy so we don't mutate the cached stats history entry.
filtered = {**stats_data}
cameras = stats_data.get("cameras")
if cameras is not None:
filtered["cameras"] = {
name: data for name, data in cameras.items() if name in allowed_set
}
bandwidth = stats_data.get("bandwidth_usages")
if bandwidth is not None:
filtered["bandwidth_usages"] = {
name: data for name, data in bandwidth.items() if name in allowed_set
}
# cmdline can leak camera URLs/paths; strip but keep cpu/mem so
# client-side problem heuristics still work.
cpu_usages = stats_data.get("cpu_usages")
if cpu_usages is not None:
filtered["cpu_usages"] = {
pid: {k: v for k, v in usage.items() if k != "cmdline"}
for pid, usage in cpu_usages.items()
}
return JSONResponse(content=filtered)
@router.get("/stats/history", dependencies=[Depends(require_role(["admin"]))]) @router.get("/stats/history", dependencies=[Depends(require_role(["admin"]))])
@@ -149,7 +172,7 @@ def stats_history(request: Request, keys: str = None):
return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys)) return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys))
@router.get("/metrics", dependencies=[Depends(require_role(["admin"]))]) @router.get("/metrics", dependencies=[Depends(allow_any_authenticated())])
def metrics(request: Request): def metrics(request: Request):
"""Expose Prometheus metrics endpoint and update metrics with latest stats""" """Expose Prometheus metrics endpoint and update metrics with latest stats"""
# Retrieve the latest statistics and update the Prometheus metrics # Retrieve the latest statistics and update the Prometheus metrics
@@ -297,12 +320,10 @@ def config(request: Request):
is_admin = request.headers.get("remote-role") == "admin" is_admin = request.headers.get("remote-role") == "admin"
# hide environment_vars, the notification email and ffmpeg args (which # hide environment_vars and the notification email from non-admin users
# can carry auth headers) from non-admin users
if not is_admin: if not is_admin:
config.pop("environment_vars", None) config.pop("environment_vars", None)
redact_credential(config["notifications"], "email") redact_credential(config["notifications"], "email")
_drop_ffmpeg_args(config.get("ffmpeg", {}))
# redact mqtt credentials # redact mqtt credentials
redact_credential(config["mqtt"], "password") redact_credential(config["mqtt"], "password")
@@ -310,15 +331,11 @@ def config(request: Request):
# redact proxy secret # redact proxy secret
redact_credential(config["proxy"], "auth_secret") redact_credential(config["proxy"], "auth_secret")
# redact genai api keys; base_url and provider_options can carry proxy auth # redact genai api keys
for _genai_name, genai_cfg in config.get("genai", {}).items(): for _genai_name, genai_cfg in config.get("genai", {}).items():
if isinstance(genai_cfg, dict): if isinstance(genai_cfg, dict):
redact_credential(genai_cfg, "api_key") redact_credential(genai_cfg, "api_key")
if not is_admin:
genai_cfg.pop("base_url", None)
genai_cfg.pop("provider_options", None)
for camera_name, camera in request.app.frigate_config.cameras.items(): for camera_name, camera in request.app.frigate_config.cameras.items():
camera_dict = config["cameras"][camera_name] camera_dict = config["cameras"][camera_name]
@@ -336,21 +353,6 @@ def config(request: Request):
for cmd in camera_dict["ffmpeg_cmds"]: for cmd in camera_dict["ffmpeg_cmds"]:
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"])) cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
camera_dict["detect_resolution_source"] = camera.detect_resolution_source
# masking misses vendor-specific credentials in paths and args, and the
# non-admin UI never reads them
if not is_admin:
ffmpeg = camera_dict.get("ffmpeg", {})
_drop_ffmpeg_args(ffmpeg)
for input in ffmpeg.get("inputs", []):
input["path"] = ""
_drop_ffmpeg_args(input)
camera_dict["ffmpeg_cmds"] = []
camera_dict.pop("webui_url", None)
# ensure that zones are relative # ensure that zones are relative
for zone_name, zone in config_obj.cameras[camera_name].zones.items(): for zone_name, zone in config_obj.cameras[camera_name].zones.items():
camera_dict["zones"][zone_name]["color"] = zone.color camera_dict["zones"][zone_name]["color"] = zone.color
@@ -361,13 +363,11 @@ def config(request: Request):
# over the camera's actual base values (e.g. threshold=20). # over the camera's actual base values (e.g. threshold=20).
if camera.profiles: if camera.profiles:
for profile_name, profile_config in camera.profiles.items(): for profile_name, profile_config in camera.profiles.items():
profile_dict = profile_config.model_dump( camera_dict.setdefault("profiles", {})[profile_name] = (
profile_config.model_dump(
mode="json", warnings="none", exclude_unset=True mode="json", warnings="none", exclude_unset=True
) )
camera_dict.setdefault("profiles", {})[profile_name] = profile_dict )
if not is_admin:
redact_credential(profile_dict.get("notifications") or {}, "email")
# When a profile is active, the top-level camera sections contain # When a profile is active, the top-level camera sections contain
# profile-merged (effective) values. Include the original base # profile-merged (effective) values. Include the original base
@@ -409,15 +409,6 @@ def config(request: Request):
_redact_go2rtc_credentials(config["go2rtc"]) _redact_go2rtc_credentials(config["go2rtc"])
if not is_admin:
# go2rtc allows arbitrary extra keys, so non-admins get only what the
# UI reads: stream names, and webrtc, whose ice_servers credentials
# the browser needs
config["go2rtc"] = {
"streams": {name: [] for name in config["go2rtc"].get("streams", {})},
"webrtc": config["go2rtc"].get("webrtc", {}),
}
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()} config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
for index, model in enumerate(config_obj.models): for index, model in enumerate(config_obj.models):
@@ -444,11 +435,6 @@ def config(request: Request):
return JSONResponse(content=config) return JSONResponse(content=config)
def _drop_ffmpeg_args(ffmpeg: dict[str, Any]) -> None:
for key in ("global_args", "input_args", "output_args"):
ffmpeg.pop(key, None)
def _redact_go2rtc_credentials(go2rtc: dict[str, Any]) -> None: def _redact_go2rtc_credentials(go2rtc: dict[str, Any]) -> None:
"""Redact go2rtc secrets outside of stream URLs, in place.""" """Redact go2rtc secrets outside of stream URLs, in place."""
for section in ("rtsp", "api", "mqtt"): for section in ("rtsp", "api", "mqtt"):
@@ -591,18 +577,14 @@ def config_raw():
) )
def _go2rtc_config(raw_config: str) -> tuple[dict[str, Any], Any]: def _go2rtc_config(raw_config: str) -> dict[str, Any]:
"""Load the go2rtc section and environment_vars with the same loader Frigate """Load the go2rtc section with the same loader Frigate and go2rtc startup use.
and go2rtc startup use.
Raises ruamel.yaml.YAMLError when the config cannot be parsed. Raises ruamel.yaml.YAMLError when the config cannot be parsed.
""" """
loaded = ruamel.yaml.YAML().load(raw_config) loaded = ruamel.yaml.YAML().load(raw_config)
if not isinstance(loaded, dict): go2rtc = loaded.get("go2rtc") if isinstance(loaded, dict) else None
return {}, None return go2rtc if isinstance(go2rtc, dict) else {}
go2rtc = loaded.get("go2rtc")
return go2rtc if isinstance(go2rtc, dict) else {}, loaded.get("environment_vars")
def _restricted_go2rtc_response( def _restricted_go2rtc_response(
@@ -614,7 +596,7 @@ def _restricted_go2rtc_response(
otherwise load them from the saved config on the next restart. otherwise load them from the saved config on the next restart.
""" """
try: try:
new_go2rtc, new_env_vars = _go2rtc_config(new_raw_config) new_go2rtc = _go2rtc_config(new_raw_config)
except ruamel.yaml.YAMLError: except ruamel.yaml.YAMLError:
logger.warning("Rejected config change that could not be parsed") logger.warning("Rejected config change that could not be parsed")
return JSONResponse( return JSONResponse(
@@ -623,13 +605,13 @@ def _restricted_go2rtc_response(
) )
try: try:
old_go2rtc, _ = _go2rtc_config(old_raw_config) old_go2rtc = _go2rtc_config(old_raw_config)
except ruamel.yaml.YAMLError: except ruamel.yaml.YAMLError:
# with no readable saved config, every source is treated as new # with no readable saved config, every source is treated as new
old_go2rtc = {} old_go2rtc = {}
issues = find_restricted_go2rtc_stream_changes( issues = find_restricted_go2rtc_stream_changes(
old_go2rtc.get("streams"), new_go2rtc.get("streams"), new_env_vars old_go2rtc.get("streams"), new_go2rtc.get("streams")
) )
exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc) exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc)
if not issues and not exec_keys: if not issues and not exec_keys:
@@ -793,20 +775,16 @@ def config_save(save_option: str, body: Any = Body(media_type="text/plain")):
) )
def _restore_masked_camera_paths( def _restore_masked_camera_paths(config_data: dict, saved: dict) -> str | None:
config_data: dict, saved: dict, shown_env_vars: dict[str, str]
) -> str | None:
"""Substitute incoming masked camera paths with the saved ones. """Substitute incoming masked camera paths with the saved ones.
The /config response masks ffmpeg input credentials, so the settings UI The /config response masks ffmpeg input credentials, so the settings UI
sends the masked path back when sibling fields (e.g. hwaccel_args) are sends the masked path back when sibling fields (e.g. hwaccel_args) are
edited. Each masked path is matched to the saved input that masks to the edited. Each masked path is matched to the saved input that masks to the
same value, with roles breaking a tie, so deleting or reordering inputs same value, with roles breaking a tie, so deleting or reordering inputs
keeps each path's own credentials. Saved paths resolve with keeps each path's own credentials. The saved path is restored as written,
`shown_env_vars`, the block the running config and /config used. The saved keeping any {FRIGATE_*} placeholder. Mutates `config_data` in place and
path is restored as written, keeping any {FRIGATE_*} placeholder. Mutates returns an error message when a masked path has no single match.
`config_data` in place and returns an error message when a masked path has
no single match.
""" """
cameras = config_data.get("cameras") cameras = config_data.get("cameras")
if not isinstance(cameras, dict): if not isinstance(cameras, dict):
@@ -842,12 +820,10 @@ def _restore_masked_camera_paths(
path = input_obj.get("path") path = input_obj.get("path")
if not isinstance(path, str) or not is_masked_camera_path(path): if not isinstance(path, str) or not is_masked_camera_path(path):
continue continue
with candidate_env_vars(shown_env_vars):
candidates = [ candidates = [
inp inp
for inp in saved_inputs for inp in saved_inputs
if clean_camera_user_pass(_resolve_frigate_vars(inp["path"])) if clean_camera_user_pass(_resolve_frigate_vars(inp["path"])) == path
== path
] ]
if len({inp["path"] for inp in candidates}) > 1: if len({inp["path"] for inp in candidates}) > 1:
candidates = [ candidates = [
@@ -892,14 +868,14 @@ def _saved_config_from_memory(config: FrigateConfig) -> dict[str, Any]:
def _config_data_to_updates( def _config_data_to_updates(
config_data: dict, saved: dict[str, Any], running: FrigateConfig config_data: dict, saved: dict[str, Any]
) -> tuple[dict[str, Any], str | None]: ) -> tuple[dict[str, Any], str | None]:
"""Flatten a /config/set payload after restoring masked credentials. """Flatten a /config/set payload after restoring masked credentials.
`saved` is the config the masked values were taken from. Returns the flat `saved` is the config the masked values were taken from. Returns the flat
updates, or an error message when a masked value can't be restored. updates, or an error message when a masked value can't be restored.
""" """
error = _restore_masked_camera_paths(config_data, saved, running.environment_vars) error = _restore_masked_camera_paths(config_data, saved)
if error: if error:
return {}, error return {}, error
@@ -953,9 +929,7 @@ def _config_set_in_memory(request: Request, body: AppConfigSetBody) -> JSONRespo
updates = {} updates = {}
if body.config_data: if body.config_data:
updates, error = _config_data_to_updates( updates, error = _config_data_to_updates(
body.config_data, body.config_data, _saved_config_from_memory(request.app.frigate_config)
_saved_config_from_memory(request.app.frigate_config),
request.app.frigate_config,
) )
if error: if error:
return JSONResponse( return JSONResponse(
@@ -1136,7 +1110,6 @@ def config_set(request: Request, body: AppConfigSetBody):
updates, error = _config_data_to_updates( updates, error = _config_data_to_updates(
body.config_data, body.config_data,
saved_config if isinstance(saved_config, dict) else {}, saved_config if isinstance(saved_config, dict) else {},
request.app.frigate_config,
) )
if error: if error:
@@ -1681,10 +1654,7 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
status_code=400, status_code=400,
) )
try:
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models() models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
if not models["list"]: if not models["list"]:
return JSONResponse( return JSONResponse(
@@ -1724,17 +1694,11 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))]) @router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
async def validate_plus_key(request: Request): async def validate_plus_key(request: Request):
"""Validate the configured Frigate+ API key with the Frigate+ server.""" """Validate the configured Frigate+ API key with the Frigate+ server."""
plus_api = request.app.frigate_config.plus_api status = await request.app.frigate_config.plus_api.validate_key()
status = await plus_api.validate_key()
content: dict[str, Any] = {
"success": status == PlusKeyStatus.valid,
"status": status.value,
}
if status == PlusKeyStatus.rate_limited: return JSONResponse(
content["retry_after"] = plus_api.rate_limit_remaining() content={"success": status == PlusKeyStatus.valid, "status": status.value}
)
return JSONResponse(content=content)
@router.get( @router.get(
+18 -16
View File
@@ -81,11 +81,10 @@ def require_admin_by_default():
"/", "/",
"/version", "/version",
"/config/schema.json", "/config/schema.json",
# Admin endpoints that enforce require_role on the route
"/metrics",
"/stats/history",
# Authenticated user endpoints (allow_any_authenticated) # Authenticated user endpoints (allow_any_authenticated)
"/metrics",
"/stats", "/stats",
"/stats/history",
"/config", "/config",
"/vainfo", "/vainfo",
"/nvinfo", "/nvinfo",
@@ -581,9 +580,8 @@ def resolve_role(
(split by proxy_config.separator) and map to roles. (split by proxy_config.separator) and map to roles.
Admin matches short-circuit to admin. Admin matches short-circuit to admin.
- If no role_map is configured, treat the header as role names directly. - If no role_map is configured, treat the header as role names directly.
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'none'. 2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'viewer'.
The literal value 'none' means access should be denied. The literal value 'none' is a valid default and means access should be denied.
A role_map match whose mapped roles no longer exist in config_roles also resolves to 'none'.
Args: Args:
headers (dict): Incoming request headers (case-insensitive). headers (dict): Incoming request headers (case-insensitive).
@@ -596,11 +594,17 @@ def resolve_role(
default_role = proxy_config.default_role default_role = proxy_config.default_role
role_header = proxy_config.header_map.role role_header = proxy_config.header_map.role
# Role names match case-insensitively, as header values are lowercased. # Validate default_role against config; fallback to 'viewer' if invalid.
# "none" is the deny sentinel; an unknown or missing default also denies, # "none" is a sentinel meaning "deny access when no mapping matches"; it is
# since falling back to viewer would grant every camera. # reserved in AuthConfig.validate_roles so it is never a configured role.
roles_by_name = {r.lower(): r for r in config_roles} validated_default = (
validated_default = roles_by_name.get((default_role or "").lower(), "none") default_role
if default_role in config_roles or default_role == "none"
else "viewer"
)
if not config_roles:
# Edge case: no roles defined
validated_default = "none" if default_role == "none" else "viewer"
if not role_header: if not role_header:
logger.debug( logger.debug(
@@ -627,7 +631,7 @@ def resolve_role(
logger.debug("Parsed groups from role header: %s", groups) logger.debug("Parsed groups from role header: %s", groups)
matched_roles = { matched_roles = {
role_name.lower() role_name
for role_name, required_groups in proxy_config.header_map.role_map.items() for role_name, required_groups in proxy_config.header_map.role_map.items()
if any(group in groups for group in required_groups) if any(group in groups for group in required_groups)
} }
@@ -639,11 +643,9 @@ def resolve_role(
logger.debug("Resolved role (with role_map) to 'admin'.") logger.debug("Resolved role (with role_map) to 'admin'.")
return "admin" return "admin"
# A mapped role that was deleted or renamed denies rather than
# widening to the default role
if matched_roles: if matched_roles:
resolved = next( resolved = next(
(r for r in config_roles if r.lower() in matched_roles), "none" (r for r in config_roles if r in matched_roles), validated_default
) )
logger.debug("Resolved role (with role_map) to '%s'.", resolved) logger.debug("Resolved role (with role_map) to '%s'.", resolved)
return resolved return resolved
@@ -662,7 +664,7 @@ def resolve_role(
logger.debug("Parsed roles directly from header: %s", roles_from_header) logger.debug("Parsed roles directly from header: %s", roles_from_header)
resolved = next( resolved = next(
(r for r in config_roles if r.lower() in roles_from_header), (r for r in config_roles if r in roles_from_header),
validated_default, validated_default,
) )
if resolved == validated_default and roles_from_header: if resolved == validated_default and roles_from_header:
+8 -24
View File
@@ -6,7 +6,6 @@ import logging
import re import re
from importlib.util import find_spec from importlib.util import find_spec
from pathlib import Path from pathlib import Path
from typing import Any
from urllib.parse import quote_plus from urllib.parse import quote_plus
import httpx import httpx
@@ -83,23 +82,6 @@ def _is_valid_host(host: str) -> bool:
return False return False
def _clean_stream(request: Request, stream: dict[str, Any]) -> dict[str, Any]:
"""Mask producer urls for admins; others get only producer medias.
Producer and consumer urls and sources can carry credentials that masking
misses, and the non-admin UI only reads producer medias.
"""
producers = stream.get("producers") or []
if request.headers.get("remote-role") != "admin":
return {"producers": [{"medias": p.get("medias")} for p in producers]}
for producer in producers:
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
return stream
@router.get("/go2rtc/streams", dependencies=[Depends(allow_any_authenticated())]) @router.get("/go2rtc/streams", dependencies=[Depends(allow_any_authenticated())])
async def go2rtc_streams(request: Request): async def go2rtc_streams(request: Request):
try: try:
@@ -132,11 +114,10 @@ async def go2rtc_streams(request: Request):
if _get_stream_owner_cameras(request, name) & allowed_cameras if _get_stream_owner_cameras(request, name) & allowed_cameras
} }
return JSONResponse( for data in stream_data.values():
content={ for producer in data.get("producers") or []:
name: _clean_stream(request, data) for name, data in stream_data.items() producer["url"] = clean_camera_user_pass(producer.get("url", ""))
} return JSONResponse(content=stream_data)
)
@router.get( @router.get(
@@ -174,7 +155,10 @@ def go2rtc_camera_stream(request: Request, stream_name: str):
content=({"success": False, "message": "Error fetching stream data"}), content=({"success": False, "message": "Error fetching stream data"}),
status_code=500, status_code=500,
) )
return JSONResponse(content=_clean_stream(request, r.json())) stream_data = r.json()
for producer in stream_data.get("producers", []):
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
return JSONResponse(content=stream_data)
@router.put( @router.put(
+4 -22
View File
@@ -6,7 +6,6 @@ import json
import logging import logging
import operator import operator
import time import time
import uuid
from datetime import datetime from datetime import datetime
from functools import reduce from functools import reduce
from typing import Any, Literal from typing import Any, Literal
@@ -15,7 +14,7 @@ import cv2
import numpy as np import numpy as np
from fastapi import APIRouter, Body, Depends, HTTPException, Request from fastapi import APIRouter, Body, Depends, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field from pydantic import BaseModel
from frigate.api.auth import ( from frigate.api.auth import (
allow_any_authenticated, allow_any_authenticated,
@@ -57,7 +56,6 @@ from frigate.genai.utils import (
) )
from frigate.jobs.export import ExportQueueFullError, start_export_job from frigate.jobs.export import ExportQueueFullError, start_export_job
from frigate.jobs.vlm_watch import ( from frigate.jobs.vlm_watch import (
MAX_WATCH_MINUTES,
VLMWatchJob, VLMWatchJob,
get_vlm_watch_job, get_vlm_watch_job,
start_vlm_watch_job, start_vlm_watch_job,
@@ -90,7 +88,7 @@ class VLMMonitorRequest(BaseModel):
camera: str camera: str
condition: str condition: str
max_duration_minutes: int = Field(default=60, ge=1, le=MAX_WATCH_MINUTES) max_duration_minutes: int = 60
labels: list[str] = [] labels: list[str] = []
zones: list[str] = [] zones: list[str] = []
@@ -1032,17 +1030,12 @@ async def _execute_start_camera_watch(
camera = arguments.get("camera", "").strip() camera = arguments.get("camera", "").strip()
condition = arguments.get("condition", "").strip() condition = arguments.get("condition", "").strip()
max_duration_minutes = int(arguments.get("max_duration_minutes", 60)) max_duration_minutes = int(arguments.get("max_duration_minutes", 60))
max_duration_minutes = max(1, min(MAX_WATCH_MINUTES, max_duration_minutes))
labels = arguments.get("labels") or [] labels = arguments.get("labels") or []
zones = arguments.get("zones") or [] zones = arguments.get("zones") or []
if not camera or not condition: if not camera or not condition:
return {"error": "camera and condition are required."} return {"error": "camera and condition are required."}
for value in (labels, zones):
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
return {"error": "labels and zones must be lists of strings."}
config = request.app.frigate_config config = request.app.frigate_config
if camera not in config.cameras: if camera not in config.cameras:
return {"error": f"Camera '{camera}' not found."} return {"error": f"Camera '{camera}' not found."}
@@ -1281,14 +1274,6 @@ def _pending_tool_calls_from_tail(
return parse_tool_calls_from_message(tail) return parse_tool_calls_from_message(tail)
def _with_server_ids(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Give each model tool call a unique id.
Approvals are keyed by id, and some providers reuse ids across calls.
"""
return [{**tc, "id": uuid.uuid4().hex[:9]} for tc in tool_calls]
def _tool_calls_awaiting_approval( def _tool_calls_awaiting_approval(
pending_tool_calls: list[dict[str, Any]], pending_tool_calls: list[dict[str, Any]],
body: ChatCompletionRequest, body: ChatCompletionRequest,
@@ -1614,7 +1599,6 @@ async def chat_completion(
return return
requested = msg.get("tool_calls") requested = msg.get("tool_calls")
if requested: if requested:
requested = _with_server_ids(requested)
stream_iterations += 1 stream_iterations += 1
conversation.append( conversation.append(
build_assistant_message_for_conversation( build_assistant_message_for_conversation(
@@ -1700,15 +1684,13 @@ async def chat_completion(
status_code=500, status_code=500,
) )
pending_tool_calls = response.get("tool_calls")
if pending_tool_calls:
pending_tool_calls = _with_server_ids(pending_tool_calls)
conversation.append( conversation.append(
build_assistant_message_for_conversation( build_assistant_message_for_conversation(
response.get("content"), pending_tool_calls response.get("content"), response.get("tool_calls")
) )
) )
pending_tool_calls = response.get("tool_calls")
if not pending_tool_calls: if not pending_tool_calls:
logger.debug( logger.debug(
f"Chat completion finished with final answer (iterations: {tool_iterations})" f"Chat completion finished with final answer (iterations: {tool_iterations})"
+8 -13
View File
@@ -216,12 +216,8 @@ def train_face(request: Request, name: str, body: dict = None):
status_code=404, status_code=404,
) )
attributes = (event.data or {}).get("attributes") or [] snapshot = get_event_snapshot(event)
snapshot = get_event_snapshot(event) if attributes else None face_box = event.data["attributes"][0]["box"]
success = False
if snapshot is not None:
face_box = attributes[0]["box"]
detect_config: DetectConfig = request.app.frigate_config.cameras[ detect_config: DetectConfig = request.app.frigate_config.cameras[
event.camera event.camera
].detect ].detect
@@ -232,12 +228,14 @@ def train_face(request: Request, name: str, body: dict = None):
x2 = x1 + int(face_box[2] * detect_config.width) - 4 x2 = x1 + int(face_box[2] * detect_config.width) - 4
y2 = y1 + int(face_box[3] * detect_config.height) - 4 y2 = y1 + int(face_box[3] * detect_config.height) - 4
face = snapshot[y1:y2, x1:x2] face = snapshot[y1:y2, x1:x2]
success = True
if face.size > 0: if face.size > 0:
try: try:
success = cv2.imwrite(os.path.join(new_file_folder, new_name), face) cv2.imwrite(os.path.join(new_file_folder, new_name), face)
except cv2.error: success = True
logger.exception("Failed to save face image for %s", event_id) except Exception:
pass
if not success: if not success:
return JSONResponse( return JSONResponse(
@@ -1275,10 +1273,7 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
if camera_name in request.app.frigate_config.cameras if camera_name in request.app.frigate_config.cameras
} }
async with example_collection_lock: collect_state_classification_examples(model_name, cameras_normalized)
await asyncio.to_thread(
collect_state_classification_examples, model_name, cameras_normalized
)
return JSONResponse( return JSONResponse(
content={"success": True, "message": "Example generation completed"}, content={"success": True, "message": "Example generation completed"},
-3
View File
@@ -41,9 +41,6 @@ def swap_runtime_config(app: FastAPI, config: FrigateConfig) -> None:
""" """
app.frigate_config = config app.frigate_config = config
if app.replay_manager is not None:
app.replay_manager.update_config(config)
if app.config_holder is not None: if app.config_holder is not None:
app.config_holder.set(config) app.config_holder.set(config)
@@ -29,6 +29,7 @@ class EventsQueryParams(BaseModel):
), ),
deprecated=True, deprecated=True,
) )
favorites: int | None = None
min_score: float | None = None min_score: float | None = None
max_score: float | None = None max_score: float | None = None
min_speed: float | None = None min_speed: float | None = None
@@ -13,7 +13,6 @@ class ReviewQueryParams(BaseModel):
severity: SeverityEnum | SkipJsonSchema[None] = None severity: SeverityEnum | SkipJsonSchema[None] = None
before: float | SkipJsonSchema[None] = None before: float | SkipJsonSchema[None] = None
after: float | SkipJsonSchema[None] = None after: float | SkipJsonSchema[None] = None
sort: str | SkipJsonSchema[None] = None
class ReviewSummaryQueryParams(BaseModel): class ReviewSummaryQueryParams(BaseModel):
@@ -15,6 +15,7 @@ class EventResponse(BaseModel):
thumbnail: str | None thumbnail: str | None
has_clip: bool has_clip: bool
has_snapshot: bool has_snapshot: bool
retain_indefinitely: bool
plus_id: str | None plus_id: str | None
model_hash: str | None model_hash: str | None
detector_type: str | None detector_type: str | None
+68 -30
View File
@@ -53,13 +53,11 @@ from frigate.api.defs.response.event_response import (
) )
from frigate.api.defs.response.generic_response import GenericResponse from frigate.api.defs.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.api.plus_util import plus_rate_limited_response
from frigate.comms.event_metadata_updater import EventMetadataTypeEnum from frigate.comms.event_metadata_updater import EventMetadataTypeEnum
from frigate.config.classification import ObjectClassificationType from frigate.config.classification import ObjectClassificationType
from frigate.const import CLIPS_DIR from frigate.const import CLIPS_DIR
from frigate.embeddings import EmbeddingsContext from frigate.embeddings import EmbeddingsContext
from frigate.models import Event, ReviewSegment, Timeline, Trigger from frigate.models import Event, ReviewSegment, Timeline, Trigger
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObject from frigate.track.object_processing import TrackedObject
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
from frigate.util.path import get_trigger_thumbnail_path, safe_join from frigate.util.path import get_trigger_thumbnail_path, safe_join
@@ -69,9 +67,6 @@ logger = logging.getLogger(__name__)
router = APIRouter(tags=[Tags.events]) router = APIRouter(tags=[Tags.events])
# event.data key holding a Frigate+ image id until its annotation is uploaded
PLUS_PENDING_ID_KEY = "plus_pending_id"
def _build_attribute_filter_clause(attributes: str): def _build_attribute_filter_clause(attributes: str):
filtered_attributes = [ filtered_attributes = [
@@ -142,6 +137,7 @@ def events(
has_snapshot = params.has_snapshot has_snapshot = params.has_snapshot
in_progress = params.in_progress in_progress = params.in_progress
include_thumbnails = params.include_thumbnails include_thumbnails = params.include_thumbnails
favorites = params.favorites
min_score = params.min_score min_score = params.min_score
max_score = params.max_score max_score = params.max_score
min_speed = params.min_speed min_speed = params.min_speed
@@ -166,6 +162,7 @@ def events(
Event.has_clip, Event.has_clip,
Event.has_snapshot, Event.has_snapshot,
Event.plus_id, Event.plus_id,
Event.retain_indefinitely,
Event.sub_label, Event.sub_label,
Event.top_score, Event.top_score,
Event.false_positive, Event.false_positive,
@@ -310,6 +307,9 @@ def events(
if include_thumbnails: if include_thumbnails:
selected_columns.append(Event.thumbnail) selected_columns.append(Event.thumbnail)
if favorites:
clauses.append(Event.retain_indefinitely == favorites)
if max_score is not None: if max_score is not None:
clauses.append(Event.data["score"] <= max_score) clauses.append(Event.data["score"] <= max_score)
@@ -410,6 +410,7 @@ def events_explore(
Event.has_clip, Event.has_clip,
Event.has_snapshot, Event.has_snapshot,
Event.plus_id, Event.plus_id,
Event.retain_indefinitely,
Event.top_score, Event.top_score,
Event.false_positive, Event.false_positive,
Event.box, Event.box,
@@ -450,6 +451,7 @@ def events_explore(
"has_clip": event.has_clip, "has_clip": event.has_clip,
"has_snapshot": event.has_snapshot, "has_snapshot": event.has_snapshot,
"plus_id": event.plus_id, "plus_id": event.plus_id,
"retain_indefinitely": event.retain_indefinitely,
"sub_label": event.sub_label, "sub_label": event.sub_label,
"top_score": event.top_score, "top_score": event.top_score,
"false_positive": event.false_positive, "false_positive": event.false_positive,
@@ -1024,6 +1026,34 @@ async def event(event_id: str, request: Request):
return JSONResponse(content="Event not found", status_code=404) return JSONResponse(content="Event not found", status_code=404)
@router.post(
"/events/{event_id}/retain",
response_model=GenericResponse,
dependencies=[Depends(require_role(["admin"]))],
summary="Set event retain indefinitely.",
description="""Sets an event to retain indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
""",
)
def set_retain(event_id: str):
try:
event = Event.get(Event.id == event_id)
except DoesNotExist:
return JSONResponse(
content=({"success": False, "message": "Event " + event_id + " not found"}),
status_code=404,
)
event.retain_indefinitely = True
event.save()
return JSONResponse(
content=({"success": True, "message": "Event " + event_id + " retained"}),
status_code=200,
)
@router.post( @router.post(
"/events/{event_id}/plus", "/events/{event_id}/plus",
response_model=EventUploadPlusResponse, response_model=EventUploadPlusResponse,
@@ -1082,21 +1112,13 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
content=({"success": False, "message": message}), status_code=400 content=({"success": False, "message": message}), status_code=400
) )
# an image uploaded by an earlier attempt whose annotation failed, so a
# retry finishes that submission instead of uploading the image again
plus_id = event.data.get(PLUS_PENDING_ID_KEY)
if plus_id is None:
try: try:
image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True) image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True)
except Exception: except Exception:
logger.error(f"Unable to load clean snapshot for event: {event.id}") logger.error(f"Unable to load clean snapshot for event: {event.id}")
return JSONResponse( return JSONResponse(
content=( content=(
{ {"success": False, "message": "Unable to load clean snapshot for event"}
"success": False,
"message": "Unable to load clean snapshot for event",
}
), ),
status_code=400, status_code=400,
) )
@@ -1117,8 +1139,6 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
plus_id = await asyncio.to_thread( plus_id = await asyncio.to_thread(
request.app.frigate_config.plus_api.upload_image, image, event.camera request.app.frigate_config.plus_api.upload_image, image, event.camera
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except Exception as ex: except Exception as ex:
logger.exception(ex) logger.exception(ex)
return JSONResponse( return JSONResponse(
@@ -1126,10 +1146,8 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
status_code=400, status_code=400,
) )
if include_annotation is not None: # store image id in the database
# the image isn't marked submitted until its annotation is, or a event.plus_id = plus_id
# failed annotation could never be retried
event.data[PLUS_PENDING_ID_KEY] = plus_id
event.save() event.save()
if include_annotation is not None: if include_annotation is not None:
@@ -1138,12 +1156,10 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
try: try:
await asyncio.to_thread( await asyncio.to_thread(
request.app.frigate_config.plus_api.add_annotation, request.app.frigate_config.plus_api.add_annotation,
plus_id, event.plus_id,
box, box,
event.label, event.label,
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError: except ValueError:
message = "Error uploading annotation, unsupported label provided." message = "Error uploading annotation, unsupported label provided."
logger.error(message) logger.error(message)
@@ -1158,11 +1174,6 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
status_code=400, status_code=400,
) )
# store image id in the database
event.plus_id = plus_id
event.data.pop(PLUS_PENDING_ID_KEY, None)
event.save()
return JSONResponse( return JSONResponse(
content=({"success": True, "plus_id": plus_id}), status_code=200 content=({"success": True, "plus_id": plus_id}), status_code=200
) )
@@ -1245,8 +1256,6 @@ async def false_positive(request: Request, event_id: str):
event.model_type, event.model_type,
event.detector_type, event.detector_type,
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError: except ValueError:
message = "Error uploading false positive, unsupported label provided." message = "Error uploading false positive, unsupported label provided."
logger.error(message) logger.error(message)
@@ -1269,6 +1278,35 @@ async def false_positive(request: Request, event_id: str):
) )
@router.delete(
"/events/{event_id}/retain",
response_model=GenericResponse,
dependencies=[Depends(require_role(["admin"]))],
summary="Stop event from being retained indefinitely",
description="""Stops an event from being retained indefinitely.
Returns a success message or an error if the event is not found.
NOTE: This is a legacy endpoint and is not supported in the frontend.
""",
)
async def delete_retain(event_id: str, request: Request):
try:
event = Event.get(Event.id == event_id)
await require_camera_access(event.camera, request=request)
except DoesNotExist:
return JSONResponse(
content=({"success": False, "message": "Event " + event_id + " not found"}),
status_code=404,
)
event.retain_indefinitely = False
event.save()
return JSONResponse(
content=({"success": True, "message": "Event " + event_id + " un-retained"}),
status_code=200,
)
@router.post( @router.post(
"/events/{event_id}/sub_label", "/events/{event_id}/sub_label",
response_model=GenericResponse, response_model=GenericResponse,
+1 -1
View File
@@ -88,7 +88,7 @@ def create_fastapi_app(
logger.info("FastAPI started") logger.info("FastAPI started")
asyncio.create_task( asyncio.create_task(
debug_replay_auto_stop_watchdog( debug_replay_auto_stop_watchdog(
replay_manager, lambda: app.frigate_config, config_publisher replay_manager, frigate_config, config_publisher
) )
) )
yield yield
+6 -18
View File
@@ -36,7 +36,6 @@ from frigate.api.defs.query.media_query_parameters import (
MediaMjpegFeedQueryParams, MediaMjpegFeedQueryParams,
) )
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.api.plus_util import plus_rate_limited_response
from frigate.camera.state import CameraState from frigate.camera.state import CameraState
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.config.camera.snapshots import SnapshotsConfig from frigate.config.camera.snapshots import SnapshotsConfig
@@ -48,11 +47,7 @@ from frigate.const import (
STREAM_TYPE_SUB, STREAM_TYPE_SUB,
) )
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
from frigate.output.preview import ( from frigate.output.preview import get_most_recent_preview_frame
get_most_recent_preview_frame,
is_camera_preview_frame,
)
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObjectProcessor from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.ffmpeg import terminate_ffmpeg_stream from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.file import ( from frigate.util.file import (
@@ -61,11 +56,7 @@ from frigate.util.file import (
get_event_thumbnail_bytes, get_event_thumbnail_bytes,
load_event_snapshot_image, load_event_snapshot_image,
) )
from frigate.util.image import ( from frigate.util.image import get_image_from_recording, get_image_quality_params
get_image_from_recording,
get_image_quality_params,
read_image,
)
from frigate.util.object import create_empty_regions_grid from frigate.util.object import create_empty_regions_grid
from frigate.util.recording_coverage import ( from frigate.util.recording_coverage import (
build_spans, build_spans,
@@ -263,7 +254,7 @@ async def latest_frame(
if preview_path: if preview_path:
logger.debug(f"Using most recent preview frame for {camera_name}") logger.debug(f"Using most recent preview frame for {camera_name}")
frame = read_image(preview_path, cv2.IMREAD_UNCHANGED) frame = cv2.imread(preview_path, cv2.IMREAD_UNCHANGED)
if frame is not None: if frame is not None:
is_offline = True is_offline = True
@@ -440,7 +431,7 @@ async def get_snapshot_from_recording(
@router.post( @router.post(
"/{camera_name}/plus/{frame_time}", dependencies=[Depends(require_role(["admin"]))] "/{camera_name}/plus/{frame_time}", dependencies=[Depends(require_camera_access)]
) )
async def submit_recording_snapshot_to_plus( async def submit_recording_snapshot_to_plus(
request: Request, camera_name: str, frame_time: str request: Request, camera_name: str, frame_time: str
@@ -485,12 +476,9 @@ async def submit_recording_snapshot_to_plus(
) )
nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR) nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
try:
await asyncio.to_thread( await asyncio.to_thread(
request.app.frigate_config.plus_api.upload_image, nd, camera_name request.app.frigate_config.plus_api.upload_image, nd, camera_name
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
return JSONResponse( return JSONResponse(
content={ content={
@@ -1618,7 +1606,7 @@ async def preview_gif(
camera_files = [ camera_files = [
entry.name entry.name
for entry in os.scandir(preview_dir) for entry in os.scandir(preview_dir)
if is_camera_preview_frame(entry.name, camera_name) if entry.name.startswith(file_start)
] ]
camera_files.sort() camera_files.sort()
@@ -1809,7 +1797,7 @@ async def preview_mp4(
camera_files = [ camera_files = [
entry.name entry.name
for entry in os.scandir(preview_dir) for entry in os.scandir(preview_dir)
if is_camera_preview_frame(entry.name, camera_name) if entry.name.startswith(file_start)
] ]
camera_files.sort() camera_files.sort()
+4 -8
View File
@@ -20,7 +20,7 @@ from urllib.parse import unquote
from peewee import DoesNotExist, Field from peewee import DoesNotExist, Field
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR, EXPORT_DIR, SUB_CACHE_TAG from frigate.const import CLIPS_DIR, EXPORT_DIR
from frigate.models import Export, User from frigate.models import Export, User
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -137,12 +137,11 @@ def _resolve_recording(
# /recordings/{date} → neutral # /recordings/{date} → neutral
# /recordings/{date}/{hour} → multi-camera listing # /recordings/{date}/{hour} → multi-camera listing
# /recordings/{date}/{hour}/{cam}/... → camera # /recordings/{date}/{hour}/{cam}/... → camera
# /recordings/{date}/{hour}/{cam}@sub/... → camera (sub stream)
if len(parts) <= 2: if len(parts) <= 2:
return MediaAuthResolution.LISTING_NEUTRAL, None return MediaAuthResolution.LISTING_NEUTRAL, None
if len(parts) == 3: if len(parts) == 3:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[3].removesuffix(SUB_CACHE_TAG) return MediaAuthResolution.CAMERA, parts[3]
def _resolve_clip( def _resolve_clip(
@@ -151,7 +150,6 @@ def _resolve_clip(
# /clips → multi-camera listing # /clips → multi-camera listing
# /clips/thumbs/{cam}/... → camera # /clips/thumbs/{cam}/... → camera
# /clips/previews/{cam}/... → camera # /clips/previews/{cam}/... → camera
# /clips/triggers/{cam}/... → camera
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed) # /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
# /clips/export/{export_id}.{ext} → camera (DB lookup) # /clips/export/{export_id}.{ext} → camera (DB lookup)
# /clips/faces/... → admin-only # /clips/faces/... → admin-only
@@ -165,7 +163,7 @@ def _resolve_clip(
second = parts[1] second = parts[1]
if second in ("thumbs", "previews", "triggers"): if second in ("thumbs", "previews"):
if len(parts) == 2: if len(parts) == 2:
return MediaAuthResolution.LISTING_MULTI_CAMERA, None return MediaAuthResolution.LISTING_MULTI_CAMERA, None
return MediaAuthResolution.CAMERA, parts[2] return MediaAuthResolution.CAMERA, parts[2]
@@ -313,9 +311,6 @@ def deny_response_for_media_uri(
if not role or role == "admin": if not role or role == "admin":
return None return None
if resolution == MediaAuthResolution.ADMIN_ONLY:
return 403
if not is_role_restricted(role, frigate_config): if not is_role_restricted(role, frigate_config):
return None return None
@@ -324,6 +319,7 @@ def deny_response_for_media_uri(
if resolution in ( if resolution in (
MediaAuthResolution.LISTING_MULTI_CAMERA, MediaAuthResolution.LISTING_MULTI_CAMERA,
MediaAuthResolution.ADMIN_ONLY,
MediaAuthResolution.UNRESOLVED_MEDIA, MediaAuthResolution.UNRESOLVED_MEDIA,
): ):
return 403 return 403
-31
View File
@@ -1,31 +0,0 @@
"""Shared responses for endpoints that call Frigate+."""
from fastapi.responses import JSONResponse
from frigate.plus import PlusRateLimitError
def plus_rate_limited_response(err: PlusRateLimitError) -> JSONResponse:
"""Tell the client Frigate+ is rate limiting requests and how long to wait.
Args:
err: The rate limit raised by the Frigate+ client
Returns:
A 429 response with the wait in retry_after (and the Retry-After
header) when Frigate+ provided one
"""
headers = None
if err.retry_after is not None:
headers = {"Retry-After": str(err.retry_after)}
return JSONResponse(
content={
"success": False,
"message": "Frigate+ is rate limiting requests, try again later",
"retry_after": err.retry_after,
},
status_code=429,
headers=headers,
)
+1 -2
View File
@@ -22,7 +22,6 @@ from frigate.api.defs.response.preview_response import (
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
from frigate.models import Previews from frigate.models import Previews
from frigate.output.preview import is_camera_preview_frame
from frigate.util.time import get_normalized_tz_name from frigate.util.time import get_normalized_tz_name
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -188,7 +187,7 @@ def get_preview_frames_from_cache(camera_name: str, start_ts: float, end_ts: flo
left = bisect.bisect_left(files, start_file) left = bisect.bisect_left(files, start_file)
right = bisect.bisect_right(files, end_file) right = bisect.bisect_right(files, end_file)
selected_previews = [ selected_previews = [
file for file in files[left:right] if is_camera_preview_frame(file, camera_name) file for file in files[left:right] if file.startswith(file_start)
] ]
return JSONResponse( return JSONResponse(
+9 -15
View File
@@ -169,13 +169,13 @@ async def review(
elif reviewed == 1: elif reviewed == 1:
review_query = review_query.where(UserReviewStatus.has_been_reviewed == True) review_query = review_query.where(UserReviewStatus.has_been_reviewed == True)
if params.sort == "date_asc":
order_by = ReviewSegment.start_time.asc()
else:
order_by = ReviewSegment.start_time.desc()
# Apply ordering and limit # Apply ordering and limit
review_query = review_query.order_by(order_by).limit(limit).dicts().iterator() review_query = (
review_query.order_by(ReviewSegment.start_time.desc())
.limit(limit)
.dicts()
.iterator()
)
return JSONResponse(content=[r for r in review_query]) return JSONResponse(content=[r for r in review_query])
@@ -713,18 +713,12 @@ def motion_activity(
response_model=ReviewSegmentResponse, response_model=ReviewSegmentResponse,
dependencies=[Depends(allow_any_authenticated())], dependencies=[Depends(allow_any_authenticated())],
) )
async def get_review_from_event( async def get_review_from_event(request: Request, event_id: str):
event_id: str,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
):
try: try:
review = ReviewSegment.get( review = ReviewSegment.get(
(ReviewSegment.camera << allowed_cameras) ReviewSegment.data["detections"].cast("text") % f'*"{event_id}"*'
& (
fn.instr(ReviewSegment.data["detections"].cast("text"), f'"{event_id}"')
> 0
)
) )
await require_camera_access(review.camera, request=request)
return JSONResponse(model_to_dict(review)) return JSONResponse(model_to_dict(review))
except DoesNotExist: except DoesNotExist:
return JSONResponse( return JSONResponse(
+12 -30
View File
@@ -4,7 +4,6 @@ import multiprocessing as mp
import os import os
import secrets import secrets
import shutil import shutil
import sys
from collections.abc import Callable from collections.abc import Callable
from multiprocessing import Queue from multiprocessing import Queue
from multiprocessing.managers import DictProxy, SyncManager from multiprocessing.managers import DictProxy, SyncManager
@@ -92,7 +91,7 @@ from frigate.timeline import TimelineProcessor
from frigate.track.object_processing import TrackedObjectProcessor from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.builtin import empty_and_close_queue from frigate.util.builtin import empty_and_close_queue
from frigate.util.image import UntrackedSharedMemory from frigate.util.image import UntrackedSharedMemory
from frigate.util.ownership import chown_to_runtime, find_unwritable_database_path from frigate.util.ownership import chown_to_runtime
from frigate.util.process import FrigateProcess from frigate.util.process import FrigateProcess
from frigate.util.runtime_deps import RuntimeDependencyError from frigate.util.runtime_deps import RuntimeDependencyError
from frigate.util.services import set_file_limit from frigate.util.services import set_file_limit
@@ -198,32 +197,8 @@ class FrigateApp:
except PermissionError: except PermissionError:
logger.error("Unable to write to /config to save DB state") logger.error("Unable to write to /config to save DB state")
def exit_if_unwritable(paths: tuple[str, ...]) -> None:
unwritable = find_unwritable_database_path(paths)
if unwritable is None:
return
logger.error(
"Frigate is running as uid %s, gid %s and can't write to %s. Make "
"sure it exists and is owned by that user, see "
"https://docs.frigate.video/configuration/non_root#custom-database-location",
os.getuid(),
os.getgid(),
unwritable,
)
sys.exit(1)
db_path = self.config.database.path
backup_path = db_path.replace("frigate.db", "backup.db")
db_files = (db_path, f"{db_path}-wal", f"{db_path}-shm", backup_path)
# the ownership sweep covers /config and /media/frigate only, so a
# database kept elsewhere can still be owned by root after upgrading
exit_if_unwritable(db_files[:3])
# Migrate DB schema # Migrate DB schema
migrate_db = SqliteDatabase(db_path) migrate_db = SqliteDatabase(self.config.database.path)
# Run migrations # Run migrations
del logging.getLogger("peewee_migrate").handlers[:] del logging.getLogger("peewee_migrate").handlers[:]
@@ -231,8 +206,10 @@ class FrigateApp:
if len(router.diff) > 0: if len(router.diff) > 0:
logger.info("Making backup of DB before migrations...") logger.info("Making backup of DB before migrations...")
exit_if_unwritable((backup_path,)) shutil.copyfile(
shutil.copyfile(db_path, backup_path) self.config.database.path,
self.config.database.path.replace("frigate.db", "backup.db"),
)
router.run() router.run()
@@ -258,7 +235,12 @@ class FrigateApp:
# a root frigate service creates these as root; wal and shm recreated # a root frigate service creates these as root; wal and shm recreated
# later in the run are realigned by the per-boot /config sweep # later in the run are realigned by the per-boot /config sweep
for db_file in db_files: 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): if os.path.exists(db_file):
chown_to_runtime(db_file) chown_to_runtime(db_file)
-2
View File
@@ -11,7 +11,6 @@ class CameraMetrics:
detection_frame: ValueProxy[float] detection_frame: ValueProxy[float]
process_fps: ValueProxy[float] process_fps: ValueProxy[float]
skipped_fps: ValueProxy[float] skipped_fps: ValueProxy[float]
dropped_fps: ValueProxy[float]
read_start: ValueProxy[float] read_start: ValueProxy[float]
audio_rms: ValueProxy[float] audio_rms: ValueProxy[float]
audio_dBFS: ValueProxy[float] audio_dBFS: ValueProxy[float]
@@ -30,7 +29,6 @@ class CameraMetrics:
self.detection_frame = manager.Value("d", 0) self.detection_frame = manager.Value("d", 0)
self.process_fps = manager.Value("d", 0) self.process_fps = manager.Value("d", 0)
self.skipped_fps = manager.Value("d", 0) self.skipped_fps = manager.Value("d", 0)
self.dropped_fps = manager.Value("d", 0)
self.read_start = manager.Value("d", 0) self.read_start = manager.Value("d", 0)
self.audio_rms = manager.Value("d", 0) self.audio_rms = manager.Value("d", 0)
self.audio_dBFS = manager.Value("d", 0) self.audio_dBFS = manager.Value("d", 0)
+1 -2
View File
@@ -24,7 +24,6 @@ from frigate.util.image import (
draw_timestamp, draw_timestamp,
is_better_thumbnail, is_better_thumbnail,
is_label_printable, is_label_printable,
write_image,
) )
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -648,7 +647,7 @@ class CameraState:
thumb = cv2.resize(img_frame, dsize=(width, 175), interpolation=cv2.INTER_AREA) thumb = cv2.resize(img_frame, dsize=(width, 175), interpolation=cv2.INTER_AREA)
thumb_path = os.path.join(THUMB_DIR, self.name) thumb_path = os.path.join(THUMB_DIR, self.name)
os.makedirs(thumb_path, exist_ok=True) os.makedirs(thumb_path, exist_ok=True)
write_image(os.path.join(thumb_path, f"{event_id}.webp"), thumb) cv2.imwrite(os.path.join(thumb_path, f"{event_id}.webp"), thumb)
def shutdown(self) -> None: def shutdown(self) -> None:
for obj in self.tracked_objects.values(): for obj in self.tracked_objects.values():
+8 -17
View File
@@ -180,8 +180,6 @@ class WebPushClient(Communicator):
self.refresh: int = 0 self.refresh: int = 0
self.web_pushers: dict[str, list[WebPusher]] = {} self.web_pushers: dict[str, list[WebPusher]] = {}
self.expired_subs: dict[str, list[str]] = {} self.expired_subs: dict[str, list[str]] = {}
self.expired_subs_lock = threading.Lock()
self.cleanup_lock = threading.Lock()
self.suspended_cameras: dict[str, int] = { self.suspended_cameras: dict[str, int] = {
c.name: 0 # type: ignore[misc] c.name: 0 # type: ignore[misc]
for c in self.config.cameras.values() for c in self.config.cameras.values()
@@ -262,23 +260,15 @@ class WebPushClient(Communicator):
self.claim_headers[endpoint] = self.vapid.sign(claim) self.claim_headers[endpoint] = self.vapid.sign(claim)
def cleanup_registrations(self) -> None: def cleanup_registrations(self) -> None:
# concurrent cleanups would each restore what the other removed # delete any expired subs
with self.cleanup_lock: if len(self.expired_subs) > 0:
with self.expired_subs_lock: for user, expired in self.expired_subs.items():
expired_subs, self.expired_subs = self.expired_subs, {}
for user, expired in expired_subs.items():
user_subs = [] user_subs = []
# get all subscriptions, removing ones that are expired # get all subscriptions, removing ones that are expired
stored_user: User | None = User.get_or_none(User.username == user) stored_user: User = User.get_by_id(user)
# the user was deleted after the endpoint expired
if stored_user is None:
continue
for token in stored_user.notification_tokens: for token in stored_user.notification_tokens:
if isinstance(token, dict) and token.get("endpoint") in expired: if token["endpoint"] in expired:
continue continue
user_subs.append(token) user_subs.append(token)
@@ -294,6 +284,8 @@ class WebPushClient(Communicator):
f"Cleaned up {len(expired)} notification subscriptions for {user}" f"Cleaned up {len(expired)} notification subscriptions for {user}"
) )
self.expired_subs = {}
def suspend_notifications(self, camera: str, minutes: int) -> None: def suspend_notifications(self, camera: str, minutes: int) -> None:
"""Suspend notifications for a specific camera.""" """Suspend notifications for a specific camera."""
suspend_until = int( suspend_until = int(
@@ -468,7 +460,6 @@ class WebPushClient(Communicator):
) )
if resp.status_code in (404, 410): if resp.status_code in (404, 410):
with self.expired_subs_lock:
self.expired_subs.setdefault(notification.user, []).append( self.expired_subs.setdefault(notification.user, []).append(
endpoint endpoint
) )
@@ -694,7 +685,7 @@ class WebPushClient(Communicator):
title = f"{name.replace('_', ' ')} triggered on {camera_name}" title = f"{name.replace('_', ' ')} triggered on {camera_name}"
message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}" message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}"
image = f"api/events/{event_id}/thumbnail.webp" image = f"clips/triggers/{camera}/{event_id}.webp"
direct_url = f"/explore?event_id={event_id}" direct_url = f"/explore?event_id={event_id}"
ttl = 0 ttl = 0
+12 -7
View File
@@ -40,7 +40,6 @@ from frigate.const import (
) )
from frigate.models import User from frigate.models import User
from frigate.output.ws_auth import ws_has_camera_access from frigate.output.ws_auth import ws_has_camera_access
from frigate.util.builtin import scope_stats_for_non_admin
from frigate.util.origin import origin_allowed from frigate.util.origin import origin_allowed
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -211,7 +210,7 @@ _WS_RESHAPE_JOB_STATE_TOPICS = frozenset(
# Topics whose payload mixes global aggregates with a ``cameras`` sub-dict # Topics whose payload mixes global aggregates with a ``cameras`` sub-dict
# keyed by camera name. Aggregates and detector data stay; per-camera entries # keyed by camera name. Aggregates and detector data stay; per-camera entries
# are filtered and process cmdlines are stripped for non-admins. # are filtered.
_WS_RESHAPE_STATS_TOPICS = frozenset( _WS_RESHAPE_STATS_TOPICS = frozenset(
{ {
"stats", "stats",
@@ -456,14 +455,20 @@ def _materialize_for_ws(
return _wrap_envelope(topic, filtered_jobs) return _wrap_envelope(topic, filtered_jobs)
if kind == "reshape_stats": if kind == "reshape_stats":
if "admin" in _ws_valid_roles(ws, config): if _ws_is_unrestricted(ws, config):
return full_message return full_message
if not isinstance(parsed_payload, dict): if not isinstance(parsed_payload, dict):
return None return None
return _wrap_envelope( allowed = _ws_allowed_cameras(ws, config)
topic, cameras_block = parsed_payload.get("cameras")
scope_stats_for_non_admin(parsed_payload, _ws_allowed_cameras(ws, config)), if isinstance(cameras_block, dict):
) filtered_cameras = {
name: data for name, data in cameras_block.items() if name in allowed
}
reshaped = dict(parsed_payload)
reshaped["cameras"] = filtered_cameras
return _wrap_envelope(topic, reshaped)
return full_message
return None return None
+5 -6
View File
@@ -88,17 +88,16 @@ class AuthConfig(FrigateBaseModel):
f"Invalid role name '{role}'. Must be alphanumeric with underscores." f"Invalid role name '{role}'. Must be alphanumeric with underscores."
) )
# Proxy role headers match role names case-insensitively, so reserved # 'none' is the deny sentinel for proxy.default_role, where it is matched
# names are reserved in every casing and names must differ beyond case # case-insensitively, so every casing of it has to be reserved here
used_reserved = sorted(r for r in v if r.lower() in ("admin", "viewer", "none")) used_reserved = sorted(
r for r in v if r in ("admin", "viewer") or r.lower() == "none"
)
if used_reserved: if used_reserved:
raise ValueError( raise ValueError(
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles." f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
) )
if len({r.lower() for r in v}) != len(v):
raise ValueError("Role names must be unique regardless of letter case.")
# Ensure no role has an empty camera list # Ensure no role has an empty camera list
for role, allowed_cameras in v.items(): for role, allowed_cameras in v.items():
if not allowed_cameras: if not allowed_cameras:
-11
View File
@@ -1,6 +1,5 @@
import os import os
from enum import Enum from enum import Enum
from typing import Literal
from pydantic import Field, PrivateAttr, model_validator from pydantic import Field, PrivateAttr, model_validator
@@ -209,12 +208,6 @@ class CameraConfig(FrigateBaseModel):
_ffmpeg_cmds: list[dict[str, list[str]]] = PrivateAttr() _ffmpeg_cmds: list[dict[str, list[str]]] = PrivateAttr()
# "config" when set by the user, "probed" from the stream at startup, or
# "default" when the probe failed and the fallback size is in use
_detect_resolution_source: Literal["config", "probed", "default"] = PrivateAttr(
default="config"
)
def __init__(self, **config): def __init__(self, **config):
# Set zone colors # Set zone colors
if "zones" in config: if "zones" in config:
@@ -256,10 +249,6 @@ class CameraConfig(FrigateBaseModel):
def ffmpeg_cmds(self) -> list[dict[str, list[str]]]: def ffmpeg_cmds(self) -> list[dict[str, list[str]]]:
return self._ffmpeg_cmds return self._ffmpeg_cmds
@property
def detect_resolution_source(self) -> Literal["config", "probed", "default"]:
return self._detect_resolution_source
def get_formatted_name(self) -> str: def get_formatted_name(self) -> str:
"""Return the friendly name if set, otherwise return a formatted version of the camera name.""" """Return the friendly name if set, otherwise return a formatted version of the camera name."""
if self.friendly_name: if self.friendly_name:
+4 -25
View File
@@ -4,7 +4,6 @@ import io
import json import json
import logging import logging
import os import os
from collections.abc import Mapping
from typing import Any, Self from typing import Any, Self
import numpy as np import numpy as np
@@ -35,7 +34,7 @@ from frigate.util.config import (
get_relative_coordinates, get_relative_coordinates,
migrate_frigate_config, migrate_frigate_config,
) )
from frigate.util.env import EnvVars, candidate_env_vars, reload_sources from frigate.util.env import EnvVars, reload_sources
from frigate.util.image import create_mask from frigate.util.image import create_mask
from frigate.util.live_streams import ( from frigate.util.live_streams import (
default_transcode_source, default_transcode_source,
@@ -1042,15 +1041,6 @@ class FrigateConfig(FrigateBaseModel):
# set notifications state # set notifications state
self.notifications.enabled_in_config = self.notifications.enabled self.notifications.enabled_in_config = self.notifications.enabled
default_role = (self.proxy.default_role or "").lower()
if default_role != "none" and default_role not in {
r.lower() for r in self.auth.roles
}:
logger.warning(
"proxy.default_role '%s' is not a configured role, so proxy users without a matching role are denied",
self.proxy.default_role,
)
# validate genai: each role (chat, descriptions, embeddings, transcribe) at most once # validate genai: each role (chat, descriptions, embeddings, transcribe) at most once
role_to_name: dict[GenAIRoleEnum, str] = {} role_to_name: dict[GenAIRoleEnum, str] = {}
for name, genai_cfg in self.genai.items(): for name, genai_cfg in self.genai.items():
@@ -1213,11 +1203,6 @@ class FrigateConfig(FrigateBaseModel):
if stream_info.get("height") if stream_info.get("height")
else DEFAULT_DETECT_DIMENSIONS["height"] else DEFAULT_DETECT_DIMENSIONS["height"]
) )
camera_config._detect_resolution_source = (
"probed"
if stream_info.get("width") and stream_info.get("height")
else "default"
)
# Warn if detect fps > 10 # Warn if detect fps > 10
if camera_config.detect.fps > 10 and camera_config.type != "lpr": if camera_config.detect.fps > 10 and camera_config.type != "lpr":
@@ -1572,12 +1557,6 @@ class FrigateConfig(FrigateBaseModel):
def parse_object( def parse_object(
cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False
): ):
context = {"plus_api": plus_api, "install": install} return cls.model_validate(
obj, context={"plus_api": plus_api, "install": install}
if install: )
return cls.model_validate(obj, context=context)
# a candidate config resolves placeholders against its own block
env_vars = obj.get("environment_vars") if isinstance(obj, Mapping) else None
with candidate_env_vars(env_vars):
return cls.model_validate(obj, context=context)
+4 -3
View File
@@ -55,9 +55,10 @@ class ProxyConfig(FrigateBaseModel):
@field_validator("default_role", mode="before") @field_validator("default_role", mode="before")
@classmethod @classmethod
def normalize_deny_sentinel(cls, v): def normalize_deny_sentinel(cls, v):
# Fail closed: "none" in any casing and a null default both deny. # Fail closed on capitalization: an unnormalized "None" would miss the
# Normalizing null keeps the value through /config, which drops nulls # sentinel and fall back to viewer, granting the access it was meant to
if v is None or (isinstance(v, str) and v.strip().lower() == "none"): # deny. Other role names stay case-sensitive.
if isinstance(v, str) and v.strip().lower() == "none":
return "none" return "none"
return v return v
@@ -19,7 +19,7 @@ from frigate.log import suppress_stderr_during
from frigate.util.builtin import EventsPerSecond, InferenceSpeed, load_labels from frigate.util.builtin import EventsPerSecond, InferenceSpeed, load_labels
from frigate.util.classification import resize_classification_image from frigate.util.classification import resize_classification_image
from frigate.util.file import trim_oldest_files from frigate.util.file import trim_oldest_files
from frigate.util.image import calculate_region, write_image from frigate.util.image import calculate_region
from frigate.util.object import box_overlaps from frigate.util.object import box_overlaps
from ..types import DataProcessorMetrics from ..types import DataProcessorMetrics
@@ -748,5 +748,5 @@ def write_classification_attempt(
file = os.path.join(folder, f"{event_id}-{timestamp}-{label}-{score}.webp") file = os.path.join(folder, f"{event_id}-{timestamp}-{label}-{score}.webp")
os.makedirs(folder, exist_ok=True) os.makedirs(folder, exist_ok=True)
write_image(file, frame) cv2.imwrite(file, frame)
trim_oldest_files(folder, max_files) trim_oldest_files(folder, max_files)
+2 -2
View File
@@ -28,7 +28,7 @@ from frigate.data_processing.common.face.recognizer import (
from frigate.types import TrackedObjectUpdateTypesEnum from frigate.types import TrackedObjectUpdateTypesEnum
from frigate.util.builtin import EventsPerSecond, InferenceSpeed from frigate.util.builtin import EventsPerSecond, InferenceSpeed
from frigate.util.file import trim_oldest_files from frigate.util.file import trim_oldest_files
from frigate.util.image import area, write_image from frigate.util.image import area
from frigate.util.path import safe_join, sanitize_path_component from frigate.util.path import safe_join, sanitize_path_component
from ..types import DataProcessorMetrics from ..types import DataProcessorMetrics
@@ -488,5 +488,5 @@ class FaceRealTimeProcessor(RealTimeProcessorApi):
folder, f"{event_id}-{timestamp}-{sub_label}-{score}.webp" folder, f"{event_id}-{timestamp}-{sub_label}-{score}.webp"
) )
os.makedirs(folder, exist_ok=True) os.makedirs(folder, exist_ok=True)
write_image(file, frame) cv2.imwrite(file, frame)
trim_oldest_files(folder, self.config.face_recognition.save_attempts) trim_oldest_files(folder, self.config.face_recognition.save_attempts)
+11 -28
View File
@@ -11,11 +11,10 @@ import os
import shutil import shutil
import threading import threading
import time import time
from collections.abc import Callable
from ruamel.yaml import YAML from ruamel.yaml import YAML
from frigate.config import CameraConfig, FrigateConfig from frigate.config import FrigateConfig
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdatePublisher, CameraConfigUpdatePublisher,
@@ -62,7 +61,6 @@ class DebugReplayManager:
self.start_ts: float | None = None self.start_ts: float | None = None
self.end_ts: float | None = None self.end_ts: float | None = None
self.session_started_at: float | None = None self.session_started_at: float | None = None
self._published_camera: CameraConfig | None = None
self._job_state_publisher = JobStatePublisher() self._job_state_publisher = JobStatePublisher()
@property @property
@@ -111,13 +109,6 @@ class DebugReplayManager:
self.start_ts = None self.start_ts = None
self.end_ts = None self.end_ts = None
self.session_started_at = None self.session_started_at = None
self._published_camera = None
def update_config(self, config: FrigateConfig) -> None:
"""Carry the published replay camera into a newly swapped-in config."""
with self._lock:
if self._published_camera is not None and self.replay_camera_name:
config.cameras[self.replay_camera_name] = self._published_camera
def publish_camera( def publish_camera(
self, self,
@@ -126,11 +117,10 @@ class DebugReplayManager:
clip_path: str, clip_path: str,
frigate_config: FrigateConfig, frigate_config: FrigateConfig,
config_publisher: CameraConfigUpdatePublisher, config_publisher: CameraConfigUpdatePublisher,
) -> bool: ) -> None:
"""Build the in-memory replay camera config and publish the add event. """Build the in-memory replay camera config and publish the add event.
Called by the job runner during the starting_camera phase. Returns Called by the job runner during the starting_camera phase.
False without publishing if the session was stopped meanwhile.
""" """
source_config = frigate_config.cameras[source_camera] source_config = frigate_config.cameras[source_camera]
camera_dict = self._build_camera_config_dict( camera_dict = self._build_camera_config_dict(
@@ -150,22 +140,13 @@ class DebugReplayManager:
new_config = FrigateConfig.parse_object(config_data) new_config = FrigateConfig.parse_object(config_data)
except Exception as e: except Exception as e:
raise RuntimeError(f"Failed to validate replay camera config: {e}") from e raise RuntimeError(f"Failed to validate replay camera config: {e}") from e
frigate_config.cameras[replay_name] = new_config.cameras[replay_name]
camera_config = new_config.cameras[replay_name]
with self._lock:
if self.replay_camera_name != replay_name:
return False
frigate_config.cameras[replay_name] = camera_config
self._published_camera = camera_config
config_publisher.publish_update( config_publisher.publish_update(
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name), CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
camera_config, new_config.cameras[replay_name],
) )
return True
def stop( def stop(
self, self,
frigate_config: FrigateConfig, frigate_config: FrigateConfig,
@@ -186,10 +167,12 @@ class DebugReplayManager:
replay_name = self.replay_camera_name replay_name = self.replay_camera_name
source_camera = self.source_camera source_camera = self.source_camera
if replay_name is not None and self._published_camera is not None: # Only publish remove if the camera was actually added to the live
# config (i.e. the runner reached the starting_camera phase).
if replay_name is not None and replay_name in frigate_config.cameras:
config_publisher.publish_update( config_publisher.publish_update(
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name), CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
self._published_camera, frigate_config.cameras[replay_name],
) )
frigate_config.cameras.pop(replay_name, None) frigate_config.cameras.pop(replay_name, None)
@@ -379,7 +362,7 @@ def cleanup_replay_cameras() -> None:
async def debug_replay_auto_stop_watchdog( async def debug_replay_auto_stop_watchdog(
manager: DebugReplayManager, manager: DebugReplayManager,
get_config: Callable[[], FrigateConfig], frigate_config: FrigateConfig,
config_publisher: CameraConfigUpdatePublisher, config_publisher: CameraConfigUpdatePublisher,
) -> None: ) -> None:
"""Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS. """Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS.
@@ -401,7 +384,7 @@ async def debug_replay_auto_stop_watchdog(
replay_name = manager.replay_camera_name replay_name = manager.replay_camera_name
await asyncio.to_thread( await asyncio.to_thread(
manager.stop, manager.stop,
frigate_config=get_config(), frigate_config=frigate_config,
config_publisher=config_publisher, config_publisher=config_publisher,
) )
logger.info( logger.info(
+1 -23
View File
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
from pydantic.fields import PrivateAttr from pydantic.fields import PrivateAttr
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
from frigate.plus import PlusApi, PlusRateLimitError, load_plus_model_info from frigate.plus import PlusApi, load_plus_model_info
from frigate.util.builtin import generate_color_palette, load_labels from frigate.util.builtin import generate_color_palette, load_labels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -52,16 +52,6 @@ DEFAULT_SCENE = "default"
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$" SCENE_PATTERN = r"^[A-Za-z0-9_-]+$"
def _rate_limited_message(model_id: str, err: PlusRateLimitError) -> str:
"""Explain a rate limited Frigate+ model download, with the wait if known."""
message = f"Frigate+ is rate limiting requests, unable to download model {model_id}"
if err.retry_after is not None:
return f"{message}. Try again in {err.retry_after} seconds"
return f"{message}. Try again later"
class ModelConfig(BaseModel): class ModelConfig(BaseModel):
scene: str = Field( scene: str = Field(
default=DEFAULT_SCENE, default=DEFAULT_SCENE,
@@ -203,16 +193,6 @@ class ModelConfig(BaseModel):
raise ValueError( raise ValueError(
f"Unable to connect to Frigate+ to download model {model_id}" f"Unable to connect to Frigate+ to download model {model_id}"
) from e ) from e
except PlusRateLimitError as e:
raise ValueError(_rate_limited_message(model_id, e)) from e
# an error body written here would be mistaken for the model on
# every later start, since only the file's existence is checked
if not r.ok:
raise ValueError(
f"Unable to download model {model_id} from Frigate+ "
f"(HTTP {r.status_code})"
)
with open(self.path, "wb") as f: with open(self.path, "wb") as f:
f.write(r.content) f.write(r.content)
@@ -225,8 +205,6 @@ class ModelConfig(BaseModel):
raise ValueError( raise ValueError(
f"Unable to connect to Frigate+ to download model info for {model_id}" f"Unable to connect to Frigate+ to download model info for {model_id}"
) from e ) from e
except PlusRateLimitError as e:
raise ValueError(_rate_limited_message(model_id, e)) from e
with open(model_info_path, "w") as f: with open(model_info_path, "w") as f:
json.dump(model_info, f) json.dump(model_info, f)
+50 -26
View File
@@ -2,11 +2,14 @@
import datetime import datetime
import logging import logging
import os
import threading import threading
from multiprocessing.synchronize import Event as MpEvent from multiprocessing.synchronize import Event as MpEvent
from pathlib import Path
from typing import Any from typing import Any
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.const import CLIPS_DIR
from frigate.db.sqlitevecq import SqliteVecQueueDatabase from frigate.db.sqlitevecq import SqliteVecQueueDatabase
from frigate.models import Event, Timeline from frigate.models import Event, Timeline
from frigate.util.file import delete_event_snapshot, delete_event_thumbnail from frigate.util.file import delete_event_snapshot, delete_event_thumbnail
@@ -89,6 +92,7 @@ class EventCleanup(threading.Thread):
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.label == event.label, Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True, Event.has_snapshot == True,
) )
.namedtuples() .namedtuples()
@@ -110,6 +114,7 @@ class EventCleanup(threading.Thread):
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.label == event.label, Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True, Event.has_snapshot == True,
) )
@@ -138,7 +143,7 @@ class EventCleanup(threading.Thread):
events_to_update = [] events_to_update = []
## Expire events from cameras based on the camera config ## Expire events from cameras based on the camera config
for name, camera in list(self.config.cameras.items()): for name, camera in self.config.cameras.items():
retain_config = camera.snapshots.retain retain_config = camera.snapshots.retain
# get distinct objects in database for this camera # get distinct objects in database for this camera
@@ -165,6 +170,7 @@ class EventCleanup(threading.Thread):
Event.camera == name, Event.camera == name,
Event.start_time < expire_after, Event.start_time < expire_after,
Event.label == event.label, Event.label == event.label,
Event.retain_indefinitely == False,
Event.has_snapshot == True, Event.has_snapshot == True,
) )
.namedtuples() .namedtuples()
@@ -199,17 +205,54 @@ class EventCleanup(threading.Thread):
self.config.record.effective_alert_days, self.config.record.effective_alert_days,
self.config.record.effective_detection_days, self.config.record.effective_detection_days,
) )
file_extension = None # mp4 clips are no longer stored in /clips
update_params = {"has_clip": False} update_params = {"has_clip": False}
# get expiration time for this label
expire_after = ( expire_after = (
datetime.datetime.now() - datetime.timedelta(days=expire_days) datetime.datetime.now() - datetime.timedelta(days=expire_days)
).timestamp() ).timestamp()
# grab all events after specific time
expired_events: list[Event] = list(
Event.select(
Event.id,
Event.camera,
)
.where(
Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after,
Event.retain_indefinitely == False,
)
.namedtuples()
.iterator()
)
logger.debug(f"{len(expired_events)} events can be expired")
# delete the media from disk
for expired in expired_events:
media_name = f"{expired.camera}-{expired.id}"
media_path = Path(f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}")
try:
media_path.unlink(missing_ok=True)
if file_extension == "jpg":
media_path = Path( # type: ignore[unreachable]
f"{os.path.join(CLIPS_DIR, media_name)}-clean.webp"
)
media_path.unlink(missing_ok=True)
# Also delete clean.png (legacy) for backward compatibility
media_path = Path(
f"{os.path.join(CLIPS_DIR, media_name)}-clean.png"
)
media_path.unlink(missing_ok=True)
except OSError as e:
logger.warning(f"Unable to delete event images: {e}")
# update the clips attribute for the db entry # update the clips attribute for the db entry
query = Event.select(Event.id).where( query = Event.select(Event.id).where(
Event.camera.not_in(self.camera_keys), Event.camera.not_in(self.camera_keys),
Event.start_time < expire_after, Event.start_time < expire_after,
Event.has_clip == True, Event.retain_indefinitely == False,
) )
events_to_update = [] events_to_update = []
@@ -237,7 +280,7 @@ class EventCleanup(threading.Thread):
now = datetime.datetime.now() now = datetime.datetime.now()
## Expire events from cameras based on the camera config ## Expire events from cameras based on the camera config
for name, camera in list(self.config.cameras.items()): for name, camera in self.config.cameras.items():
# effective days cover the sub window, keeping tracked objects # effective days cover the sub window, keeping tracked objects
# in Explore while sub recordings and review items still exist # in Explore while sub recordings and review items still exist
alert_expire_date = ( alert_expire_date = (
@@ -254,7 +297,7 @@ class EventCleanup(threading.Thread):
) )
.where( .where(
Event.camera == name, Event.camera == name,
Event.has_clip == True, Event.retain_indefinitely == False,
( (
( (
(Event.data["max_severity"] != "detection") (Event.data["max_severity"] != "detection")
@@ -292,24 +335,6 @@ class EventCleanup(threading.Thread):
# only expire events every 5 minutes # only expire events every 5 minutes
while not self.stop_event.wait(300): while not self.stop_event.wait(300):
try:
self.expire_events()
except Exception:
logger.exception("Event cleanup failed, retrying next cycle")
logger.info("Exiting event cleanup...")
def refresh_camera_keys(self) -> None:
"""Track cameras added or removed at runtime."""
camera_keys = list(self.config.cameras)
if set(camera_keys) != set(self.camera_keys):
self.camera_keys = camera_keys
self.removed_camera_labels = None
def expire_events(self) -> None:
"""Run one cleanup cycle: expire clips and snapshots, then drop dead events."""
self.refresh_camera_keys()
events_with_expired_clips = self.expire_clips() events_with_expired_clips = self.expire_clips()
# delete timeline entries for events that have expired recordings # delete timeline entries for events that have expired recordings
@@ -332,10 +357,7 @@ class EventCleanup(threading.Thread):
events_to_delete: list[Event] = [e for e in events] events_to_delete: list[Event] = [e for e in events]
for e in events_to_delete: for e in events_to_delete:
if not delete_event_thumbnail(e): delete_event_thumbnail(e)
logger.warning(
f"Unable to delete event thumbnail for {e.camera}: {e.id}"
)
logger.debug(f"Found {len(events_to_delete)} events that can be expired") logger.debug(f"Found {len(events_to_delete)} events that can be expired")
if len(events_to_delete) > 0: if len(events_to_delete) > 0:
@@ -351,3 +373,5 @@ class EventCleanup(threading.Thread):
self.db.delete_embeddings_description(event_ids=chunk) self.db.delete_embeddings_description(event_ids=chunk)
self.db.delete_embeddings_thumbnail(event_ids=chunk) self.db.delete_embeddings_thumbnail(event_ids=chunk)
logger.debug(f"Deleted {len(chunk)} embeddings") logger.debug(f"Deleted {len(chunk)} embeddings")
logger.info("Exiting event cleanup...")
-15
View File
@@ -67,17 +67,6 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | None:
return None return None
def _tool_names_by_id(messages: list[dict[str, Any]]) -> dict[str, str]:
"""Map each assistant tool call id to its function name."""
return {
tc["id"]: (tc.get("function") or {}).get("name") or ""
for msg in messages
if msg.get("role") == "assistant"
for tc in msg.get("tool_calls") or []
if tc.get("id")
}
def _parts_from_content(content: Any) -> list[types.Part]: def _parts_from_content(content: Any) -> list[types.Part]:
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts.""" """Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
if isinstance(content, list): if isinstance(content, list):
@@ -469,7 +458,6 @@ class GeminiClient(GenAIClient):
try: try:
# Convert messages to Gemini format # Convert messages to Gemini format
gemini_messages: list[types.Content] = [] gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages: for msg in messages:
role = msg.get("role", "user") role = msg.get("role", "user")
content = msg.get("content", "") content = msg.get("content", "")
@@ -532,7 +520,6 @@ class GeminiClient(GenAIClient):
parts=[ parts=[
types.Part.from_function_response( types.Part.from_function_response(
name=msg.get("name") name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id") or msg.get("tool_call_id")
or "", or "",
response=response_payload, response=response_payload,
@@ -727,7 +714,6 @@ class GeminiClient(GenAIClient):
try: try:
# Convert messages to Gemini format # Convert messages to Gemini format
gemini_messages: list[types.Content] = [] gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages: for msg in messages:
role = msg.get("role", "user") role = msg.get("role", "user")
content = msg.get("content", "") content = msg.get("content", "")
@@ -790,7 +776,6 @@ class GeminiClient(GenAIClient):
parts=[ parts=[
types.Part.from_function_response( types.Part.from_function_response(
name=msg.get("name") name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id") or msg.get("tool_call_id")
or "", or "",
response=response_payload, response=response_payload,
+12 -9
View File
@@ -110,13 +110,6 @@ class LlamaCppClient(GenAIClient):
"""POST with the configured auth headers injected.""" """POST with the configured auth headers injected."""
return requests.post(url, headers=self._auth_headers(), **kwargs) return requests.post(url, headers=self._auth_headers(), **kwargs)
def _server_url(self) -> str | None:
"""Return the configured base_url without a trailing slash or /v1."""
if not self.genai_config.base_url:
return None
return self.genai_config.base_url.rstrip("/").removesuffix("/v1")
def _fetch_llama_props(self, base_url: str, model: str) -> dict[str, Any]: def _fetch_llama_props(self, base_url: str, model: str) -> dict[str, Any]:
"""Fetch /props from a llama.cpp server, with llama-swap fallback. """Fetch /props from a llama.cpp server, with llama-swap fallback.
@@ -150,10 +143,16 @@ class LlamaCppClient(GenAIClient):
self._supports_tools = False self._supports_tools = False
self._supports_reasoning = False self._supports_reasoning = False
base_url = self._server_url() base_url = (
self.genai_config.base_url.rstrip("/")
if self.genai_config.base_url
else None
)
if base_url is None: if base_url is None:
return None return None
else:
base_url = base_url.replace("/v1", "") # Strip /v1 if included in base_url
if not self.validate_model: if not self.validate_model:
# Probe path # Probe path
@@ -507,7 +506,11 @@ class LlamaCppClient(GenAIClient):
def _fetch_models_data(self) -> list[dict[str, Any]]: def _fetch_models_data(self) -> list[dict[str, Any]]:
"""Return the raw /v1/models entries, or an empty list if unreachable.""" """Return the raw /v1/models entries, or an empty list if unreachable."""
base_url = self.provider or self._server_url() base_url = self.provider or (
self.genai_config.base_url.rstrip("/")
if self.genai_config.base_url
else None
)
if base_url is None: if base_url is None:
return [] return []
+16 -5
View File
@@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator
from typing import Any from typing import Any
import numpy as np import numpy as np
from httpx import HTTPError from httpx import RemoteProtocolError, TimeoutException
from ollama import AsyncClient as OllamaAsyncClient from ollama import AsyncClient as OllamaAsyncClient
from ollama import Client as ApiClient from ollama import Client as ApiClient
from ollama import ResponseError from ollama import ResponseError
@@ -282,7 +282,12 @@ class OllamaClient(GenAIClient):
try: try:
response = self.provider.chat(**request_params) response = self.provider.chat(**request_params)
except (HTTPError, ResponseError, ConnectionError) as e: except (
TimeoutException,
ResponseError,
RemoteProtocolError,
ConnectionError,
) as e:
logger.warning("Ollama returned an error: %s", str(e)) logger.warning("Ollama returned an error: %s", str(e))
return None return None
@@ -401,7 +406,13 @@ class OllamaClient(GenAIClient):
# image items have to bypass it and post the JSON directly. # image items have to bypass it and post the JSON directly.
response = self.provider._request_raw("POST", "/api/embed", json=payload) response = self.provider._request_raw("POST", "/api/embed", json=payload)
body = response.json() body = response.json()
except (HTTPError, ResponseError, ConnectionError, ValueError) as e: except (
TimeoutException,
ResponseError,
RemoteProtocolError,
ConnectionError,
ValueError,
) as e:
logger.warning("Ollama embeddings error: %s", str(e)) logger.warning("Ollama embeddings error: %s", str(e))
return [] return []
@@ -542,7 +553,7 @@ class OllamaClient(GenAIClient):
) )
response = self.provider.chat(**request_params) response = self.provider.chat(**request_params)
return self._message_from_response(response) return self._message_from_response(response)
except (HTTPError, ResponseError, ConnectionError) as e: except (TimeoutException, ResponseError, ConnectionError) as e:
logger.warning("Ollama returned an error: %s", str(e)) logger.warning("Ollama returned an error: %s", str(e))
return { return {
"content": None, "content": None,
@@ -674,7 +685,7 @@ class OllamaClient(GenAIClient):
"finish_reason": "stop", "finish_reason": "stop",
}, },
) )
except (HTTPError, ResponseError, ConnectionError) as e: except (TimeoutException, ResponseError, ConnectionError) as e:
logger.warning("Ollama streaming error: %s", str(e)) logger.warning("Ollama streaming error: %s", str(e))
yield ( yield (
"message", "message",
+2 -5
View File
@@ -376,16 +376,13 @@ class DebugReplayJobRunner(threading.Thread):
self._finalize_cancelled(clip_path) self._finalize_cancelled(clip_path)
return return
if not self.replay_manager.publish_camera( self.replay_manager.publish_camera(
source_camera=self.job.source_camera, source_camera=self.job.source_camera,
replay_name=replay_name, replay_name=replay_name,
clip_path=clip_path, clip_path=clip_path,
frigate_config=self.frigate_config, frigate_config=self.frigate_config,
config_publisher=self.config_publisher, config_publisher=self.config_publisher,
): )
self._finalize_cancelled(clip_path)
return
self.replay_manager.mark_session_ready(clip_path) self.replay_manager.mark_session_ready(clip_path)
self.job.status = JobStatusTypesEnum.success self.job.status = JobStatusTypesEnum.success
-3
View File
@@ -487,9 +487,6 @@ def get_export_job_manager(config: FrigateConfig) -> ExportJobManager:
with _job_manager_lock: with _job_manager_lock:
if _job_manager is None: if _job_manager is None:
_job_manager = ExportJobManager(config, _get_max_concurrent(config)) _job_manager = ExportJobManager(config, _get_max_concurrent(config))
# callers pass the live config, which a save replaces
_job_manager.config = config
_job_manager.ensure_started() _job_manager.ensure_started()
return _job_manager return _job_manager
+6 -16
View File
@@ -28,8 +28,6 @@ _MAX_INTERVAL = 300
# Minimum seconds between VLM iterations when woken by detections (no zone filter) # Minimum seconds between VLM iterations when woken by detections (no zone filter)
_DETECTION_COOLDOWN_WITHOUT_ZONE = 10 _DETECTION_COOLDOWN_WITHOUT_ZONE = 10
MAX_WATCH_MINUTES = 1440
# Max user/assistant turn pairs to keep in conversation history # Max user/assistant turn pairs to keep in conversation history
_MAX_HISTORY = 10 _MAX_HISTORY = 10
@@ -77,17 +75,15 @@ class VLMWatchRunner(threading.Thread):
self.conversation: list[dict[str, Any]] = [] self.conversation: list[dict[str, Any]] = []
def run(self) -> None: def run(self) -> None:
try:
self.job.status = JobStatusTypesEnum.running self.job.status = JobStatusTypesEnum.running
self.job.start_time = time.time() self.job.start_time = time.time()
self._broadcast_status() self._broadcast_status()
self.conversation = [ self.conversation = [{"role": "system", "content": self._build_system_prompt()}]
{"role": "system", "content": self._build_system_prompt()}
]
# monotonic so a wall clock step can't end the job early or let it overrun # monotonic so a wall clock step can't end the job early or let it overrun
max_end_time = time.monotonic() + self.job.max_duration_minutes * 60 max_end_time = time.monotonic() + self.job.max_duration_minutes * 60
try:
while not self.cancel_event.is_set(): while not self.cancel_event.is_set():
if time.monotonic() > max_end_time: if time.monotonic() > max_end_time:
logger.debug( logger.debug(
@@ -208,13 +204,7 @@ class VLMWatchRunner(threading.Thread):
) )
reasoning = str(parsed.get("reasoning", "")) reasoning = str(parsed.get("reasoning", ""))
notification_message = str(parsed.get("notification_message", "")) notification_message = str(parsed.get("notification_message", ""))
except ( except (json.JSONDecodeError, ValueError, TypeError) as e:
json.JSONDecodeError,
ValueError,
TypeError,
AttributeError,
OverflowError,
) as e:
logger.warning( logger.warning(
"VLM watch job %s: failed to parse VLM response: %s", self.job.id, e "VLM watch job %s: failed to parse VLM response: %s", self.job.id, e
) )
@@ -413,6 +403,9 @@ def start_vlm_watch_job(
username=username, username=username,
) )
cancel_ev = threading.Event() cancel_ev = threading.Event()
_current_job = job
_cancel_event = cancel_ev
runner = VLMWatchRunner( runner = VLMWatchRunner(
job=job, job=job,
config=config, config=config,
@@ -421,9 +414,6 @@ def start_vlm_watch_job(
genai_manager=genai_manager, genai_manager=genai_manager,
dispatcher=dispatcher, dispatcher=dispatcher,
) )
_current_job = job
_cancel_event = cancel_ev
runner.start() runner.start()
logger.debug( logger.debug(
+1
View File
@@ -40,6 +40,7 @@ class Event(Model):
area = ( area = (
IntegerField() IntegerField()
) # TODO remove when columns can be dropped without rebuilding table ) # TODO remove when columns can be dropped without rebuilding table
retain_indefinitely = BooleanField(default=False)
ratio = FloatField( ratio = FloatField(
default=1.0 default=1.0
) # TODO remove when columns can be dropped without rebuilding table ) # TODO remove when columns can be dropped without rebuilding table
+3
View File
@@ -73,11 +73,14 @@ _KINDS = (
"detect_high_cpu", NoticeSeverity.warning, "camera", link="/system#cameras" "detect_high_cpu", NoticeSeverity.warning, "camera", link="/system#cameras"
), ),
NoticeKind("shm_too_low", NoticeSeverity.warning, "system", link="/system#storage"), NoticeKind("shm_too_low", NoticeSeverity.warning, "system", link="/system#storage"),
# every camera process raises it when the shared queue backs up, so repeats
# wait for the next flush instead of writing once per camera
NoticeKind( NoticeKind(
"object_processing_behind", "object_processing_behind",
NoticeSeverity.warning, NoticeSeverity.warning,
"system", "system",
link="/system#cameras", link="/system#cameras",
batch_repeats=True,
), ),
# one row per user per burst; the login log lines carry the address # one row per user per burst; the login log lines carry the address
NoticeKind( NoticeKind(
+3 -7
View File
@@ -789,7 +789,7 @@ class BirdsEyeFrameManager:
force_update = True force_update = True
else: else:
return False, False return False, False
else:
# update the last active frame for the camera # update the last active frame for the camera
camera_state["current_frame"] = frame.copy() camera_state["current_frame"] = frame.copy()
camera_state["current_frame_time"] = frame_time camera_state["current_frame_time"] = frame_time
@@ -865,10 +865,7 @@ class Birdseye:
(1.0 / self.idle_fps) if self.idle_fps > 0 else None (1.0 / self.idle_fps) if self.idle_fps > 0 else None
) )
# restream changes need a restart, so the buffer exists only if it did at init if config.birdseye.restream:
self.restream = config.birdseye.restream
if self.restream:
self.birdseye_buffer: Any = self.frame_manager.create( self.birdseye_buffer: Any = self.frame_manager.create(
"birdseye", "birdseye",
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1], self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
@@ -880,7 +877,7 @@ class Birdseye:
def __send_new_frame(self) -> None: def __send_new_frame(self) -> None:
frame_bytes = self.birdseye_manager.frame.tobytes() frame_bytes = self.birdseye_manager.frame.tobytes()
if self.restream: if self.config.birdseye.restream:
self.birdseye_buffer[:] = frame_bytes self.birdseye_buffer[:] = frame_bytes
try: try:
@@ -957,7 +954,6 @@ class Birdseye:
>= self._idle_interval >= self._idle_interval
): ):
self.__send_new_frame() self.__send_new_frame()
self.birdseye_manager.last_output_time = now
def stop(self) -> None: def stop(self) -> None:
self.review_subscriber.stop() self.review_subscriber.stop()
+2 -7
View File
@@ -22,12 +22,7 @@ from frigate.ffmpeg_presets import (
parse_preset_hardware_acceleration_encode, parse_preset_hardware_acceleration_encode,
) )
from frigate.models import Previews from frigate.models import Previews
from frigate.util.image import ( from frigate.util.image import copy_yuv_to_position, get_blank_yuv_frame, get_yuv_crop
copy_yuv_to_position,
get_blank_yuv_frame,
get_yuv_crop,
write_image,
)
from frigate.util.ownership import chown_to_runtime from frigate.util.ownership import chown_to_runtime
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -378,7 +373,7 @@ class PreviewRecorder:
) )
cache_path = get_cache_image_name(self.camera_name, frame_time) cache_path = get_cache_image_name(self.camera_name, frame_time)
if not write_image( if not cv2.imwrite(
cache_path, cache_path,
small_frame, small_frame,
[ [
+14 -135
View File
@@ -1,12 +1,8 @@
import datetime import datetime
import email.utils
import json import json
import logging import logging
import math
import os import os
import re import re
import threading
import time
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from typing import Any, TypeGuard from typing import Any, TypeGuard
@@ -25,11 +21,6 @@ logger = logging.getLogger(__name__)
PLUS_VALIDATE_TIMEOUT = 10 PLUS_VALIDATE_TIMEOUT = 10
# Requests run on several threads, and a reply that arrives late must not
# shorten a wait recorded from another one. The lock is kept out of PlusApi
# because the client is pickled with the config to start worker processes.
_rate_limit_lock = threading.Lock()
class PlusKeyStatus(str, Enum): class PlusKeyStatus(str, Enum):
"""Result of validating a Frigate+ API key with the server.""" """Result of validating a Frigate+ API key with the server."""
@@ -37,7 +28,6 @@ class PlusKeyStatus(str, Enum):
valid = "valid" valid = "valid"
invalid = "invalid" invalid = "invalid"
unreachable = "unreachable" unreachable = "unreachable"
rate_limited = "rate_limited"
not_set = "not_set" not_set = "not_set"
@@ -80,51 +70,6 @@ def load_plus_model_info(model_id: str) -> dict[str, Any] | None:
return add_hailo_alias(model_info) return add_hailo_alias(model_info)
class PlusRateLimitError(Exception):
"""Frigate+ rejected a request because too many requests were made."""
def __init__(self, retry_after: int | None) -> None:
self.retry_after = retry_after
super().__init__(
f"Rate limited by Frigate+, retry in {retry_after} seconds"
if retry_after is not None
else "Rate limited by Frigate+"
)
def parse_retry_after(value: str | None) -> int | None:
"""Read the number of seconds to wait from a Retry-After header.
The header (RFC 9110 section 10.2.3) is either a number of seconds or an
HTTP date to retry after.
Args:
value: The raw header value
Returns:
Whole seconds to wait, or None when the header is missing or invalid
"""
if not value:
return None
value = value.strip()
if value.isdigit():
return int(value)
try:
retry_at = email.utils.parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
# HTTP dates are always GMT, but "-0000" parses as a naive datetime
if retry_at.tzinfo is None:
retry_at = retry_at.replace(tzinfo=datetime.UTC)
remaining = (retry_at - datetime.datetime.now(datetime.UTC)).total_seconds()
return max(0, math.ceil(remaining))
def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes: def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
if image.shape[1] >= image.shape[0]: if image.shape[1] >= image.shape[0]:
width = min(max_dim, image.shape[1]) width = min(max_dim, image.shape[1])
@@ -183,61 +128,13 @@ class PlusApi:
self._is_active: bool = self.key is not None self._is_active: bool = self.key is not None
self._token_data: dict = {} self._token_data: dict = {}
# when Frigate+ last asked us to back off, requests are refused locally
# until this time instead of being sent to the server again
self._rate_limited_until: float | None = None
# Retry connection failures so a network that comes up late at startup # Retry connection failures so a network that comes up late at startup
# doesn't fail the Frigate+ model download. Retry-After is not honored # doesn't fail the Frigate+ model download
# here, since urllib3 would block the calling thread for as long as the
# server asks; a 429 is raised to the caller as PlusRateLimitError.
self._session = requests.Session() self._session = requests.Session()
self._session.mount( self._session.mount(
self.host, self.host, HTTPAdapter(max_retries=Retry(connect=5, backoff_factor=1))
HTTPAdapter(
max_retries=Retry(
connect=5, backoff_factor=1, respect_retry_after_header=False
) )
),
)
def rate_limit_remaining(self) -> int | None:
"""Seconds until Frigate+ accepts requests again, or None if not limited."""
rate_limited_until = self._rate_limited_until
if rate_limited_until is None:
return None
remaining = math.ceil(rate_limited_until - time.time())
return remaining if remaining > 0 else None
def _note_rate_limit(self, retry_after: int | None) -> None:
"""Remember how long Frigate+ asked us to wait."""
logger.warning(
"Frigate+ rate limit reached, retry after %s seconds",
retry_after if retry_after is not None else "unknown",
)
if retry_after is None:
return
until = time.time() + retry_after
with _rate_limit_lock:
if self._rate_limited_until is None or until > self._rate_limited_until:
self._rate_limited_until = until
def _raise_if_rate_limited(self) -> None:
remaining = self.rate_limit_remaining()
if remaining is not None:
raise PlusRateLimitError(remaining)
def _check_rate_limit(self, r: Response) -> None:
if r.status_code == 429:
retry_after = parse_retry_after(r.headers.get("Retry-After"))
self._note_rate_limit(retry_after)
raise PlusRateLimitError(retry_after)
def _refresh_token_if_needed(self) -> None: def _refresh_token_if_needed(self) -> None:
if ( if (
@@ -248,12 +145,10 @@ class PlusApi:
raise Exception( raise Exception(
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key" "Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key"
) )
self._raise_if_rate_limited()
parts = self.key.split(":") parts = self.key.split(":")
r = self._session.get( r = self._session.get(
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1]) f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
) )
self._check_rate_limit(r)
if not r.ok: if not r.ok:
raise Exception(f"Unable to refresh API token: {r.text}") raise Exception(f"Unable to refresh API token: {r.text}")
self._token_data = r.json() self._token_data = r.json()
@@ -262,30 +157,24 @@ class PlusApi:
self._refresh_token_if_needed() self._refresh_token_if_needed()
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"} return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
def _request(self, method: str, path: str, data: dict | None = None) -> Response: def _get(self, path: str) -> Response:
"""Make an authenticated Frigate+ request. return self._session.get(
f"{self.host}/v1/{path}", headers=self._get_authorization_header()
)
Raises: def _post(self, path: str, data: dict) -> Response:
PlusRateLimitError: Frigate+ is rate limiting requests return self._session.post(
"""
self._raise_if_rate_limited()
r = self._session.request(
method,
f"{self.host}/v1/{path}", f"{self.host}/v1/{path}",
headers=self._get_authorization_header(), headers=self._get_authorization_header(),
json=data, json=data,
) )
self._check_rate_limit(r)
return r
def _get(self, path: str) -> Response:
return self._request("GET", path)
def _post(self, path: str, data: dict) -> Response:
return self._request("POST", path, data)
def _put(self, path: str, data: dict) -> Response: def _put(self, path: str, data: dict) -> Response:
return self._request("PUT", path, data) return self._session.put(
f"{self.host}/v1/{path}",
headers=self._get_authorization_header(),
json=data,
)
def is_active(self) -> bool: def is_active(self) -> bool:
return self._is_active return self._is_active
@@ -298,16 +187,11 @@ class PlusApi:
result reflects the key's current state rather than a cached token. result reflects the key's current state rather than a cached token.
Returns: Returns:
The key's status as reported by the Frigate+ server. When it is The key's status as reported by the Frigate+ server
rate_limited, rate_limit_remaining() gives the wait if known.
""" """
if self.key is None: if self.key is None:
return PlusKeyStatus.not_set return PlusKeyStatus.not_set
# asking again before the wait is over would only be refused again
if self.rate_limit_remaining() is not None:
return PlusKeyStatus.rate_limited
key_id, _, secret = self.key.partition(":") key_id, _, secret = self.key.partition(":")
# Use a single request with a timeout instead of the retrying session, # Use a single request with a timeout instead of the retrying session,
@@ -323,7 +207,6 @@ class PlusApi:
auth=aiohttp.BasicAuth(key_id, secret), auth=aiohttp.BasicAuth(key_id, secret),
) as r: ) as r:
status = r.status status = r.status
retry_after = parse_retry_after(r.headers.get("Retry-After"))
token_data = await r.json(content_type=None) if r.ok else None token_data = await r.json(content_type=None) if r.ok else None
except (aiohttp.ClientError, TimeoutError) as err: except (aiohttp.ClientError, TimeoutError) as err:
logger.warning("Unable to reach Frigate+ to validate API key: %s", err) logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
@@ -335,10 +218,6 @@ class PlusApi:
if status in (401, 403): if status in (401, 403):
return PlusKeyStatus.invalid return PlusKeyStatus.invalid
if status == 429:
self._note_rate_limit(retry_after)
return PlusKeyStatus.rate_limited
if status >= 400: if status >= 400:
logger.warning( logger.warning(
"Unexpected response validating Frigate+ API key: %s", status "Unexpected response validating Frigate+ API key: %s", status
+5 -3
View File
@@ -1191,10 +1191,9 @@ class PtzAutoTracker(threading.Thread):
# absolute zooming separately from pan/tilt # absolute zooming separately from pan/tilt
if camera_config.onvif.autotracking.zooming == ZoomingModeEnum.absolute: if camera_config.onvif.autotracking.zooming == ZoomingModeEnum.absolute:
# don't zoom on initial move. the stored zoom level can still be # don't zoom on initial move
# the previous track's if this one starts right after a preset return
if "target_box" not in tom: if "target_box" not in tom:
zoom = 0 zoom = current_zoom_level
else: else:
if ( if (
result := self._should_zoom_in( result := self._should_zoom_in(
@@ -1422,6 +1421,9 @@ class PtzAutoTracker(threading.Thread):
autotracker_config.return_preset.lower(), autotracker_config.return_preset.lower(),
) )
# update stored zoom level from preset
await self._wait_until_stopped(camera)
self.dispatcher.publish( self.dispatcher.publish(
f"{camera}/ptz_autotracker/active", "OFF", retain=False f"{camera}/ptz_autotracker/active", "OFF", retain=False
) )
+17 -28
View File
@@ -301,13 +301,13 @@ class OnvifController:
logger.debug(f"Imaging service not supported for {camera_name}: {e}") logger.debug(f"Imaging service not supported for {camera_name}: {e}")
imaging = None imaging = None
cam["imaging"] = imaging cam["imaging"] = imaging
cam["video_source_token"] = None
try: try:
video_sources = await media.GetVideoSources() video_sources = await media.GetVideoSources()
if video_sources and len(video_sources) > 0: if video_sources and len(video_sources) > 0:
cam["video_source_token"] = video_sources[0].token cam["video_source_token"] = video_sources[0].token
except Exception as e: except Exception as e:
logger.debug(f"Unable to get video sources for {camera_name}: {e}") logger.debug(f"Unable to get video sources for {camera_name}: {e}")
cam["video_source_token"] = None
# setup continuous moving request # setup continuous moving request
move_request = ptz.create_type("ContinuousMove") move_request = ptz.create_type("ContinuousMove")
@@ -351,13 +351,12 @@ class OnvifController:
autotracking_config.enabled_in_config and autotracking_config.enabled autotracking_config.enabled_in_config and autotracking_config.enabled
) )
fov_supported = ( # setup relative move request when FOV relative movement is supported
if (
fov_space_id is not None fov_space_id is not None
and configs.DefaultRelativePanTiltTranslationSpace is not None and configs.DefaultRelativePanTiltTranslationSpace is not None
) ):
# one-off GetStatus to seed Translation field
# relative moves are seeded from the current position
if fov_supported:
status = None status = None
try: try:
status = await ptz.GetStatus({"ProfileToken": profile.token}) status = await ptz.GetStatus({"ProfileToken": profile.token})
@@ -365,15 +364,6 @@ class OnvifController:
except Exception as e: except Exception as e:
logger.warning(f"Unable to get status from camera {camera_name}: {e}") logger.warning(f"Unable to get status from camera {camera_name}: {e}")
if status is None or status.Position is None:
logger.warning(
"Disabling relative movement for %s: camera does not report its PTZ position",
camera_name,
)
fov_supported = False
# setup relative move request when FOV relative movement is supported
if fov_supported:
rel_move_request = ptz.create_type("RelativeMove") rel_move_request = ptz.create_type("RelativeMove")
rel_move_request.ProfileToken = profile.token rel_move_request.ProfileToken = profile.token
logger.debug(f"{camera_name}: Relative move request: {rel_move_request}") logger.debug(f"{camera_name}: Relative move request: {rel_move_request}")
@@ -383,8 +373,15 @@ class OnvifController:
]["URI"] ]["URI"]
if rel_move_request.Translation is None: if rel_move_request.Translation is None:
if status is not None:
# seed from current position
rel_move_request.Translation = status.Position rel_move_request.Translation = status.Position
rel_move_request.Translation.PanTilt.space = fov_uri rel_move_request.Translation.PanTilt.space = fov_uri
else:
# fallback: construct Translation explicitly
rel_move_request.Translation = {
"PanTilt": {"x": 0, "y": 0, "space": fov_uri}
}
# configure zoom on relative move request # configure zoom on relative move request
if ( if (
@@ -500,7 +497,11 @@ class OnvifController:
except Exception as e: except Exception as e:
logger.debug(f"Focus not supported for {camera_name}: {e}") logger.debug(f"Focus not supported for {camera_name}: {e}")
if fov_supported: # detect FOV relative movement support
if (
fov_space_id is not None
and configs.DefaultRelativePanTiltTranslationSpace is not None
):
supported_features.append("pt-r-fov") supported_features.append("pt-r-fov")
cam["relative_fov_range"] = ( cam["relative_fov_range"] = (
ptz_config.Spaces.RelativePanTiltTranslationSpace[fov_space_id] ptz_config.Spaces.RelativePanTiltTranslationSpace[fov_space_id]
@@ -659,15 +660,12 @@ class OnvifController:
move_request = cam["move_request"] move_request = cam["move_request"]
preset_token = cam["presets"][preset] preset_token = cam["presets"][preset]
try:
await cam["ptz"].GotoPreset( await cam["ptz"].GotoPreset(
{ {
"ProfileToken": move_request.ProfileToken, "ProfileToken": move_request.ProfileToken,
"PresetToken": preset_token, "PresetToken": preset_token,
} }
) )
except Exception as e:
logger.warning(f"Onvif sending preset request to {camera_name} failed: {e}")
cam["active"] = False cam["active"] = False
@@ -692,11 +690,7 @@ class OnvifController:
elif command == OnvifCommandEnum.zoom_out: elif command == OnvifCommandEnum.zoom_out:
move_request.Velocity = {"Zoom": {"x": -0.5}} move_request.Velocity = {"Zoom": {"x": -0.5}}
try:
await cam["ptz"].ContinuousMove(move_request) await cam["ptz"].ContinuousMove(move_request)
except Exception as e:
logger.warning(f"Onvif sending zoom request to {camera_name} failed: {e}")
cam["active"] = False
async def _zoom_absolute(self, camera_name: str, zoom, speed) -> None: async def _zoom_absolute(self, camera_name: str, zoom, speed) -> None:
cam = self.cams[camera_name] cam = self.cams[camera_name]
@@ -735,7 +729,6 @@ class OnvifController:
logger.debug(f"{camera_name}: Absolute zoom: {zoom}") logger.debug(f"{camera_name}: Absolute zoom: {zoom}")
try:
await cam["ptz"].AbsoluteMove( await cam["ptz"].AbsoluteMove(
{ {
"ProfileToken": cam["move_request"].ProfileToken, "ProfileToken": cam["move_request"].ProfileToken,
@@ -743,10 +736,6 @@ class OnvifController:
"Speed": {"Zoom": speed}, "Speed": {"Zoom": speed},
} }
) )
except Exception as e:
logger.warning(
f"Onvif sending absolute zoom request to {camera_name} failed: {e}"
)
cam["active"] = False cam["active"] = False
+3 -15
View File
@@ -261,18 +261,6 @@ def validate_ffmpeg_args(args: str) -> tuple[bool, str]:
return True, "" return True, ""
def normalize_ffmpeg_args(args: str | None) -> str | None:
"""Rejoin args with single spaces.
validate_ffmpeg_args tokenizes on any whitespace, while export commands are
built with split(" "). Normalizing keeps the two token lists identical.
"""
if args is None:
return None
return " ".join(args.split())
class PlaybackSourceEnum(str, Enum): class PlaybackSourceEnum(str, Enum):
recordings = "recordings" recordings = "recordings"
preview = "preview" preview = "preview"
@@ -339,8 +327,8 @@ class RecordingExporter(threading.Thread):
self.end_time = end_time self.end_time = end_time
self.playback_source = playback_source self.playback_source = playback_source
self.export_case_id = export_case_id self.export_case_id = export_case_id
self.ffmpeg_input_args = normalize_ffmpeg_args(ffmpeg_input_args) self.ffmpeg_input_args = ffmpeg_input_args
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args) self.ffmpeg_output_args = ffmpeg_output_args
self.cpu_fallback = cpu_fallback self.cpu_fallback = cpu_fallback
self.chapters = chapters self.chapters = chapters
self.stream = stream self.stream = stream
@@ -1345,7 +1333,7 @@ class RecordingExporter(threading.Thread):
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}" end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
for file in sorted(os.listdir(preview_dir)): for file in sorted(os.listdir(preview_dir)):
if not is_camera_preview_frame(file, self.camera): if not file.startswith(file_start):
continue continue
if file < start_file: if file < start_file:
+3 -7
View File
@@ -33,11 +33,7 @@ from frigate.models import ReviewSegment
from frigate.review.severity import get_review_severity from frigate.review.severity import get_review_severity
from frigate.review.types import SeverityEnum from frigate.review.types import SeverityEnum
from frigate.track.object_processing import ManualEventState from frigate.track.object_processing import ManualEventState
from frigate.util.image import ( from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop
SharedMemoryFrameManager,
calculate_16_9_crop,
write_image,
)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -151,7 +147,7 @@ class PendingReviewSegment:
self.thumb_time = datetime.datetime.now().timestamp() self.thumb_time = datetime.datetime.now().timestamp()
self.has_frame = True self.has_frame = True
Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True) Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True)
if not write_image( if not cv2.imwrite(
self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60] self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60]
): ):
logger.error("Failed to write review thumbnail to %s", self.frame_path) logger.error("Failed to write review thumbnail to %s", self.frame_path)
@@ -166,7 +162,7 @@ class PendingReviewSegment:
if self._frame is not None: if self._frame is not None:
self.has_frame = True self.has_frame = True
Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True) Path(self.frame_path).parent.mkdir(parents=True, exist_ok=True)
if not write_image( if not cv2.imwrite(
self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60] self.frame_path, self._frame, [int(cv2.IMWRITE_WEBP_QUALITY), 60]
): ):
logger.error("Failed to write review thumbnail to %s", self.frame_path) logger.error("Failed to write review thumbnail to %s", self.frame_path)
+1 -17
View File
@@ -10,7 +10,7 @@ from typing import Any
from frigate.comms.inter_process import InterProcessRequestor from frigate.comms.inter_process import InterProcessRequestor
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.const import FREQUENCY_STATS_POINTS, REPLAY_CAMERA_PREFIX from frigate.const import FREQUENCY_STATS_POINTS
from frigate.notices import flush_notices, raise_notice, resolve_kind, resolve_notice from frigate.notices import flush_notices, raise_notice, resolve_kind, resolve_notice
from frigate.stats.hardware import HardwareStats from frigate.stats.hardware import HardwareStats
from frigate.stats.prometheus import update_metrics from frigate.stats.prometheus import update_metrics
@@ -29,10 +29,6 @@ VERSION_REFRESH_S = 24 * 60 * 60
# a camera skipping at least this percent of its frames is falling behind # a camera skipping at least this percent of its frames is falling behind
SKIPPED_DETECTIONS_PCT = 5 SKIPPED_DETECTIONS_PCT = 5
# a camera dropping at least this percent of its frames because the tracked
# object processor is behind
DROPPED_FRAMES_PCT = 5
# lifetime CPU averages at or above these are high; they match # lifetime CPU averages at or above these are high; they match
# CameraFfmpegThreshold.error and CameraDetectThreshold.error in the UI # CameraFfmpegThreshold.error and CameraDetectThreshold.error in the UI
FFMPEG_HIGH_CPU_PCT = 20 FFMPEG_HIGH_CPU_PCT = 20
@@ -106,7 +102,6 @@ class StatsEmitter(threading.Thread):
self.hardware_stats = HardwareStats(config) self.hardware_stats = HardwareStats(config)
self.stats_history: list[dict[str, Any]] = [] self.stats_history: list[dict[str, Any]] = []
self.skipped_detections = EpisodeTracker(SKIPPED_DETECTIONS_PCT) self.skipped_detections = EpisodeTracker(SKIPPED_DETECTIONS_PCT)
self.dropped_frames = EpisodeTracker(DROPPED_FRAMES_PCT)
self.ffmpeg_cpu = EpisodeTracker(FFMPEG_HIGH_CPU_PCT) self.ffmpeg_cpu = EpisodeTracker(FFMPEG_HIGH_CPU_PCT)
self.detect_cpu = EpisodeTracker(DETECT_HIGH_CPU_PCT) self.detect_cpu = EpisodeTracker(DETECT_HIGH_CPU_PCT)
@@ -274,17 +269,6 @@ class StatsEmitter(threading.Thread):
params={"pct": skipped[camera]}, params={"pct": skipped[camera]},
) )
# all cameras share one processor, so the episode spans every camera.
# a replay camera's own drops are ignored since it can outpace real time
dropped = [
camera_stats["dropped_pct"]
for camera, camera_stats in cameras.items()
if not camera.startswith(REPLAY_CAMERA_PREFIX)
]
if self.dropped_frames.update({"all": max(dropped, default=0.0)}, now):
raise_notice("object_processing_behind")
# high ffmpeg and detect CPU # high ffmpeg and detect CPU
for tracker, kind, pid_key in ( for tracker, kind, pid_key in (
(self.ffmpeg_cpu, "ffmpeg_high_cpu", "ffmpeg_pid"), (self.ffmpeg_cpu, "ffmpeg_high_cpu", "ffmpeg_pid"),
+7 -16
View File
@@ -232,16 +232,16 @@ def embeddings_stats(
return stats return stats
def frame_percent(fps: float, camera_fps: float, enabled: bool) -> float: def skipped_percent(skipped_fps: float, camera_fps: float, enabled: bool) -> float:
"""Share of a camera's frames, in percent, that a rate such as skipped_fps represents. """Percent of a camera's frames dropped before detection.
camera_fps counts every frame read from the camera. A disabled camera keeps camera_fps counts the dropped frames too. A disabled camera keeps its last
its last readings, so it reports zero. readings, so it reports zero.
""" """
if not enabled or camera_fps <= 0: if not enabled or camera_fps <= 0:
return 0.0 return 0.0
return round(fps / camera_fps * 100, 1) return round(skipped_fps / camera_fps * 100, 1)
def get_go2rtc_pid(cpu_usages: dict[str, dict[str, Any]]) -> int | None: def get_go2rtc_pid(cpu_usages: dict[str, dict[str, Any]]) -> int | None:
@@ -262,8 +262,7 @@ def stats_snapshot(
camera_metrics = stats_tracking["camera_metrics"] camera_metrics = stats_tracking["camera_metrics"]
stats: dict[str, Any] = {} stats: dict[str, Any] = {}
total_camera_fps = total_process_fps = total_skipped_fps = total_dropped_fps = 0 total_camera_fps = total_process_fps = total_skipped_fps = total_detection_fps = 0
total_detection_fps = 0
stats["cameras"] = {} stats["cameras"] = {}
for name, camera_stats in list(camera_metrics.items()): for name, camera_stats in list(camera_metrics.items()):
@@ -274,7 +273,6 @@ def stats_snapshot(
total_camera_fps += camera_stats.camera_fps.value total_camera_fps += camera_stats.camera_fps.value
total_process_fps += camera_stats.process_fps.value total_process_fps += camera_stats.process_fps.value
total_skipped_fps += camera_stats.skipped_fps.value total_skipped_fps += camera_stats.skipped_fps.value
total_dropped_fps += camera_stats.dropped_fps.value
total_detection_fps += camera_stats.detection_fps.value total_detection_fps += camera_stats.detection_fps.value
pid = camera_stats.process_pid.value if camera_stats.process_pid.value else None pid = camera_stats.process_pid.value if camera_stats.process_pid.value else None
ffmpeg_pid = camera_stats.ffmpeg_pid.value if camera_stats.ffmpeg_pid else None ffmpeg_pid = camera_stats.ffmpeg_pid.value if camera_stats.ffmpeg_pid else None
@@ -313,17 +311,11 @@ def stats_snapshot(
"camera_fps": round(camera_stats.camera_fps.value, 2), "camera_fps": round(camera_stats.camera_fps.value, 2),
"process_fps": round(camera_stats.process_fps.value, 2), "process_fps": round(camera_stats.process_fps.value, 2),
"skipped_fps": round(camera_stats.skipped_fps.value, 2), "skipped_fps": round(camera_stats.skipped_fps.value, 2),
"skipped_pct": frame_percent( "skipped_pct": skipped_percent(
camera_stats.skipped_fps.value, camera_stats.skipped_fps.value,
current_fps, current_fps,
config.cameras[name].enabled, config.cameras[name].enabled,
), ),
"dropped_fps": round(camera_stats.dropped_fps.value, 2),
"dropped_pct": frame_percent(
camera_stats.dropped_fps.value,
current_fps,
config.cameras[name].enabled,
),
"detection_fps": round(camera_stats.detection_fps.value, 2), "detection_fps": round(camera_stats.detection_fps.value, 2),
"detection_enabled": camera_config.detect.enabled, "detection_enabled": camera_config.detect.enabled,
"pid": pid, "pid": pid,
@@ -338,7 +330,6 @@ def stats_snapshot(
stats["camera_fps"] = round(total_camera_fps, 2) stats["camera_fps"] = round(total_camera_fps, 2)
stats["process_fps"] = round(total_process_fps, 2) stats["process_fps"] = round(total_process_fps, 2)
stats["skipped_fps"] = round(total_skipped_fps, 2) stats["skipped_fps"] = round(total_skipped_fps, 2)
stats["dropped_fps"] = round(total_dropped_fps, 2)
stats["detection_fps"] = round(total_detection_fps, 2) stats["detection_fps"] = round(total_detection_fps, 2)
stats["embeddings"] = embeddings_stats( stats["embeddings"] = embeddings_stats(
+75 -4
View File
@@ -137,7 +137,7 @@ class StorageMaintainer(threading.Thread):
def calculate_camera_bandwidth(self) -> None: def calculate_camera_bandwidth(self) -> None:
"""Calculate an average MB/hr for each camera.""" """Calculate an average MB/hr for each camera."""
for camera in list(self.config.cameras): for camera in self.config.cameras.keys():
# Skip replay cameras # Skip replay cameras
if camera.startswith(REPLAY_CAMERA_PREFIX): if camera.startswith(REPLAY_CAMERA_PREFIX):
continue continue
@@ -186,7 +186,7 @@ class StorageMaintainer(threading.Thread):
"""Calculate the storage usage of each camera.""" """Calculate the storage usage of each camera."""
usages: dict[str, dict] = {} usages: dict[str, dict] = {}
for camera in list(self.config.cameras): for camera in self.config.cameras.keys():
# Skip replay cameras # Skip replay cameras
if camera.startswith(REPLAY_CAMERA_PREFIX): if camera.startswith(REPLAY_CAMERA_PREFIX):
continue continue
@@ -208,7 +208,10 @@ class StorageMaintainer(threading.Thread):
"bandwidth_by_stream", {} "bandwidth_by_stream", {}
) )
usages[camera] = { camera_key = (
getattr(self.config.cameras[camera], "friendly_name", None) or camera
)
usages[camera_key] = {
"usage": sum(stream_usages.values()), "usage": sum(stream_usages.values()),
"bandwidth": self.camera_storage_stats.get(camera, {}).get( "bandwidth": self.camera_storage_stats.get(camera, {}).get(
"bandwidth", 0 "bandwidth", 0
@@ -260,12 +263,53 @@ class StorageMaintainer(threading.Thread):
.iterator() .iterator()
) )
retained_events = (
Event.select(
Event.start_time,
Event.end_time,
)
.where(
Event.retain_indefinitely == True,
Event.has_clip,
)
.order_by(Event.start_time.asc())
.namedtuples()
)
event_start = 0
deleted_recordings = [] deleted_recordings = []
for recording in recordings: for recording in recordings:
# check if 1 hour of storage has been reclaimed # check if 1 hour of storage has been reclaimed
if deleted_segments_size > hourly_bandwidth: if deleted_segments_size > hourly_bandwidth:
break break
keep = False
# Now look for a reason to keep this recording segment
for idx in range(event_start, len(retained_events)):
event = retained_events[idx]
# if the event starts in the future, stop checking events
# and let this recording segment expire
if event.start_time > recording.end_time:
keep = False
break
# if the event is in progress or ends after the recording starts, keep it
# and stop looking at events
if event.end_time is None or event.end_time >= recording.start_time:
keep = True
break
# if the event ends before this recording segment starts, skip
# this event and check the next event for an overlap.
# since the events and recordings are sorted, we can skip events
# that end before the previous recording segment started on future segments
if event.end_time < recording.start_time:
event_start = idx
# Delete recordings not retained indefinitely
if not keep:
try: try:
clear_and_unlink(Path(recording.path), missing_ok=False) clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_recordings.append(recording) deleted_recordings.append(recording)
@@ -274,10 +318,37 @@ class StorageMaintainer(threading.Thread):
# this file was not found so we must assume no space was cleaned up # this file was not found so we must assume no space was cleaned up
pass pass
# check if need to delete retained segments
if deleted_segments_size < hourly_bandwidth: if deleted_segments_size < hourly_bandwidth:
logger.error( logger.error(
f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared." f"Could not clear {hourly_bandwidth} MB, currently {deleted_segments_size:.2f} MB have been cleared. Retained recordings must be deleted."
) )
recordings = (
Recordings.select(
Recordings.id,
Recordings.camera,
Recordings.start_time,
Recordings.end_time,
Recordings.path,
Recordings.segment_size,
)
.order_by(Recordings.start_time.asc())
.namedtuples()
.iterator()
)
for recording in recordings:
if deleted_segments_size > hourly_bandwidth:
break
try:
clear_and_unlink(Path(recording.path), missing_ok=False)
deleted_segments_size += recording.segment_size
deleted_recordings.append(recording)
except FileNotFoundError:
# this file was not found so we must assume no space was cleaned up
pass
self.retention_unmet = True self.retention_unmet = True
else: else:
logger.info(f"Cleaned up {deleted_segments_size:.2f} MB of recordings") logger.info(f"Cleaned up {deleted_segments_size:.2f} MB of recordings")
-178
View File
@@ -1,4 +1,3 @@
import copy
import json import json
import os import os
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
@@ -32,23 +31,6 @@ class TestHttpApp(BaseTestHttp):
response_json = response.json() response_json = response.json()
assert response_json == self.test_stats assert response_json == self.test_stats
def test_stats_endpoint_strips_cmdline_for_viewers(self):
stats = Mock(spec=StatsEmitter)
stats.get_latest_stats.return_value = {
**self.test_stats,
"cpu_usages": {"52": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
"bandwidth_usages": {"52": {"bandwidth": 1.0}},
}
app = super().create_app(stats)
with AuthTestClient(app) as client:
response = client.get(
"/stats",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.json()["cpu_usages"] == {"52": {"cpu": "1.0"}}
assert "bandwidth_usages" not in response.json()
def test_recordings_storage_requires_admin(self): def test_recordings_storage_requires_admin(self):
stats = Mock(spec=StatsEmitter) stats = Mock(spec=StatsEmitter)
stats.get_latest_stats.return_value = self.test_stats stats.get_latest_stats.return_value = self.test_stats
@@ -199,10 +181,6 @@ class TestHttpApp(BaseTestHttp):
def test_config_response_hides_notification_email_from_viewers(self): def test_config_response_hides_notification_email_from_viewers(self):
self.minimal_config["notifications"] = {"email": "{FRIGATE_TEST_EMAIL}"} self.minimal_config["notifications"] = {"email": "{FRIGATE_TEST_EMAIL}"}
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
self.minimal_config["cameras"]["front_door"]["profiles"] = {
"away": {"notifications": {"email": "{FRIGATE_TEST_EMAIL}"}}
}
with patch.dict(FRIGATE_ENV_VARS, {"FRIGATE_TEST_EMAIL": "me@example.com"}): with patch.dict(FRIGATE_ENV_VARS, {"FRIGATE_TEST_EMAIL": "me@example.com"}):
app = super().create_app() app = super().create_app()
@@ -221,166 +199,10 @@ class TestHttpApp(BaseTestHttp):
config["cameras"]["front_door"]["notifications"]["email"] config["cameras"]["front_door"]["notifications"]["email"]
== REDACTED_CREDENTIAL_SENTINEL == REDACTED_CREDENTIAL_SENTINEL
) )
assert (
config["cameras"]["front_door"]["profiles"]["away"]["notifications"][
"email"
]
== REDACTED_CREDENTIAL_SENTINEL
)
response = client.get("/config") response = client.get("/config")
assert response.json()["notifications"]["email"] == "me@example.com" assert response.json()["notifications"]["email"] == "me@example.com"
def test_config_response_limits_urls_and_go2rtc_for_viewers(self):
secret_path = "rtsp://10.0.0.1:554/user=admin_password=hunter2_channel=1"
self.minimal_config["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"] = (
secret_path
)
auth_header = "-headers 'Authorization: Basic c2VjcmV0'"
args = {
"global_args": auth_header,
"input_args": auth_header,
"output_args": {"detect": auth_header},
}
self.minimal_config["ffmpeg"] = dict(args)
front_door = self.minimal_config["cameras"]["front_door"]
front_door["ffmpeg"].update(args)
front_door["ffmpeg"]["inputs"][0].update(
global_args=auth_header, input_args=auth_header
)
front_door["webui_url"] = "http://admin:hunter2@10.0.0.1/"
self.minimal_config["go2rtc"] = {
"streams": {"front_door": [secret_path, "ffmpeg:front_door#audio=opus"]},
"webrtc": {"candidates": ["10.0.0.2:8555"]},
"webtorrent": {"shares": {"share": {"src": "front_door", "pwd": "x"}}},
}
app = super().create_app()
with AuthTestClient(app) as client:
response = client.get(
"/config",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.status_code == 200
config = response.json()
camera = config["cameras"]["front_door"]
assert camera["ffmpeg"]["inputs"][0]["path"] == ""
assert camera["ffmpeg_cmds"] == []
assert "webui_url" not in camera
assert "hunter2" not in response.text
assert "c2VjcmV0" not in response.text
assert config["go2rtc"] == {
"streams": {"front_door": []},
"webrtc": {"candidates": ["10.0.0.2:8555"]},
}
config = client.get("/config").json()
camera = config["cameras"]["front_door"]
assert camera["ffmpeg"]["inputs"][0]["path"] == secret_path
assert camera["ffmpeg"]["inputs"][0]["input_args"] == auth_header
assert camera["ffmpeg"]["input_args"] == auth_header
assert camera["ffmpeg_cmds"]
assert camera["detect_resolution_source"] == "config"
assert config["go2rtc"]["streams"]["front_door"][0] == secret_path
assert "webtorrent" in config["go2rtc"]
def test_config_response_hides_genai_endpoint_from_viewers(self):
self.minimal_config["genai"] = {
"local": {
"provider": "ollama",
"model": "llava",
"base_url": "http://user:pass@ollama:11434",
"provider_options": {"keep_alive": -1},
}
}
app = super().create_app()
with AuthTestClient(app) as client:
genai = client.get(
"/config",
headers={"remote-user": "viewer", "remote-role": "viewer"},
).json()["genai"]["local"]
assert "base_url" not in genai
assert "provider_options" not in genai
assert genai["provider"] == "ollama"
genai = client.get("/config").json()["genai"]["local"]
assert genai["base_url"] == "http://user:pass@ollama:11434"
def test_metrics_requires_admin(self):
stats = Mock(spec=StatsEmitter)
stats.get_latest_stats.return_value = self.test_stats
app = super().create_app(stats)
with AuthTestClient(app) as client:
response = client.get(
"/metrics",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.status_code == 403
assert client.get("/metrics").status_code == 200
def test_config_response_allows_null_profile_notifications(self):
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
self.minimal_config["cameras"]["front_door"]["profiles"] = {
"away": {"notifications": None}
}
app = super().create_app()
with AuthTestClient(app) as client:
response = client.get(
"/config",
headers={"remote-user": "viewer", "remote-role": "viewer"},
)
assert response.status_code == 200
def test_go2rtc_stream_producer_sources_hidden_from_viewers(self):
secret_url = "ffmpeg:rtsp://admin:hunter2@10.0.0.1:554/live"
stream = {
"producers": [
{
"url": secret_url,
"source": "ffmpeg -i rtsp://admin:hunter2@10.0.0.1:554/live",
"medias": ["video, recvonly, H264"],
}
],
"consumers": [{"url": "rtmp://a.rtmp.youtube.com/live2/hunter2"}],
}
app = super().create_app()
viewer = {"remote-user": "viewer", "remote-role": "viewer"}
with (
patch("frigate.api.camera.requests.get") as get,
AuthTestClient(app) as client,
):
get.return_value.json.side_effect = lambda: copy.deepcopy(stream)
viewer_stream = {"producers": [{"medias": ["video, recvonly, H264"]}]}
response = client.get("/go2rtc/streams/front_door", headers=viewer)
assert response.json() == viewer_stream
producer = client.get("/go2rtc/streams/front_door").json()["producers"][0]
assert producer["medias"] == ["video, recvonly, H264"]
assert "hunter2" not in producer["url"]
get.return_value.json.side_effect = lambda: {
"front_door": copy.deepcopy(stream)
}
response = client.get("/go2rtc/streams", headers=viewer)
assert response.json() == {"front_door": viewer_stream}
# unconnected streams have url-only producers and null consumers
get.return_value.json.side_effect = lambda: {
"front_door": {"producers": [{"url": secret_url}], "consumers": None}
}
response = client.get("/go2rtc/streams")
assert response.status_code == 200
assert "hunter2" not in response.text
response = client.get("/go2rtc/streams", headers=viewer)
assert response.json() == {"front_door": {"producers": [{"medias": None}]}}
def test_config_response_keeps_plus_model_reference(self): def test_config_response_keeps_plus_model_reference(self):
model_id = "test_plus_reference" model_id = "test_plus_reference"
model_path = os.path.join(MODEL_CACHE_DIR, model_id) model_path = os.path.join(MODEL_CACHE_DIR, model_id)
@@ -10,13 +10,7 @@ import ruamel.yaml
from frigate.models import Event, Recordings, ReviewSegment from frigate.models import Event, Recordings, ReviewSegment
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
from frigate.util.env import ( from frigate.util.env import _CONTAINER_ENV, FRIGATE_ENV_VARS, reload_sources
_CONFIG_ENV_VARS,
_CONTAINER_ENV,
FRIGATE_ENV_VARS,
apply_config_env_vars,
reload_sources,
)
# shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced # shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced
_INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'" _INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
@@ -24,8 +18,6 @@ _INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
# an unrestricted ffmpeg: source the operator already has in the file on disk # an unrestricted ffmpeg: source the operator already has in the file on disk
_EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn" _EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn"
_PLACEHOLDER_SRC = "ffmpeg:rtsp://10.0.0.1:554/{FRIGATE_CAM_PATH}"
_CONFIG = { _CONFIG = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}}, "go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}},
@@ -119,28 +111,6 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp):
headers={"Content-Type": "text/plain"}, headers={"Content-Type": "text/plain"},
) )
def _save(self, config: dict):
with AuthTestClient(self.app) as client:
return client.post(
"/config/save?save_option=saveonly",
content=_dump(config),
headers={"Content-Type": "text/plain"},
)
def _start_with_placeholder_source(self) -> dict:
"""Write and install a config whose stream reads FRIGATE_CAM_PATH from
environment_vars, as if Frigate had started with it."""
config = copy.deepcopy(_CONFIG)
config["environment_vars"] = {"FRIGATE_CAM_PATH": "video"}
config["go2rtc"]["streams"]["front_door"].append(_PLACEHOLDER_SRC)
with open(self.config_path, "w") as f:
f.write(_dump(config))
apply_config_env_vars(config["environment_vars"])
self.addCleanup(reload_sources, warn=False)
self.addCleanup(_CONFIG_ENV_VARS.clear)
return config
# --- config/set --- # --- config/set ---
def test_set_rejects_injected_ffmpeg_source(self): def test_set_rejects_injected_ffmpeg_source(self):
@@ -285,52 +255,6 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp):
assert resp.status_code == 200, resp.text assert resp.status_code == 200, resp.text
assert src in self._read_config() assert src in self._read_config()
def test_save_rejects_changed_env_var_in_existing_source(self):
config = self._start_with_placeholder_source()
before = self._read_config()
config["environment_vars"]["FRIGATE_CAM_PATH"] = "video#raw=-vn"
resp = self._save(config)
assert resp.status_code == 400
assert "Restricted go2rtc stream source" in resp.json()["message"]
assert self._read_config() == before
def test_save_allows_safe_env_var_change_in_existing_source(self):
config = self._start_with_placeholder_source()
config["environment_vars"]["FRIGATE_CAM_PATH"] = "video2"
resp = self._save(config)
assert resp.status_code == 200, resp.text
def test_save_resubmitting_placeholder_source_allowed(self):
config = self._start_with_placeholder_source()
resp = self._save(config)
assert resp.status_code == 200, resp.text
def test_save_rejects_removed_env_var_in_existing_source(self):
config = self._start_with_placeholder_source()
before = self._read_config()
del config["environment_vars"]
resp = self._save(config)
assert resp.status_code == 400
assert self._read_config() == before
def test_save_allows_env_var_added_with_its_source(self):
config = copy.deepcopy(_CONFIG)
config["environment_vars"] = {"FRIGATE_NEW_PATH": "video"}
config["go2rtc"]["streams"]["new_stream"] = (
"ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}"
)
resp = self._save(config)
assert resp.status_code == 200, resp.text
def test_save_rejects_unsafe_env_var_added_with_its_source(self):
config = copy.deepcopy(_CONFIG)
config["environment_vars"] = {"FRIGATE_NEW_PATH": "video#raw=-vn"}
config["go2rtc"]["streams"]["new_stream"] = (
"ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}"
)
resp = self._save(config)
assert resp.status_code == 400
# --- go2rtc ffmpeg and ngrok options --- # --- go2rtc ffmpeg and ngrok options ---
def test_save_rejects_ffmpeg_bin_override(self): def test_save_rejects_ffmpeg_bin_override(self):
@@ -624,96 +624,6 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
finally: finally:
os.unlink(config_path) os.unlink(config_path)
@patch.dict("frigate.util.env._CONFIG_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"})
@patch.dict("frigate.util.env.FRIGATE_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"})
@patch("frigate.api.app.find_config_file")
def test_masked_path_matches_after_saved_env_var_swap(self, mock_find_config):
"""A no-restart update swaps in a config resolved with the saved
environment_vars, so /config shows the saved value until a restart."""
path = "rtsp://admin:pw@{FRIGATE_CAM_HOST}:554/live"
self._set_inputs([(path, "detect")])
self.minimal_config["environment_vars"] = {"FRIGATE_CAM_HOST": "10.0.0.2"}
config_path = self._write_config_file()
mock_find_config.return_value = config_path
try:
app, _ = self._create_app_with_publisher()
with AuthTestClient(app) as client:
resp = self._save(
client, {"cameras": {"front_door": {"detect": {"fps": 6}}}}
)
self.assertEqual(resp.status_code, 200, resp.text)
camera = client.get("/config").json()["cameras"]["front_door"]
inputs = camera["ffmpeg"]["inputs"]
self.assertIn("10.0.0.2", inputs[0]["path"])
resp = self._save(
client,
{
"cameras": {
"front_door": {
"ffmpeg": {"inputs": inputs},
"detect": {"fps": 7},
}
}
},
)
self.assertEqual(resp.status_code, 200, resp.text)
_, saved = self._read_config_file(config_path)
self.assertEqual(
saved["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"], path
)
finally:
os.unlink(config_path)
@patch.dict(
"frigate.util.env._CONFIG_ENV_VARS",
{"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"},
)
@patch.dict(
"frigate.util.env.FRIGATE_ENV_VARS",
{"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"},
)
@patch("frigate.api.app.find_config_file")
def test_masked_paths_match_running_env_vars(self, mock_find_config):
"""A saved but not yet applied environment_vars change must not make
one input's masked path match another's."""
path_a = "rtsp://admin:pw@{FRIGATE_HOST_A}:554/live"
path_b = "rtsp://admin:pw@{FRIGATE_HOST_B}:554/live"
self._set_inputs([(path_a, "detect"), (path_b, "record")])
self.minimal_config["environment_vars"] = {
"FRIGATE_HOST_A": "10.0.0.1",
"FRIGATE_HOST_B": "10.0.0.2",
}
app, _ = self._create_app_with_publisher()
self.minimal_config["environment_vars"]["FRIGATE_HOST_A"] = "10.0.0.2"
config_path = self._write_config_file()
mock_find_config.return_value = config_path
try:
with AuthTestClient(app) as client:
camera = client.get("/config").json()["cameras"]["front_door"]
inputs = camera["ffmpeg"]["inputs"]
inputs[0]["roles"], inputs[1]["roles"] = ["record"], ["detect"]
resp = self._save(
client, {"cameras": {"front_door": {"ffmpeg": {"inputs": inputs}}}}
)
self.assertEqual(resp.status_code, 200, resp.text)
_, saved = self._read_config_file(config_path)
saved_inputs = saved["cameras"]["front_door"]["ffmpeg"]["inputs"]
self.assertEqual(
[(inp["path"], inp["roles"]) for inp in saved_inputs],
[(path_a, ["record"]), (path_b, ["detect"])],
)
finally:
os.unlink(config_path)
@patch("frigate.api.app.find_config_file") @patch("frigate.api.app.find_config_file")
def test_over_masked_path_round_trips(self, mock_find_config): def test_over_masked_path_round_trips(self, mock_find_config):
path = "rtsp://10.0.0.1:554/live?x=a@b" path = "rtsp://10.0.0.1:554/live?x=a@b"
+33 -3
View File
@@ -374,6 +374,22 @@ class TestHttpApp(BaseTestHttp):
event_after_delete = client.get(f"/events/{id}") event_after_delete = client.get(f"/events/{id}")
assert event_after_delete.status_code == 404 assert event_after_delete.status_code == 404
def test_event_retention(self):
id = "123456.random"
with AuthTestClient(self.app) as client:
super().insert_mock_event(id)
client.post(f"/events/{id}/retain", headers={"remote-role": "admin"})
event = client.get(f"/events/{id}").json()
assert event
assert event["id"] == id
assert event["retain_indefinitely"] is True
client.delete(f"/events/{id}/retain", headers={"remote-role": "admin"})
event = client.get(f"/events/{id}").json()
assert event
assert event["id"] == id
assert event["retain_indefinitely"] is False
def test_event_time_filtering(self): def test_event_time_filtering(self):
morning_id = "123456.random" morning_id = "123456.random"
evening_id = "654321.random" evening_id = "654321.random"
@@ -511,32 +527,42 @@ class TestHttpApp(BaseTestHttp):
with AuthTestClient(self.app) as client: with AuthTestClient(self.app) as client:
ts_start = datetime.now().timestamp() ts_start = datetime.now().timestamp()
ts_end = ts_start + 30 ts_end = ts_start + 30
_insert_mock_event(id="abcde.random", start=ts_start, end=ts_end) _insert_mock_event(
_insert_mock_event(id="01234.random", start=ts_start, end=ts_end) id="abcde.random", start=ts_start, end=ts_end, retain=True
_insert_mock_event(id="56789.random", start=ts_start, end=ts_end) )
_insert_mock_event(
id="01234.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event(
id="56789.random", start=ts_start, end=ts_end, retain=True
)
_insert_mock_event( _insert_mock_event(
id="101112.random", id="101112.random",
label="outside", label="outside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="131415.random", id="131415.random",
label="outside", label="outside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="161718.random", id="161718.random",
camera="porch", camera="porch",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="192021.random", id="192021.random",
camera="porch", camera="porch",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="222324.random", id="222324.random",
@@ -544,6 +570,7 @@ class TestHttpApp(BaseTestHttp):
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="252627.random", id="252627.random",
@@ -551,18 +578,21 @@ class TestHttpApp(BaseTestHttp):
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="282930.random", id="282930.random",
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
_insert_mock_event( _insert_mock_event(
id="313233.random", id="313233.random",
label="inside", label="inside",
start=ts_start, start=ts_start,
end=ts_end, end=ts_end,
retain=True,
) )
stats_emitter = Mock(spec=StatsEmitter) stats_emitter = Mock(spec=StatsEmitter)
-20
View File
@@ -14,7 +14,6 @@ from fastapi import Request
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user
from frigate.const import MAX_SEGMENT_DURATION from frigate.const import MAX_SEGMENT_DURATION
from frigate.models import Event, Recordings from frigate.models import Event, Recordings
from frigate.plus import PlusRateLimitError
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -2145,22 +2144,3 @@ class TestHttpMedia(BaseTestHttp):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
upload.assert_called_once_with("frame", "front_door") upload.assert_called_once_with("frame", "front_door")
def test_plus_snapshot_rate_limited(self):
self._insert_recording("snapshot", 1000, 1010)
with (
AuthTestClient(self.app) as client,
patch("frigate.api.media.get_image_from_recording", return_value=b"png"),
patch("frigate.api.media.cv2.imdecode", return_value="frame"),
patch.object(
self.app.frigate_config.plus_api,
"upload_image",
side_effect=PlusRateLimitError(60),
),
):
response = client.post("/front_door/plus/1005")
self.assertEqual(response.status_code, 429)
self.assertEqual(response.json()["retry_after"], 60)
self.assertEqual(response.headers["Retry-After"], "60")
+4 -120
View File
@@ -3,10 +3,8 @@
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
import numpy as np
from frigate.models import Event from frigate.models import Event
from frigate.plus import PlusKeyStatus, PlusRateLimitError from frigate.plus import PlusKeyStatus
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -14,13 +12,11 @@ class TestHttpPlusValidate(BaseTestHttp):
def setUp(self): def setUp(self):
super().setUp([Event]) super().setUp([Event])
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict: def _validate(self, status: PlusKeyStatus) -> dict:
app = self.create_app() app = self.create_app()
plus_api = app.frigate_config.plus_api
with ( with patch.object(
patch.object(plus_api, "validate_key", return_value=status), app.frigate_config.plus_api, "validate_key", return_value=status
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
): ):
with AuthTestClient(app) as client: with AuthTestClient(app) as client:
response = client.post("/plus/validate") response = client.post("/plus/validate")
@@ -39,12 +35,6 @@ class TestHttpPlusValidate(BaseTestHttp):
{"success": False, "status": "invalid"}, {"success": False, "status": "invalid"},
) )
def test_a_rate_limited_key_includes_the_wait(self):
self.assertEqual(
self._validate(PlusKeyStatus.rate_limited, 90),
{"success": False, "status": "rate_limited", "retry_after": 90},
)
def test_viewers_cannot_validate(self): def test_viewers_cannot_validate(self):
app = self.create_app() app = self.create_app()
@@ -57,111 +47,5 @@ class TestHttpPlusValidate(BaseTestHttp):
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
class TestHttpPlusRateLimit(BaseTestHttp):
"""A Frigate+ rate limit reaches the client as a 429 with the wait."""
def setUp(self):
super().setUp([Event])
self.app = self.create_app()
self.plus_api = self.app.frigate_config.plus_api
patcher = patch.object(self.plus_api, "is_active", return_value=True)
patcher.start()
self.addCleanup(patcher.stop)
def _assert_rate_limited(self, response, retry_after: int | None) -> None:
self.assertEqual(response.status_code, 429)
self.assertEqual(response.json()["retry_after"], retry_after)
self.assertFalse(response.json()["success"])
self.assertEqual(
response.headers.get("Retry-After"),
None if retry_after is None else str(retry_after),
)
def test_listing_models(self):
for retry_after in (30, None):
with (
self.subTest(retry_after=retry_after),
patch.object(
self.plus_api,
"get_models",
side_effect=PlusRateLimitError(retry_after),
),
AuthTestClient(self.app) as client,
):
self._assert_rate_limited(client.get("/plus/models"), retry_after)
def test_submitting_an_event(self):
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
with (
patch(
"frigate.api.event.load_event_snapshot_image",
return_value=(np.ones((10, 10, 3), np.uint8), True),
),
patch.object(
self.plus_api, "upload_image", side_effect=PlusRateLimitError(30)
),
AuthTestClient(self.app) as client,
):
response = client.post("/events/event/plus", json={})
self._assert_rate_limited(response, 30)
self.assertIsNone(Event.get(Event.id == "event").plus_id)
def test_a_rate_limited_annotation_can_be_retried(self):
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
snapshot = patch(
"frigate.api.event.load_event_snapshot_image",
return_value=(np.ones((10, 10, 3), np.uint8), True),
)
with (
snapshot,
patch.object(self.plus_api, "upload_image", return_value="img") as upload,
patch.object(
self.plus_api,
"add_annotation",
side_effect=[PlusRateLimitError(30), None],
) as annotate,
AuthTestClient(self.app) as client,
):
first = client.post("/events/event/plus", json={"include_annotation": 1})
# the image isn't marked submitted while its annotation is missing
self.assertIsNone(Event.get(Event.id == "event").plus_id)
retry = client.post("/events/event/plus", json={"include_annotation": 1})
self._assert_rate_limited(first, 30)
self.assertEqual(retry.status_code, 200)
self.assertEqual(retry.json()["plus_id"], "img")
upload.assert_called_once()
self.assertEqual(
[call.args[0] for call in annotate.call_args_list], ["img", "img"]
)
event = Event.get(Event.id == "event")
self.assertEqual(event.plus_id, "img")
self.assertNotIn("plus_pending_id", event.data)
def test_submitting_a_false_positive(self):
self.insert_mock_event(
"event", data={"box": [0, 0, 1, 1], "region": [0, 0, 1, 1], "score": 0.9}
)
Event.update(plus_id="plus").where(Event.id == "event").execute()
with (
patch.object(
self.plus_api,
"add_false_positive",
side_effect=PlusRateLimitError(45),
),
AuthTestClient(self.app) as client,
):
response = client.put("/events/event/false_positive")
self._assert_rate_limited(response, 45)
self.assertFalse(Event.get(Event.id == "event").false_positive)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)
@@ -1,98 +0,0 @@
"""Current-hour preview frame routes only return the requested camera's frames."""
import os
import shutil
import tempfile
import time
from unittest.mock import MagicMock, patch
from frigate.const import PREVIEW_FRAME_TYPE
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
CAMERA = "front_door"
# camera names that extend CAMERA with "-" share its file name prefix
SIBLINGS = (f"{CAMERA}-2", f"{CAMERA}-door")
class TestHttpPreviewFrames(BaseTestHttp):
def setUp(self):
super().setUp([])
self.app = super().create_app()
self.cache_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
os.makedirs(self.preview_dir)
for target, value in (
("frigate.api.media.CACHE_DIR", self.cache_dir),
("frigate.api.preview.CACHE_DIR", self.cache_dir),
("frigate.api.preview._preview_listing_cache", (-1.0, [])),
):
patcher = patch(target, value)
patcher.start()
self.addCleanup(patcher.stop)
# ahead of now so the media routes never fall back to stored previews
self.start_ts = time.time() + 60
self._write_frame(CAMERA, self.start_ts - 10)
self.own_frames = [self._write_frame(CAMERA, self.start_ts + 1)]
for sibling in SIBLINGS:
self._write_frame(sibling, self.start_ts + 1)
def _write_frame(self, camera: str, frame_time: float) -> str:
name = f"preview_{camera}-{frame_time}.{PREVIEW_FRAME_TYPE}"
with open(os.path.join(self.preview_dir, name), "wb") as f:
f.write(b"frame")
return name
def _concat_files(self, mock_run: MagicMock) -> set[str]:
concat = mock_run.call_args.kwargs["input"].decode()
return {
os.path.basename(line.split("'")[1])
for line in concat.splitlines()
if line.startswith("file ")
}
def test_frames_listing_excludes_sibling_camera(self):
with AuthTestClient(self.app) as client:
response = client.get(
f"/preview/{CAMERA}/start/{self.start_ts}/end/inf/frames"
)
assert response.status_code == 200
assert response.json() == self.own_frames
def test_preview_gif_excludes_sibling_camera(self):
result = MagicMock(returncode=0, stdout=b"GIF89a")
with (
patch("frigate.api.media.sp.run", return_value=result) as mock_run,
AuthTestClient(self.app) as client,
):
response = client.get(
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.gif"
)
assert response.status_code == 200
assert self._concat_files(mock_run) == set(self.own_frames)
def test_preview_mp4_excludes_sibling_camera(self):
def fake_run(cmd, **kwargs):
with open(cmd[-1], "wb") as f:
f.write(b"mp4")
return MagicMock(returncode=0)
with (
patch("frigate.api.media.sp.run", side_effect=fake_run) as mock_run,
AuthTestClient(self.app) as client,
):
response = client.get(
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.mp4"
)
assert response.status_code == 200
assert self._concat_files(mock_run) == set(self.own_frames)
-113
View File
@@ -1,5 +1,4 @@
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from urllib.parse import quote
from fastapi import Request from fastapi import Request
from peewee import DoesNotExist from peewee import DoesNotExist
@@ -277,82 +276,6 @@ class TestHttpReview(BaseTestHttp):
assert len(response_json) == 1 assert len(response_json) == 1
assert response_json[0]["id"] == id_reviewed assert response_json[0]["id"] == id_reviewed
def _insert_unordered_reviews(self, now: float) -> None:
"""Insert three reviews out of start-time order."""
super().insert_mock_review_segment("123456.middle", now - 200, now - 190)
super().insert_mock_review_segment("123456.newest", now - 100, now - 90)
super().insert_mock_review_segment("123456.oldest", now - 300, now - 290)
def test_get_review_sort_date_asc(self):
now = datetime.now().timestamp()
with AuthTestClient(self.app) as client:
self._insert_unordered_reviews(now)
response = client.get("/review", params={"sort": "date_asc"})
assert response.status_code == 200
assert [r["id"] for r in response.json()] == [
"123456.oldest",
"123456.middle",
"123456.newest",
]
def test_get_review_sort_date_desc(self):
now = datetime.now().timestamp()
with AuthTestClient(self.app) as client:
self._insert_unordered_reviews(now)
response = client.get("/review", params={"sort": "date_desc"})
assert response.status_code == 200
assert [r["id"] for r in response.json()] == [
"123456.newest",
"123456.middle",
"123456.oldest",
]
def test_get_review_sort_default_is_newest_first(self):
now = datetime.now().timestamp()
with AuthTestClient(self.app) as client:
self._insert_unordered_reviews(now)
response = client.get("/review")
assert response.status_code == 200
assert [r["id"] for r in response.json()] == [
"123456.newest",
"123456.middle",
"123456.oldest",
]
def test_get_review_sort_unknown_value_is_newest_first(self):
now = datetime.now().timestamp()
with AuthTestClient(self.app) as client:
self._insert_unordered_reviews(now)
response = client.get("/review", params={"sort": "score_asc"})
assert response.status_code == 200
assert [r["id"] for r in response.json()] == [
"123456.newest",
"123456.middle",
"123456.oldest",
]
def test_get_review_sort_date_asc_with_after_and_limit(self):
"""Test that date_asc with a limit returns the oldest reviews in the range."""
now = datetime.now().timestamp()
with AuthTestClient(self.app) as client:
super().insert_mock_review_segment("123456.third", now - 200, now - 190)
super().insert_mock_review_segment("123456.first", now - 400, now - 390)
super().insert_mock_review_segment("123456.too_early", now - 500, now - 490)
super().insert_mock_review_segment("123456.fourth", now - 100, now - 90)
super().insert_mock_review_segment("123456.second", now - 300, now - 290)
params = {"after": now - 450, "limit": 2, "sort": "date_asc"}
response = client.get("/review", params=params)
assert response.status_code == 200
assert [r["id"] for r in response.json()] == [
"123456.first",
"123456.second",
]
def test_get_review_with_label_filter_matches_verified(self): def test_get_review_with_label_filter_matches_verified(self):
"""Test that a label filter also matches the `-verified` variant.""" """Test that a label filter also matches the `-verified` variant."""
now = datetime.now().timestamp() now = datetime.now().timestamp()
@@ -917,42 +840,6 @@ class TestHttpReview(BaseTestHttp):
response_json, response_json,
) )
def test_review_event_wildcards_match_literally(self):
now = datetime.now().timestamp()
super().insert_mock_review_segment(
"123456.review.random",
now + 1,
now + 2,
data={"detections": ["1763812345.0-abc123"]},
)
with AuthTestClient(self.app) as client:
for pattern in ["1763812345*", "176381234?.0-abc123", "176381234[0-9]*"]:
response = client.get(f"/review/event/{quote(pattern, safe='')}")
assert response.status_code == 404
response = client.get("/review/event/1763812345.0-abc123")
assert response.status_code == 200
def test_review_event_on_forbidden_camera_is_not_found(self):
now = datetime.now().timestamp()
event_id = "1763812345.0-abc123"
super().insert_mock_review_segment(
"123456.review.random",
now + 1,
now + 2,
data={"detections": [event_id]},
camera="back_door",
)
with AuthTestClient(self.app) as client:
response = client.get(f"/review/event/{event_id}")
assert response.status_code == 404
self.assertDictEqual(
{"success": False, "message": "Review item not found"},
response.json(),
)
#################################################################################################################### ####################################################################################################################
################################### GET /review/{review_id} Endpoint ####################################### ################################### GET /review/{review_id} Endpoint #######################################
#################################################################################################################### ####################################################################################################################
+1 -69
View File
@@ -2,9 +2,7 @@
import multiprocessing as mp import multiprocessing as mp
import unittest import unittest
from unittest.mock import Mock, patch from unittest.mock import Mock
import numpy as np
from frigate.config import ( from frigate.config import (
BirdseyeModeEnum, BirdseyeModeEnum,
@@ -609,72 +607,6 @@ class TestBirdseyeModePayload(unittest.TestCase):
assert birdseye_modes_from_mqtt_payload(payload) is None assert birdseye_modes_from_mqtt_payload(payload) is None
class TestBirdseyeRuntimeToggles(unittest.TestCase):
"""Runtime config changes must not crash or overdrive Birdseye."""
def setUp(self):
config = {
"mqtt": {"enabled": False},
"birdseye": {"enabled": True, "modes": ["continuous"]},
"cameras": {
"front": {
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
}
},
}
self.config = FrigateConfig(**config)
self.manager = BirdsEyeFrameManager(self.config, mp.Event())
self.frame = np.zeros((1620, 1920), np.uint8)
self.activity = BirdseyeActivity(
has_object=True, has_motion=True, severity=None
)
def test_disabled_camera_forces_one_update_only(self):
self.manager.update("front", self.activity, 1000.0, self.frame)
self.config.cameras["front"].birdseye.enabled = False
changed, _ = self.manager.update("front", self.activity, 1000.2, self.frame)
assert changed
changed, _ = self.manager.update("front", self.activity, 1000.4, self.frame)
assert not changed
def test_enabling_restream_at_runtime_does_not_write_missing_buffer(self):
birdseye = Birdseye.__new__(Birdseye)
birdseye.restream = False
birdseye.config = self.config
birdseye.birdseye_manager = self.manager
birdseye.input = Mock()
self.config.birdseye.restream = True
birdseye._Birdseye__send_new_frame()
birdseye.input.put_nowait.assert_called_once()
def test_idle_heartbeat_waits_a_full_interval_between_sends(self):
birdseye = Birdseye.__new__(Birdseye)
birdseye.review_severity = {}
birdseye.birdseye_manager = Mock()
birdseye.birdseye_manager.update.return_value = (False, False)
birdseye.birdseye_manager.camera_layout = []
birdseye.birdseye_manager.last_output_time = 0.0
birdseye._idle_interval = 0.2
with (
patch.object(Birdseye, "_Birdseye__send_new_frame") as send,
patch("frigate.output.birdseye.time.monotonic", side_effect=[10.0, 10.1]),
):
birdseye.write_data("front", [], [], 1.0, Mock())
birdseye.write_data("front", [], [], 1.1, Mock())
assert send.call_count == 1
class TestBirdseyeReviewSeverity(unittest.TestCase): class TestBirdseyeReviewSeverity(unittest.TestCase):
"""Test that review updates drive the per-camera severity map.""" """Test that review updates drive the per-camera severity map."""
-38
View File
@@ -264,41 +264,3 @@ class TestCameraFileCleanup(unittest.TestCase):
] ]
self.assertEqual(remaining, other) self.assertEqual(remaining, other)
def test_delete_removes_recordings_and_keeps_colliding_dirs(self):
own = [
"recordings/2026-11-22/10/front/00.00.mp4",
"recordings/2026-11-22/10/front@sub/00.00.mp4",
"recordings/2026-11-23/03/front/10.00.mp4",
"clips/thumbs/front/a.webp",
"clips/previews/front/1.mp4",
"clips/lpr/front/a/1.jpg",
"clips/triggers/front/t.webp",
]
other = [
"recordings/2026-11-22/10/front_door/00.00.mp4",
"recordings/front/keep.mp4",
"clips/front/dataset/a.jpg",
"clips/thumbs/front_door/b.webp",
]
with tempfile.TemporaryDirectory() as root:
for name in own + other:
path = os.path.join(root, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
open(path, "w").close()
clips = os.path.join(root, "clips")
with patch.multiple(
camera_cleanup,
CLIPS_DIR=clips,
RECORD_DIR=os.path.join(root, "recordings"),
THUMB_DIR=os.path.join(clips, "thumbs"),
):
camera_cleanup.cleanup_camera_files("front")
remaining = [
n for n in own + other if os.path.exists(os.path.join(root, n))
]
self.assertEqual(remaining, other)
@@ -122,6 +122,7 @@ class TestExecuteFindSimilarObjects(unittest.TestCase):
region=[0, 0, 1, 1], region=[0, 0, 1, 1],
box=[0, 0, 1, 1], box=[0, 0, 1, 1],
area=1, area=1,
retain_indefinitely=False,
ratio=1.0, ratio=1.0,
plus_id="", plus_id="",
model_hash="", model_hash="",
+1 -48
View File
@@ -1,14 +1,12 @@
"""Tests for camera watch ownership in the chat tools.""" """Tests for camera watch ownership in the chat tools."""
import asyncio import asyncio
import threading
import unittest import unittest
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch from unittest.mock import AsyncMock, MagicMock, patch
from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch
from frigate.jobs.vlm_watch import MAX_WATCH_MINUTES, VLMWatchJob, VLMWatchRunner from frigate.jobs.vlm_watch import VLMWatchJob
from frigate.types import JobStatusTypesEnum
def _request(user: str, role: str) -> SimpleNamespace: def _request(user: str, role: str) -> SimpleNamespace:
@@ -60,51 +58,6 @@ class TestStartCameraWatch(unittest.TestCase):
self.assertEqual(start.call_args.kwargs["username"], "alice") self.assertEqual(start.call_args.kwargs["username"], "alice")
@patch("frigate.api.chat.require_camera_access", new_callable=AsyncMock)
@patch("frigate.api.chat.start_vlm_watch_job", return_value="job1")
def test_rejects_non_string_labels_and_clamps_duration(self, start, _access):
request = _request("alice", "viewer")
request.app = MagicMock()
request.app.frigate_config.cameras = {"front": None}
request.app.genai_manager.chat_client.supports_vision = True
arguments = {"camera": "front", "condition": "person"}
result = asyncio.run(
_execute_start_camera_watch(request, {**arguments, "labels": [1]})
)
self.assertIn("error", result)
start.assert_not_called()
asyncio.run(
_execute_start_camera_watch(
request, {**arguments, "max_duration_minutes": 1e308}
)
)
self.assertEqual(
start.call_args.kwargs["max_duration_minutes"], MAX_WATCH_MINUTES
)
class TestWatchRunnerSetup(unittest.TestCase):
@patch("frigate.jobs.vlm_watch.DetectionSubscriber")
@patch("frigate.jobs.vlm_watch.InterProcessRequestor")
def test_setup_error_fails_job_and_closes_sockets(self, requestor, subscriber):
job = VLMWatchJob(camera="front", condition="person", labels=[1])
runner = VLMWatchRunner(
job=job,
config=MagicMock(),
cancel_event=threading.Event(),
frame_processor=MagicMock(),
genai_manager=MagicMock(),
dispatcher=MagicMock(),
)
runner.run()
self.assertEqual(job.status, JobStatusTypesEnum.failed)
requestor.return_value.stop.assert_called_once()
subscriber.return_value.stop.assert_called_once()
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+1 -17
View File
@@ -22,7 +22,6 @@ from frigate.api.chat import (
_execute_pending_tools, _execute_pending_tools,
_pending_tool_calls_from_tail, _pending_tool_calls_from_tail,
_tool_calls_awaiting_approval, _tool_calls_awaiting_approval,
_with_server_ids,
) )
from frigate.api.defs.request.chat_body import ChatCompletionRequest from frigate.api.defs.request.chat_body import ChatCompletionRequest
from frigate.genai.prompts import ( from frigate.genai.prompts import (
@@ -153,22 +152,6 @@ class TestApprovalHelpers(unittest.TestCase):
body = _body(tool_decisions={"c2": "approve", "c3": "reject"}) body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), []) self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), [])
def test_repeated_provider_ids_get_unique_server_ids(self):
calls = [
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
]
renamed = _with_server_ids(calls)
self.assertEqual(len({tc["id"] for tc in renamed}), 2)
self.assertNotIn("set_camera_state", {tc["id"] for tc in renamed})
# A later call to the same tool is not covered by an earlier decision.
body = _body(tool_decisions={renamed[0]["id"]: "approve"})
later = _with_server_ids(calls[:1])
self.assertEqual(
len(_tool_calls_awaiting_approval(later, body, WRITE_TOOLS)), 1
)
class TestExecutePendingTools(unittest.TestCase): class TestExecutePendingTools(unittest.TestCase):
def test_rejected_call_is_not_executed(self): def test_rejected_call_is_not_executed(self):
@@ -259,6 +242,7 @@ class DatabaseTestCase(unittest.TestCase):
region=[0, 0, 1, 1], region=[0, 0, 1, 1],
box=[0, 0, 1, 1], box=[0, 0, 1, 1],
area=1, area=1,
retain_indefinitely=False,
ratio=1.0, ratio=1.0,
plus_id="", plus_id="",
model_hash="", model_hash="",
+1 -16
View File
@@ -7,10 +7,7 @@ from unittest.mock import patch
import numpy as np import numpy as np
from frigate.util.classification import ( from frigate.util.classification import _extract_event_thumbnails
_extract_event_thumbnails,
_select_balanced_timestamps,
)
class TestExtractEventThumbnails(unittest.TestCase): class TestExtractEventThumbnails(unittest.TestCase):
@@ -32,17 +29,5 @@ class TestExtractEventThumbnails(unittest.TestCase):
self.assertEqual(load.call_count, 7) self.assertEqual(load.call_count, 7)
class TestSelectBalancedTimestamps(unittest.TestCase):
def test_terminates_when_items_cannot_fill_target(self):
items = [
SimpleNamespace(camera="front", start_time=1000.0, end_time=1000.0),
SimpleNamespace(camera="front", start_time=2000.0, end_time=2001.0),
]
timestamps = _select_balanced_timestamps(items, target_count=100)
self.assertEqual(len(timestamps), 1)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+1 -97
View File
@@ -1,10 +1,9 @@
import json import json
import os import os
import pickle
import tempfile import tempfile
import unittest import unittest
from copy import deepcopy from copy import deepcopy
from unittest.mock import MagicMock, patch from unittest.mock import patch
import numpy as np import numpy as np
import requests import requests
@@ -15,7 +14,6 @@ from frigate.config import BirdseyeModeEnum, FrigateConfig, RetainModeEnum
from frigate.const import MODEL_CACHE_DIR from frigate.const import MODEL_CACHE_DIR
from frigate.detectors import DetectorTypeEnum from frigate.detectors import DetectorTypeEnum
from frigate.detectors.device import build_detector_config, runner_names from frigate.detectors.device import build_detector_config, runner_names
from frigate.plus import PlusApi, PlusRateLimitError
from frigate.util.builtin import deep_merge from frigate.util.builtin import deep_merge
from frigate.util.config import resolve_ffmpeg_path from frigate.util.config import resolve_ffmpeg_path
@@ -1639,60 +1637,6 @@ class TestConfig(unittest.TestCase):
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"): with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
FrigateConfig(**config) FrigateConfig(**config)
def _plus_model_config(self, model_id: str) -> dict:
return {
"mqtt": {"host": "mqtt"},
"models": [{"path": f"plus://{model_id}", "devices": ["cpu"]}],
"cameras": {
"back": {
"ffmpeg": {
"inputs": [
{
"path": "rtsp://10.0.0.1:554/video",
"roles": ["detect"],
},
]
},
}
},
}
@patch("frigate.detectors.detector_config.requests.get")
@patch(
"frigate.plus.PlusApi.get_model_download_url",
return_value="https://download.invalid/model",
)
def test_plus_model_error_response_is_not_saved(self, _, download):
model_id = "error_response_model"
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
download.return_value = MagicMock(ok=False, status_code=429, content=b"busy")
with self.assertRaisesRegex(ValidationError, r"HTTP 429"):
FrigateConfig(**self._plus_model_config(model_id))
self.assertFalse(os.path.exists(model_path))
def test_config_can_be_sent_to_a_worker_process(self):
# worker processes start from the forkserver, which pickles the config
# along with the Frigate+ client it holds
frigate_config = FrigateConfig(**self.minimal)
copy = pickle.loads(pickle.dumps(frigate_config))
self.assertIsInstance(copy.plus_api, PlusApi)
def test_plus_rate_limit_is_validation_error(self):
for retry_after, message in ((45, "Try again in 45 seconds"), (None, "later")):
with (
self.subTest(retry_after=retry_after),
patch(
"frigate.plus.PlusApi.get_model_download_url",
side_effect=PlusRateLimitError(retry_after),
),
self.assertRaisesRegex(ValidationError, f"rate limiting.*{message}"),
):
FrigateConfig(**self._plus_model_config("rate_limited_model"))
def test_fails_on_invalid_role(self): def test_fails_on_invalid_role(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
@@ -2483,45 +2427,5 @@ class TestFfmpegPath(unittest.TestCase):
) )
class TestDetectResolutionSource(unittest.TestCase):
def setUp(self):
self.config = {
"mqtt": {"host": "mqtt"},
"cameras": {
"back": {
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
]
},
}
},
}
def test_set_in_config(self):
self.config["cameras"]["back"]["detect"] = {"width": 1920, "height": 1080}
camera = FrigateConfig(**self.config).cameras["back"]
assert camera.detect_resolution_source == "config"
def test_set_globally(self):
self.config["detect"] = {"width": 1920, "height": 1080}
camera = FrigateConfig(**self.config).cameras["back"]
assert camera.detect_resolution_source == "config"
@patch(
"frigate.config.config.stream_info_retriever.get_stream_info",
return_value={"width": 2560, "height": 1440, "fourcc": "h264"},
)
def test_probed_from_stream(self, _):
camera = FrigateConfig(**self.config).cameras["back"]
assert camera.detect_resolution_source == "probed"
assert (camera.detect.width, camera.detect.height) == (2560, 1440)
def test_probe_failed_uses_default(self):
camera = FrigateConfig(**self.config).cameras["back"]
assert camera.detect_resolution_source == "default"
assert (camera.detect.width, camera.detect.height) == (1280, 720)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)
-1
View File
@@ -24,7 +24,6 @@ class TestSwapRuntimeConfig(unittest.TestCase):
self.assertIs(app.frigate_config, config) self.assertIs(app.frigate_config, config)
app.genai_manager.update_config.assert_called_once_with(config) app.genai_manager.update_config.assert_called_once_with(config)
app.replay_manager.update_config.assert_called_once_with(config)
app.profile_manager.update_config.assert_called_once_with(config) app.profile_manager.update_config.assert_called_once_with(config)
self.assertIs(app.stats_emitter.config, config) self.assertIs(app.stats_emitter.config, config)
app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config) app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config)
-100
View File
@@ -101,7 +101,6 @@ class TestDebugReplayManagerStop(unittest.TestCase):
manager.mark_session_ready("/tmp/replay/_replay_front.mp4") manager.mark_session_ready("/tmp/replay/_replay_front.mp4")
camera_config = MagicMock() camera_config = MagicMock()
manager._published_camera = camera_config
frigate_config = MagicMock() frigate_config = MagicMock()
frigate_config.cameras = {"_replay_front": camera_config} frigate_config.cameras = {"_replay_front": camera_config}
publisher = MagicMock() publisher = MagicMock()
@@ -170,7 +169,6 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
from frigate.debug_replay import DebugReplayManager from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager() manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
source_config = MagicMock() source_config = MagicMock()
new_camera_config = MagicMock() new_camera_config = MagicMock()
@@ -248,103 +246,5 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
publisher.publish_update.assert_not_called() publisher.publish_update.assert_not_called()
class TestDebugReplayManagerLifecycle(unittest.TestCase):
def setUp(self) -> None:
patcher = patch("frigate.debug_replay.JobStatePublisher")
patcher.start()
self.addCleanup(patcher.stop)
def _publish(self, manager, frigate_config, publisher) -> bool:
from frigate.debug_replay import DebugReplayManager
parsed = MagicMock()
parsed.cameras = {"_replay_front": MagicMock(name="replay_camera")}
with (
patch.object(
DebugReplayManager,
"_build_camera_config_dict",
return_value={"enabled": True},
),
patch("frigate.debug_replay.find_config_file", return_value="/cfg.yml"),
patch("frigate.debug_replay.YAML") as yaml_cls,
patch(
"frigate.debug_replay.FrigateConfig.parse_object",
return_value=parsed,
),
patch("builtins.open", unittest.mock.mock_open(read_data="cameras:\n")),
):
yaml_cls.return_value.load.return_value = {"cameras": {}}
return manager.publish_camera(
source_camera="front",
replay_name="_replay_front",
clip_path="/tmp/clip.mp4",
frigate_config=frigate_config,
config_publisher=publisher,
)
def _config(self, name: str) -> MagicMock:
config = MagicMock(name=name)
config.cameras = {"front": MagicMock()}
return config
def _stop(self, manager, frigate_config, publisher) -> None:
with (
patch.object(manager, "_cleanup_db"),
patch.object(manager, "_cleanup_files"),
patch("frigate.debug_replay.cancel_debug_replay_job", return_value=False),
):
manager.stop(frigate_config=frigate_config, config_publisher=publisher)
def test_publish_after_stop_is_skipped(self) -> None:
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
config = self._config("live")
publisher = MagicMock()
self._stop(manager, config, publisher)
self.assertFalse(self._publish(manager, config, publisher))
self.assertNotIn("_replay_front", config.cameras)
publisher.publish_update.assert_not_called()
def test_config_swap_keeps_replay_camera_and_stop_removes_it(self) -> None:
from frigate.config.camera.updater import CameraConfigUpdateEnum
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
boot = self._config("boot")
publisher = MagicMock()
self.assertTrue(self._publish(manager, boot, publisher))
swapped = self._config("swapped")
manager.update_config(swapped)
self.assertIn("_replay_front", swapped.cameras)
self._stop(manager, swapped, publisher)
topic = publisher.publish_update.call_args.args[0]
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
self.assertNotIn("_replay_front", swapped.cameras)
def test_stop_with_stale_config_still_publishes_remove(self) -> None:
from frigate.config.camera.updater import CameraConfigUpdateEnum
from frigate.debug_replay import DebugReplayManager
manager = DebugReplayManager()
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
live = self._config("live")
publisher = MagicMock()
self.assertTrue(self._publish(manager, live, publisher))
self._stop(manager, self._config("stale"), publisher)
topic = publisher.publish_update.call_args.args[0]
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+1 -1
View File
@@ -302,7 +302,7 @@ class TestRunnerHappyPath(unittest.TestCase):
patch.object( patch.object(
self.manager, self.manager,
"publish_camera", "publish_camera",
side_effect=lambda *a, **kw: captured.append("published") or True, side_effect=lambda *a, **kw: captured.append("published"),
), ),
patch("os.path.exists", return_value=True), patch("os.path.exists", return_value=True),
patch("os.makedirs"), patch("os.makedirs"),
+103
View File
@@ -0,0 +1,103 @@
"""Tests for the notice raised when object processing drops camera frames."""
import threading
import unittest
from unittest.mock import patch
from frigate.const import REPLAY_CAMERA_PREFIX
from frigate.notices.types import NOTICE_KINDS
from frigate.video.detect import (
DROPPED_FRAMES_NOTICE_COUNT,
DROPPED_FRAMES_NOTICE_INTERVAL_S,
DROPPED_FRAMES_WINDOW_S,
DroppedFrameTracker,
)
class TestDroppedFrameTracker(unittest.TestCase):
def setUp(self):
raise_patch = patch("frigate.video.detect.raise_notice")
self.raise_notice = raise_patch.start()
self.addCleanup(raise_patch.stop)
def _drop(self, tracker: DroppedFrameTracker, count: int, start: float) -> None:
for i in range(count):
tracker.dropped(start + i * 0.2)
# the notice is sent on a background thread
if tracker._sender is not None:
tracker._sender.join(timeout=5)
def test_kind_is_registered(self):
self.assertIn("object_processing_behind", NOTICE_KINDS)
def test_a_few_drops_raise_nothing(self):
tracker = DroppedFrameTracker("front_door")
self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT - 1, 0.0)
self.raise_notice.assert_not_called()
def test_enough_drops_raise_the_notice(self):
tracker = DroppedFrameTracker("front_door")
self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT, 0.0)
self.raise_notice.assert_called_once_with("object_processing_behind")
def test_drops_outside_the_window_do_not_add_up(self):
tracker = DroppedFrameTracker("front_door")
for i in range(DROPPED_FRAMES_NOTICE_COUNT):
tracker.dropped(i * (DROPPED_FRAMES_WINDOW_S + 1.0))
self.raise_notice.assert_not_called()
def test_repeats_wait_for_the_interval(self):
tracker = DroppedFrameTracker("front_door")
self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT, 0.0)
self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT * 2, 5.0)
self.assertEqual(self.raise_notice.call_count, 1)
self._drop(
tracker, DROPPED_FRAMES_NOTICE_COUNT, DROPPED_FRAMES_NOTICE_INTERVAL_S
)
self.assertEqual(self.raise_notice.call_count, 2)
def test_a_pending_send_does_not_block_or_start_another(self):
sending = threading.Event()
release = threading.Event()
def wait_for_reply(*_) -> None:
sending.set()
release.wait(5)
self.raise_notice.side_effect = wait_for_reply
tracker = DroppedFrameTracker("front_door")
# the first notice gets no reply while the second burst arrives
for i in range(DROPPED_FRAMES_NOTICE_COUNT):
tracker.dropped(i * 0.2)
self.assertTrue(sending.wait(5))
for i in range(DROPPED_FRAMES_NOTICE_COUNT):
tracker.dropped(DROPPED_FRAMES_NOTICE_INTERVAL_S + i * 0.2)
self.assertEqual(self.raise_notice.call_count, 1)
release.set()
assert tracker._sender is not None
tracker._sender.join(timeout=5)
def test_replay_camera_never_raises(self):
tracker = DroppedFrameTracker(f"{REPLAY_CAMERA_PREFIX}front_door")
self._drop(tracker, DROPPED_FRAMES_NOTICE_COUNT * 2, 0.0)
self.raise_notice.assert_not_called()
if __name__ == "__main__":
unittest.main()

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