mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-10-03 05:16:50 +03:00
Compare commits
9
Commits
master
..
6fe7d68fe7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fe7d68fe7 | ||
|
|
8731df9ce3 | ||
|
|
74c932c3f5 | ||
|
|
a0042b8d7f | ||
|
|
659d26658b | ||
|
|
6c47bbfbbc | ||
|
|
c4d53484b7 | ||
|
|
928dac506a | ||
|
|
c1bde8ca20 |
@@ -1,7 +1,7 @@
|
|||||||
default_target: local
|
default_target: local
|
||||||
|
|
||||||
COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1)
|
COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1)
|
||||||
VERSION = 0.18.1
|
VERSION = 0.19.0
|
||||||
IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate
|
IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate
|
||||||
GITHUB_REF_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
|
GITHUB_REF_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
|
||||||
BOARDS= #Initialized empty
|
BOARDS= #Initialized empty
|
||||||
|
|||||||
@@ -150,9 +150,7 @@ http {
|
|||||||
include auth_request.conf;
|
include auth_request.conf;
|
||||||
types {
|
types {
|
||||||
video/mp4 mp4;
|
video/mp4 mp4;
|
||||||
image/jpeg jpg jpeg;
|
image/jpeg jpg;
|
||||||
image/png png;
|
|
||||||
image/webp webp;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
expires 7d;
|
expires 7d;
|
||||||
|
|||||||
@@ -894,41 +894,6 @@ deepstack:
|
|||||||
api_url: http://<your_codeproject_ai_server_ip>:<port>/v1/vision/detection
|
api_url: http://<your_codeproject_ai_server_ip>:<port>/v1/vision/detection
|
||||||
type: deepstack
|
type: deepstack
|
||||||
api_timeout: 0.1 # seconds
|
api_timeout: 0.1 # seconds
|
||||||
xdna2:
|
|
||||||
title: AMD XDNA2
|
|
||||||
models:
|
|
||||||
- key: yolov9
|
|
||||||
label: YOLOv9
|
|
||||||
recommended: true
|
|
||||||
download: |-
|
|
||||||
Prepare the model using the frigate-xdna setup instructions linked above. For local YOLO models, Frigate must have access to the same ONNX file bytes as the sidecar. The example below uses YOLOv9-C at 320x320. Frigate+ models may instead use the same `plus://MODEL_ID` in Frigate and the sidecar.
|
|
||||||
ui: |-
|
|
||||||
Navigate to **Settings > System > Detectors and model** and select **ZMQ IPC** from the detector type dropdown and click **Add**, then set the endpoint to `tcp://xdna:5555`. Then on the same page, in the **Custom Model** tab, configure:
|
|
||||||
|
|
||||||
| Field | Value |
|
|
||||||
| ---------------------------------------- | ------------------------------------------ |
|
|
||||||
| **Custom object detector model path** | `/config/models/yolov9-c-320.onnx` |
|
|
||||||
| **Label map for custom object detector** | `/labelmap/coco-80.txt` |
|
|
||||||
| **Object detection model input width** | `320` |
|
|
||||||
| **Object detection model input height** | `320` |
|
|
||||||
| **Model Input Pixel Color Format** | `rgb` (Frigate's default value) |
|
|
||||||
| **Model Input Tensor Shape** | `nchw` |
|
|
||||||
| **Model Input D Type** | `float` |
|
|
||||||
| **Object Detection Model Type** | `yolo-generic` |
|
|
||||||
yaml: |-
|
|
||||||
detectors:
|
|
||||||
xdna:
|
|
||||||
type: zmq
|
|
||||||
endpoint: tcp://xdna:5555
|
|
||||||
|
|
||||||
model:
|
|
||||||
model_type: yolo-generic
|
|
||||||
width: 320
|
|
||||||
height: 320
|
|
||||||
input_tensor: nchw
|
|
||||||
input_dtype: float
|
|
||||||
path: /config/models/yolov9-c-320.onnx
|
|
||||||
labelmap_path: /labelmap/coco-80.txt
|
|
||||||
memryx:
|
memryx:
|
||||||
title: MemryX
|
title: MemryX
|
||||||
models:
|
models:
|
||||||
@@ -1135,7 +1100,7 @@ synaptics:
|
|||||||
- key: ssd
|
- key: ssd
|
||||||
label: SSD MobileNet
|
label: SSD MobileNet
|
||||||
recommended: true
|
recommended: true
|
||||||
download: A synap model is provided in the container at `/synaptics/mobilenet.synap` and is used by this detector type by default. The model comes from the [Synap-release Github](https://github.com/synaptics-astra/synap-release/tree/v1.5.0/models/dolphin/object_detection/coco/model/mobilenet224_full80).
|
download: A synap model is provided in the container at `/mobilenet.synap` and is used by this detector type by default. The model comes from the [Synap-release Github](https://github.com/synaptics-astra/synap-release/tree/v1.5.0/models/dolphin/object_detection/coco/model/mobilenet224_full80).
|
||||||
ui: |-
|
ui: |-
|
||||||
Navigate to **Settings > System > Detectors and model** and select **Synaptics** from the detector type dropdown and click **Add**. Then on the same page, in the **Custom Model** tab, configure:
|
Navigate to **Settings > System > Detectors and model** and select **Synaptics** from the detector type dropdown and click **Add**. Then on the same page, in the **Custom Model** tab, configure:
|
||||||
|
|
||||||
|
|||||||
@@ -251,11 +251,17 @@ birdseye:
|
|||||||
# Optional: Encoding quality of the mpeg1 feed (default: shown below)
|
# Optional: Encoding quality of the mpeg1 feed (default: shown below)
|
||||||
# 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources.
|
# 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources.
|
||||||
quality: 8
|
quality: 8
|
||||||
# Optional: Mode of the view. Available options are: objects, motion, and continuous
|
# Optional: Activity types that include cameras in Birdseye (default: shown below)
|
||||||
# objects - cameras are included if they have had a tracked object within the last 30 seconds
|
# Multiple activity types can be enabled at the same time.
|
||||||
# motion - cameras are included if motion was detected in the last 30 seconds
|
mode:
|
||||||
# continuous - all cameras are included always
|
# Optional: All cameras are included always (default: shown below)
|
||||||
mode: objects
|
continuous: False
|
||||||
|
# Optional: Cameras are included if motion was detected in the last 30 seconds (default: shown below)
|
||||||
|
motion: False
|
||||||
|
# Optional: Cameras are included if they have had an active tracked object within the last 30 seconds (default: shown below)
|
||||||
|
objects: True
|
||||||
|
# Optional: Cameras are included while they have a stationary tracked object (default: shown below)
|
||||||
|
stationary_objects: False
|
||||||
# Optional: Threshold for camera activity to stop showing camera (default: shown below)
|
# Optional: Threshold for camera activity to stop showing camera (default: shown below)
|
||||||
inactivity_threshold: 30
|
inactivity_threshold: 30
|
||||||
# Optional: Configure the birdseye layout
|
# Optional: Configure the birdseye layout
|
||||||
@@ -286,7 +292,7 @@ ffmpeg:
|
|||||||
# Optional: output args for detect streams (default: shown below)
|
# Optional: output args for detect streams (default: shown below)
|
||||||
detect: -threads 2 -f rawvideo -pix_fmt yuv420p
|
detect: -threads 2 -f rawvideo -pix_fmt yuv420p
|
||||||
# Optional: output args for record streams (default: shown below)
|
# Optional: output args for record streams (default: shown below)
|
||||||
record: preset-record-generic-audio-aac
|
record: preset-record-generic
|
||||||
# Optional: Time in seconds to wait before ffmpeg retries connecting to the camera. (default: shown below)
|
# Optional: Time in seconds to wait before ffmpeg retries connecting to the camera. (default: shown below)
|
||||||
# If set too low, frigate will retry a connection to the camera's stream too frequently, using up the limited streams some cameras can allow at once
|
# If set too low, frigate will retry a connection to the camera's stream too frequently, using up the limited streams some cameras can allow at once
|
||||||
# If set too high, then if a ffmpeg crash or camera stream timeout occurs, you could potentially lose up to a maximum of retry_interval second(s) of footage
|
# If set too high, then if a ffmpeg crash or camera stream timeout occurs, you could potentially lose up to a maximum of retry_interval second(s) of footage
|
||||||
|
|||||||
@@ -18,13 +18,14 @@ Each camera tile in Birdseye is composed from the frames of the stream assigned
|
|||||||
|
|
||||||
## Birdseye Behavior
|
## Birdseye Behavior
|
||||||
|
|
||||||
### Birdseye Modes
|
### Birdseye Activity Types
|
||||||
|
|
||||||
Birdseye offers different modes to customize which cameras show under which circumstances.
|
Birdseye offers independent activity types that control when cameras are shown. Multiple activity types can be enabled together.
|
||||||
|
|
||||||
- **continuous:** All cameras are always included
|
- **continuous:** The camera is always included
|
||||||
- **motion:** Cameras that have detected motion within the last 30 seconds are included
|
- **motion:** The camera is included when motion was detected within the last 30 seconds
|
||||||
- **objects:** Cameras that have tracked an active object within the last 30 seconds are included
|
- **objects:** The camera is included when an active object was tracked within the last 30 seconds
|
||||||
|
- **stationary_objects:** The camera is included while a stationary object is tracked
|
||||||
|
|
||||||
### Custom Birdseye Icon
|
### Custom Birdseye Icon
|
||||||
|
|
||||||
@@ -39,27 +40,30 @@ To include a camera in Birdseye view only for specific circumstances, or exclude
|
|||||||
|
|
||||||
**Global settings:** Navigate to <NavPath path="Settings > System > Birdseye" /> to configure the default Birdseye behavior for all cameras.
|
**Global settings:** Navigate to <NavPath path="Settings > System > Birdseye" /> to configure the default Birdseye behavior for all cameras.
|
||||||
|
|
||||||
**Per-camera overrides:** Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> to override the mode or disable Birdseye for a specific camera.
|
**Per-camera overrides:** Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> to override the activity types or disable Birdseye for a specific camera.
|
||||||
|
|
||||||
| Field | Description |
|
| Field | Description |
|
||||||
| ------------------- | ------------------------------------------------------------- |
|
| ---------------------- | ---------------------------------------------------------- |
|
||||||
| **Enable Birdseye** | Whether this camera appears in Birdseye view |
|
| **Enable Birdseye** | Whether this camera appears in Birdseye view |
|
||||||
| **Tracking mode** | When to show the camera: `continuous`, `motion`, or `objects` |
|
| **Activity types** | Conditions that determine when to show the camera |
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
<TabItem value="yaml">
|
<TabItem value="yaml">
|
||||||
|
|
||||||
```yaml {8-10,12-14}
|
```yaml {8-11,13-15}
|
||||||
# Include all cameras by default in Birdseye view
|
# Include all cameras by default in Birdseye view
|
||||||
birdseye:
|
birdseye:
|
||||||
enabled: True
|
enabled: True
|
||||||
mode: continuous
|
mode:
|
||||||
|
continuous: True
|
||||||
|
|
||||||
cameras:
|
cameras:
|
||||||
front:
|
front:
|
||||||
# Only include the "front" camera in Birdseye view when objects are detected
|
# Only include the "front" camera in Birdseye view when objects are detected
|
||||||
birdseye:
|
birdseye:
|
||||||
mode: objects
|
mode:
|
||||||
|
continuous: False
|
||||||
|
objects: True
|
||||||
back:
|
back:
|
||||||
# Exclude the "back" camera from Birdseye view
|
# Exclude the "back" camera from Birdseye view
|
||||||
birdseye:
|
birdseye:
|
||||||
|
|||||||
@@ -59,17 +59,13 @@ Running Generative AI models on CPU is not recommended, as high inference times
|
|||||||
|
|
||||||
### Recommended Local Models
|
### Recommended Local Models
|
||||||
|
|
||||||
#### Vision models
|
|
||||||
|
|
||||||
You must use a vision-capable model with Frigate. The following models are recommended for local deployment of the `descriptions` and `chat` roles:
|
You must use a vision-capable model with Frigate. The following models are recommended for local deployment of the `descriptions` and `chat` roles:
|
||||||
|
|
||||||
| Model | Notes |
|
| Model | Notes |
|
||||||
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `qwen3-vl` | Strong visual and situational understanding, enhanced ability to identify smaller objects and interactions with object. |
|
| `qwen3-vl` | Strong visual and situational understanding, enhanced ability to identify smaller objects and interactions with object. |
|
||||||
| `qwen3.6`/`qwen3.8` | Strong situational understanding, but missing DeepStack from qwen3-vl leading to worse performance for identifying objects in people's hand and other small details. |
|
| `qwen3.6` | Strong situational understanding, but missing DeepStack from qwen3-vl leading to worse performance for identifying objects in people's hand and other small details. |
|
||||||
| `gemma4` | Strong situational understanding, sometimes resorts to more vague terms like 'interacts' instead of assigning a specific action. |
|
| `gemma4` | Strong situational understanding, sometimes resorts to more vague terms like 'interacts' instead of assigning a specific action. |
|
||||||
|
|
||||||
#### Embedding models
|
|
||||||
|
|
||||||
The `embeddings` role needs a different kind of model. Text queries are matched against the stored image embeddings, so the model must be trained to place images and text into the same vector space. A chat or description model will still return vectors when asked, but those vectors are not trained for retrieval and text searches will return poor matches with no error to indicate why.
|
The `embeddings` role needs a different kind of model. Text queries are matched against the stored image embeddings, so the model must be trained to place images and text into the same vector space. A chat or description model will still return vectors when asked, but those vectors are not trained for retrieval and text searches will return poor matches with no error to indicate why.
|
||||||
|
|
||||||
|
|||||||
@@ -498,7 +498,7 @@ cameras:
|
|||||||
|
|
||||||
## Synaptics
|
## Synaptics
|
||||||
|
|
||||||
Hardware accelerated video de-/encoding is supported on Synaptics SL-series SoC.
|
Hardware accelerated video de-/encoding is supported on Synpatics SL-series SoC.
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import TabItem from "@theme/TabItem";
|
|||||||
import NavPath from "@site/src/components/NavPath";
|
import NavPath from "@site/src/components/NavPath";
|
||||||
import FaqItem from "@site/src/components/FaqItem";
|
import FaqItem from "@site/src/components/FaqItem";
|
||||||
|
|
||||||
Frigate can recognize license plates on vehicles and automatically add the detected characters to the `recognized_license_plate` field or a [known](#matching) name as a `sub_label` to tracked objects of type `car`, `motorcycle`, `bus`, `truck`, `school_bus`, or `garbage_truck`, depending on which of those labels your model detects. A common use case may be to read the license plates of cars pulling into a driveway or cars passing by on a street.
|
Frigate can recognize license plates on vehicles and automatically add the detected characters to the `recognized_license_plate` field or a [known](#matching) name as a `sub_label` to tracked objects of type `car` or `motorcycle`. A common use case may be to read the license plates of cars pulling into a driveway or cars passing by on a street.
|
||||||
|
|
||||||
LPR works best when the license plate is clearly visible to the camera. For moving vehicles, Frigate continuously refines the recognition process, keeping the most confident result. When a vehicle becomes stationary, LPR continues to run for a short time after to attempt recognition.
|
LPR works best when the license plate is clearly visible to the camera. For moving vehicles, Frigate continuously refines the recognition process, keeping the most confident result. When a vehicle becomes stationary, LPR continues to run for a short time after to attempt recognition.
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ When a plate is recognized, the details are:
|
|||||||
- Viewable in the Details pane in Review/History.
|
- Viewable in the Details pane in Review/History.
|
||||||
- Viewable in the Tracked Object Details pane in Explore (sub labels and recognized license plates).
|
- Viewable in the Tracked Object Details pane in Explore (sub labels and recognized license plates).
|
||||||
- Filterable through the More Filters menu in Explore.
|
- Filterable through the More Filters menu in Explore.
|
||||||
- Published via the `frigate/events` MQTT topic as a `sub_label` ([known](#matching)) or `recognized_license_plate` (unknown) for the vehicle tracked object.
|
- Published via the `frigate/events` MQTT topic as a `sub_label` ([known](#matching)) or `recognized_license_plate` (unknown) for the `car` or `motorcycle` tracked object.
|
||||||
- Published via the `frigate/tracked_object_update` MQTT topic with `name` (if [known](#matching)) and `plate`.
|
- Published via the `frigate/tracked_object_update` MQTT topic with `name` (if [known](#matching)) and `plate`.
|
||||||
|
|
||||||
## Model Requirements
|
## Model Requirements
|
||||||
@@ -35,7 +35,7 @@ Users without a model that detects license plates can still run LPR. Frigate use
|
|||||||
|
|
||||||
:::note
|
:::note
|
||||||
|
|
||||||
In the default mode, Frigate's LPR needs to first detect a vehicle before it can recognize a license plate. If you're using a dedicated LPR camera and have a zoomed-in view where a vehicle will not be detected, you can still run LPR, but the configuration parameters will differ from the default mode. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section below.
|
In the default mode, Frigate's LPR needs to first detect a `car` or `motorcycle` before it can recognize a license plate. If you're using a dedicated LPR camera and have a zoomed-in view where a `car` or `motorcycle` will not be detected, you can still run LPR, but the configuration parameters will differ from the default mode. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section below.
|
||||||
|
|
||||||
:::
|
:::
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ cameras:
|
|||||||
</TabItem>
|
</TabItem>
|
||||||
</ConfigTabs>
|
</ConfigTabs>
|
||||||
|
|
||||||
For non-dedicated LPR cameras, ensure that your camera is configured to detect vehicle objects, and that a vehicle is actually being detected by Frigate. Otherwise, LPR will not run. The object types that can carry a plate are defined by your model's `attributes_map`, so if your model detects other vehicle labels, you can add them there.
|
For non-dedicated LPR cameras, ensure that your camera is configured to detect objects of type `car` or `motorcycle`, and that a car or motorcycle is actually being detected by Frigate. Otherwise, LPR will not run.
|
||||||
|
|
||||||
Like the other real-time processors in Frigate, license plate recognition runs on the camera stream defined by the `detect` role in your config. To ensure optimal performance, select a suitable resolution for this stream in your camera's firmware that fits your specific scene and requirements.
|
Like the other real-time processors in Frigate, license plate recognition runs on the camera stream defined by the `detect` role in your config. To ensure optimal performance, select a suitable resolution for this stream in your camera's firmware that fits your specific scene and requirements.
|
||||||
|
|
||||||
@@ -158,7 +158,7 @@ lpr:
|
|||||||
|
|
||||||
Navigate to <NavPath path="Settings > Enrichments > License plate recognition" />.
|
Navigate to <NavPath path="Settings > Enrichments > License plate recognition" />.
|
||||||
|
|
||||||
- **Known plates**: Assign custom `sub_label` values to vehicle objects when a recognized plate matches a known value. These labels appear in the UI, filters, and notifications. Unknown plates are still saved but are added to the `recognized_license_plate` field rather than the `sub_label`.
|
- **Known plates**: Assign custom `sub_label` values to `car` and `motorcycle` objects when a recognized plate matches a known value. These labels appear in the UI, filters, and notifications. Unknown plates are still saved but are added to the `recognized_license_plate` field rather than the `sub_label`.
|
||||||
- **Match distance**: Allows for minor variations (missing/incorrect characters) when matching a detected plate to a known plate. For example, setting to `1` allows a plate `ABCDE` to match `ABCBE` or `ABCD`. This parameter will _not_ operate on known plates that are defined as regular expressions.
|
- **Match distance**: Allows for minor variations (missing/incorrect characters) when matching a detected plate to a known plate. For example, setting to `1` allows a plate `ABCDE` to match `ABCBE` or `ABCD`. This parameter will _not_ operate on known plates that are defined as regular expressions.
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
@@ -316,7 +316,7 @@ lpr:
|
|||||||
|
|
||||||
:::note
|
:::note
|
||||||
|
|
||||||
If a camera is configured to detect vehicles but you don't want Frigate to run LPR for that camera, disable LPR at the camera level:
|
If a camera is configured to detect `car` or `motorcycle` but you don't want Frigate to run LPR for that camera, disable LPR at the camera level:
|
||||||
|
|
||||||
<ConfigTabs>
|
<ConfigTabs>
|
||||||
<TabItem value="ui">
|
<TabItem value="ui">
|
||||||
@@ -378,10 +378,10 @@ Navigate to <NavPath path="Settings > Camera configuration > Object detection" /
|
|||||||
|
|
||||||
Navigate to <NavPath path="Settings > Camera configuration > Objects" />.
|
Navigate to <NavPath path="Settings > Camera configuration > Objects" />.
|
||||||
|
|
||||||
| Field | Description |
|
| Field | Description |
|
||||||
| --------------------------------------------------------- | ------------------- |
|
| ---------------------------------------------- | ------------------- |
|
||||||
| **Objects to track** | Add `license_plate` |
|
| **Objects to track** | Add `license_plate` |
|
||||||
| **Object filters > License Plate > Confidence threshold** | Set to `0.7` |
|
| **Object filters > License Plate > Threshold** | Set to `0.7` |
|
||||||
|
|
||||||
Navigate to <NavPath path="Settings > Camera configuration > Motion detection" />.
|
Navigate to <NavPath path="Settings > Camera configuration > Motion detection" />.
|
||||||
|
|
||||||
@@ -456,7 +456,7 @@ With this setup:
|
|||||||
- Snapshots will have license plate bounding boxes on them.
|
- Snapshots will have license plate bounding boxes on them.
|
||||||
- The `frigate/events` MQTT topic will publish tracked object updates.
|
- The `frigate/events` MQTT topic will publish tracked object updates.
|
||||||
- Debug view will display `license_plate` bounding boxes.
|
- Debug view will display `license_plate` bounding boxes.
|
||||||
- If you are using a Frigate+ model and want to submit images from your dedicated LPR camera for model training and fine-tuning, annotate both the vehicle and the `license_plate` in the snapshots on the Frigate+ website, even if the vehicle is barely visible.
|
- If you are using a Frigate+ model and want to submit images from your dedicated LPR camera for model training and fine-tuning, annotate both the `car` / `motorcycle` and the `license_plate` in the snapshots on the Frigate+ website, even if the car is barely visible.
|
||||||
|
|
||||||
### Using the Secondary LPR Pipeline (Without Frigate+)
|
### Using the Secondary LPR Pipeline (Without Frigate+)
|
||||||
|
|
||||||
@@ -611,9 +611,9 @@ If you are still having issues detecting plates, start with a basic configuratio
|
|||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
|
|
||||||
<FaqItem id="can-i-run-lpr-without-detecting-car-or-motorcycle-objects" question={<>Can I run LPR without detecting vehicle objects?</>}>
|
<FaqItem id="can-i-run-lpr-without-detecting-car-or-motorcycle-objects" question={<>Can I run LPR without detecting <code>car</code> or <code>motorcycle</code> objects?</>}>
|
||||||
|
|
||||||
In normal LPR mode, Frigate requires a vehicle to be detected first before recognizing a license plate. If you have a dedicated LPR camera, you can change the camera `type` to `"lpr"` to use the Dedicated LPR Camera algorithm. This comes with important caveats, though. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section above.
|
In normal LPR mode, Frigate requires a `car` or `motorcycle` to be detected first before recognizing a license plate. If you have a dedicated LPR camera, you can change the camera `type` to `"lpr"` to use the Dedicated LPR Camera algorithm. This comes with important caveats, though. See the [Dedicated LPR Cameras](#dedicated-lpr-cameras) section above.
|
||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
|
|
||||||
@@ -699,7 +699,7 @@ lpr:
|
|||||||
4. Ensure the characters on detected plates are being _recognized_.
|
4. Ensure the characters on detected plates are being _recognized_.
|
||||||
- Check the **Plate recognition** inference time in Enrichment metrics (<NavPath path="System metrics > Enrichments" />). High inference times (> 100ms) could lead to poor recognition results, especially for dedicated LPR cameras where the plate crosses the frame quickly.
|
- Check the **Plate recognition** inference time in Enrichment metrics (<NavPath path="System metrics > Enrichments" />). High inference times (> 100ms) could lead to poor recognition results, especially for dedicated LPR cameras where the plate crosses the frame quickly.
|
||||||
- Enable `debug_save_plates` to save images of detected text on plates to the clips directory (`/media/frigate/clips/lpr`). Ensure these images are readable and the text is clear.
|
- Enable `debug_save_plates` to save images of detected text on plates to the clips directory (`/media/frigate/clips/lpr`). Ensure these images are readable and the text is clear.
|
||||||
- Watch the debug view to see plates recognized in real-time. For non-dedicated LPR cameras, the vehicle's label will change to the recognized plate when LPR is enabled and working.
|
- Watch the debug view to see plates recognized in real-time. For non-dedicated LPR cameras, the `car` or `motorcycle` label will change to the recognized plate when LPR is enabled and working.
|
||||||
- Adjust `recognition_threshold` settings per the suggestions [above](#advanced-configuration).
|
- Adjust `recognition_threshold` settings per the suggestions [above](#advanced-configuration).
|
||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
@@ -714,13 +714,13 @@ LPR's performance impact depends on your hardware. Ensure you have at least 4GB
|
|||||||
|
|
||||||
The YOLOv9 license plate detector model will run (and the metric will appear) if you've enabled LPR but haven't defined `license_plate` as an object to track, either at the global or camera level.
|
The YOLOv9 license plate detector model will run (and the metric will appear) if you've enabled LPR but haven't defined `license_plate` as an object to track, either at the global or camera level.
|
||||||
|
|
||||||
If you are detecting vehicles on cameras where you don't want to run LPR, make sure you disable LPR it at the camera level. And if you do want to run LPR on those cameras, make sure you define `license_plate` as an object to track.
|
If you are detecting `car` or `motorcycle` on cameras where you don't want to run LPR, make sure you disable LPR it at the camera level. And if you do want to run LPR on those cameras, make sure you define `license_plate` as an object to track.
|
||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
|
|
||||||
<FaqItem id="it-looks-like-frigate-picked-up-my-cameras-timestamp-or-overlay-text-as-the-license-plate-how-can-i-prevent-this" question="It looks like Frigate picked up my camera's timestamp or overlay text as the license plate. How can I prevent this?">
|
<FaqItem id="it-looks-like-frigate-picked-up-my-cameras-timestamp-or-overlay-text-as-the-license-plate-how-can-i-prevent-this" question="It looks like Frigate picked up my camera's timestamp or overlay text as the license plate. How can I prevent this?">
|
||||||
|
|
||||||
This could happen if vehicles travel close to your camera's timestamp or overlay text. You could either move the text through your camera's firmware, or apply a mask to it in Frigate.
|
This could happen if cars or motorcycles travel close to your camera's timestamp or overlay text. You could either move the text through your camera's firmware, or apply a mask to it in Frigate.
|
||||||
|
|
||||||
If you are using a model that natively detects `license_plate`, add an _object mask_ of type `license_plate` and a _motion mask_ over your text.
|
If you are using a model that natively detects `license_plate`, add an _object mask_ of type `license_plate` and a _motion mask_ over your text.
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ Frigate supports multiple different detectors that work on different types of ha
|
|||||||
|
|
||||||
- [ROCm](#amdrocm-gpu-detector): ROCm can run on AMD Discrete GPUs to provide efficient object detection.
|
- [ROCm](#amdrocm-gpu-detector): ROCm can run on AMD Discrete GPUs to provide efficient object detection.
|
||||||
- [ONNX](#onnx): ROCm will automatically be detected and used as a detector in the `-rocm` Frigate image when a supported ONNX model is configured.
|
- [ONNX](#onnx): ROCm will automatically be detected and used as a detector in the `-rocm` Frigate image when a supported ONNX model is configured.
|
||||||
- <CommunityBadge /> [XDNA2](#amd-xdna2): AMD Ryzen AI / XDNA2 NPUs can run object detection through the community-maintained `frigate-xdna` ZMQ sidecar.
|
|
||||||
|
|
||||||
**Apple Silicon**
|
**Apple Silicon**
|
||||||
|
|
||||||
@@ -509,28 +508,6 @@ To verify that the integration is working correctly, start Frigate and observe t
|
|||||||
|
|
||||||
# Community Supported Detectors
|
# Community Supported Detectors
|
||||||
|
|
||||||
## AMD XDNA2
|
|
||||||
|
|
||||||
AMD Ryzen AI / XDNA2 NPUs can be used through the community-maintained
|
|
||||||
[frigate-xdna](https://github.com/mitchins/frigate-xdna) detector sidecar.
|
|
||||||
The sidecar runs separately from Frigate and connects using Frigate's ZMQ
|
|
||||||
detector interface.
|
|
||||||
|
|
||||||
Currently qualified on **Ryzen AI Max 300 / Strix Halo**. Other XDNA2 devices
|
|
||||||
are not yet qualified; XDNA1 is unsupported.
|
|
||||||
|
|
||||||
Follow the frigate-xdna setup instructions to prepare and start the sidecar
|
|
||||||
before starting Frigate.
|
|
||||||
|
|
||||||
### Configuration {#configuration-xdna2}
|
|
||||||
|
|
||||||
Using the detector config below will connect Frigate to the sidecar:
|
|
||||||
|
|
||||||
<ModelConfigDropdown detectorTitle="AMD XDNA2" models={objectDetectorsModels.xdna2.models} />
|
|
||||||
|
|
||||||
The example assumes Frigate and the sidecar share a Docker network where the
|
|
||||||
sidecar is named `xdna`.
|
|
||||||
|
|
||||||
## MemryX MX3
|
## MemryX MX3
|
||||||
|
|
||||||
This detector is available for use with the MemryX MX3 accelerator M.2 module. Frigate supports the MX3 on compatible hardware platforms, providing efficient and high-performance object detection.
|
This detector is available for use with the MemryX MX3 accelerator M.2 module. Frigate supports the MX3 on compatible hardware platforms, providing efficient and high-performance object detection.
|
||||||
|
|||||||
@@ -45,10 +45,10 @@ Any detection below `min_score` will be immediately thrown out and never tracked
|
|||||||
|
|
||||||
Navigate to <NavPath path="Settings > Global configuration > Objects" /> to set score filters globally.
|
Navigate to <NavPath path="Settings > Global configuration > Objects" /> to set score filters globally.
|
||||||
|
|
||||||
| Field | Description |
|
| Field | Description |
|
||||||
| -------------------------------------------------- | ---------------------------------------------------------------- |
|
| --------------------------------------- | ---------------------------------------------------------------- |
|
||||||
| **Object filters > Person > Minimum confidence** | Minimum score for a single detection to initiate tracking |
|
| **Object filters > Person > Min Score** | Minimum score for a single detection to initiate tracking |
|
||||||
| **Object filters > Person > Confidence threshold** | Minimum computed (median) score to be considered a true positive |
|
| **Object filters > Person > Threshold** | Minimum computed (median) score to be considered a true positive |
|
||||||
|
|
||||||
To override score filters for a specific camera, navigate to <NavPath path="Settings > Camera configuration > Objects" /> and select the camera.
|
To override score filters for a specific camera, navigate to <NavPath path="Settings > Camera configuration > Objects" /> and select the camera.
|
||||||
|
|
||||||
@@ -103,12 +103,12 @@ Conceptually, a ratio of 1 is a square, 0.5 is a "tall skinny" box, and 2 is a "
|
|||||||
|
|
||||||
Navigate to <NavPath path="Settings > Global configuration > Objects" /> to set shape filters globally.
|
Navigate to <NavPath path="Settings > Global configuration > Objects" /> to set shape filters globally.
|
||||||
|
|
||||||
| Field | Description |
|
| Field | Description |
|
||||||
| -------------------------------------------------- | ------------------------------------------------------------------------ |
|
| --------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
| **Object filters > Person > Minimum object area** | Minimum bounding box area in pixels (or decimal for percentage of frame) |
|
| **Object filters > Person > Min Area** | Minimum bounding box area in pixels (or decimal for percentage of frame) |
|
||||||
| **Object filters > Person > Maximum object area** | Maximum bounding box area in pixels (or decimal for percentage of frame) |
|
| **Object filters > Person > Max Area** | Maximum bounding box area in pixels (or decimal for percentage of frame) |
|
||||||
| **Object filters > Person > Minimum aspect ratio** | Minimum width/height ratio of the bounding box |
|
| **Object filters > Person > Min Ratio** | Minimum width/height ratio of the bounding box |
|
||||||
| **Object filters > Person > Maximum aspect ratio** | Maximum width/height ratio of the bounding box |
|
| **Object filters > Person > Max Ratio** | Maximum width/height ratio of the bounding box |
|
||||||
|
|
||||||
To override shape filters for a specific camera, navigate to <NavPath path="Settings > Camera configuration > Objects" /> and select the camera.
|
To override shape filters for a specific camera, navigate to <NavPath path="Settings > Camera configuration > Objects" /> and select the camera.
|
||||||
|
|
||||||
|
|||||||
@@ -70,14 +70,14 @@ Object filters help reduce false positives by constraining the size, shape, and
|
|||||||
|
|
||||||
Navigate to <NavPath path="Settings > Global configuration > Objects" />.
|
Navigate to <NavPath path="Settings > Global configuration > Objects" />.
|
||||||
|
|
||||||
| Field | Description |
|
| Field | Description |
|
||||||
| -------------------------------------------------- | ------------------------------------------------------------------------ |
|
| --------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
| **Object filters > Person > Minimum object area** | Minimum bounding box area in pixels (or decimal for percentage of frame) |
|
| **Object filters > Person > Min Area** | Minimum bounding box area in pixels (or decimal for percentage of frame) |
|
||||||
| **Object filters > Person > Maximum object area** | Maximum bounding box area in pixels (or decimal for percentage of frame) |
|
| **Object filters > Person > Max Area** | Maximum bounding box area in pixels (or decimal for percentage of frame) |
|
||||||
| **Object filters > Person > Minimum aspect ratio** | Minimum width/height ratio of the bounding box |
|
| **Object filters > Person > Min Ratio** | Minimum width/height ratio of the bounding box |
|
||||||
| **Object filters > Person > Maximum aspect ratio** | Maximum width/height ratio of the bounding box |
|
| **Object filters > Person > Max Ratio** | Maximum width/height ratio of the bounding box |
|
||||||
| **Object filters > Person > Minimum confidence** | Minimum score for the object to initiate tracking |
|
| **Object filters > Person > Min Score** | Minimum score for the object to initiate tracking |
|
||||||
| **Object filters > Person > Confidence threshold** | Minimum computed score to be considered a true positive |
|
| **Object filters > Person > Threshold** | Minimum computed score to be considered a true positive |
|
||||||
|
|
||||||
To override filters for a specific camera, navigate to <NavPath path="Settings > Camera configuration > Objects" />.
|
To override filters for a specific camera, navigate to <NavPath path="Settings > Camera configuration > Objects" />.
|
||||||
|
|
||||||
|
|||||||
@@ -191,12 +191,14 @@ cameras:
|
|||||||
detect:
|
detect:
|
||||||
enabled: false
|
enabled: false
|
||||||
record:
|
record:
|
||||||
enabled: true
|
enabled: false
|
||||||
profiles:
|
profiles:
|
||||||
away:
|
away:
|
||||||
enabled: true
|
enabled: true
|
||||||
detect:
|
detect:
|
||||||
enabled: true
|
enabled: true
|
||||||
|
record:
|
||||||
|
enabled: true
|
||||||
home:
|
home:
|
||||||
enabled: false
|
enabled: false
|
||||||
```
|
```
|
||||||
@@ -249,12 +251,6 @@ Leaving the `objects` section empty (or omitting `track`) does not clear the lis
|
|||||||
|
|
||||||
Fields that require a Frigate restart to take effect cannot be overridden by profiles, since profiles are applied at runtime without restarting. Those fields are hidden when editing a profile override and can only be changed on the base configuration.
|
Fields that require a Frigate restart to take effect cannot be overridden by profiles, since profiles are applied at runtime without restarting. Those fields are hidden when editing a profile override and can only be changed on the base configuration.
|
||||||
|
|
||||||
### Why can't a profile enable recording when it's disabled in the base config?
|
|
||||||
|
|
||||||
Frigate only sets up a camera's recording stream at startup when recording is enabled in the base config, so enabling it later from a profile has no effect. The same applies to turning recording on from the UI or MQTT.
|
|
||||||
|
|
||||||
To keep recording off by default, leave `record.enabled: true` in the base config and create a profile that sets `record.enabled: false`. Activate that profile and it will be restored automatically when Frigate starts.
|
|
||||||
|
|
||||||
### Can I schedule profiles to be enabled or disabled at certain times?
|
### Can I schedule profiles to be enabled or disabled at certain times?
|
||||||
|
|
||||||
Not within Frigate itself. Frigate is an NVR, not an automation platform, so it intentionally does not include a scheduler for activating profiles. Instead, activate profiles from an automation platform that already handles time- and event-based triggers well, such as [Home Assistant](https://www.home-assistant.io/) or [Node-RED](https://nodered.org/). These integrate with Frigate and give you far more robust and flexible scheduling than a built-in scheduler could.
|
Not within Frigate itself. Frigate is an NVR, not an automation platform, so it intentionally does not include a scheduler for activating profiles. Instead, activate profiles from an automation platform that already handles time- and event-based triggers well, such as [Home Assistant](https://www.home-assistant.io/) or [Node-RED](https://nodered.org/). These integrate with Frigate and give you far more robust and flexible scheduling than a built-in scheduler could.
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
|
|||||||
|
|
||||||
Recordings can be enabled and are stored at `/media/frigate/recordings`. The folder structure for the recordings is `YYYY-MM-DD/HH/<camera_name>/MM.SS.mp4` in **UTC time**. These recordings are written directly from your camera stream without re-encoding. Each camera supports a configurable retention policy. Frigate chooses the largest matching retention value between the recording retention and the tracked object retention when determining if a recording should be removed.
|
Recordings can be enabled and are stored at `/media/frigate/recordings`. The folder structure for the recordings is `YYYY-MM-DD/HH/<camera_name>/MM.SS.mp4` in **UTC time**. These recordings are written directly from your camera stream without re-encoding. Each camera supports a configurable retention policy. Frigate chooses the largest matching retention value between the recording retention and the tracked object retention when determining if a recording should be removed.
|
||||||
|
|
||||||
New recording segments are written from the camera stream to cache, they are only moved to disk if they pass a validation check and match the setup recording retention policy.
|
New recording segments are written from the camera stream to cache, they are only moved to disk if they match the setup recording retention policy.
|
||||||
|
|
||||||
:::tip
|
:::tip
|
||||||
|
|
||||||
@@ -291,7 +291,7 @@ For advanced use cases, the [custom export HTTP API](../integrations/api/export-
|
|||||||
POST /export/custom/{camera_name}/start/{start_time}/end/{end_time}
|
POST /export/custom/{camera_name}/start/{start_time}/end/{end_time}
|
||||||
```
|
```
|
||||||
|
|
||||||
The request body accepts `ffmpeg_input_args` and `ffmpeg_output_args` to control encoding, frame rate, filters, and other FFmpeg options. If neither is provided, Frigate defaults to time-lapse output settings (25x speed, 30 FPS) with audio removed (`-an`). When providing your own `ffmpeg_input_args`, include `-an` if you want audio stripped from the export.
|
The request body accepts `ffmpeg_input_args` and `ffmpeg_output_args` to control encoding, frame rate, filters, and other FFmpeg options. If neither is provided, Frigate defaults to time-lapse output settings (25x speed, 30 FPS).
|
||||||
|
|
||||||
The following example exports a time-lapse at 60x speed with 25 FPS:
|
The following example exports a time-lapse at 60x speed with 25 FPS:
|
||||||
|
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ For cameras that support two-way talk, go2rtc will automatically establish an au
|
|||||||
To prevent this, you must configure two separate stream instances:
|
To prevent this, you must configure two separate stream instances:
|
||||||
|
|
||||||
1. One stream instance with `#backchannel=0` for Frigate's viewing, recording, and detection (prevents go2rtc from establishing the blocking backchannel)
|
1. One stream instance with `#backchannel=0` for Frigate's viewing, recording, and detection (prevents go2rtc from establishing the blocking backchannel)
|
||||||
2. A second stream instance with no `#` parameters at all for two-way talk functionality (can be used by Frigate's WebRTC viewer or other applications)
|
2. A second stream instance without `#backchannel=0` for two-way talk functionality (can be used by Frigate's WebRTC viewer or other applications)
|
||||||
|
|
||||||
Configuration example:
|
Configuration example:
|
||||||
|
|
||||||
@@ -215,8 +215,6 @@ In this configuration:
|
|||||||
- `front_door` stream is used by Frigate for viewing, recording, and detection. The `#backchannel=0` parameter prevents go2rtc from establishing the audio output backchannel, so it won't block two-way talk access.
|
- `front_door` stream is used by Frigate for viewing, recording, and detection. The `#backchannel=0` parameter prevents go2rtc from establishing the audio output backchannel, so it won't block two-way talk access.
|
||||||
- `front_door_twoway` stream is used for two-way talk functionality. This stream can be used by Frigate's WebRTC viewer when two-way talk is enabled, or by other applications (like Home Assistant Advanced Camera Card) that need access to the camera's audio output channel.
|
- `front_door_twoway` stream is used for two-way talk functionality. This stream can be used by Frigate's WebRTC viewer when two-way talk is enabled, or by other applications (like Home Assistant Advanced Camera Card) that need access to the camera's audio output channel.
|
||||||
|
|
||||||
Any `#` parameter on a bare `rtsp://` source disables the backchannel unless the URL explicitly contains `#backchannel=1`. A two-way talk stream with something like `#video=h264` on it silently loses two-way audio, and Frigate will report that two-way talk is unavailable for that stream.
|
|
||||||
|
|
||||||
## Security: Restricted Stream Sources
|
## Security: Restricted Stream Sources
|
||||||
|
|
||||||
For security reasons, the `echo:`, `expr:`, and `exec:` stream sources are disabled by default in go2rtc. These sources allow arbitrary command execution and can pose security risks if misconfigured.
|
For security reasons, the `echo:`, `expr:`, and `exec:` stream sources are disabled by default in go2rtc. These sources allow arbitrary command execution and can pose security risks if misconfigured.
|
||||||
|
|||||||
@@ -245,8 +245,8 @@ Triggers are best configured through the Frigate UI.
|
|||||||
1. Navigate to <NavPath path="Settings > Enrichments > Triggers" /> and select a camera from the dropdown menu.
|
1. Navigate to <NavPath path="Settings > Enrichments > Triggers" /> and select a camera from the dropdown menu.
|
||||||
2. Click **Add Trigger** to create a new trigger or use the pencil icon to edit an existing one.
|
2. Click **Add Trigger** to create a new trigger or use the pencil icon to edit an existing one.
|
||||||
3. In the **Create Trigger** wizard:
|
3. In the **Create Trigger** wizard:
|
||||||
- Enter a **Name** for the trigger (e.g., "Red Car Alert"). Frigate derives the trigger's
|
- Enter a **Name** for the trigger (e.g., "Red Car Alert").
|
||||||
internal **ID** from this name, which can be revealed and edited with the show/hide toggle.
|
- Enter a descriptive **Friendly Name** for the trigger (e.g., "Red car on the driveway camera").
|
||||||
- Select the **Type** (`Thumbnail` or `Description`).
|
- Select the **Type** (`Thumbnail` or `Description`).
|
||||||
- For `Thumbnail`, select an image to trigger this action when a similar thumbnail image is detected, based on the threshold.
|
- For `Thumbnail`, select an image to trigger this action when a similar thumbnail image is detected, based on the threshold.
|
||||||
- For `Description`, enter text to trigger this action when a similar tracked object description is detected.
|
- For `Description`, enter text to trigger this action when a similar tracked object description is detected.
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ During testing, enable the Zones option for the [Debug view](/usage/live#the-sin
|
|||||||
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
||||||
2. Under the **Zones** section, click the plus icon to add a new zone.
|
2. Under the **Zones** section, click the plus icon to add a new zone.
|
||||||
3. Click on the camera's latest image to create the points for the zone boundary. Click the first point again to close the polygon.
|
3. Click on the camera's latest image to create the points for the zone boundary. Click the first point again to close the polygon.
|
||||||
4. Configure zone options such as **Name**, **Objects**, **Loitering Time**, and **Inertia** in the zone editor.
|
4. Configure zone options such as **Friendly name**, **Objects**, **Loitering time**, and **Inertia** in the zone editor.
|
||||||
5. Press **Save** when finished.
|
5. Press **Save** when finished.
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
@@ -200,7 +200,7 @@ When using loitering zones, a review item will behave in the following way:
|
|||||||
|
|
||||||
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
||||||
2. Edit or create the zone (e.g., `sidewalk`).
|
2. Edit or create the zone (e.g., `sidewalk`).
|
||||||
- Set **Loitering Time** to the desired number of seconds (e.g., `4`)
|
- Set **Loitering time** to the desired number of seconds (e.g., `4`)
|
||||||
- Under **Objects**, add the relevant object types (e.g., `person`)
|
- Under **Objects**, add the relevant object types (e.g., `person`)
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
@@ -291,7 +291,7 @@ Accurate real-world distance measurements are required to estimate speeds. These
|
|||||||
|
|
||||||
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
||||||
2. Create or edit a zone with exactly 4 points aligned to the ground plane.
|
2. Create or edit a zone with exactly 4 points aligned to the ground plane.
|
||||||
3. In the zone editor, enable **Speed Estimation** and enter the real-world **Line A distance**, **Line B distance**, **Line C distance**, and **Line D distance** between each pair of consecutive points.
|
3. In the zone editor, enter the real-world **Distances** between each pair of consecutive points.
|
||||||
- For example, if the distance between the first and second points is 10 meters, between the second and third is 12 meters, etc.
|
- For example, if the distance between the first and second points is 10 meters, between the second and third is 12 meters, etc.
|
||||||
4. Distances are measured in meters (metric) or feet (imperial), depending on the **Unit system** setting.
|
4. Distances are measured in meters (metric) or feet (imperial), depending on the **Unit system** setting.
|
||||||
|
|
||||||
@@ -358,7 +358,7 @@ Zones can be configured with a minimum speed requirement, meaning an object must
|
|||||||
|
|
||||||
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
1. Navigate to <NavPath path="Settings > Camera configuration > Masks / Zones" /> and select the desired camera.
|
||||||
2. Edit or create the zone with distances configured.
|
2. Edit or create the zone with distances configured.
|
||||||
- Set **Speed Threshold** to the desired minimum speed (e.g., `20`)
|
- Set **Speed threshold** to the desired minimum speed (e.g., `20`)
|
||||||
- The unit is kph or mph, depending on the **Unit system** setting
|
- The unit is kph or mph, depending on the **Unit system** setting
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ An object filter mask drops any [bounding box](#bounding-box) whose bottom cente
|
|||||||
|
|
||||||
## Min Score
|
## Min Score
|
||||||
|
|
||||||
The lowest score a detected object can have to be kept during tracking. Anything scoring below the minimum is assumed to be a [false positive](#false-positive) and discarded. Set with `min_score` in the config, shown as **Minimum confidence** in the settings UI.
|
The lowest score a detected object can have to be kept during tracking. Anything scoring below the minimum is assumed to be a [false positive](#false-positive) and discarded.
|
||||||
|
|
||||||
## Model
|
## Model
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ A more specific identity assigned to a [tracked object](#tracked-object-event-in
|
|||||||
|
|
||||||
## Threshold
|
## Threshold
|
||||||
|
|
||||||
The median score an object must reach to be considered a true positive. Set with `threshold` in the config, shown as **Confidence threshold** in the settings UI.
|
The median score an object must reach to be considered a true positive.
|
||||||
|
|
||||||
## Top Score
|
## Top Score
|
||||||
|
|
||||||
|
|||||||
@@ -70,9 +70,6 @@ Frigate supports multiple different detectors that work on different types of ha
|
|||||||
- [ROCm](#rocm---amd-gpu): ROCm can run on AMD Discrete GPUs to provide efficient object detection
|
- [ROCm](#rocm---amd-gpu): ROCm can run on AMD Discrete GPUs to provide efficient object detection
|
||||||
- [Supports limited model architectures](../../configuration/object_detectors#amdrocm-gpu-detector)
|
- [Supports limited model architectures](../../configuration/object_detectors#amdrocm-gpu-detector)
|
||||||
- Runs best on discrete AMD GPUs
|
- Runs best on discrete AMD GPUs
|
||||||
- <CommunityBadge /> [XDNA2 (Ryzen AI)](#amd-xdna2): AMD XDNA2 NPU (sub-watt power AI/ML processor separate to the GPU) inside Strix and other "AI" branded AMD platforms
|
|
||||||
- Has only been tested with YOLOv9, in theory other graphs may be compiled too.
|
|
||||||
- Runs via ZMQ proxy which adds some latency, only recommended for local connection
|
|
||||||
|
|
||||||
**Apple Silicon**
|
**Apple Silicon**
|
||||||
|
|
||||||
@@ -299,32 +296,6 @@ The inference time of a rk3588 with all 3 cores enabled is typically 25-30 ms fo
|
|||||||
| ---------------- | ----------------------------------- |
|
| ---------------- | ----------------------------------- |
|
||||||
| yolov9-tiny | ~ 4 ms |
|
| yolov9-tiny | ~ 4 ms |
|
||||||
|
|
||||||
### AMD Ryzen AI / XDNA2
|
|
||||||
|
|
||||||
Frigate supports AMD XDNA2 NPUs through the community-maintained
|
|
||||||
frigate-xdna ZMQ sidecar. It works with stock Frigate and supports
|
|
||||||
Frigate+ models or compatible local YOLO ONNX models. Models are compiled
|
|
||||||
once on the target system and cached for subsequent use.
|
|
||||||
|
|
||||||
Currently qualified on **Ryzen AI Max 300 / Strix Halo**. Other XDNA2
|
|
||||||
devices are not yet qualified; XDNA1 is unsupported.
|
|
||||||
|
|
||||||
Measured YOLOv9 detector latency on Strix Halo:
|
|
||||||
|
|
||||||
| Model | 320 | 640 |
|
|
||||||
| ----- | ---: | ---: |
|
|
||||||
| YOLOv9-T | ~7.4 ms | unsupported |
|
|
||||||
| YOLOv9-S | ~9.0 ms | ~20.0 ms |
|
|
||||||
| YOLOv9-M | ~13.1 ms | ~34.4 ms |
|
|
||||||
| YOLOv9-C | ~14.1 ms | ~35.2 ms |
|
|
||||||
| YOLOv9-E | ~69.4 ms | ~224.8 ms |
|
|
||||||
|
|
||||||
**YOLOv9-C at 320 is the recommended quality/performance balance.**
|
|
||||||
C at 640 is also usable where the lower throughput is acceptable.
|
|
||||||
|
|
||||||
Setup, model preparation, and compatibility details are available
|
|
||||||
[in the frigate-xdna documentation](https://github.com/mitchins/frigate-xdna).
|
|
||||||
|
|
||||||
## What does Frigate use the CPU for and what does it use a detector for? (ELI5 Version)
|
## What does Frigate use the CPU for and what does it use a detector for? (ELI5 Version)
|
||||||
|
|
||||||
This is taken from a [user question on reddit](https://www.reddit.com/r/homeassistant/comments/q8mgau/comment/hgqbxh5/?utm_source=share&utm_medium=web2x&context=3). Modified slightly for clarity.
|
This is taken from a [user question on reddit](https://www.reddit.com/r/homeassistant/comments/q8mgau/comment/hgqbxh5/?utm_source=share&utm_medium=web2x&context=3). Modified slightly for clarity.
|
||||||
|
|||||||
@@ -11,12 +11,6 @@ MQTT requires a network connection to your broker. This is typically local, but
|
|||||||
|
|
||||||
:::
|
:::
|
||||||
|
|
||||||
:::note
|
|
||||||
|
|
||||||
Wherever a topic below includes a camera, mask, or zone name, use its `ID` from the config, not its `friendly_name`. For example, a camera with `friendly_name: "Back Yard"` and ID `back_yard` publishes to `frigate/back_yard/...`, not `frigate/Back Yard/...`.
|
|
||||||
|
|
||||||
:::
|
|
||||||
|
|
||||||
## General Frigate Topics
|
## General Frigate Topics
|
||||||
|
|
||||||
### `frigate/available`
|
### `frigate/available`
|
||||||
@@ -561,20 +555,21 @@ Topic with current state of Birdseye for a camera. Published values are `ON` and
|
|||||||
|
|
||||||
### `frigate/<camera_name>/birdseye_mode/set`
|
### `frigate/<camera_name>/birdseye_mode/set`
|
||||||
|
|
||||||
Topic to set Birdseye mode for a camera. Birdseye offers different modes to customize under which circumstances the camera is shown.
|
Topic to set the Birdseye activity types for a camera. Send one uppercase activity type or combine multiple types with commas, for example `MOTION,OBJECTS,STATIONARY_OBJECTS`.
|
||||||
|
|
||||||
_Note: Changing the value from `CONTINUOUS` -> `MOTION | OBJECTS` will take up to 30 seconds for
|
_Note: Changing the value from `CONTINUOUS` to non-continuous activity types will take up to 30 seconds for
|
||||||
the camera to be removed from the view._
|
the camera to be removed from the view._
|
||||||
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
| ------------ | ----------------------------------------------------------------- |
|
| -------------------- | ---------------------------------------------------------------- |
|
||||||
| `CONTINUOUS` | Always included |
|
| `CONTINUOUS` | Always included |
|
||||||
| `MOTION` | Show when detected motion within the last 30 seconds are included |
|
| `MOTION` | Shown if motion was detected within the last 30 seconds |
|
||||||
| `OBJECTS` | Shown if an active object tracked within the last 30 seconds |
|
| `OBJECTS` | Shown if an active object was tracked within the last 30 seconds |
|
||||||
|
| `STATIONARY_OBJECTS` | Shown while a stationary object is tracked |
|
||||||
|
|
||||||
### `frigate/<camera_name>/birdseye_mode/state`
|
### `frigate/<camera_name>/birdseye_mode/state`
|
||||||
|
|
||||||
Topic with current state of the Birdseye mode for a camera. Published values are `CONTINUOUS`, `MOTION`, `OBJECTS`.
|
Topic with the current Birdseye activity types for a camera. Multiple enabled types are published as a comma-separated value in the order `OBJECTS`, `MOTION`, `STATIONARY_OBJECTS`, `CONTINUOUS`.
|
||||||
|
|
||||||
### `frigate/<camera_name>/notifications/set`
|
### `frigate/<camera_name>/notifications/set`
|
||||||
|
|
||||||
|
|||||||
@@ -27,10 +27,6 @@ The [Advanced Camera Card](https://card.camera/#/README) is a Home Assistant das
|
|||||||
It supports automatically setting the sub labels in Frigate for person objects that are detected and recognized.
|
It supports automatically setting the sub labels in Frigate for person objects that are detected and recognized.
|
||||||
This is a fork (with fixed errors and new features) of [original Double Take](https://github.com/jakowenko/double-take) project which, unfortunately, isn't being maintained by author.
|
This is a fork (with fixed errors and new features) of [original Double Take](https://github.com/jakowenko/double-take) project which, unfortunately, isn't being maintained by author.
|
||||||
|
|
||||||
## [frigate-abr](https://github.com/007hacky007/frigate-abr)
|
|
||||||
|
|
||||||
[frigate-abr](https://github.com/007hacky007/frigate-abr) is a drop-in Docker image of Frigate that adds adaptive bitrate (ABR) playback for recordings: a sidecar transcodes footage to lower quality tiers on demand, for reviewing over slow remote connections. Segments are transcoded when played and cached, so no additional stream is recorded. Frigate itself is not modified.
|
|
||||||
|
|
||||||
## [Frigate Notify](https://github.com/0x2142/frigate-notify)
|
## [Frigate Notify](https://github.com/0x2142/frigate-notify)
|
||||||
|
|
||||||
[Frigate Notify](https://github.com/0x2142/frigate-notify) is a simple app designed to send notifications from Frigate to your favorite platforms. Intended to be used with standalone Frigate installations - Home Assistant not required, MQTT is optional but recommended.
|
[Frigate Notify](https://github.com/0x2142/frigate-notify) is a simple app designed to send notifications from Frigate to your favorite platforms. Intended to be used with standalone Frigate installations - Home Assistant not required, MQTT is optional but recommended.
|
||||||
|
|||||||
@@ -21,13 +21,7 @@ Yes. Models and metadata are stored in the `model_cache` directory within the co
|
|||||||
|
|
||||||
### Can I keep using my Frigate+ models even if I do not renew my subscription?
|
### Can I keep using my Frigate+ models even if I do not renew my subscription?
|
||||||
|
|
||||||
Yes. Subscriptions to Frigate+ provide access to the infrastructure used to train the models. Models you train during an active subscription remain licensed for your continued use even after your subscription ends — models already in your model cache will keep working indefinitely. An active subscription is required to train new models and download new versions.
|
Yes. Subscriptions to Frigate+ provide access to the infrastructure used to train the models. Models trained with your subscription are yours to keep and use forever. However, do note that the terms and conditions prohibit you from sharing, reselling, or creating derivative products from the models.
|
||||||
|
|
||||||
### Can I use Frigate+ models commercially?
|
|
||||||
|
|
||||||
A standard subscription covers use on camera systems you own or operate, including for your business. A shop, restaurant, warehouse, or office running Frigate+ at its own locations (including multiple locations) is exactly the kind of use the subscription is for.
|
|
||||||
What the standard subscription does not cover is using Frigate+ models to provide a product or service to others. If you're deploying models at your customers' sites, bundling them with hardware you sell, or running them as part of a hosted or managed service, even if your customers never receive the model files themselves, you'll need a commercial license.
|
|
||||||
Note that professional installers are fine under standard subscriptions when each customer holds their own Frigate+ subscription. The commercial license is for cases where your license powers your customers' sites.
|
|
||||||
|
|
||||||
### Why can't I submit images to Frigate+?
|
### Why can't I submit images to Frigate+?
|
||||||
|
|
||||||
|
|||||||
@@ -64,20 +64,20 @@ Frigate+ models generally have much higher scores than the default model provide
|
|||||||
<ConfigTabs>
|
<ConfigTabs>
|
||||||
<TabItem value="ui">
|
<TabItem value="ui">
|
||||||
|
|
||||||
Navigate to <NavPath path="Settings > Global configuration > Objects" />. Under **Object filters**, set **Minimum confidence** and **Confidence threshold** for each object type, then click **Save**.
|
Navigate to <NavPath path="Settings > Global configuration > Objects" />. Under **Object filters**, set **Min Score** and **Threshold** for each object type, then click **Save**.
|
||||||
|
|
||||||
| Object | Minimum confidence | Confidence threshold |
|
| Object | Min Score | Threshold |
|
||||||
| ----------------- | ------------------ | -------------------- |
|
| ----------------- | --------- | --------- |
|
||||||
| **dog** | .7 | .9 |
|
| **dog** | .7 | .9 |
|
||||||
| **cat** | .65 | .8 |
|
| **cat** | .65 | .8 |
|
||||||
| **face** | .7 | |
|
| **face** | .7 | |
|
||||||
| **package** | .65 | .9 |
|
| **package** | .65 | .9 |
|
||||||
| **license_plate** | .6 | |
|
| **license_plate** | .6 | |
|
||||||
| **amazon** | .75 | |
|
| **amazon** | .75 | |
|
||||||
| **ups** | .75 | |
|
| **ups** | .75 | |
|
||||||
| **fedex** | .75 | |
|
| **fedex** | .75 | |
|
||||||
| **person** | .65 | .85 |
|
| **person** | .65 | .85 |
|
||||||
| **car** | .65 | .85 |
|
| **car** | .65 | .85 |
|
||||||
|
|
||||||
</TabItem>
|
</TabItem>
|
||||||
<TabItem value="yaml">
|
<TabItem value="yaml">
|
||||||
|
|||||||
@@ -65,11 +65,11 @@ Some users may find that Frigate+ models result in more false positives initiall
|
|||||||
|
|
||||||
Frigate+ models support a more relevant set of objects for security cameras. The labels for annotation in Frigate+ are configurable by editing the camera in the Cameras section of Frigate+. Currently, the following objects are supported:
|
Frigate+ models support a more relevant set of objects for security cameras. The labels for annotation in Frigate+ are configurable by editing the camera in the Cameras section of Frigate+. Currently, the following objects are supported:
|
||||||
|
|
||||||
- **People**: `person`, `face`, `baby`
|
- **People**: `person`, `face`
|
||||||
- **Vehicles**: `car`, `motorcycle`, `bicycle`, `boat`, `school_bus`, `garbage truck`, `license_plate`
|
- **Vehicles**: `car`, `motorcycle`, `bicycle`, `boat`, `school_bus`, `license_plate`
|
||||||
- **Delivery Logos**: `amazon`, `usps`, `ups`, `fedex`, `dhl`, `an_post`, `purolator`, `postnl`, `nzpost`, `postnord`, `gls`, `dpd`, `canada_post`, `royal_mail`
|
- **Delivery Logos**: `amazon`, `usps`, `ups`, `fedex`, `dhl`, `an_post`, `purolator`, `postnl`, `nzpost`, `postnord`, `gls`, `dpd`, `canada_post`, `royal_mail`
|
||||||
- **Animals**: `dog`, `cat`, `deer`, `horse`, `bird`, `raccoon`, `fox`, `bear`, `cow`, `squirrel`, `goat`, `rabbit`, `skunk`, `kangaroo`, `possum`, `rodent`
|
- **Animals**: `dog`, `cat`, `deer`, `horse`, `bird`, `raccoon`, `fox`, `bear`, `cow`, `squirrel`, `goat`, `rabbit`, `skunk`, `kangaroo`
|
||||||
- **Other**: `package`, `waste_bin`, `bbq_grill`, `robot_lawnmower`, `umbrella`, `baby_stroller`
|
- **Other**: `package`, `waste_bin`, `bbq_grill`, `robot_lawnmower`, `umbrella`
|
||||||
|
|
||||||
Other object types available in the default Frigate model are not available. Additional object types will be added in future releases.
|
Other object types available in the default Frigate model are not available. Additional object types will be added in future releases.
|
||||||
|
|
||||||
@@ -77,12 +77,9 @@ Other object types available in the default Frigate model are not available. Add
|
|||||||
|
|
||||||
Candidate labels are also available for annotation. These labels don't have enough data to be included in the model yet, but using them will help add support sooner. You can enable these labels by editing the camera settings.
|
Candidate labels are also available for annotation. These labels don't have enough data to be included in the model yet, but using them will help add support sooner. You can enable these labels by editing the camera settings.
|
||||||
|
|
||||||
Where possible, these labels are mapped to existing labels during training. For example, any `duck` labels are mapped to `bird` until support for new labels is added.
|
Where possible, these labels are mapped to existing labels during training. For example, any `baby` labels are mapped to `person` until support for new labels is added.
|
||||||
|
|
||||||
- **Vehicles**: `tractor`, `golf_cart`, `bus`, `airplane`, `helicopter`, `rickshaw`, `scooter`
|
The candidate labels are: `baby`, `bpost`, `badger`, `possum`, `rodent`, `chicken`, `groundhog`, `boar`, `hedgehog`, `tractor`, `golf cart`, `garbage truck`, `bus`, `sports ball`, `la_poste`, `lawnmower`, `heron`, `rickshaw`, `wombat`, `auspost`, `aramex`, `bobcat`, `mustelid`, `transoflex`, `airplane`, `drone`, `mountain_lion`, `crocodile`, `turkey`, `baby_stroller`, `monkey`, `coyote`, `porcupine`, `parcelforce`, `sheep`, `snake`, `helicopter`, `lizard`, `duck`, `hermes`, `cargus`, `fan_courier`, `sameday`
|
||||||
- **Delivery Logos**: `bpost`, `auspost`, `aramex`, `transoflex`, `parcelforce`, `hermes`, `cargus`, `fan_courier`, `sameday`, `la_poste`
|
|
||||||
- **Animals**: `badger`, `chicken`, `duck`, `turkey`, `groundhog`, `boar`, `hedgehog`, `wombat`, `bobcat`, `mustelid`, `mountain_lion`, `crocodile`, `monkey`, `coyote`, `porcupine`, `sheep`, `snake`, `lizard`, `heron`, `elk`, `moose`, `pig`, `donkey`, `civet`
|
|
||||||
- **Other**: `sports_ball`, `drone`, `lawnmower`
|
|
||||||
|
|
||||||
Candidate labels are not available for automatic suggestions.
|
Candidate labels are not available for automatic suggestions.
|
||||||
|
|
||||||
|
|||||||
@@ -66,19 +66,17 @@ An FFmpeg message meaning it probed the stream but never saw enough decodable vi
|
|||||||
|
|
||||||
## Recording
|
## Recording
|
||||||
|
|
||||||
<FaqItem id="no-new-recording-segments" question="No new recording segments were created (or: No new valid recording segments were created / No valid segments created since last invalid segment) for <camera> in the last 120s">
|
<FaqItem id="no-new-recording-segments" question="No new recording segments were created for <camera> in the last 120s">
|
||||||
|
|
||||||
Frigate's record watchdog is restarting the record FFmpeg process because the camera stopped producing usable recordings. The wording distinguishes the cases: `No new recording segments` means no new segment file reached the cache, so ffmpeg isn't getting video out of the record stream; the two `valid` variants mean recordings are arriving but keep failing validation. Either way the fault is on the camera or network side, and the restart is Frigate trying to recover.
|
Frigate's record watchdog is restarting the record FFmpeg process because no valid segment has reached the cache. This means the record stream is not connecting or the segments are being rejected (see the audio-codec entry below).
|
||||||
|
|
||||||
See [Recordings: no new recording segments were created](/troubleshooting/recordings#no-new-recording-segments-were-created).
|
See [Recordings: the record stream isn't connecting](/troubleshooting/recordings#the-record-stream-isnt-connecting).
|
||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
|
|
||||||
<FaqItem id="invalid-or-missing-video-stream-in-segment" question="Invalid or missing video stream in segment. Discarding. / Discarding a corrupt recording segment / Failed to probe corrupt segment / Invalid recording segment detected">
|
<FaqItem id="invalid-or-missing-video-stream-in-segment" question="Invalid or missing video stream in segment. Discarding.">
|
||||||
|
|
||||||
A cached recording segment failed validation and was deleted, either because it had no readable video stream or because its length was impossible. This nearly always means the camera stopped sending usable video partway through the segment: a camera that rebooted, dropped the connection, or ran out of simultaneous connections, or an unreliable link such as WiFi or a failing switch port. Broken camera timestamps (a "Smart Codec" / H.264+ mode) cause the corrupt-segment variants. The same stream failure trips the record watchdog, so the restarts above usually appear alongside these messages.
|
A cached recording segment failed validation (no readable video stream) and was deleted. The most common cause is a segment that was truncated because the record FFmpeg process was killed mid-write, so this often appears alongside, and as a consequence of, the record-stream restarts above. A segment containing only audio triggers it too.
|
||||||
|
|
||||||
See [Recordings: invalid or missing video stream in segment](/troubleshooting/recordings#invalid-or-missing-video-stream-in-segment).
|
|
||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
|
|
||||||
|
|||||||
@@ -3,31 +3,7 @@ id: cpu
|
|||||||
title: High CPU Usage
|
title: High CPU Usage
|
||||||
---
|
---
|
||||||
|
|
||||||
High CPU usage can impact Frigate's performance and responsiveness. This guide explains how to interpret the CPU values Frigate reports and outlines the most effective configuration changes to help reduce CPU consumption and optimize resource usage.
|
High CPU usage can impact Frigate's performance and responsiveness. This guide outlines the most effective configuration changes to help reduce CPU consumption and optimize resource usage.
|
||||||
|
|
||||||
## Understanding Frigate's Reported CPU Usage
|
|
||||||
|
|
||||||
Frigate's CPU percentages often look much higher than what the host reports. Usually both numbers are correct and are simply measured against different denominators, so confirm you actually have a problem before tuning anything.
|
|
||||||
|
|
||||||
### Per-process values are relative to a single core
|
|
||||||
|
|
||||||
The values Frigate reports for FFmpeg, capture, detect, detector, and other processes follow the same convention as `top`: 100% means one CPU core is fully saturated, not that the whole system is saturated. A multithreaded process such as FFmpeg can legitimately report well over 100%.
|
|
||||||
|
|
||||||
Host and hypervisor tools instead report a percentage of the machine's total capacity across all cores. This includes `docker stats`, the `htop` summary, the Proxmox summary graph, the Unraid dashboard, Synology Resource Monitor, and Home Assistant's system monitor sensors. To reconcile the two:
|
|
||||||
|
|
||||||
```
|
|
||||||
host percentage ≈ (sum of Frigate's process percentages) / (number of cores)
|
|
||||||
```
|
|
||||||
|
|
||||||
On a 4 core system, an FFmpeg process reporting 100% is consuming one quarter of the machine, so the host will show roughly 25 to 30% once the remaining Frigate processes are included. That same 100% on a 16 core system is about 6%. Frigate's own warning thresholds use the per-core convention as well, so an FFmpeg process is flagged at 20% of a single core, not 20% of the system.
|
|
||||||
|
|
||||||
### Instantaneous samples and averages measure different things
|
|
||||||
|
|
||||||
Frigate collects stats every 15 seconds, and the `cpu` value covers only the interval since the previous collection. The `cpu_average` value in the stats API and MQTT payload is the average across the entire life of the process, and it is what the high CPU usage warnings are based on. Host dashboards generally plot data averaged over a longer window, so a single Frigate sample can show a peak that a host graph never displays. A process that has just started, such as FFmpeg after a camera reconnect, reports 0 until it has been sampled twice.
|
|
||||||
|
|
||||||
### The system-wide value depends on what the container can see
|
|
||||||
|
|
||||||
The system CPU value is read from `/proc/stat`. Under Docker that file belongs to the host, so the value covers the entire machine including workloads unrelated to Frigate, and it will not match `docker stats` for the Frigate container. Under an LXC container, lxcfs virtualizes `/proc/stat` and the value reflects only the cores assigned to the container. In a virtual machine, the guest sees only its assigned vCPUs while the hypervisor divides by every physical thread on the node, so guest and host percentages will not agree even when both are accurate.
|
|
||||||
|
|
||||||
## 1. Hardware Acceleration for Video Decoding
|
## 1. Hardware Acceleration for Video Decoding
|
||||||
|
|
||||||
@@ -96,19 +72,3 @@ The model you use significantly impacts detector performance. Frigate provides d
|
|||||||
- Larger models (640x640): Slower inference, can sometimes have higher accuracy on very large objects that take up a majority of the frame.
|
- Larger models (640x640): Slower inference, can sometimes have higher accuracy on very large objects that take up a majority of the frame.
|
||||||
|
|
||||||
For more detail on picking the right size, see [Choosing a model size](../configuration/object_detectors.md#choosing-a-model-size).
|
For more detail on picking the right size, see [Choosing a model size](../configuration/object_detectors.md#choosing-a-model-size).
|
||||||
|
|
||||||
## 3. Reducing Detector CPU Usage
|
|
||||||
|
|
||||||
**Priority: High**
|
|
||||||
|
|
||||||
The **Detector CPU Usage** metric measures the CPU spent converting frames into the tensor format the model expects and post-processing the model's output. It does not include inference, so this value can be high even when you've configured a GPU, NPU, or Coral for object detection.
|
|
||||||
|
|
||||||
This metric scales with how many detections per second Frigate runs and how expensive each one is to prepare. Tuning [motion detection](../configuration/motion_detection) is usually the first recommendation to reduce the number of detections. Additionally, you can:
|
|
||||||
|
|
||||||
- **Lower `detect -> fps`.** 5 is the recommended value for nearly all cameras. Running at 10 doubles the frames eligible for detection and is one of the largest contributors to this metric.
|
|
||||||
- **Use a 320x320 model.** A 640x640 model has 4 times as many pixels to transpose, convert, and copy on every inference.
|
|
||||||
- **Prefer a model that takes integer input.** Models configured with `input_dtype: float` require each frame to be converted to float32 and normalized on the CPU first. Models taking `int` input, such as the tflite models used by the Edge TPU, skip that step.
|
|
||||||
- **Do not match the detect resolution to the model resolution.** The detect stream should match your camera's aspect ratio, for example `1280x720`, not the model's input size. Frigate crops and scales regions of motion itself, so an oversized detect stream only adds work.
|
|
||||||
- **Tune stationary object behavior.** Objects that never settle into a stationary state are re-detected continuously. Raising `detect -> stationary -> interval` reduces how often detection runs on objects that are already parked. See [stationary objects](../configuration/stationary_objects).
|
|
||||||
|
|
||||||
Adding [more detector instances](#multiple-detector-instances) spreads this work across more CPU cores, but does not reduce the total CPU used.
|
|
||||||
|
|||||||
@@ -39,20 +39,6 @@ To do this efficiently the following setup is required:
|
|||||||
|
|
||||||
When this is done correctly, the GPU will do the decoding and scaling which will result in a small increase in CPU usage but with better results.
|
When this is done correctly, the GPU will do the decoding and scaling which will result in a small increase in CPU usage but with better results.
|
||||||
|
|
||||||
### How can I rotate my camera's video feed?
|
|
||||||
|
|
||||||
Rotation is best done in the camera's firmware settings (usually called rotate, flip, or corridor mode) so the video arrives already rotated and no extra processing is needed. Check there first.
|
|
||||||
|
|
||||||
If your camera does not support rotation, go2rtc's ffmpeg module can rotate the stream with the `#rotate` parameter (`90`, `180`, `270`, or `-90`), but this is not recommended: rotation requires transcoding (re-encoding) the video, which significantly increases CPU usage, especially for high resolution streams.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
go2rtc:
|
|
||||||
streams:
|
|
||||||
my_camera: "ffmpeg:rtsp://user:password@192.168.1.10:554/stream#video=h264#hardware#rotate=90"
|
|
||||||
```
|
|
||||||
|
|
||||||
Point the camera's inputs at the restream as described in the [restream docs](/configuration/restream.md), and swap `detect -> width` and `detect -> height` to match the rotated resolution.
|
|
||||||
|
|
||||||
### My mjpeg stream or snapshots look green and crazy
|
### My mjpeg stream or snapshots look green and crazy
|
||||||
|
|
||||||
This almost always means that the width/height defined for your camera are not correct. Double check the resolution with VLC or another player. Also make sure you don't have the width and height values backwards.
|
This almost always means that the width/height defined for your camera are not correct. Double check the resolution with VLC or another player. Also make sure you don't have the width and height values backwards.
|
||||||
@@ -147,12 +133,6 @@ cameras:
|
|||||||
height: 720
|
height: 720
|
||||||
```
|
```
|
||||||
|
|
||||||
### What is the `version` key in my config file?
|
|
||||||
|
|
||||||
`version` records the config format that your config was last migrated to. On startup Frigate compares it against the format the running version expects, and if it is older it copies your config to `/config/backup_config.yaml`, rewrites it to the new format, and updates `version` as the final step. A config with no `version` key is assumed to predate 0.14 and is migrated from there.
|
|
||||||
|
|
||||||
Frigate manages this key for you, so do not set or edit it. Raising it makes Frigate skip migrations your config still needs, and lowering it re-runs migrations against config that has already been converted. Either can leave you with a config that no longer validates.
|
|
||||||
|
|
||||||
### Why does Frigate keep creating new tracked objects for my parked car?
|
### Why does Frigate keep creating new tracked objects for my parked car?
|
||||||
|
|
||||||
Stationary tracking is designed to _prevent_ this: a parked car should remain a single tracked object rather than generating new ones. If you're repeatedly getting new tracked objects for the same car, it's likely that Frigate is losing the object and re-detecting it as a new one.
|
Stationary tracking is designed to _prevent_ this: a parked car should remain a single tracked object rather than generating new ones. If you're repeatedly getting new tracked objects for the same car, it's likely that Frigate is losing the object and re-detecting it as a new one.
|
||||||
|
|||||||
@@ -78,9 +78,7 @@ go2rtc:
|
|||||||
|
|
||||||
:::warning
|
:::warning
|
||||||
|
|
||||||
The transcoding modifiers (`#video=`, `#audio=`, `#hardware`, …) **only take effect on a source that is prefixed with `ffmpeg:`**. Adding them to a bare `rtsp://…#audio=opus` source does nothing: go2rtc ignores them. Likewise, when a source references another stream by name (e.g. `ffmpeg:back#audio=aac`), the name must match the stream key **exactly** (it is case sensitive), or the transcode is silently never produced. This is the single most common configuration mistake. In the Frigate UI, the **Use compatibility mode (ffmpeg)** toggle adds the `ffmpeg:` prefix for you.
|
The `#`-modifiers (`#video=`, `#audio=`, `#hardware`, `#backchannel=0`, …) **only take effect on a source that is prefixed with `ffmpeg:`**. Adding them to a bare `rtsp://…#audio=opus` source does nothing: go2rtc ignores them. Likewise, when a source references another stream by name (e.g. `ffmpeg:back#audio=aac`), the name must match the stream key **exactly** (it is case sensitive), or the transcode is silently never produced. This is the single most common configuration mistake. In the Frigate UI, the **Use compatibility mode (ffmpeg)** toggle adds the `ffmpeg:` prefix for you.
|
||||||
|
|
||||||
A bare `rtsp://` source reads a different set of modifiers: `#backchannel=`, `#media=`, `#timeout=`, and `#transport=`. These do nothing on an `ffmpeg:` source. Adding **any** modifier to a bare `rtsp://` source also disables the camera's backchannel unless the URL explicitly contains `#backchannel=1`, so a stream dedicated to two-way talk should carry no modifiers at all.
|
|
||||||
|
|
||||||
:::
|
:::
|
||||||
|
|
||||||
@@ -155,7 +153,7 @@ WebRTC is only attempted when MSE fails or when using a camera's two-way talk fe
|
|||||||
|
|
||||||
- **Codec mismatch**: WebRTC cannot carry H.265 or AAC. The stream backing the WebRTC view must provide Opus (or PCMA/PCMU) audio and H.264 video. Add an `ffmpeg:back#audio=opus` source as shown above.
|
- **Codec mismatch**: WebRTC cannot carry H.265 or AAC. The stream backing the WebRTC view must provide Opus (or PCMA/PCMU) audio and H.264 video. Add an `ffmpeg:back#audio=opus` source as shown above.
|
||||||
- **Port `8555` not reachable, or no candidates set**: WebRTC needs port `8555` (both TCP and UDP) open and a reachable candidate advertised. On Docker installs running on a custom/overlay network, go2rtc may advertise unreachable container IPs as ICE candidates; setting `webrtc.filters.candidates: []` and supplying only your host's LAN IP resolves this. See [WebRTC extra configuration](/configuration/live#webrtc-extra-configuration).
|
- **Port `8555` not reachable, or no candidates set**: WebRTC needs port `8555` (both TCP and UDP) open and a reachable candidate advertised. On Docker installs running on a custom/overlay network, go2rtc may advertise unreachable container IPs as ICE candidates; setting `webrtc.filters.candidates: []` and supplying only your host's LAN IP resolves this. See [WebRTC extra configuration](/configuration/live#webrtc-extra-configuration).
|
||||||
- **Two-way talk** additionally requires a secure context (HTTPS or the authenticated port `8971`, because browsers block microphone access on plain HTTP). The camera's RTSP backchannel must also be handled correctly: go2rtc seizes the backchannel by default, which blocks two-way audio for other consumers and can inject static. Disable it on the primary stream with `#backchannel=0` and use a separate dedicated stream for talk, carrying no `#` modifiers of any kind, as documented in [preventing go2rtc from blocking two-way audio](/configuration/restream#two-way-talk-restream).
|
- **Two-way talk** additionally requires a secure context (HTTPS or the authenticated port `8971`, because browsers block microphone access on plain HTTP). The camera's RTSP backchannel must also be handled correctly: go2rtc seizes the backchannel by default, which blocks two-way audio for other consumers and can inject static. Disable it on the primary stream with `#backchannel=0` and use a separate dedicated stream for talk, as documented in [preventing go2rtc from blocking two-way audio](/configuration/restream#two-way-talk-restream).
|
||||||
|
|
||||||
## High CPU usage
|
## High CPU usage
|
||||||
|
|
||||||
|
|||||||
@@ -209,50 +209,6 @@ If the record stream uses a "Smart Codec"/H.264+ mode or changes encoding parame
|
|||||||
|
|
||||||
</FaqItem>
|
</FaqItem>
|
||||||
|
|
||||||
<FaqItem id="invalid-or-missing-video-stream-in-segment" question="I see the message: WARNING : Invalid or missing video stream in segment ... Discarding.">
|
|
||||||
|
|
||||||
Every recording segment is validated before it leaves the cache. Frigate probes each finished `.mp4` in `/tmp/cache` and requires a readable video stream and a valid duration before moving to storage. A segment that fails is deleted, so those ~10 seconds of footage are lost. Three messages come from this check:
|
|
||||||
|
|
||||||
- `Invalid or missing video stream in segment <path>. Discarding.` The segment holds no video, or could not be read at all.
|
|
||||||
- `Failed to probe corrupt segment <path>` followed by `Discarding a corrupt recording segment: <path>`. The segment was read, but its length could not be determined.
|
|
||||||
- `Discarding a corrupt recording segment: <path>` on its own. The segment's length is impossible (empty, or longer than ten minutes), which points at broken timestamps coming from the camera.
|
|
||||||
|
|
||||||
For each one, the camera watchdog also logs `Invalid recording segment detected for <camera> at <timestamp>`.
|
|
||||||
|
|
||||||
:::warning
|
|
||||||
|
|
||||||
This is almost always a **camera or network problem**, not a Frigate one. A segment is only complete once ffmpeg has finished writing it, so anything that interrupts the stream partway through leaves behind a file that cannot be saved. Frigate is reporting the interruption, not causing it.
|
|
||||||
|
|
||||||
:::
|
|
||||||
|
|
||||||
#### Start with the camera and the network
|
|
||||||
|
|
||||||
- **The camera dropped the connection.** Cameras reboot, reinitialize their stream when switching to night mode, and cut clients off when they are overloaded or out of simultaneous connections. Count everything pulling from the camera at once: Frigate's detect and record streams, go2rtc, a phone app, and any other NVR each use one. Routing all roles through a single [RTSP restream](/configuration/restream#reduce-connections-to-camera) so the camera only ever sees one connection often resolves this by itself.
|
|
||||||
- **The link to the camera is unreliable.** WiFi cameras, powerline adapters, a saturated uplink, a failing switch port, or a marginal cable all produce this pattern, and usually only on one camera at a time. WiFi cameras are [not recommended](https://ipcamtalk.com/threads/multiple-cameras-high-bandwidth.77100/#post-861110).
|
|
||||||
- **The camera cannot reliably send what it is being asked for.** A high bitrate 4K stream can be more than the camera's own hardware can encode and push out under load. Lower the bitrate, or record a lower-resolution profile.
|
|
||||||
- **The camera is using a "Smart Codec", H.264+, or H.265+ mode.** These change encoding parameters mid-stream and produce the broken timestamps behind the corrupt-segment variant. Turn the mode off and set the camera's keyframe interval equal to its frame rate. See [Segments are only ~1 second long](#segments-are-only-1-second-long).
|
|
||||||
|
|
||||||
Read the rest of the Frigate and/or go2rtc log around the **first** occurrence. When the camera or the network is at fault, other messages show up with it, such as `No frames received from <camera> in 20 seconds`, `Non-monotonic DTS`, `RTP: PT=xx: bad cseq`, `error while decoding MB`, or a connection timeout. Each of those is explained in [Common error messages](/troubleshooting/common_errors). To confirm the camera is the source, open its stream in the [go2rtc web interface](/troubleshooting/go2rtc) on port `1984` or play the same URL in VLC, and leave it running long enough for the failures to happen again.
|
|
||||||
|
|
||||||
#### If the camera and network check out
|
|
||||||
|
|
||||||
- **Audio the recording cannot store.** Some cameras send G.711 audio, which cannot be saved in an MP4 and stops segments from finalizing. See [Incompatible audio codec](#incompatible-audio-codec-recordings-silently-fail-to-save).
|
|
||||||
- **Frigate itself was stopped or restarted.** A single warning per camera around a restart is expected and needs no action.
|
|
||||||
- **The system ran out of room or memory.** A full `/tmp/cache`, or the host killing Frigate for using too much memory, cuts off the segment being written. Both leave other errors in the log alongside this one. See [No space left on device](#errno-28-no-space-left-on-device).
|
|
||||||
|
|
||||||
</FaqItem>
|
|
||||||
|
|
||||||
<FaqItem id="no-new-recording-segments-were-created" question="I see the message: ERROR : No new recording segments were created for <camera> in the last 120s. Restarting the ffmpeg record process...">
|
|
||||||
|
|
||||||
When a camera stops producing usable recordings for two minutes, Frigate restarts that camera's record process to try to recover. The wording tells you how far the recordings got:
|
|
||||||
|
|
||||||
- **`No new recording segments were created`**: no new segment file showed up in the cache at all, so ffmpeg isn't getting video out of the record stream. The camera is unreachable or refusing the connection, the stream URL, path, or credentials are wrong, or the camera accepted the connection and then sent nothing. See [The record stream isn't connecting](#the-record-stream-isnt-connecting).
|
|
||||||
- **`No new valid recording segments were created`** and **`No valid segments created since last invalid segment`**: recordings are arriving, but they keep failing validation, so the camera is sending video that cannot be saved. See [Invalid or missing video stream in segment](#invalid-or-missing-video-stream-in-segment) above.
|
|
||||||
|
|
||||||
The restart is Frigate recovering from a problem, not causing one. One of these after a camera reboot or a brief network drop is normal. Seeing them repeat every couple of minutes means the camera or the network is still failing, and the restarts can extend the damage, because each one cuts off the segment that was being written. Work from the earliest failure in that camera's log rather than from the restarts.
|
|
||||||
|
|
||||||
</FaqItem>
|
|
||||||
|
|
||||||
<FaqItem id="i-see-the-message-warning--unable-to-keep-up-with-recording-segments-in-cache-for-camera-keeping-the-5-most-recent-segments-out-of-6-and-discarding-the-rest" question="I see the message: WARNING : Unable to keep up with recording segments in cache for camera. Keeping the 5 most recent segments out of 6 and discarding the rest...">
|
<FaqItem id="i-see-the-message-warning--unable-to-keep-up-with-recording-segments-in-cache-for-camera-keeping-the-5-most-recent-segments-out-of-6-and-discarding-the-rest" question="I see the message: WARNING : Unable to keep up with recording segments in cache for camera. Keeping the 5 most recent segments out of 6 and discarding the rest...">
|
||||||
|
|
||||||
This warning means the recording maintainer cannot move recording segments from the RAM cache to disk fast enough. When the cache fills up, Frigate discards the oldest segments to avoid running out of memory and crashing, so you lose recorded footage. This is almost always a storage throughput or system resource problem. Work through the steps below to identify which.
|
This warning means the recording maintainer cannot move recording segments from the RAM cache to disk fast enough. When the cache fills up, Frigate discards the oldest segments to avoid running out of memory and crashing, so you lose recorded footage. This is almost always a storage throughput or system resource problem. Work through the steps below to identify which.
|
||||||
@@ -397,11 +353,19 @@ dmesg | grep -i -E "gpu|drm|reset|hang"
|
|||||||
|
|
||||||
Messages like `trying reset from guc_exec_queue_timedout_job` or similar GPU reset/hang messages indicate a driver or hardware issue. Ensure your kernel and GPU drivers (especially Intel) are up to date.
|
Messages like `trying reset from guc_exec_queue_timedout_job` or similar GPU reset/hang messages indicate a driver or hardware issue. Ensure your kernel and GPU drivers (especially Intel) are up to date.
|
||||||
|
|
||||||
#### Step 6: Verify go2rtc stream configuration
|
#### Step 6: Verify hardware acceleration configuration
|
||||||
|
|
||||||
|
An incorrect `hwaccel_args` preset can cause ffmpeg to fail silently or consume excessive CPU, starving the detector of resources.
|
||||||
|
|
||||||
|
- After upgrading Frigate, verify your preset matches your hardware (e.g., `preset-intel-qsv-h264` instead of the deprecated `preset-vaapi`).
|
||||||
|
- For h265 cameras, use the corresponding h265 preset (e.g., `preset-intel-qsv-h265`).
|
||||||
|
- Note that `hwaccel_args` are only relevant for the detect stream. Frigate does not decode the record stream.
|
||||||
|
|
||||||
|
#### Step 7: Verify go2rtc stream configuration
|
||||||
|
|
||||||
Ensure that the ffmpeg source names in your go2rtc configuration match the correct camera stream. A misconfigured stream name (e.g., copying a config from one camera to another without updating the stream reference) will cause the wrong stream to be used or the stream to fail entirely.
|
Ensure that the ffmpeg source names in your go2rtc configuration match the correct camera stream. A misconfigured stream name (e.g., copying a config from one camera to another without updating the stream reference) will cause the wrong stream to be used or the stream to fail entirely.
|
||||||
|
|
||||||
#### Step 7: Check system resources
|
#### Step 8: Check system resources
|
||||||
|
|
||||||
If none of the above apply, the issue may be a general resource constraint. Monitor the following on your host:
|
If none of the above apply, the issue may be a general resource constraint. Monitor the following on your host:
|
||||||
|
|
||||||
|
|||||||
+22
-30
@@ -3,9 +3,6 @@ import * as path from "node:path";
|
|||||||
import type { Config, PluginConfig } from "@docusaurus/types";
|
import type { Config, PluginConfig } from "@docusaurus/types";
|
||||||
import type * as OpenApiPlugin from "docusaurus-plugin-openapi-docs";
|
import type * as OpenApiPlugin from "docusaurus-plugin-openapi-docs";
|
||||||
|
|
||||||
// Bump when a new stable release ships
|
|
||||||
const STABLE_VERSION = "0.18";
|
|
||||||
|
|
||||||
const config: Config = {
|
const config: Config = {
|
||||||
title: "Frigate",
|
title: "Frigate",
|
||||||
tagline: "NVR With Realtime Object Detection for IP Cameras",
|
tagline: "NVR With Realtime Object Detection for IP Cameras",
|
||||||
@@ -26,17 +23,17 @@ const config: Config = {
|
|||||||
mermaid: true,
|
mermaid: true,
|
||||||
},
|
},
|
||||||
i18n: {
|
i18n: {
|
||||||
defaultLocale: "en",
|
defaultLocale: 'en',
|
||||||
locales: ["en"],
|
locales: ['en'],
|
||||||
localeConfigs: {
|
localeConfigs: {
|
||||||
en: {
|
en: {
|
||||||
label: "English",
|
label: 'English',
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
themeConfig: {
|
themeConfig: {
|
||||||
announcementBar: {
|
announcementBar: {
|
||||||
id: "frigate_plus",
|
id: 'frigate_plus',
|
||||||
content: `
|
content: `
|
||||||
<span style="margin-right: 8px; display: inline-block; animation: pulse 2s infinite;">🚀</span>
|
<span style="margin-right: 8px; display: inline-block; animation: pulse 2s infinite;">🚀</span>
|
||||||
Get more relevant and accurate detections with Frigate+ models.
|
Get more relevant and accurate detections with Frigate+ models.
|
||||||
@@ -48,8 +45,8 @@ const config: Config = {
|
|||||||
50% { transform: scale(1.1); }
|
50% { transform: scale(1.1); }
|
||||||
}
|
}
|
||||||
</style>`,
|
</style>`,
|
||||||
backgroundColor: "#005f73",
|
backgroundColor: '#005f73',
|
||||||
textColor: "#e0fbfc",
|
textColor: '#e0fbfc',
|
||||||
isCloseable: false,
|
isCloseable: false,
|
||||||
},
|
},
|
||||||
docs: {
|
docs: {
|
||||||
@@ -86,15 +83,15 @@ const config: Config = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
prism: {
|
prism: {
|
||||||
magicComments: [
|
magicComments:[
|
||||||
{
|
{
|
||||||
className: "theme-code-block-highlighted-line",
|
className: 'theme-code-block-highlighted-line',
|
||||||
line: "highlight-next-line",
|
line: 'highlight-next-line',
|
||||||
block: { start: "highlight-start", end: "highlight-end" },
|
block: {start: 'highlight-start', end: 'highlight-end'},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
className: "code-block-error-line",
|
className: 'code-block-error-line',
|
||||||
line: "highlight-error-line",
|
line: 'highlight-error-line',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
additionalLanguages: ["bash", "json"],
|
additionalLanguages: ["bash", "json"],
|
||||||
@@ -134,11 +131,6 @@ const config: Config = {
|
|||||||
srcDark: "img/branding/logo-dark.svg",
|
srcDark: "img/branding/logo-dark.svg",
|
||||||
},
|
},
|
||||||
items: [
|
items: [
|
||||||
{
|
|
||||||
href: "https://github.com/blakeblackshear/frigate/releases",
|
|
||||||
label: `${STABLE_VERSION}`,
|
|
||||||
position: "left",
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
to: "/",
|
to: "/",
|
||||||
activeBasePath: "docs",
|
activeBasePath: "docs",
|
||||||
@@ -156,19 +148,19 @@ const config: Config = {
|
|||||||
position: "right",
|
position: "right",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: "localeDropdown",
|
type: 'localeDropdown',
|
||||||
position: "right",
|
position: 'right',
|
||||||
dropdownItemsAfter: [
|
dropdownItemsAfter: [
|
||||||
{
|
{
|
||||||
label: "简体中文(社区翻译)",
|
label: '简体中文(社区翻译)',
|
||||||
href: "https://docs.frigate-cn.video",
|
href: 'https://docs.frigate-cn.video',
|
||||||
},
|
}
|
||||||
],
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
href: "https://github.com/blakeblackshear/frigate",
|
href: 'https://github.com/blakeblackshear/frigate',
|
||||||
label: "GitHub",
|
label: 'GitHub',
|
||||||
position: "right",
|
position: 'right',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
Vendored
+47
-31
@@ -1476,7 +1476,7 @@ paths:
|
|||||||
- Classification
|
- Classification
|
||||||
summary: Get custom classification attributes
|
summary: Get custom classification attributes
|
||||||
description: |-
|
description: |-
|
||||||
**Access:** Authenticated user with access to all cameras.
|
**Access:** Admin role required.
|
||||||
|
|
||||||
Returns custom classification attributes for a given object type.
|
Returns custom classification attributes for a given object type.
|
||||||
Only includes models with classification_type set to 'attribute'.
|
Only includes models with classification_type set to 'attribute'.
|
||||||
@@ -1510,8 +1510,8 @@ paths:
|
|||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/HTTPValidationError'
|
$ref: '#/components/schemas/HTTPValidationError'
|
||||||
security:
|
security:
|
||||||
- frigateUserAuth: []
|
- frigateAdminAuth: []
|
||||||
x-required-role: all_cameras
|
x-required-role: admin
|
||||||
/classification/{name}/train:
|
/classification/{name}/train:
|
||||||
get:
|
get:
|
||||||
tags:
|
tags:
|
||||||
@@ -2308,15 +2308,15 @@ paths:
|
|||||||
$ref: '#/components/schemas/HTTPValidationError'
|
$ref: '#/components/schemas/HTTPValidationError'
|
||||||
security:
|
security:
|
||||||
- frigateUserAuth: []
|
- frigateUserAuth: []
|
||||||
x-required-role: camera
|
x-required-role: any
|
||||||
description: '**Access:** Authenticated user with access to the referenced camera.'
|
description: '**Access:** Any authenticated user.'
|
||||||
/review/summarize/start/{start_ts}/end/{end_ts}:
|
/review/summarize/start/{start_ts}/end/{end_ts}:
|
||||||
post:
|
post:
|
||||||
tags:
|
tags:
|
||||||
- Review
|
- Review
|
||||||
summary: Generate Review Summary
|
summary: Generate Review Summary
|
||||||
description: |-
|
description: |-
|
||||||
**Access:** Authenticated user with access to all cameras.
|
**Access:** Admin role required.
|
||||||
|
|
||||||
Use GenAI to summarize review items over a period of time.
|
Use GenAI to summarize review items over a period of time.
|
||||||
operationId:
|
operationId:
|
||||||
@@ -2347,8 +2347,8 @@ paths:
|
|||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/HTTPValidationError'
|
$ref: '#/components/schemas/HTTPValidationError'
|
||||||
security:
|
security:
|
||||||
- frigateUserAuth: []
|
- frigateAdminAuth: []
|
||||||
x-required-role: all_cameras
|
x-required-role: admin
|
||||||
/:
|
/:
|
||||||
get:
|
get:
|
||||||
tags:
|
tags:
|
||||||
@@ -2946,6 +2946,44 @@ paths:
|
|||||||
- frigateUserAuth: []
|
- frigateUserAuth: []
|
||||||
x-required-role: any
|
x-required-role: any
|
||||||
description: '**Access:** Any authenticated user.'
|
description: '**Access:** Any authenticated user.'
|
||||||
|
/categorized_object_names:
|
||||||
|
get:
|
||||||
|
tags:
|
||||||
|
- App
|
||||||
|
summary: Get known object names by object type
|
||||||
|
description: |-
|
||||||
|
**Access:** Any authenticated user.
|
||||||
|
|
||||||
|
Returns the sub labels and attributes this install can attach,
|
||||||
|
grouped by object type. Unlike /sub_labels, which reflects what has already been
|
||||||
|
detected, this reads the config and model files, so it covers recognized face
|
||||||
|
names, named license plates, custom object classification categories, and the
|
||||||
|
detector attributes of tracked objects.
|
||||||
|
operationId: categorized_object_names_categorized_object_names_get
|
||||||
|
parameters:
|
||||||
|
- name: object_type
|
||||||
|
in: query
|
||||||
|
required: false
|
||||||
|
schema:
|
||||||
|
anyOf:
|
||||||
|
- type: string
|
||||||
|
- type: 'null'
|
||||||
|
title: Object Type
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Successful Response
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {}
|
||||||
|
'422':
|
||||||
|
description: Validation Error
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: '#/components/schemas/HTTPValidationError'
|
||||||
|
security:
|
||||||
|
- frigateUserAuth: []
|
||||||
|
x-required-role: any
|
||||||
/audio_labels:
|
/audio_labels:
|
||||||
get:
|
get:
|
||||||
tags:
|
tags:
|
||||||
@@ -4073,16 +4111,6 @@ paths:
|
|||||||
- type: 'null'
|
- type: 'null'
|
||||||
default: 100
|
default: 100
|
||||||
title: Limit
|
title: Limit
|
||||||
- name: offset
|
|
||||||
in: query
|
|
||||||
required: false
|
|
||||||
schema:
|
|
||||||
anyOf:
|
|
||||||
- type: integer
|
|
||||||
minimum: 0
|
|
||||||
- type: 'null'
|
|
||||||
default: 0
|
|
||||||
title: Offset
|
|
||||||
- name: after
|
- name: after
|
||||||
in: query
|
in: query
|
||||||
required: false
|
required: false
|
||||||
@@ -4388,16 +4416,6 @@ paths:
|
|||||||
- type: 'null'
|
- type: 'null'
|
||||||
default: 50
|
default: 50
|
||||||
title: Limit
|
title: Limit
|
||||||
- name: offset
|
|
||||||
in: query
|
|
||||||
required: false
|
|
||||||
schema:
|
|
||||||
anyOf:
|
|
||||||
- type: integer
|
|
||||||
minimum: 0
|
|
||||||
- type: 'null'
|
|
||||||
default: 0
|
|
||||||
title: Offset
|
|
||||||
- name: cameras
|
- name: cameras
|
||||||
in: query
|
in: query
|
||||||
required: false
|
required: false
|
||||||
@@ -7129,9 +7147,7 @@ paths:
|
|||||||
schema:
|
schema:
|
||||||
$ref: '#/components/schemas/DebugReplayStartResponse'
|
$ref: '#/components/schemas/DebugReplayStartResponse'
|
||||||
'400':
|
'400':
|
||||||
description: Invalid camera or time range
|
description: Invalid camera, time range, or no recordings
|
||||||
'404':
|
|
||||||
description: No recordings in the requested time range
|
|
||||||
'409':
|
'409':
|
||||||
description: A replay session is already active
|
description: A replay session is already active
|
||||||
'422':
|
'422':
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ from frigate.util.config import (
|
|||||||
find_config_file,
|
find_config_file,
|
||||||
redact_credential,
|
redact_credential,
|
||||||
)
|
)
|
||||||
|
from frigate.util.object_names import get_categorized_object_names
|
||||||
from frigate.util.schema import get_config_schema
|
from frigate.util.schema import get_config_schema
|
||||||
from frigate.util.services import (
|
from frigate.util.services import (
|
||||||
get_nvidia_driver_info,
|
get_nvidia_driver_info,
|
||||||
@@ -1313,6 +1314,28 @@ def get_sub_labels(
|
|||||||
return JSONResponse(content=sub_labels)
|
return JSONResponse(content=sub_labels)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/categorized_object_names",
|
||||||
|
dependencies=[Depends(allow_any_authenticated())],
|
||||||
|
summary="Get known object names by object type",
|
||||||
|
description="""Returns the sub labels and attributes this install can attach,
|
||||||
|
grouped by object type. Unlike /sub_labels, which reflects what has already been
|
||||||
|
detected, this reads the config and model files, so it covers recognized face
|
||||||
|
names, named license plates, custom object classification categories, and the
|
||||||
|
detector attributes of tracked objects.""",
|
||||||
|
)
|
||||||
|
def categorized_object_names(
|
||||||
|
request: Request,
|
||||||
|
object_type: str | None = None,
|
||||||
|
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
|
||||||
|
):
|
||||||
|
return JSONResponse(
|
||||||
|
content=get_categorized_object_names(
|
||||||
|
request.app.frigate_config, allowed_cameras, object_type
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/audio_labels", dependencies=[Depends(allow_any_authenticated())])
|
@router.get("/audio_labels", dependencies=[Depends(allow_any_authenticated())])
|
||||||
def get_audio_labels():
|
def get_audio_labels():
|
||||||
labels = load_labels("/audio-labelmap.txt", prefill=521)
|
labels = load_labels("/audio-labelmap.txt", prefill=521)
|
||||||
|
|||||||
+21
-38
@@ -83,9 +83,9 @@ def require_admin_by_default():
|
|||||||
"/nvinfo",
|
"/nvinfo",
|
||||||
"/labels",
|
"/labels",
|
||||||
"/sub_labels",
|
"/sub_labels",
|
||||||
|
"/categorized_object_names",
|
||||||
"/plus/models",
|
"/plus/models",
|
||||||
"/recognized_license_plates",
|
"/recognized_license_plates",
|
||||||
"/classification/attributes",
|
|
||||||
"/timeline",
|
"/timeline",
|
||||||
"/timeline/hourly",
|
"/timeline/hourly",
|
||||||
"/recordings/storage",
|
"/recordings/storage",
|
||||||
@@ -127,18 +127,23 @@ def require_admin_by_default():
|
|||||||
if path.startswith(EXEMPT_PREFIXES):
|
if path.startswith(EXEMPT_PREFIXES):
|
||||||
return
|
return
|
||||||
|
|
||||||
# Camera routes enforce per-camera access via route-level dependencies
|
# Dynamic camera path exemption:
|
||||||
# (e.g. require_camera_access). Match on the route template, not the raw
|
# Any path whose first segment matches a configured camera name should
|
||||||
# path, so a camera named like another namespace (e.g. "faces") can't
|
# bypass the global admin requirement. These endpoints enforce access
|
||||||
# waive the admin check for that namespace's routes.
|
# via route-level dependencies (e.g. require_camera_access) to ensure
|
||||||
route = request.scope.get("route")
|
# per-camera authorization. This allows non-admin authenticated users
|
||||||
if (
|
# (e.g. viewer role) to access camera-specific resources without
|
||||||
route is not None
|
# needing admin privileges.
|
||||||
and route.path.startswith("/{camera_name}")
|
try:
|
||||||
and request.path_params.get("camera_name")
|
if path.startswith("/"):
|
||||||
in request.app.frigate_config.cameras
|
first_segment = path.split("/", 2)[1]
|
||||||
):
|
if (
|
||||||
return
|
first_segment
|
||||||
|
and first_segment in request.app.frigate_config.cameras
|
||||||
|
):
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
# For all other paths, require admin role
|
# For all other paths, require admin role
|
||||||
# Internal port requests have admin role set automatically
|
# Internal port requests have admin role set automatically
|
||||||
@@ -967,7 +972,6 @@ def delete_user(request: Request, username: str):
|
|||||||
summary="Update user password",
|
summary="Update user password",
|
||||||
description="Updates a user's password. Users can only change their own password unless they have admin role. Requires the current password to verify identity for non-admin users. Password must be at least 12 characters long. If user changes their own password, a new JWT cookie is automatically issued.",
|
description="Updates a user's password. Users can only change their own password unless they have admin role. Requires the current password to verify identity for non-admin users. Password must be at least 12 characters long. If user changes their own password, a new JWT cookie is automatically issued.",
|
||||||
)
|
)
|
||||||
@limiter.limit(limit_value=rateLimiter.get_limit)
|
|
||||||
async def update_password(
|
async def update_password(
|
||||||
request: Request,
|
request: Request,
|
||||||
username: str,
|
username: str,
|
||||||
@@ -981,11 +985,10 @@ async def update_password(
|
|||||||
current_username = current_user.get("username")
|
current_username = current_user.get("username")
|
||||||
current_role = current_user.get("role")
|
current_role = current_user.get("role")
|
||||||
|
|
||||||
# Only admins may target another account. This has to cover every non-admin
|
# viewers can only change their own password
|
||||||
# role rather than just viewer, since custom roles are arbitrary names
|
if current_role == "viewer" and current_username != username:
|
||||||
if current_role != "admin" and current_username != username:
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=403, detail="Users can only update their own password"
|
status_code=403, detail="Viewers can only update their own password"
|
||||||
)
|
)
|
||||||
|
|
||||||
HASH_ITERATIONS = request.app.frigate_config.auth.hash_iterations
|
HASH_ITERATIONS = request.app.frigate_config.auth.hash_iterations
|
||||||
@@ -1249,23 +1252,3 @@ async def get_allowed_cameras_for_filter(request: Request):
|
|||||||
all_camera_names = set(request.app.frigate_config.cameras.keys())
|
all_camera_names = set(request.app.frigate_config.cameras.keys())
|
||||||
roles_dict = request.app.frigate_config.auth.roles
|
roles_dict = request.app.frigate_config.auth.roles
|
||||||
return User.get_allowed_cameras(role, roles_dict, all_camera_names)
|
return User.get_allowed_cameras(role, roles_dict, all_camera_names)
|
||||||
|
|
||||||
|
|
||||||
async def require_full_camera_access(
|
|
||||||
request: Request,
|
|
||||||
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
|
|
||||||
):
|
|
||||||
"""Dependency for endpoints returning data that spans every camera.
|
|
||||||
|
|
||||||
Some responses cannot be meaningfully scoped to a subset of cameras, so
|
|
||||||
rather than filter them the endpoint is limited to callers who can already
|
|
||||||
see every camera. Admin and viewer always qualify; a custom role qualifies
|
|
||||||
only when its camera list covers all configured cameras.
|
|
||||||
"""
|
|
||||||
all_camera_names = set(request.app.frigate_config.cameras.keys())
|
|
||||||
|
|
||||||
if not all_camera_names.issubset(allowed_cameras):
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=403,
|
|
||||||
detail="Access to all cameras is required for this endpoint",
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -35,11 +35,7 @@ from frigate.config.camera.updater import (
|
|||||||
)
|
)
|
||||||
from frigate.config.env import substitute_frigate_vars
|
from frigate.config.env import substitute_frigate_vars
|
||||||
from frigate.models import User
|
from frigate.models import User
|
||||||
from frigate.util.builtin import (
|
from frigate.util.builtin import clean_camera_user_pass, get_record_segment_time
|
||||||
clean_camera_user_pass,
|
|
||||||
clear_orphaned_comments,
|
|
||||||
get_record_segment_time,
|
|
||||||
)
|
|
||||||
from frigate.util.camera_cleanup import cleanup_camera_db, cleanup_camera_files
|
from frigate.util.camera_cleanup import cleanup_camera_db, cleanup_camera_files
|
||||||
from frigate.util.config import find_config_file
|
from frigate.util.config import find_config_file
|
||||||
from frigate.util.image import run_ffmpeg_snapshot
|
from frigate.util.image import run_ffmpeg_snapshot
|
||||||
@@ -1205,7 +1201,6 @@ async def delete_camera(
|
|||||||
# Remove camera from config
|
# Remove camera from config
|
||||||
if "cameras" in data and camera_name in data["cameras"]:
|
if "cameras" in data and camera_name in data["cameras"]:
|
||||||
del data["cameras"][camera_name]
|
del data["cameras"][camera_name]
|
||||||
clear_orphaned_comments(data["cameras"], data, "cameras")
|
|
||||||
|
|
||||||
# Remove camera from auth roles
|
# Remove camera from auth roles
|
||||||
auth = data.get("auth", {})
|
auth = data.get("auth", {})
|
||||||
|
|||||||
+27
-4
@@ -50,6 +50,7 @@ from frigate.jobs.vlm_watch import (
|
|||||||
stop_vlm_watch_job,
|
stop_vlm_watch_job,
|
||||||
)
|
)
|
||||||
from frigate.models import Event
|
from frigate.models import Event
|
||||||
|
from frigate.util.object_names import get_categorized_object_names
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -539,6 +540,11 @@ async def execute_tool(
|
|||||||
if tool_name == "search_objects":
|
if tool_name == "search_objects":
|
||||||
return await _execute_search_objects(request, arguments, allowed_cameras)
|
return await _execute_search_objects(request, arguments, allowed_cameras)
|
||||||
|
|
||||||
|
if tool_name == "get_categorized_object_names":
|
||||||
|
return JSONResponse(
|
||||||
|
content=_execute_get_categorized_object_names(request, allowed_cameras)
|
||||||
|
)
|
||||||
|
|
||||||
if tool_name == "find_similar_objects":
|
if tool_name == "find_similar_objects":
|
||||||
result = await _execute_find_similar_objects(
|
result = await _execute_find_similar_objects(
|
||||||
request, arguments, allowed_cameras
|
request, arguments, allowed_cameras
|
||||||
@@ -591,7 +597,7 @@ async def _execute_get_live_context(
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
frame_processor = request.app.detected_frames_processor
|
frame_processor = request.app.detected_frames_processor
|
||||||
camera_state = frame_processor.camera_states.get(camera)
|
camera_state = frame_processor.get_camera_state(camera)
|
||||||
|
|
||||||
if camera_state is None:
|
if camera_state is None:
|
||||||
return {
|
return {
|
||||||
@@ -655,7 +661,7 @@ async def _get_live_frame_image_url(
|
|||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
frame_processor = request.app.detected_frames_processor
|
frame_processor = request.app.detected_frames_processor
|
||||||
if camera not in frame_processor.camera_states:
|
if frame_processor.get_camera_state(camera) is None:
|
||||||
return None
|
return None
|
||||||
frame = frame_processor.get_current_frame(camera, {})
|
frame = frame_processor.get_current_frame(camera, {})
|
||||||
if frame is None:
|
if frame is None:
|
||||||
@@ -717,6 +723,21 @@ async def _execute_set_camera_state(
|
|||||||
return {"success": True, "camera": camera, "feature": feature, "value": value}
|
return {"success": True, "camera": camera, "feature": feature, "value": value}
|
||||||
|
|
||||||
|
|
||||||
|
def _execute_get_categorized_object_names(
|
||||||
|
request: Request,
|
||||||
|
allowed_cameras: list[str],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
names = get_categorized_object_names(request.app.frigate_config, allowed_cameras)
|
||||||
|
|
||||||
|
if not names:
|
||||||
|
return {
|
||||||
|
"names": {},
|
||||||
|
"message": "No names configured; search by label or semantic_query.",
|
||||||
|
}
|
||||||
|
|
||||||
|
return {"names": names}
|
||||||
|
|
||||||
|
|
||||||
async def _execute_tool_internal(
|
async def _execute_tool_internal(
|
||||||
tool_name: str,
|
tool_name: str,
|
||||||
arguments: dict[str, Any],
|
arguments: dict[str, Any],
|
||||||
@@ -741,6 +762,8 @@ async def _execute_tool_internal(
|
|||||||
except (json.JSONDecodeError, AttributeError) as e:
|
except (json.JSONDecodeError, AttributeError) as e:
|
||||||
logger.warning(f"Failed to extract tool result: {e}")
|
logger.warning(f"Failed to extract tool result: {e}")
|
||||||
return {"error": "Failed to parse tool result"}
|
return {"error": "Failed to parse tool result"}
|
||||||
|
elif tool_name == "get_categorized_object_names":
|
||||||
|
return _execute_get_categorized_object_names(request, allowed_cameras)
|
||||||
elif tool_name == "find_similar_objects":
|
elif tool_name == "find_similar_objects":
|
||||||
return await _execute_find_similar_objects(request, arguments, allowed_cameras)
|
return await _execute_find_similar_objects(request, arguments, allowed_cameras)
|
||||||
elif tool_name == "set_camera_state":
|
elif tool_name == "set_camera_state":
|
||||||
@@ -773,8 +796,8 @@ async def _execute_tool_internal(
|
|||||||
else:
|
else:
|
||||||
logger.error(
|
logger.error(
|
||||||
"Tool call failed: unknown tool %r. Expected one of: search_objects, find_similar_objects, "
|
"Tool call failed: unknown tool %r. Expected one of: search_objects, find_similar_objects, "
|
||||||
"get_live_context, start_camera_watch, stop_camera_watch, get_profile_status, get_recap. "
|
"get_categorized_object_names, get_live_context, start_camera_watch, stop_camera_watch, "
|
||||||
"Arguments received: %s",
|
"get_profile_status, get_recap. Arguments received: %s",
|
||||||
tool_name,
|
tool_name,
|
||||||
json.dumps(arguments),
|
json.dumps(arguments),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from fastapi.responses import JSONResponse
|
|||||||
from peewee import DoesNotExist
|
from peewee import DoesNotExist
|
||||||
from playhouse.shortcuts import model_to_dict
|
from playhouse.shortcuts import model_to_dict
|
||||||
|
|
||||||
from frigate.api.auth import require_full_camera_access, require_role
|
from frigate.api.auth import require_role
|
||||||
from frigate.api.defs.request.classification_body import (
|
from frigate.api.defs.request.classification_body import (
|
||||||
AudioTranscriptionBody,
|
AudioTranscriptionBody,
|
||||||
DeleteFaceImagesBody,
|
DeleteFaceImagesBody,
|
||||||
@@ -741,7 +741,6 @@ def get_classification_dataset(name: str):
|
|||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/classification/attributes",
|
"/classification/attributes",
|
||||||
dependencies=[Depends(require_full_camera_access)],
|
|
||||||
summary="Get custom classification attributes",
|
summary="Get custom classification attributes",
|
||||||
description="""Returns custom classification attributes for a given object type.
|
description="""Returns custom classification attributes for a given object type.
|
||||||
Only includes models with classification_type set to 'attribute'.
|
Only includes models with classification_type set to 'attribute'.
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ from frigate.api.auth import require_role
|
|||||||
from frigate.api.defs.tags import Tags
|
from frigate.api.defs.tags import Tags
|
||||||
from frigate.jobs.debug_replay import (
|
from frigate.jobs.debug_replay import (
|
||||||
ExportDebugReplaySource,
|
ExportDebugReplaySource,
|
||||||
NoRecordingsError,
|
|
||||||
RecordingDebugReplaySource,
|
RecordingDebugReplaySource,
|
||||||
start_debug_replay_job,
|
start_debug_replay_job,
|
||||||
)
|
)
|
||||||
@@ -75,8 +74,7 @@ class DebugReplayStopResponse(BaseModel):
|
|||||||
response_model=DebugReplayStartResponse,
|
response_model=DebugReplayStartResponse,
|
||||||
status_code=202,
|
status_code=202,
|
||||||
responses={
|
responses={
|
||||||
400: {"description": "Invalid camera or time range"},
|
400: {"description": "Invalid camera, time range, or no recordings"},
|
||||||
404: {"description": "No recordings in the requested time range"},
|
|
||||||
409: {"description": "A replay session is already active"},
|
409: {"description": "A replay session is already active"},
|
||||||
},
|
},
|
||||||
dependencies=[Depends(require_role(["admin"]))],
|
dependencies=[Depends(require_role(["admin"]))],
|
||||||
@@ -115,14 +113,6 @@ async def start_debug_replay(request: Request, body: DebugReplayStartBody):
|
|||||||
},
|
},
|
||||||
status_code=409,
|
status_code=409,
|
||||||
)
|
)
|
||||||
except NoRecordingsError:
|
|
||||||
return JSONResponse(
|
|
||||||
content={
|
|
||||||
"success": False,
|
|
||||||
"message": "No recordings found in the selected time range",
|
|
||||||
},
|
|
||||||
status_code=404,
|
|
||||||
)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
logger.exception("Rejected debug replay start request")
|
logger.exception("Rejected debug replay start request")
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ class EventsQueryParams(BaseModel):
|
|||||||
zone: str | None = "all"
|
zone: str | None = "all"
|
||||||
zones: str | None = "all"
|
zones: str | None = "all"
|
||||||
limit: int | None = 100
|
limit: int | None = 100
|
||||||
offset: int | None = Field(0, ge=0)
|
|
||||||
after: float | None = None
|
after: float | None = None
|
||||||
before: float | None = None
|
before: float | None = None
|
||||||
time_range: str | None = DEFAULT_TIME_RANGE
|
time_range: str | None = DEFAULT_TIME_RANGE
|
||||||
@@ -56,7 +55,6 @@ class EventsSearchQueryParams(BaseModel):
|
|||||||
deprecated=True,
|
deprecated=True,
|
||||||
)
|
)
|
||||||
limit: int | None = 50
|
limit: int | None = 50
|
||||||
offset: int | None = Field(0, ge=0)
|
|
||||||
cameras: str | None = "all"
|
cameras: str | None = "all"
|
||||||
labels: str | None = "all"
|
labels: str | None = "all"
|
||||||
sub_labels: str | None = "all"
|
sub_labels: str | None = "all"
|
||||||
|
|||||||
+4
-13
@@ -129,7 +129,6 @@ def events(
|
|||||||
zones = zone
|
zones = zone
|
||||||
|
|
||||||
limit = params.limit
|
limit = params.limit
|
||||||
offset = params.offset
|
|
||||||
after = params.after
|
after = params.after
|
||||||
before = params.before
|
before = params.before
|
||||||
time_range = params.time_range
|
time_range = params.time_range
|
||||||
@@ -362,15 +361,11 @@ def events(
|
|||||||
else:
|
else:
|
||||||
order_by = Event.start_time.desc()
|
order_by = Event.start_time.desc()
|
||||||
|
|
||||||
# offset paging needs a stable order when scores or speeds tie
|
|
||||||
tiebreaker = [Event.id] if sort and sort.startswith(("score", "speed")) else []
|
|
||||||
|
|
||||||
events = (
|
events = (
|
||||||
Event.select(*selected_columns)
|
Event.select(*selected_columns)
|
||||||
.where(reduce(operator.and_, clauses))
|
.where(reduce(operator.and_, clauses))
|
||||||
.order_by(order_by, *tiebreaker)
|
.order_by(order_by)
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.offset(offset)
|
|
||||||
.dicts()
|
.dicts()
|
||||||
.iterator()
|
.iterator()
|
||||||
)
|
)
|
||||||
@@ -523,7 +518,6 @@ def events_search(
|
|||||||
search_type = params.search_type
|
search_type = params.search_type
|
||||||
include_thumbnails = params.include_thumbnails
|
include_thumbnails = params.include_thumbnails
|
||||||
limit = params.limit
|
limit = params.limit
|
||||||
offset = params.offset
|
|
||||||
sort = params.sort
|
sort = params.sort
|
||||||
|
|
||||||
# Filters
|
# Filters
|
||||||
@@ -830,9 +824,6 @@ def events_search(
|
|||||||
if search_results:
|
if search_results:
|
||||||
events_query = events_query.where(Event.id << list(search_results.keys()))
|
events_query = events_query.where(Event.id << list(search_results.keys()))
|
||||||
|
|
||||||
# sorts below are stable, so this orders ties for offset paging
|
|
||||||
events_query = events_query.order_by(Event.id)
|
|
||||||
|
|
||||||
# Fetch events and process them in a single pass
|
# Fetch events and process them in a single pass
|
||||||
processed_events = []
|
processed_events = []
|
||||||
for event in events_query.dicts():
|
for event in events_query.dicts():
|
||||||
@@ -890,7 +881,7 @@ def events_search(
|
|||||||
processed_events.sort(key=lambda x: x["start_time"], reverse=True)
|
processed_events.sort(key=lambda x: x["start_time"], reverse=True)
|
||||||
|
|
||||||
# Limit the number of events returned
|
# Limit the number of events returned
|
||||||
processed_events = processed_events[offset:][:limit]
|
processed_events = processed_events[:limit]
|
||||||
|
|
||||||
return JSONResponse(content=processed_events)
|
return JSONResponse(content=processed_events)
|
||||||
|
|
||||||
@@ -1322,7 +1313,7 @@ async def set_sub_label(
|
|||||||
if request.app.detected_frames_processor:
|
if request.app.detected_frames_processor:
|
||||||
tracked_obj: TrackedObject = None
|
tracked_obj: TrackedObject = None
|
||||||
|
|
||||||
for state in request.app.detected_frames_processor.camera_states.values():
|
for state in request.app.detected_frames_processor.get_camera_states():
|
||||||
tracked_obj = state.tracked_objects.get(event_id)
|
tracked_obj = state.tracked_objects.get(event_id)
|
||||||
|
|
||||||
if tracked_obj is not None:
|
if tracked_obj is not None:
|
||||||
@@ -1381,7 +1372,7 @@ async def set_plate(
|
|||||||
if request.app.detected_frames_processor:
|
if request.app.detected_frames_processor:
|
||||||
tracked_obj: TrackedObject = None
|
tracked_obj: TrackedObject = None
|
||||||
|
|
||||||
for state in request.app.detected_frames_processor.camera_states.values():
|
for state in request.app.detected_frames_processor.get_camera_states():
|
||||||
tracked_obj = state.tracked_objects.get(event_id)
|
tracked_obj = state.tracked_objects.get(event_id)
|
||||||
|
|
||||||
if tracked_obj is not None:
|
if tracked_obj is not None:
|
||||||
|
|||||||
+2
-22
@@ -9,7 +9,6 @@ import zipfile
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from urllib.parse import quote
|
|
||||||
|
|
||||||
import psutil
|
import psutil
|
||||||
from fastapi import APIRouter, Depends, Query, Request
|
from fastapi import APIRouter, Depends, Query, Request
|
||||||
@@ -69,7 +68,6 @@ from frigate.jobs.export import (
|
|||||||
from frigate.models import Export, ExportCase, Previews, Recordings
|
from frigate.models import Export, ExportCase, Previews, Recordings
|
||||||
from frigate.record.export import (
|
from frigate.record.export import (
|
||||||
DEFAULT_TIME_LAPSE_FFMPEG_ARGS,
|
DEFAULT_TIME_LAPSE_FFMPEG_ARGS,
|
||||||
DEFAULT_TIME_LAPSE_FFMPEG_INPUT_ARGS,
|
|
||||||
ChaptersEnum,
|
ChaptersEnum,
|
||||||
PlaybackSourceEnum,
|
PlaybackSourceEnum,
|
||||||
validate_ffmpeg_args,
|
validate_ffmpeg_args,
|
||||||
@@ -455,22 +453,6 @@ def _stream_case_archive(exports: list[Export]) -> Iterator[bytes]:
|
|||||||
yield from buffer.drain()
|
yield from buffer.drain()
|
||||||
|
|
||||||
|
|
||||||
def _content_disposition(filename: str, ascii_fallback: str) -> str:
|
|
||||||
"""Build an attachment Content-Disposition that survives non-ASCII names.
|
|
||||||
|
|
||||||
Header values are encoded as latin-1, so a name outside that range cannot
|
|
||||||
go in filename at all. RFC 6266 handles this with a pair: a plain ASCII
|
|
||||||
filename for old clients, plus a percent-encoded UTF-8 filename* that
|
|
||||||
every current browser prefers.
|
|
||||||
"""
|
|
||||||
ascii_name = filename if filename.isascii() else ascii_fallback
|
|
||||||
|
|
||||||
return (
|
|
||||||
f'attachment; filename="{ascii_name}"; '
|
|
||||||
f"filename*=UTF-8''{quote(filename, safe='')}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/cases/{case_id}/download",
|
"/cases/{case_id}/download",
|
||||||
dependencies=[Depends(allow_any_authenticated())],
|
dependencies=[Depends(allow_any_authenticated())],
|
||||||
@@ -513,9 +495,7 @@ def download_export_case(
|
|||||||
_stream_case_archive(exports),
|
_stream_case_archive(exports),
|
||||||
media_type="application/zip",
|
media_type="application/zip",
|
||||||
headers={
|
headers={
|
||||||
"Content-Disposition": _content_disposition(
|
"Content-Disposition": f'attachment; filename="{archive_base}.zip"',
|
||||||
f"{archive_base}.zip", f"{case_id}.zip"
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1013,7 +993,7 @@ def export_recording_custom(
|
|||||||
|
|
||||||
# Set default values if not provided (timelapse defaults)
|
# Set default values if not provided (timelapse defaults)
|
||||||
if ffmpeg_input_args is None:
|
if ffmpeg_input_args is None:
|
||||||
ffmpeg_input_args = DEFAULT_TIME_LAPSE_FFMPEG_INPUT_ARGS
|
ffmpeg_input_args = ""
|
||||||
|
|
||||||
if ffmpeg_output_args is None:
|
if ffmpeg_output_args is None:
|
||||||
ffmpeg_output_args = DEFAULT_TIME_LAPSE_FFMPEG_ARGS
|
ffmpeg_output_args = DEFAULT_TIME_LAPSE_FFMPEG_ARGS
|
||||||
|
|||||||
@@ -575,11 +575,11 @@ async def vod_ts(
|
|||||||
Recordings.start_time,
|
Recordings.start_time,
|
||||||
)
|
)
|
||||||
.where(
|
.where(
|
||||||
Recordings.start_time.between(start_ts, end_ts)
|
Recordings.camera == camera_name,
|
||||||
| Recordings.end_time.between(start_ts, end_ts)
|
Recordings.start_time >= start_ts - MAX_SEGMENT_DURATION,
|
||||||
| ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time))
|
Recordings.start_time <= end_ts,
|
||||||
|
Recordings.end_time >= start_ts,
|
||||||
)
|
)
|
||||||
.where(Recordings.camera == camera_name)
|
|
||||||
.order_by(Recordings.start_time.asc())
|
.order_by(Recordings.start_time.asc())
|
||||||
.iterator()
|
.iterator()
|
||||||
)
|
)
|
||||||
@@ -820,7 +820,7 @@ async def event_snapshot(
|
|||||||
# see if the object is currently being tracked
|
# see if the object is currently being tracked
|
||||||
try:
|
try:
|
||||||
camera_states: list[CameraState] = (
|
camera_states: list[CameraState] = (
|
||||||
request.app.detected_frames_processor.camera_states.values()
|
request.app.detected_frames_processor.get_camera_states()
|
||||||
)
|
)
|
||||||
for camera_state in camera_states:
|
for camera_state in camera_states:
|
||||||
if event_id in camera_state.tracked_objects:
|
if event_id in camera_state.tracked_objects:
|
||||||
@@ -898,7 +898,7 @@ async def event_thumbnail(
|
|||||||
if thumbnail_bytes is None:
|
if thumbnail_bytes is None:
|
||||||
# see if the object is currently being tracked
|
# see if the object is currently being tracked
|
||||||
try:
|
try:
|
||||||
camera_states = request.app.detected_frames_processor.camera_states.values()
|
camera_states = request.app.detected_frames_processor.get_camera_states()
|
||||||
for camera_state in camera_states:
|
for camera_state in camera_states:
|
||||||
if event_id in camera_state.tracked_objects:
|
if event_id in camera_state.tracked_objects:
|
||||||
tracked_obj = camera_state.tracked_objects.get(event_id)
|
tracked_obj = camera_state.tracked_objects.get(event_id)
|
||||||
@@ -1127,7 +1127,7 @@ async def event_snapshot_clean(request: Request, event_id: str, download: bool =
|
|||||||
# see if the object is currently being tracked
|
# see if the object is currently being tracked
|
||||||
try:
|
try:
|
||||||
camera_states = (
|
camera_states = (
|
||||||
request.app.detected_frames_processor.camera_states.values()
|
request.app.detected_frames_processor.get_camera_states()
|
||||||
)
|
)
|
||||||
for camera_state in camera_states:
|
for camera_state in camera_states:
|
||||||
if event_id in camera_state.tracked_objects:
|
if event_id in camera_state.tracked_objects:
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
"""Notification apis."""
|
"""Notification apis."""
|
||||||
|
|
||||||
import ipaddress
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from urllib.parse import urlparse
|
|
||||||
|
|
||||||
from cryptography.hazmat.primitives import serialization
|
from cryptography.hazmat.primitives import serialization
|
||||||
from fastapi import APIRouter, Depends, Request
|
from fastapi import APIRouter, Depends, Request
|
||||||
@@ -21,95 +19,6 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
router = APIRouter(tags=[Tags.notifications])
|
router = APIRouter(tags=[Tags.notifications])
|
||||||
|
|
||||||
# Push endpoints are opaque URLs but stay well under this in practice
|
|
||||||
MAX_ENDPOINT_LENGTH = 2048
|
|
||||||
|
|
||||||
# Suffixes that only ever resolve on the local network
|
|
||||||
INTERNAL_HOST_SUFFIXES = (".local", ".localdomain", ".internal", ".home.arpa")
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_push_endpoint(endpoint: Any) -> str | None:
|
|
||||||
"""Return a reason the endpoint is unusable, or None when it is valid.
|
|
||||||
|
|
||||||
Subscriptions are issued by the browser vendor's push service, so a valid
|
|
||||||
endpoint is always a public https URL. Anything else is either a broken
|
|
||||||
registration or an attempt to aim the notification sender somewhere it
|
|
||||||
should not reach.
|
|
||||||
"""
|
|
||||||
if not isinstance(endpoint, str) or not endpoint:
|
|
||||||
return "endpoint must be a url"
|
|
||||||
|
|
||||||
if len(endpoint) > MAX_ENDPOINT_LENGTH:
|
|
||||||
return "endpoint is too long"
|
|
||||||
|
|
||||||
try:
|
|
||||||
parsed = urlparse(endpoint)
|
|
||||||
port = parsed.port
|
|
||||||
except ValueError:
|
|
||||||
return "endpoint is not a valid url"
|
|
||||||
|
|
||||||
if parsed.scheme != "https":
|
|
||||||
return "endpoint must use https"
|
|
||||||
|
|
||||||
if parsed.username or parsed.password:
|
|
||||||
return "endpoint must not include credentials"
|
|
||||||
|
|
||||||
if port is not None and port != 443:
|
|
||||||
return "endpoint must use the default https port"
|
|
||||||
|
|
||||||
hostname = parsed.hostname
|
|
||||||
|
|
||||||
if not hostname:
|
|
||||||
return "endpoint must include a hostname"
|
|
||||||
|
|
||||||
try:
|
|
||||||
address = ipaddress.ip_address(hostname)
|
|
||||||
except ValueError:
|
|
||||||
address = None
|
|
||||||
|
|
||||||
if address is not None:
|
|
||||||
# A push service is never reachable at an address only this network can
|
|
||||||
# route, so anything non-global is a misconfiguration at best
|
|
||||||
if not address.is_global:
|
|
||||||
return "endpoint must not use a private address"
|
|
||||||
elif hostname == "localhost" or "." not in hostname:
|
|
||||||
return "endpoint must use a fully qualified hostname"
|
|
||||||
elif hostname.endswith(INTERNAL_HOST_SUFFIXES):
|
|
||||||
return "endpoint must not use an internal hostname"
|
|
||||||
|
|
||||||
# The subscription token lives in the path, and webpush.py assumes there is
|
|
||||||
# a separator after the host when it builds the VAPID audience
|
|
||||||
if len(parsed.path) <= 1:
|
|
||||||
return "endpoint must include a subscription path"
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_subscription(sub: Any) -> str | None:
|
|
||||||
"""Return a reason the subscription is unusable, or None when it is valid."""
|
|
||||||
if not isinstance(sub, dict):
|
|
||||||
return "subscription must be an object"
|
|
||||||
|
|
||||||
reason = _validate_push_endpoint(sub.get("endpoint"))
|
|
||||||
|
|
||||||
if reason:
|
|
||||||
return reason
|
|
||||||
|
|
||||||
keys = sub.get("keys")
|
|
||||||
|
|
||||||
if not isinstance(keys, dict):
|
|
||||||
return "subscription must include keys"
|
|
||||||
|
|
||||||
# WebPusher raises on a missing key, which would break every send for the
|
|
||||||
# user rather than just this registration
|
|
||||||
for name in ("p256dh", "auth"):
|
|
||||||
value = keys.get(name)
|
|
||||||
|
|
||||||
if not isinstance(value, str) or not value:
|
|
||||||
return f"subscription keys must include {name}"
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/notifications/pubkey",
|
"/notifications/pubkey",
|
||||||
@@ -162,17 +71,6 @@ def register_notifications(request: Request, body: dict = None):
|
|||||||
status_code=400,
|
status_code=400,
|
||||||
)
|
)
|
||||||
|
|
||||||
reason = _validate_subscription(sub)
|
|
||||||
|
|
||||||
if reason:
|
|
||||||
logger.warning(
|
|
||||||
"Rejected notification registration for %s: %s", username, reason
|
|
||||||
)
|
|
||||||
return JSONResponse(
|
|
||||||
content={"success": False, "message": f"Invalid subscription: {reason}"},
|
|
||||||
status_code=400,
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
User.update(notification_tokens=User.notification_tokens.append(sub)).where(
|
User.update(notification_tokens=User.notification_tokens.append(sub)).where(
|
||||||
User.username == username
|
User.username == username
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ from frigate.api.defs.query.recordings_query_parameters import (
|
|||||||
)
|
)
|
||||||
from frigate.api.defs.response.generic_response import GenericResponse
|
from frigate.api.defs.response.generic_response import GenericResponse
|
||||||
from frigate.api.defs.tags import Tags
|
from frigate.api.defs.tags import Tags
|
||||||
from frigate.const import RECORD_DIR
|
from frigate.const import MAX_SEGMENT_DURATION, RECORD_DIR
|
||||||
from frigate.models import Event, Recordings
|
from frigate.models import Event, Recordings
|
||||||
from frigate.util.time import get_dst_transitions
|
from frigate.util.time import get_dst_transitions
|
||||||
|
|
||||||
@@ -243,6 +243,7 @@ async def recordings(
|
|||||||
)
|
)
|
||||||
.where(
|
.where(
|
||||||
Recordings.camera == camera_name,
|
Recordings.camera == camera_name,
|
||||||
|
Recordings.start_time >= after - MAX_SEGMENT_DURATION,
|
||||||
Recordings.end_time >= after,
|
Recordings.end_time >= after,
|
||||||
Recordings.start_time <= before,
|
Recordings.start_time <= before,
|
||||||
)
|
)
|
||||||
|
|||||||
+12
-28
@@ -17,7 +17,6 @@ from frigate.api.auth import (
|
|||||||
get_allowed_cameras_for_filter,
|
get_allowed_cameras_for_filter,
|
||||||
get_current_user,
|
get_current_user,
|
||||||
require_camera_access,
|
require_camera_access,
|
||||||
require_full_camera_access,
|
|
||||||
require_role,
|
require_role,
|
||||||
)
|
)
|
||||||
from frigate.api.defs.query.review_query_parameters import (
|
from frigate.api.defs.query.review_query_parameters import (
|
||||||
@@ -43,22 +42,6 @@ logger = logging.getLogger(__name__)
|
|||||||
router = APIRouter(tags=[Tags.review])
|
router = APIRouter(tags=[Tags.review])
|
||||||
|
|
||||||
|
|
||||||
def get_label_clause(label: str, include_audio: bool = True):
|
|
||||||
"""Build a clause matching a label within a review segment's data.
|
|
||||||
|
|
||||||
Verified objects are stored with a `-verified` suffix (eg. `person-verified`)
|
|
||||||
so that variant is matched as well.
|
|
||||||
"""
|
|
||||||
clause = (ReviewSegment.data["objects"].cast("text") % f'*"{label}"*') | (
|
|
||||||
ReviewSegment.data["objects"].cast("text") % f'*"{label}-verified"*'
|
|
||||||
)
|
|
||||||
|
|
||||||
if include_audio:
|
|
||||||
clause |= ReviewSegment.data["audio"].cast("text") % f'*"{label}"*'
|
|
||||||
|
|
||||||
return clause
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/review",
|
"/review",
|
||||||
response_model=list[ReviewSegmentResponse],
|
response_model=list[ReviewSegmentResponse],
|
||||||
@@ -108,7 +91,10 @@ async def review(
|
|||||||
filtered_labels = labels.split(",")
|
filtered_labels = labels.split(",")
|
||||||
|
|
||||||
for label in filtered_labels:
|
for label in filtered_labels:
|
||||||
label_clauses.append(get_label_clause(label))
|
label_clauses.append(
|
||||||
|
(ReviewSegment.data["objects"].cast("text") % f'*"{label}"*')
|
||||||
|
| (ReviewSegment.data["audio"].cast("text") % f'*"{label}"*')
|
||||||
|
)
|
||||||
clauses.append(reduce(operator.or_, label_clauses))
|
clauses.append(reduce(operator.or_, label_clauses))
|
||||||
|
|
||||||
if zones != "all":
|
if zones != "all":
|
||||||
@@ -249,7 +235,10 @@ async def review_summary(
|
|||||||
filtered_labels = labels.split(",")
|
filtered_labels = labels.split(",")
|
||||||
|
|
||||||
for label in filtered_labels:
|
for label in filtered_labels:
|
||||||
label_clauses.append(get_label_clause(label))
|
label_clauses.append(
|
||||||
|
(ReviewSegment.data["objects"].cast("text") % f'*"{label}"*')
|
||||||
|
| (ReviewSegment.data["audio"].cast("text") % f'*"{label}"*')
|
||||||
|
)
|
||||||
clauses.append(reduce(operator.or_, label_clauses))
|
clauses.append(reduce(operator.or_, label_clauses))
|
||||||
if zones != "all":
|
if zones != "all":
|
||||||
# use matching so segments with multiple zones
|
# use matching so segments with multiple zones
|
||||||
@@ -347,8 +336,9 @@ async def review_summary(
|
|||||||
filtered_labels = labels.split(",")
|
filtered_labels = labels.split(",")
|
||||||
|
|
||||||
for label in filtered_labels:
|
for label in filtered_labels:
|
||||||
label_clauses.append(get_label_clause(label, include_audio=False))
|
label_clauses.append(
|
||||||
|
ReviewSegment.data["objects"].cast("text") % f'*"{label}"*'
|
||||||
|
)
|
||||||
clauses.append(reduce(operator.or_, label_clauses))
|
clauses.append(reduce(operator.or_, label_clauses))
|
||||||
|
|
||||||
# Find the time range of available data
|
# Find the time range of available data
|
||||||
@@ -719,7 +709,6 @@ async def get_review(request: Request, review_id: str):
|
|||||||
dependencies=[Depends(allow_any_authenticated())],
|
dependencies=[Depends(allow_any_authenticated())],
|
||||||
)
|
)
|
||||||
async def set_not_reviewed(
|
async def set_not_reviewed(
|
||||||
request: Request,
|
|
||||||
review_id: str,
|
review_id: str,
|
||||||
current_user: dict = Depends(get_current_user),
|
current_user: dict = Depends(get_current_user),
|
||||||
):
|
):
|
||||||
@@ -738,8 +727,6 @@ async def set_not_reviewed(
|
|||||||
status_code=404,
|
status_code=404,
|
||||||
)
|
)
|
||||||
|
|
||||||
await require_camera_access(review.camera, request=request)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user_review = UserReviewStatus.get(
|
user_review = UserReviewStatus.get(
|
||||||
UserReviewStatus.user_id == user_id,
|
UserReviewStatus.user_id == user_id,
|
||||||
@@ -756,12 +743,9 @@ async def set_not_reviewed(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# Intentionally not camera scoped, as the summary correlates each flagged event
|
|
||||||
# with overlapping activity on other cameras. Restricted to callers who can
|
|
||||||
# already see every camera, so the unscoped query discloses nothing.
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/review/summarize/start/{start_ts}/end/{end_ts}",
|
"/review/summarize/start/{start_ts}/end/{end_ts}",
|
||||||
dependencies=[Depends(require_full_camera_access)],
|
dependencies=[Depends(require_role(["admin"]))],
|
||||||
description="Use GenAI to summarize review items over a period of time.",
|
description="Use GenAI to summarize review items over a period of time.",
|
||||||
)
|
)
|
||||||
def generate_review_summary(request: Request, start_ts: float, end_ts: float):
|
def generate_review_summary(request: Request, start_ts: float, end_ts: float):
|
||||||
|
|||||||
@@ -103,13 +103,12 @@ class CameraActivityManager:
|
|||||||
all_objects: list[dict[str, Any]] = []
|
all_objects: list[dict[str, Any]] = []
|
||||||
|
|
||||||
for camera in new_activity.keys():
|
for camera in new_activity.keys():
|
||||||
camera_config = self.config.cameras.get(camera)
|
if camera not in self.config.cameras:
|
||||||
if camera_config is None:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# handle cameras that were added dynamically
|
# handle cameras that were added dynamically
|
||||||
if camera not in self.camera_all_object_counts:
|
if camera not in self.camera_all_object_counts:
|
||||||
self.__init_camera(camera_config)
|
self.__init_camera(self.config.cameras[camera])
|
||||||
|
|
||||||
new_objects = new_activity[camera].get("objects", [])
|
new_objects = new_activity[camera].get("objects", [])
|
||||||
all_objects.extend(new_objects)
|
all_objects.extend(new_objects)
|
||||||
@@ -234,13 +233,12 @@ class AudioActivityManager:
|
|||||||
now = datetime.datetime.now().timestamp()
|
now = datetime.datetime.now().timestamp()
|
||||||
|
|
||||||
for camera in new_activity.keys():
|
for camera in new_activity.keys():
|
||||||
camera_config = self.config.cameras.get(camera)
|
if camera not in self.config.cameras:
|
||||||
if camera_config is None:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# handle cameras that were added dynamically
|
# handle cameras that were added dynamically
|
||||||
if camera not in self.current_audio_detections:
|
if camera not in self.current_audio_detections:
|
||||||
self.__init_camera(camera_config)
|
self.__init_camera(self.config.cameras[camera])
|
||||||
|
|
||||||
new_detections = new_activity[camera].get("detections", [])
|
new_detections = new_activity[camera].get("detections", [])
|
||||||
if self.compare_audio_activity(camera, new_detections, now):
|
if self.compare_audio_activity(camera, new_detections, now):
|
||||||
|
|||||||
@@ -60,11 +60,6 @@ class CameraState:
|
|||||||
# face/LPR pipelines when using a model without built-in detection.
|
# face/LPR pipelines when using a model without built-in detection.
|
||||||
self.face_recognition_min_obj_area: int = 0
|
self.face_recognition_min_obj_area: int = 0
|
||||||
self.lpr_min_obj_area: int = 0
|
self.lpr_min_obj_area: int = 0
|
||||||
self.lp_objects = {
|
|
||||||
label
|
|
||||||
for label, attributes in config.model.attributes_map.items()
|
|
||||||
if "license_plate" in attributes
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
self.camera_config.face_recognition.enabled
|
self.camera_config.face_recognition.enabled
|
||||||
@@ -457,7 +452,7 @@ class CameraState:
|
|||||||
and obj_area >= self.face_recognition_min_obj_area
|
and obj_area >= self.face_recognition_min_obj_area
|
||||||
and updated_obj.obj_data.get("sub_label") is None
|
and updated_obj.obj_data.get("sub_label") is None
|
||||||
) or (
|
) or (
|
||||||
obj_label in self.lp_objects
|
obj_label in ("car", "motorcycle")
|
||||||
and self.lpr_min_obj_area > 0
|
and self.lpr_min_obj_area > 0
|
||||||
and obj_area >= self.lpr_min_obj_area
|
and obj_area >= self.lpr_min_obj_area
|
||||||
and updated_obj.obj_data.get("sub_label") is None
|
and updated_obj.obj_data.get("sub_label") is None
|
||||||
@@ -553,7 +548,7 @@ class CameraState:
|
|||||||
current_best.thumbnail_data is not None
|
current_best.thumbnail_data is not None
|
||||||
and obj.thumbnail_data is not None
|
and obj.thumbnail_data is not None
|
||||||
and is_better_thumbnail(
|
and is_better_thumbnail(
|
||||||
obj.thumbnail_attributes,
|
object_type,
|
||||||
current_best.thumbnail_data,
|
current_best.thumbnail_data,
|
||||||
obj.thumbnail_data,
|
obj.thumbnail_data,
|
||||||
self.camera_config.frame_shape,
|
self.camera_config.frame_shape,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from frigate.camera.activity_manager import AudioActivityManager, CameraActivity
|
|||||||
from frigate.comms.base_communicator import Communicator
|
from frigate.comms.base_communicator import Communicator
|
||||||
from frigate.comms.runtime_state import RuntimeStatePersistence
|
from frigate.comms.runtime_state import RuntimeStatePersistence
|
||||||
from frigate.comms.webpush import WebPushClient
|
from frigate.comms.webpush import WebPushClient
|
||||||
from frigate.config import BirdseyeModeEnum, FrigateConfig
|
from frigate.config import BirdseyeModeConfig, FrigateConfig
|
||||||
from frigate.config.camera.updater import (
|
from frigate.config.camera.updater import (
|
||||||
CameraConfigUpdateEnum,
|
CameraConfigUpdateEnum,
|
||||||
CameraConfigUpdatePublisher,
|
CameraConfigUpdatePublisher,
|
||||||
@@ -882,8 +882,9 @@ class Dispatcher:
|
|||||||
def _on_birdseye_mode_command(self, camera_name: str, payload: str) -> None:
|
def _on_birdseye_mode_command(self, camera_name: str, payload: str) -> None:
|
||||||
"""Callback for birdseye mode topic."""
|
"""Callback for birdseye mode topic."""
|
||||||
|
|
||||||
if payload not in ["CONTINUOUS", "MOTION", "OBJECTS"]:
|
mode = BirdseyeModeConfig.from_mqtt_payload(payload)
|
||||||
logger.info(f"Invalid birdseye_mode command: {payload}")
|
if mode is None:
|
||||||
|
logger.info("Invalid birdseye_mode command: %s", payload)
|
||||||
return
|
return
|
||||||
|
|
||||||
birdseye_settings = self.config.cameras[camera_name].birdseye
|
birdseye_settings = self.config.cameras[camera_name].birdseye
|
||||||
@@ -892,7 +893,7 @@ class Dispatcher:
|
|||||||
logger.info(f"Birdseye mode not enabled for {camera_name}")
|
logger.info(f"Birdseye mode not enabled for {camera_name}")
|
||||||
return
|
return
|
||||||
|
|
||||||
birdseye_settings.mode = BirdseyeModeEnum(payload.lower())
|
birdseye_settings.mode = mode
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Setting birdseye mode for {camera_name} to {birdseye_settings.mode}"
|
f"Setting birdseye mode for {camera_name} to {birdseye_settings.mode}"
|
||||||
)
|
)
|
||||||
@@ -901,7 +902,9 @@ class Dispatcher:
|
|||||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.birdseye, camera_name),
|
CameraConfigUpdateTopic(CameraConfigUpdateEnum.birdseye, camera_name),
|
||||||
birdseye_settings,
|
birdseye_settings,
|
||||||
)
|
)
|
||||||
self.publish(f"{camera_name}/birdseye_mode/state", payload, retain=True)
|
self.publish(
|
||||||
|
f"{camera_name}/birdseye_mode/state", mode.to_mqtt_payload(), retain=True
|
||||||
|
)
|
||||||
|
|
||||||
def _on_camera_notification_command(self, camera_name: str, payload: str) -> None:
|
def _on_camera_notification_command(self, camera_name: str, payload: str) -> None:
|
||||||
"""Callback for camera level notifications topic."""
|
"""Callback for camera level notifications topic."""
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ class MqttClient(Communicator):
|
|||||||
self.publish(
|
self.publish(
|
||||||
f"{camera_name}/birdseye_mode/state",
|
f"{camera_name}/birdseye_mode/state",
|
||||||
(
|
(
|
||||||
camera.birdseye.mode.value.upper()
|
camera.birdseye.mode.to_mqtt_payload()
|
||||||
if camera.birdseye.enabled
|
if camera.birdseye.enabled
|
||||||
else "OFF"
|
else "OFF"
|
||||||
),
|
),
|
||||||
|
|||||||
+13
-13
@@ -89,9 +89,7 @@ class WebPushClient(Communicator):
|
|||||||
# notification and auth config updater
|
# notification and auth config updater
|
||||||
self.global_config_subscriber = ConfigSubscriber("config/")
|
self.global_config_subscriber = ConfigSubscriber("config/")
|
||||||
self.config_subscriber = CameraConfigUpdateSubscriber(
|
self.config_subscriber = CameraConfigUpdateSubscriber(
|
||||||
self.config,
|
self.config, self.config.cameras, [CameraConfigUpdateEnum.notifications]
|
||||||
self.config.cameras,
|
|
||||||
[CameraConfigUpdateEnum.add, CameraConfigUpdateEnum.notifications],
|
|
||||||
)
|
)
|
||||||
self._refresh_user_cameras()
|
self._refresh_user_cameras()
|
||||||
|
|
||||||
@@ -215,12 +213,12 @@ class WebPushClient(Communicator):
|
|||||||
self.suspended_cameras[camera] = 0
|
self.suspended_cameras[camera] = 0
|
||||||
self.last_camera_notification_time[camera] = 0
|
self.last_camera_notification_time[camera] = 0
|
||||||
|
|
||||||
self._refresh_user_cameras()
|
|
||||||
|
|
||||||
if topic == "reviews":
|
if topic == "reviews":
|
||||||
decoded = json.loads(payload)
|
decoded = json.loads(payload)
|
||||||
camera = decoded["before"]["camera"]
|
camera = decoded["before"]["camera"]
|
||||||
if not self.config.cameras[camera].notifications.enabled:
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
|
if camera_config is None or not camera_config.notifications.enabled:
|
||||||
return
|
return
|
||||||
if self.is_camera_suspended(camera):
|
if self.is_camera_suspended(camera):
|
||||||
logger.debug(f"Notifications for {camera} are currently suspended.")
|
logger.debug(f"Notifications for {camera} are currently suspended.")
|
||||||
@@ -234,13 +232,14 @@ class WebPushClient(Communicator):
|
|||||||
|
|
||||||
# ensure notifications are enabled and the specific trigger has
|
# ensure notifications are enabled and the specific trigger has
|
||||||
# notification action enabled
|
# notification action enabled
|
||||||
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
not self.config.cameras[camera].notifications.enabled
|
camera_config is None
|
||||||
or name not in self.config.cameras[camera].semantic_search.triggers
|
or not camera_config.notifications.enabled
|
||||||
|
or name not in camera_config.semantic_search.triggers
|
||||||
or "notification"
|
or "notification"
|
||||||
not in self.config.cameras[camera]
|
not in camera_config.semantic_search.triggers[name].actions
|
||||||
.semantic_search.triggers[name]
|
|
||||||
.actions
|
|
||||||
):
|
):
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -251,7 +250,9 @@ class WebPushClient(Communicator):
|
|||||||
elif topic == "camera_monitoring":
|
elif topic == "camera_monitoring":
|
||||||
decoded = json.loads(payload)
|
decoded = json.loads(payload)
|
||||||
camera = decoded["camera"]
|
camera = decoded["camera"]
|
||||||
if not self.config.cameras[camera].notifications.enabled:
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
|
if camera_config is None or not camera_config.notifications.enabled:
|
||||||
return
|
return
|
||||||
if self.is_camera_suspended(camera):
|
if self.is_camera_suspended(camera):
|
||||||
logger.debug(f"Notifications for {camera} are currently suspended.")
|
logger.debug(f"Notifications for {camera} are currently suspended.")
|
||||||
@@ -421,7 +422,6 @@ class WebPushClient(Communicator):
|
|||||||
# Don't notify if message is an update and important fields don't have an update
|
# Don't notify if message is an update and important fields don't have an update
|
||||||
if (
|
if (
|
||||||
state == "update"
|
state == "update"
|
||||||
and payload["before"]["severity"] == payload["after"]["severity"]
|
|
||||||
and len(payload["before"]["data"]["objects"])
|
and len(payload["before"]["data"]["objects"])
|
||||||
== len(payload["after"]["data"]["objects"])
|
== len(payload["after"]["data"]["objects"])
|
||||||
and len(payload["before"]["data"]["zones"])
|
and len(payload["before"]["data"]["zones"])
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
from enum import Enum
|
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
from ..base import FrigateBaseModel
|
from ..base import FrigateBaseModel
|
||||||
@@ -8,22 +6,78 @@ __all__ = [
|
|||||||
"BirdseyeCameraConfig",
|
"BirdseyeCameraConfig",
|
||||||
"BirdseyeConfig",
|
"BirdseyeConfig",
|
||||||
"BirdseyeLayoutConfig",
|
"BirdseyeLayoutConfig",
|
||||||
"BirdseyeModeEnum",
|
"BirdseyeModeConfig",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
BIRDSEYE_ACTIVITY_TYPES = (
|
||||||
|
"objects",
|
||||||
|
"motion",
|
||||||
|
"stationary_objects",
|
||||||
|
"continuous",
|
||||||
|
)
|
||||||
|
|
||||||
class BirdseyeModeEnum(str, Enum):
|
|
||||||
objects = "objects"
|
class BirdseyeModeConfig(FrigateBaseModel):
|
||||||
motion = "motion"
|
continuous: bool = Field(
|
||||||
continuous = "continuous"
|
default=False,
|
||||||
|
title="Continuous",
|
||||||
|
description="Always include the camera in Birdseye.",
|
||||||
|
)
|
||||||
|
motion: bool = Field(
|
||||||
|
default=False,
|
||||||
|
title="Motion",
|
||||||
|
description="Include the camera in Birdseye when motion is detected.",
|
||||||
|
)
|
||||||
|
objects: bool = Field(
|
||||||
|
default=False,
|
||||||
|
title="Active objects",
|
||||||
|
description="Include the camera in Birdseye while an active object is tracked.",
|
||||||
|
)
|
||||||
|
stationary_objects: bool = Field(
|
||||||
|
default=False,
|
||||||
|
title="Stationary objects",
|
||||||
|
description="Include the camera in Birdseye while a stationary object is tracked.",
|
||||||
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_index(cls, type):
|
def from_mqtt_payload(cls, payload: str) -> "BirdseyeModeConfig | None":
|
||||||
return list(cls).index(type)
|
"""Create mode options from an uppercase MQTT payload."""
|
||||||
|
raw_modes = payload.split(",")
|
||||||
|
if not raw_modes or any(not mode for mode in raw_modes):
|
||||||
|
return None
|
||||||
|
|
||||||
@classmethod
|
modes = [mode.lower() for mode in raw_modes]
|
||||||
def get(cls, index):
|
if any(
|
||||||
return list(cls)[index]
|
raw_mode != mode.upper() or mode not in BIRDSEYE_ACTIVITY_TYPES
|
||||||
|
for raw_mode, mode in zip(raw_modes, modes)
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
|
||||||
|
if len(modes) != len(set(modes)):
|
||||||
|
return None
|
||||||
|
|
||||||
|
return cls(**{mode: True for mode in modes})
|
||||||
|
|
||||||
|
def has_enabled_activity(self) -> bool:
|
||||||
|
"""Return whether at least one activity type is enabled."""
|
||||||
|
return any(getattr(self, activity) for activity in BIRDSEYE_ACTIVITY_TYPES)
|
||||||
|
|
||||||
|
def to_mqtt_payload(self) -> str:
|
||||||
|
"""Serialize enabled mode options for MQTT state topics."""
|
||||||
|
payload = ",".join(
|
||||||
|
activity.upper()
|
||||||
|
for activity in BIRDSEYE_ACTIVITY_TYPES
|
||||||
|
if getattr(self, activity)
|
||||||
|
)
|
||||||
|
if not payload:
|
||||||
|
raise ValueError("At least one Birdseye activity type must be enabled")
|
||||||
|
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def default_birdseye_mode() -> BirdseyeModeConfig:
|
||||||
|
"""Return the default Birdseye mode configuration."""
|
||||||
|
return BirdseyeModeConfig(objects=True)
|
||||||
|
|
||||||
|
|
||||||
class BirdseyeLayoutConfig(FrigateBaseModel):
|
class BirdseyeLayoutConfig(FrigateBaseModel):
|
||||||
@@ -47,10 +101,10 @@ class BirdseyeConfig(FrigateBaseModel):
|
|||||||
title="Enable Birdseye",
|
title="Enable Birdseye",
|
||||||
description="Enable or disable the Birdseye view feature.",
|
description="Enable or disable the Birdseye view feature.",
|
||||||
)
|
)
|
||||||
mode: BirdseyeModeEnum = Field(
|
mode: BirdseyeModeConfig = Field(
|
||||||
default=BirdseyeModeEnum.objects,
|
default_factory=default_birdseye_mode,
|
||||||
title="Tracking mode",
|
title="Activity types",
|
||||||
description="Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'.",
|
description="Activity types that include cameras in Birdseye.",
|
||||||
)
|
)
|
||||||
|
|
||||||
restream: bool = Field(
|
restream: bool = Field(
|
||||||
@@ -102,10 +156,10 @@ class BirdseyeCameraConfig(BaseModel):
|
|||||||
title="Enable Birdseye",
|
title="Enable Birdseye",
|
||||||
description="Enable or disable the Birdseye view feature.",
|
description="Enable or disable the Birdseye view feature.",
|
||||||
)
|
)
|
||||||
mode: BirdseyeModeEnum = Field(
|
mode: BirdseyeModeConfig = Field(
|
||||||
default=BirdseyeModeEnum.objects,
|
default_factory=default_birdseye_mode,
|
||||||
title="Tracking mode",
|
title="Activity types",
|
||||||
description="Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'.",
|
description="Activity types that include cameras in Birdseye.",
|
||||||
)
|
)
|
||||||
|
|
||||||
order: int = Field(
|
order: int = Field(
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ from .auth import AuthConfig
|
|||||||
from .base import FrigateBaseModel
|
from .base import FrigateBaseModel
|
||||||
from .camera import CameraConfig, CameraLiveConfig
|
from .camera import CameraConfig, CameraLiveConfig
|
||||||
from .camera.audio import AudioConfig, AudioFilterConfig
|
from .camera.audio import AudioConfig, AudioFilterConfig
|
||||||
from .camera.birdseye import BirdseyeConfig
|
from .camera.birdseye import BirdseyeConfig, BirdseyeModeConfig
|
||||||
from .camera.detect import DetectConfig
|
from .camera.detect import DetectConfig
|
||||||
from .camera.ffmpeg import FfmpegConfig
|
from .camera.ffmpeg import FfmpegConfig
|
||||||
from .camera.genai import GenAIConfig, GenAIRoleEnum
|
from .camera.genai import GenAIConfig, GenAIRoleEnum
|
||||||
@@ -326,8 +326,20 @@ def verify_required_zones_exist(camera_config: CameraConfig) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def verify_profile_overrides_match_base(camera_config: CameraConfig) -> None:
|
def verify_profile_overrides_match_base(camera_config: CameraConfig) -> None:
|
||||||
"""Verify that profile zone and mask IDs reference entries defined on the base camera."""
|
"""Verify profile overrides against the resolved base camera configuration."""
|
||||||
for profile_name, profile in camera_config.profiles.items():
|
for profile_name, profile in camera_config.profiles.items():
|
||||||
|
if profile.birdseye is not None:
|
||||||
|
overrides = profile.birdseye.mode.model_dump(exclude_unset=True)
|
||||||
|
base_mode = camera_config.birdseye.mode.model_dump()
|
||||||
|
resolved_mode = BirdseyeModeConfig.model_validate(
|
||||||
|
deep_merge(overrides, base_mode)
|
||||||
|
)
|
||||||
|
if not resolved_mode.has_enabled_activity():
|
||||||
|
raise ValueError(
|
||||||
|
f"Camera '{camera_config.name}' profile '{profile_name}' must "
|
||||||
|
"enable at least one Birdseye activity type"
|
||||||
|
)
|
||||||
|
|
||||||
if profile.zones:
|
if profile.zones:
|
||||||
for zone_name in profile.zones:
|
for zone_name in profile.zones:
|
||||||
if zone_name not in camera_config.zones:
|
if zone_name not in camera_config.zones:
|
||||||
@@ -998,6 +1010,10 @@ class FrigateConfig(FrigateBaseModel):
|
|||||||
self.cameras[name] = camera_config
|
self.cameras[name] = camera_config
|
||||||
|
|
||||||
verify_config_roles(camera_config)
|
verify_config_roles(camera_config)
|
||||||
|
if not camera_config.birdseye.mode.has_enabled_activity():
|
||||||
|
raise ValueError(
|
||||||
|
f"Camera '{name}' must enable at least one Birdseye activity type"
|
||||||
|
)
|
||||||
verify_valid_live_stream_names(self, camera_config)
|
verify_valid_live_stream_names(self, camera_config)
|
||||||
verify_recording_segments_setup_with_reasonable_time(camera_config)
|
verify_recording_segments_setup_with_reasonable_time(camera_config)
|
||||||
verify_zone_objects_are_tracked(camera_config)
|
verify_zone_objects_are_tracked(camera_config)
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ SECTION_STATE_TOPICS: dict[str, list[tuple[str, Callable[[Any], Any]]]] = {
|
|||||||
("birdseye", lambda c: "ON" if c.birdseye.enabled else "OFF"),
|
("birdseye", lambda c: "ON" if c.birdseye.enabled else "OFF"),
|
||||||
(
|
(
|
||||||
"birdseye_mode",
|
"birdseye_mode",
|
||||||
lambda c: c.birdseye.mode.value.upper() if c.birdseye.enabled else "OFF",
|
lambda c: (
|
||||||
|
c.birdseye.mode.to_mqtt_payload() if c.birdseye.enabled else "OFF"
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
"detect": [("detect", lambda c: "ON" if c.detect.enabled else "OFF")],
|
"detect": [("detect", lambda c: "ON" if c.detect.enabled else "OFF")],
|
||||||
|
|||||||
@@ -44,11 +44,7 @@ DEFAULT_ATTRIBUTE_LABEL_MAP = {
|
|||||||
"ups",
|
"ups",
|
||||||
"usps",
|
"usps",
|
||||||
],
|
],
|
||||||
"truck": ["license_plate"],
|
|
||||||
"garbage_truck": ["license_plate"],
|
|
||||||
"motorcycle": ["license_plate"],
|
"motorcycle": ["license_plate"],
|
||||||
"bus": ["license_plate"],
|
|
||||||
"school_bus": ["license_plate"],
|
|
||||||
}
|
}
|
||||||
ATTRIBUTE_LABEL_DISPLAY_MAP = {
|
ATTRIBUTE_LABEL_DISPLAY_MAP = {
|
||||||
"amazon": "Amazon",
|
"amazon": "Amazon",
|
||||||
|
|||||||
@@ -1290,7 +1290,7 @@ class LicensePlateProcessingMixin:
|
|||||||
and obj_data.get("label") != "license_plate"
|
and obj_data.get("label") != "license_plate"
|
||||||
):
|
):
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera}: Not a processing license plate for {obj_data.get('label', 'unknown')}."
|
f"{camera}: Not a processing license plate for non car/motorcycle object."
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -1367,7 +1367,7 @@ class LicensePlateProcessingMixin:
|
|||||||
|
|
||||||
if not license_plate:
|
if not license_plate:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera}: Detected no license plates for {obj_data.get('label', 'unknown')} object."
|
f"{camera}: Detected no license plates for car/motorcycle object."
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|||||||
@@ -83,6 +83,10 @@ class AudioTranscriptionPostProcessor(PostProcessorApi):
|
|||||||
"""
|
"""
|
||||||
event_id = data["event_id"]
|
event_id = data["event_id"]
|
||||||
camera_name = data["camera"]
|
camera_name = data["camera"]
|
||||||
|
camera_config = self.config.cameras.get(camera_name)
|
||||||
|
|
||||||
|
if camera_config is None:
|
||||||
|
return
|
||||||
|
|
||||||
if data_type == PostProcessDataEnum.recording:
|
if data_type == PostProcessDataEnum.recording:
|
||||||
start_ts = data["frame_time"]
|
start_ts = data["frame_time"]
|
||||||
@@ -104,7 +108,7 @@ class AudioTranscriptionPostProcessor(PostProcessorApi):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
audio_data = get_audio_from_recording(
|
audio_data = get_audio_from_recording(
|
||||||
self.config.cameras[camera_name].ffmpeg,
|
camera_config.ffmpeg,
|
||||||
camera_name,
|
camera_name,
|
||||||
start_ts,
|
start_ts,
|
||||||
end_ts,
|
end_ts,
|
||||||
|
|||||||
@@ -151,7 +151,12 @@ class ObjectDescriptionProcessor(PostProcessorApi):
|
|||||||
logger.error(f"Event {event_id} not found for description regeneration")
|
logger.error(f"Event {event_id} not found for description regeneration")
|
||||||
return
|
return
|
||||||
|
|
||||||
camera_config = self.config.cameras[str(event.camera)]
|
camera_config = self.config.cameras.get(str(event.camera))
|
||||||
|
|
||||||
|
if camera_config is None:
|
||||||
|
logger.error("Camera %s no longer exists", event.camera)
|
||||||
|
return
|
||||||
|
|
||||||
if not camera_config.objects.genai.enabled and not force:
|
if not camera_config.objects.genai.enabled and not force:
|
||||||
logger.error(f"GenAI not enabled for camera {event.camera}")
|
logger.error(f"GenAI not enabled for camera {event.camera}")
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -137,7 +137,10 @@ class ReviewDescriptionProcessor(PostProcessorApi):
|
|||||||
return
|
return
|
||||||
|
|
||||||
camera = data["after"]["camera"]
|
camera = data["after"]["camera"]
|
||||||
camera_config = self.config.cameras[camera]
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
|
if camera_config is None:
|
||||||
|
return
|
||||||
|
|
||||||
if not camera_config.review.genai.enabled:
|
if not camera_config.review.genai.enabled:
|
||||||
return
|
return
|
||||||
|
|||||||
+15
-76
@@ -1,10 +1,8 @@
|
|||||||
import logging
|
import logging
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import threading
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import regex
|
import regex
|
||||||
from peewee import DatabaseError
|
|
||||||
from playhouse.sqliteq import SqliteQueueDatabase
|
from playhouse.sqliteq import SqliteQueueDatabase
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -19,7 +17,6 @@ class SqliteVecQueueDatabase(SqliteQueueDatabase):
|
|||||||
self.load_vec_extension: bool = load_vec_extension
|
self.load_vec_extension: bool = load_vec_extension
|
||||||
# no extension necessary, sqlite will load correctly for each platform
|
# no extension necessary, sqlite will load correctly for each platform
|
||||||
self.sqlite_vec_path = "/usr/local/lib/vec0"
|
self.sqlite_vec_path = "/usr/local/lib/vec0"
|
||||||
self.upsert_lock = threading.Lock()
|
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
def _connect(self, *args: Any, **kwargs: Any) -> sqlite3.Connection:
|
def _connect(self, *args: Any, **kwargs: Any) -> sqlite3.Connection:
|
||||||
@@ -56,22 +53,6 @@ class SqliteVecQueueDatabase(SqliteQueueDatabase):
|
|||||||
|
|
||||||
conn.create_function("REGEXP", 2, regexp)
|
conn.create_function("REGEXP", 2, regexp)
|
||||||
|
|
||||||
def execute_write(self, sql: str, params: Any = None) -> None:
|
|
||||||
"""Run a write and wait for it, so that failures are raised here.
|
|
||||||
|
|
||||||
SqliteQueueDatabase hands non-SELECT statements to a writer thread and
|
|
||||||
stores any exception on the cursor it returns, so callers that ignore
|
|
||||||
that cursor never learn the write failed.
|
|
||||||
"""
|
|
||||||
self.execute_sql(sql, params).fetchall()
|
|
||||||
|
|
||||||
def _table_exists(self, table: str) -> bool:
|
|
||||||
cursor = self.execute_sql(
|
|
||||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
|
|
||||||
(table,),
|
|
||||||
)
|
|
||||||
return cursor.fetchone() is not None
|
|
||||||
|
|
||||||
def _delete_embeddings(self, table: str, event_ids: list[str]) -> None:
|
def _delete_embeddings(self, table: str, event_ids: list[str]) -> None:
|
||||||
"""Delete embeddings for the given events, if the table exists.
|
"""Delete embeddings for the given events, if the table exists.
|
||||||
|
|
||||||
@@ -82,17 +63,17 @@ class SqliteVecQueueDatabase(SqliteQueueDatabase):
|
|||||||
return
|
return
|
||||||
|
|
||||||
# the embeddings tables are only created once semantic search has run
|
# the embeddings tables are only created once semantic search has run
|
||||||
if not self._table_exists(table):
|
cursor = self.execute_sql(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
|
||||||
|
(table,),
|
||||||
|
)
|
||||||
|
|
||||||
|
if cursor.fetchone() is None:
|
||||||
logger.debug("Skipping %s cleanup, table does not exist", table)
|
logger.debug("Skipping %s cleanup, table does not exist", table)
|
||||||
return
|
return
|
||||||
|
|
||||||
ids = ",".join(["?" for _ in event_ids])
|
ids = ",".join(["?" for _ in event_ids])
|
||||||
|
self.execute_sql(f"DELETE FROM {table} WHERE id IN ({ids})", event_ids)
|
||||||
# callers treat cleanup as best effort, so log rather than propagate
|
|
||||||
try:
|
|
||||||
self.execute_write(f"DELETE FROM {table} WHERE id IN ({ids})", event_ids)
|
|
||||||
except DatabaseError:
|
|
||||||
logger.exception("Failed to delete embeddings from %s", table)
|
|
||||||
|
|
||||||
def delete_embeddings_thumbnail(self, event_ids: list[str]) -> None:
|
def delete_embeddings_thumbnail(self, event_ids: list[str]) -> None:
|
||||||
self._delete_embeddings("vec_thumbnails", event_ids)
|
self._delete_embeddings("vec_thumbnails", event_ids)
|
||||||
@@ -100,67 +81,25 @@ class SqliteVecQueueDatabase(SqliteQueueDatabase):
|
|||||||
def delete_embeddings_description(self, event_ids: list[str]) -> None:
|
def delete_embeddings_description(self, event_ids: list[str]) -> None:
|
||||||
self._delete_embeddings("vec_descriptions", event_ids)
|
self._delete_embeddings("vec_descriptions", event_ids)
|
||||||
|
|
||||||
def _restore_vec_info_table(self, table: str) -> None:
|
|
||||||
"""Recreate the _info shadow table a legacy vec0 table is missing.
|
|
||||||
|
|
||||||
sqlite-vec added _info in 0.1.6 and drops it unconditionally when a
|
|
||||||
table is destroyed, so tables written by Frigate 0.17 and earlier fail
|
|
||||||
to drop. An empty stub is enough, and leaving it unseeded keeps the
|
|
||||||
table reading as pre-0.1.10 if the drop does not follow.
|
|
||||||
"""
|
|
||||||
if not self._table_exists(table) or self._table_exists(f"{table}_info"):
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.debug("Restoring the %s_info shadow table before dropping", table)
|
|
||||||
self.execute_write(
|
|
||||||
f'CREATE TABLE "{table}_info" (key TEXT PRIMARY KEY, value ANY)'
|
|
||||||
)
|
|
||||||
|
|
||||||
def drop_embeddings_tables(self) -> None:
|
def drop_embeddings_tables(self) -> None:
|
||||||
for table in ("vec_descriptions", "vec_thumbnails"):
|
self.execute_sql("""
|
||||||
self._restore_vec_info_table(table)
|
DROP TABLE vec_descriptions;
|
||||||
self.execute_write(f"DROP TABLE IF EXISTS {table}")
|
""")
|
||||||
|
self.execute_sql("""
|
||||||
|
DROP TABLE vec_thumbnails;
|
||||||
|
""")
|
||||||
|
|
||||||
def create_embeddings_tables(self) -> None:
|
def create_embeddings_tables(self) -> None:
|
||||||
"""Create vec0 virtual table for embeddings"""
|
"""Create vec0 virtual table for embeddings"""
|
||||||
self.execute_write("""
|
self.execute_sql("""
|
||||||
CREATE VIRTUAL TABLE IF NOT EXISTS vec_thumbnails USING vec0(
|
CREATE VIRTUAL TABLE IF NOT EXISTS vec_thumbnails USING vec0(
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
thumbnail_embedding FLOAT[768] distance_metric=cosine
|
thumbnail_embedding FLOAT[768] distance_metric=cosine
|
||||||
);
|
);
|
||||||
""")
|
""")
|
||||||
self.execute_write("""
|
self.execute_sql("""
|
||||||
CREATE VIRTUAL TABLE IF NOT EXISTS vec_descriptions USING vec0(
|
CREATE VIRTUAL TABLE IF NOT EXISTS vec_descriptions USING vec0(
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
description_embedding FLOAT[768] distance_metric=cosine
|
description_embedding FLOAT[768] distance_metric=cosine
|
||||||
);
|
);
|
||||||
""")
|
""")
|
||||||
|
|
||||||
def upsert_embeddings(
|
|
||||||
self, table: str, column: str, embeddings: dict[str, bytes]
|
|
||||||
) -> None:
|
|
||||||
"""Write embeddings for the given event ids, replacing any that exist.
|
|
||||||
|
|
||||||
vec0 implements neither REPLACE nor UPSERT, so rows that are already
|
|
||||||
there have to be deleted first.
|
|
||||||
"""
|
|
||||||
if not embeddings:
|
|
||||||
return
|
|
||||||
|
|
||||||
event_ids = list(embeddings.keys())
|
|
||||||
ids = ",".join(["?" for _ in event_ids])
|
|
||||||
params: list[Any] = []
|
|
||||||
|
|
||||||
for event_id in event_ids:
|
|
||||||
params.extend((event_id, embeddings[event_id]))
|
|
||||||
|
|
||||||
values = ", ".join(["(?, ?)"] * len(event_ids))
|
|
||||||
|
|
||||||
# reindexing and live embedding run on separate threads, and each write
|
|
||||||
# is queued separately, so the delete and the insert have to be held
|
|
||||||
# together or an interleaved pair fails on the vec0 primary key
|
|
||||||
with self.upsert_lock:
|
|
||||||
self.execute_write(f"DELETE FROM {table} WHERE id IN ({ids})", event_ids)
|
|
||||||
self.execute_write(
|
|
||||||
f"INSERT INTO {table}(id, {column}) VALUES {values}", params
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -25,31 +25,25 @@ def is_arm64_platform() -> bool:
|
|||||||
return machine in ("aarch64", "arm64", "armv8", "armv7l")
|
return machine in ("aarch64", "arm64", "armv8", "armv7l")
|
||||||
|
|
||||||
|
|
||||||
def get_ort_session_options(model_type: str | None = None) -> ort.SessionOptions | None:
|
def get_ort_session_options(
|
||||||
|
is_complex_model: bool = False,
|
||||||
|
) -> ort.SessionOptions | None:
|
||||||
"""Get ONNX Runtime session options with appropriate settings.
|
"""Get ONNX Runtime session options with appropriate settings.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
model_type: Model being loaded, used to pin its graph optimization level.
|
is_complex_model: Whether the model needs basic optimization to avoid graph fusion issues.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
SessionOptions with a pinned optimization level, or None for default settings.
|
SessionOptions with appropriate optimization level, or None for default settings.
|
||||||
"""
|
"""
|
||||||
# Import here to avoid circular imports
|
if is_complex_model:
|
||||||
from frigate.embeddings.types import EnrichmentModelTypeEnum
|
sess_options = ort.SessionOptions()
|
||||||
|
sess_options.graph_optimization_level = (
|
||||||
|
ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
|
||||||
|
)
|
||||||
|
return sess_options
|
||||||
|
|
||||||
if model_type == EnrichmentModelTypeEnum.jina_v2.value:
|
return None
|
||||||
# below EXTENDED the CUDA EP returns an identical vector for every image,
|
|
||||||
# and ORT_ENABLE_ALL fails to build on CPU with a SimplifiedLayerNormFusion error
|
|
||||||
level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED
|
|
||||||
elif model_type == EnrichmentModelTypeEnum.jina_v1.value:
|
|
||||||
# aggressive optimizations create or expect nodes that don't exist
|
|
||||||
level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
sess_options = ort.SessionOptions()
|
|
||||||
sess_options.graph_optimization_level = level
|
|
||||||
return sess_options
|
|
||||||
|
|
||||||
|
|
||||||
# Import OpenVINO only when needed to avoid circular dependencies
|
# Import OpenVINO only when needed to avoid circular dependencies
|
||||||
@@ -121,6 +115,21 @@ class BaseModelRunner(ABC):
|
|||||||
class ONNXModelRunner(BaseModelRunner):
|
class ONNXModelRunner(BaseModelRunner):
|
||||||
"""Run ONNX models using ONNX Runtime."""
|
"""Run ONNX models using ONNX Runtime."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_cpu_complex_model(model_type: str) -> bool:
|
||||||
|
"""Check if model needs basic optimization level to avoid graph fusion issues.
|
||||||
|
|
||||||
|
Some models (like Jina-CLIP) have issues with aggressive optimizations like
|
||||||
|
SimplifiedLayerNormFusion that create or expect nodes that don't exist.
|
||||||
|
"""
|
||||||
|
# Import here to avoid circular imports
|
||||||
|
from frigate.embeddings.types import EnrichmentModelTypeEnum
|
||||||
|
|
||||||
|
return model_type in [
|
||||||
|
EnrichmentModelTypeEnum.jina_v1.value,
|
||||||
|
EnrichmentModelTypeEnum.jina_v2.value,
|
||||||
|
]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def is_migraphx_complex_model(model_type: str) -> bool:
|
def is_migraphx_complex_model(model_type: str) -> bool:
|
||||||
# Import here to avoid circular imports
|
# Import here to avoid circular imports
|
||||||
@@ -199,20 +208,15 @@ class CudaGraphRunner(BaseModelRunner):
|
|||||||
EnrichmentModelTypeEnum.yolov9_license_plate.value,
|
EnrichmentModelTypeEnum.yolov9_license_plate.value,
|
||||||
]
|
]
|
||||||
|
|
||||||
# ORT performs two regular runs before it starts capturing, but on some
|
|
||||||
# driver / cuDNN combinations the arena still has to extend on the run that
|
|
||||||
# captures, and cudaMalloc is not allowed during capture. Running with
|
|
||||||
# capture disabled first keeps those allocations outside of the capture.
|
|
||||||
GRAPH_FREE_WARMUP_RUNS = 2
|
|
||||||
|
|
||||||
def __init__(self, session: ort.InferenceSession, cuda_device_id: int):
|
def __init__(self, session: ort.InferenceSession, cuda_device_id: int):
|
||||||
self._session = session
|
self._session = session
|
||||||
self._cuda_device_id = cuda_device_id
|
self._cuda_device_id = cuda_device_id
|
||||||
self._prepared = False
|
self._captured = False
|
||||||
self._io_binding: ort.IOBinding | None = None
|
self._io_binding: ort.IOBinding | None = None
|
||||||
self._input_name: str | None = None
|
self._input_name: str | None = None
|
||||||
self._output_names: list[str] | None = None
|
self._output_names: list[str] | None = None
|
||||||
self._input_ortvalue: ort.OrtValue | None = None
|
self._input_ortvalue: ort.OrtValue | None = None
|
||||||
|
self._output_ortvalues: ort.OrtValue | None = None
|
||||||
|
|
||||||
def get_input_names(self) -> list[str]:
|
def get_input_names(self) -> list[str]:
|
||||||
"""Get input names for the model."""
|
"""Get input names for the model."""
|
||||||
@@ -222,41 +226,35 @@ class CudaGraphRunner(BaseModelRunner):
|
|||||||
"""Get the input width of the model."""
|
"""Get the input width of the model."""
|
||||||
return self._session.get_inputs()[0].shape[3]
|
return self._session.get_inputs()[0].shape[3]
|
||||||
|
|
||||||
def _prepare(self, input_name: str, tensor_input: np.ndarray) -> None:
|
|
||||||
"""Bind CUDA buffers and warm the session up with capture disabled."""
|
|
||||||
self._io_binding = self._session.io_binding()
|
|
||||||
self._input_name = input_name
|
|
||||||
self._output_names = [o.name for o in self._session.get_outputs()]
|
|
||||||
|
|
||||||
self._input_ortvalue = ort.OrtValue.ortvalue_from_numpy(
|
|
||||||
tensor_input, "cuda", self._cuda_device_id
|
|
||||||
)
|
|
||||||
self._io_binding.bind_ortvalue_input(self._input_name, self._input_ortvalue)
|
|
||||||
|
|
||||||
for name in self._output_names:
|
|
||||||
# Bind outputs to CUDA and allow ORT to allocate appropriately
|
|
||||||
self._io_binding.bind_output(name, "cuda", self._cuda_device_id)
|
|
||||||
|
|
||||||
# gpu_graph_id -1 disables capture and replay for the run
|
|
||||||
warmup_options = ort.RunOptions()
|
|
||||||
warmup_options.add_run_config_entry("gpu_graph_id", "-1")
|
|
||||||
|
|
||||||
for _ in range(self.GRAPH_FREE_WARMUP_RUNS):
|
|
||||||
self._session.run_with_iobinding(self._io_binding, warmup_options)
|
|
||||||
|
|
||||||
self._prepared = True
|
|
||||||
|
|
||||||
def run(self, input: dict[str, Any]):
|
def run(self, input: dict[str, Any]):
|
||||||
# Extract the single tensor input (assuming one input)
|
# Extract the single tensor input (assuming one input)
|
||||||
input_name = list(input.keys())[0]
|
input_name = list(input.keys())[0]
|
||||||
tensor_input = np.ascontiguousarray(input[input_name])
|
tensor_input = input[input_name]
|
||||||
|
tensor_input = np.ascontiguousarray(tensor_input)
|
||||||
|
|
||||||
if not self._prepared:
|
if not self._captured:
|
||||||
self._prepare(input_name, tensor_input)
|
# Prepare IOBinding with CUDA buffers and let ORT allocate outputs on device
|
||||||
else:
|
self._io_binding = self._session.io_binding()
|
||||||
# Replay using updated input
|
self._input_name = input_name
|
||||||
self._input_ortvalue.update_inplace(tensor_input)
|
self._output_names = [o.name for o in self._session.get_outputs()]
|
||||||
|
|
||||||
|
self._input_ortvalue = ort.OrtValue.ortvalue_from_numpy(
|
||||||
|
tensor_input, "cuda", self._cuda_device_id
|
||||||
|
)
|
||||||
|
self._io_binding.bind_ortvalue_input(self._input_name, self._input_ortvalue)
|
||||||
|
|
||||||
|
for name in self._output_names:
|
||||||
|
# Bind outputs to CUDA and allow ORT to allocate appropriately
|
||||||
|
self._io_binding.bind_output(name, "cuda", self._cuda_device_id)
|
||||||
|
|
||||||
|
# First IOBinding run to allocate, execute, and capture CUDA Graph
|
||||||
|
ro = ort.RunOptions()
|
||||||
|
self._session.run_with_iobinding(self._io_binding, ro)
|
||||||
|
self._captured = True
|
||||||
|
return self._io_binding.copy_outputs_to_cpu()
|
||||||
|
|
||||||
|
# Replay using updated input, copy results to CPU
|
||||||
|
self._input_ortvalue.update_inplace(tensor_input)
|
||||||
ro = ort.RunOptions()
|
ro = ort.RunOptions()
|
||||||
self._session.run_with_iobinding(self._io_binding, ro)
|
self._session.run_with_iobinding(self._io_binding, ro)
|
||||||
return self._io_binding.copy_outputs_to_cpu()
|
return self._io_binding.copy_outputs_to_cpu()
|
||||||
@@ -325,12 +323,6 @@ class OpenVINOModelRunner(BaseModelRunner):
|
|||||||
if device in ["GPU", "AUTO", "NPU"]:
|
if device in ["GPU", "AUTO", "NPU"]:
|
||||||
self.ov_core.set_property(device, {"PERFORMANCE_HINT": "LATENCY"})
|
self.ov_core.set_property(device, {"PERFORMANCE_HINT": "LATENCY"})
|
||||||
|
|
||||||
if device in ["GPU", "AUTO"]:
|
|
||||||
try:
|
|
||||||
self.ov_core.set_property("GPU", {"GPU_QUEUE_THROTTLE": "LOW"})
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"GPU_QUEUE_THROTTLE not supported: {e}")
|
|
||||||
|
|
||||||
if device == "NPU" and OpenVINOModelRunner.is_detection_model(model_type):
|
if device == "NPU" and OpenVINOModelRunner.is_detection_model(model_type):
|
||||||
try:
|
try:
|
||||||
self.ov_core.set_property(device, {"NPU_TURBO": "YES"})
|
self.ov_core.set_property(device, {"NPU_TURBO": "YES"})
|
||||||
@@ -634,7 +626,9 @@ def get_optimized_runner(
|
|||||||
return ONNXModelRunner(
|
return ONNXModelRunner(
|
||||||
ort.InferenceSession(
|
ort.InferenceSession(
|
||||||
model_path,
|
model_path,
|
||||||
sess_options=get_ort_session_options(model_type),
|
sess_options=get_ort_session_options(
|
||||||
|
ONNXModelRunner.is_cpu_complex_model(model_type)
|
||||||
|
),
|
||||||
providers=providers,
|
providers=providers,
|
||||||
provider_options=options,
|
provider_options=options,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -6,10 +6,9 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from peewee import DatabaseError, DoesNotExist, IntegrityError
|
from peewee import DoesNotExist, IntegrityError
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from playhouse.shortcuts import model_to_dict
|
from playhouse.shortcuts import model_to_dict
|
||||||
|
|
||||||
@@ -208,10 +207,12 @@ class Embeddings:
|
|||||||
embedding = self.vision_embedding([thumbnail])[0]
|
embedding = self.vision_embedding([thumbnail])[0]
|
||||||
|
|
||||||
if upsert:
|
if upsert:
|
||||||
self.db.upsert_embeddings(
|
self.db.execute_sql(
|
||||||
"vec_thumbnails",
|
"""
|
||||||
"thumbnail_embedding",
|
INSERT OR REPLACE INTO vec_thumbnails(id, thumbnail_embedding)
|
||||||
{event_id: serialize(embedding)},
|
VALUES(?, ?)
|
||||||
|
""",
|
||||||
|
(event_id, serialize(embedding)),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.image_inference_speed.update(datetime.datetime.now().timestamp() - start)
|
self.image_inference_speed.update(datetime.datetime.now().timestamp() - start)
|
||||||
@@ -250,12 +251,19 @@ class Embeddings:
|
|||||||
embeddings = self.vision_embedding(valid_thumbs)
|
embeddings = self.vision_embedding(valid_thumbs)
|
||||||
|
|
||||||
if upsert:
|
if upsert:
|
||||||
items = {}
|
items = []
|
||||||
for i in range(len(valid_ids)):
|
for i in range(len(valid_ids)):
|
||||||
items[valid_ids[i]] = serialize(embeddings[i])
|
items.append(valid_ids[i])
|
||||||
|
items.append(serialize(embeddings[i]))
|
||||||
self.image_eps.update()
|
self.image_eps.update()
|
||||||
|
|
||||||
self.db.upsert_embeddings("vec_thumbnails", "thumbnail_embedding", items)
|
self.db.execute_sql(
|
||||||
|
"""
|
||||||
|
INSERT OR REPLACE INTO vec_thumbnails(id, thumbnail_embedding)
|
||||||
|
VALUES {}
|
||||||
|
""".format(", ".join(["(?, ?)"] * len(valid_ids))),
|
||||||
|
items,
|
||||||
|
)
|
||||||
|
|
||||||
duration = datetime.datetime.now().timestamp() - start
|
duration = datetime.datetime.now().timestamp() - start
|
||||||
self.image_inference_speed.update(duration / len(valid_ids))
|
self.image_inference_speed.update(duration / len(valid_ids))
|
||||||
@@ -269,10 +277,12 @@ class Embeddings:
|
|||||||
embedding = self.text_embedding([description])[0]
|
embedding = self.text_embedding([description])[0]
|
||||||
|
|
||||||
if upsert:
|
if upsert:
|
||||||
self.db.upsert_embeddings(
|
self.db.execute_sql(
|
||||||
"vec_descriptions",
|
"""
|
||||||
"description_embedding",
|
INSERT OR REPLACE INTO vec_descriptions(id, description_embedding)
|
||||||
{event_id: serialize(embedding)},
|
VALUES(?, ?)
|
||||||
|
""",
|
||||||
|
(event_id, serialize(embedding)),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.text_inference_speed.update(datetime.datetime.now().timestamp() - start)
|
self.text_inference_speed.update(datetime.datetime.now().timestamp() - start)
|
||||||
@@ -292,14 +302,19 @@ class Embeddings:
|
|||||||
|
|
||||||
if upsert:
|
if upsert:
|
||||||
ids = list(event_descriptions.keys())
|
ids = list(event_descriptions.keys())
|
||||||
items = {}
|
items = []
|
||||||
|
|
||||||
for i in range(len(ids)):
|
for i in range(len(ids)):
|
||||||
items[ids[i]] = serialize(embeddings[i])
|
items.append(ids[i])
|
||||||
|
items.append(serialize(embeddings[i]))
|
||||||
self.text_eps.update()
|
self.text_eps.update()
|
||||||
|
|
||||||
self.db.upsert_embeddings(
|
self.db.execute_sql(
|
||||||
"vec_descriptions", "description_embedding", items
|
"""
|
||||||
|
INSERT OR REPLACE INTO vec_descriptions(id, description_embedding)
|
||||||
|
VALUES {}
|
||||||
|
""".format(", ".join(["(?, ?)"] * len(ids))),
|
||||||
|
items,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.text_inference_speed.update(datetime.datetime.now().timestamp() - start)
|
self.text_inference_speed.update(datetime.datetime.now().timestamp() - start)
|
||||||
@@ -307,17 +322,6 @@ class Embeddings:
|
|||||||
return embeddings
|
return embeddings
|
||||||
|
|
||||||
def reindex(self) -> None:
|
def reindex(self) -> None:
|
||||||
"""Rebuild every tracked object embedding from scratch."""
|
|
||||||
totals: dict[str, Any] = {"status": "indexing"}
|
|
||||||
|
|
||||||
try:
|
|
||||||
self._reindex(totals)
|
|
||||||
except DatabaseError:
|
|
||||||
logger.exception("Unable to reindex tracked object embeddings")
|
|
||||||
totals["status"] = "failed"
|
|
||||||
self.requestor.send_data(UPDATE_EMBEDDINGS_REINDEX_PROGRESS, totals)
|
|
||||||
|
|
||||||
def _reindex(self, totals: dict[str, Any]) -> None:
|
|
||||||
logger.info("Indexing tracked object embeddings...")
|
logger.info("Indexing tracked object embeddings...")
|
||||||
|
|
||||||
self.db.drop_embeddings_tables()
|
self.db.drop_embeddings_tables()
|
||||||
@@ -342,18 +346,14 @@ class Embeddings:
|
|||||||
batch_size = 32
|
batch_size = 32
|
||||||
current_page = 1
|
current_page = 1
|
||||||
|
|
||||||
totals.update(
|
totals = {
|
||||||
{
|
"thumbnails": 0,
|
||||||
"thumbnails": 0,
|
"descriptions": 0,
|
||||||
"descriptions": 0,
|
"processed_objects": total_events - 1 if total_events < batch_size else 0,
|
||||||
"processed_objects": total_events - 1
|
"total_objects": total_events,
|
||||||
if total_events < batch_size
|
"time_remaining": 0 if total_events < batch_size else -1,
|
||||||
else 0,
|
"status": "indexing",
|
||||||
"total_objects": total_events,
|
}
|
||||||
"time_remaining": 0 if total_events < batch_size else -1,
|
|
||||||
"status": "indexing",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
self.requestor.send_data(UPDATE_EMBEDDINGS_REINDEX_PROGRESS, totals)
|
self.requestor.send_data(UPDATE_EMBEDDINGS_REINDEX_PROGRESS, totals)
|
||||||
|
|
||||||
|
|||||||
@@ -609,6 +609,18 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
# Embed the thumbnail
|
# Embed the thumbnail
|
||||||
self._embed_thumbnail(event_id, thumbnail)
|
self._embed_thumbnail(event_id, thumbnail)
|
||||||
|
|
||||||
|
# every post processor below reads config.cameras[camera], but
|
||||||
|
# tracked_events still has to be released or the thumbnails held
|
||||||
|
# for this event leak, same as the two exits above
|
||||||
|
if camera not in self.config.cameras:
|
||||||
|
logger.debug("Skipping post processing for removed camera %s", camera)
|
||||||
|
|
||||||
|
for processor in self.post_processors:
|
||||||
|
if isinstance(processor, ObjectDescriptionProcessor):
|
||||||
|
processor.cleanup_event(event_id)
|
||||||
|
|
||||||
|
continue
|
||||||
|
|
||||||
# call any defined post processors
|
# call any defined post processors
|
||||||
for processor in self.post_processors:
|
for processor in self.post_processors:
|
||||||
if isinstance(processor, LicensePlatePostProcessor):
|
if isinstance(processor, LicensePlatePostProcessor):
|
||||||
@@ -666,11 +678,18 @@ class EmbeddingMaintainer(threading.Thread):
|
|||||||
to_remove = []
|
to_remove = []
|
||||||
|
|
||||||
for id, data in self.detected_license_plates.items():
|
for id, data in self.detected_license_plates.items():
|
||||||
|
camera_config = self.config.cameras.get(data["camera"])
|
||||||
|
|
||||||
|
if camera_config is None:
|
||||||
|
# camera was removed, drop the entry rather than expiring it
|
||||||
|
to_remove.append(id)
|
||||||
|
continue
|
||||||
|
|
||||||
last_seen = data.get("last_seen", 0)
|
last_seen = data.get("last_seen", 0)
|
||||||
if not last_seen:
|
if not last_seen:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if now - last_seen > self.config.cameras[data["camera"]].lpr.expire_time:
|
if now - last_seen > camera_config.lpr.expire_time:
|
||||||
to_remove.append(id)
|
to_remove.append(id)
|
||||||
for id in to_remove:
|
for id in to_remove:
|
||||||
self.event_metadata_publisher.publish(
|
self.event_metadata_publisher.publish(
|
||||||
|
|||||||
@@ -365,7 +365,6 @@ class EventCleanup(threading.Thread):
|
|||||||
chunk = ids_to_delete[i : i + CHUNK_SIZE]
|
chunk = ids_to_delete[i : i + CHUNK_SIZE]
|
||||||
logger.debug(f"Deleting {len(chunk)} events from the database")
|
logger.debug(f"Deleting {len(chunk)} events from the database")
|
||||||
Event.delete().where(Event.id << chunk).execute()
|
Event.delete().where(Event.id << chunk).execute()
|
||||||
Timeline.delete().where(Timeline.source_id << chunk).execute()
|
|
||||||
|
|
||||||
# embeddings are always cleaned up, even when semantic search
|
# embeddings are always cleaned up, even when semantic search
|
||||||
# is disabled, so that they don't outlive their events
|
# is disabled, so that they don't outlive their events
|
||||||
|
|||||||
@@ -121,8 +121,8 @@ PRESETS_HW_ACCEL_SCALE = {
|
|||||||
"preset-rpi-64-h264": "-r {0} -vf fps={0},scale={1}:{2}",
|
"preset-rpi-64-h264": "-r {0} -vf fps={0},scale={1}:{2}",
|
||||||
"preset-rpi-64-h265": "-r {0} -vf fps={0},scale={1}:{2}",
|
"preset-rpi-64-h265": "-r {0} -vf fps={0},scale={1}:{2}",
|
||||||
FFMPEG_HWACCEL_VAAPI: "-r {0} -vf fps={0},scale_vaapi=w={1}:h={2},hwdownload,format=nv12",
|
FFMPEG_HWACCEL_VAAPI: "-r {0} -vf fps={0},scale_vaapi=w={1}:h={2},hwdownload,format=nv12",
|
||||||
"preset-intel-qsv-h264": "-r {0} -vf fps={0},vpp_qsv=w={1}:h={2}:format=nv12,hwdownload,format=nv12,format=yuv420p",
|
"preset-intel-qsv-h264": "-r {0} -vf vpp_qsv=w={1}:h={2}:format=nv12,hwdownload,format=nv12,fps={0},format=yuv420p",
|
||||||
"preset-intel-qsv-h265": "-r {0} -vf fps={0},vpp_qsv=w={1}:h={2}:format=nv12,hwdownload,format=nv12,format=yuv420p",
|
"preset-intel-qsv-h265": "-r {0} -vf vpp_qsv=w={1}:h={2}:format=nv12,hwdownload,format=nv12,fps={0},format=yuv420p",
|
||||||
FFMPEG_HWACCEL_NVIDIA: "-r {0} -vf fps={0},scale_cuda=w={1}:h={2},hwdownload,format=nv12",
|
FFMPEG_HWACCEL_NVIDIA: "-r {0} -vf fps={0},scale_cuda=w={1}:h={2},hwdownload,format=nv12",
|
||||||
"preset-jetson-h264": "-r {0}", # scaled in decoder
|
"preset-jetson-h264": "-r {0}", # scaled in decoder
|
||||||
"preset-jetson-h265": "-r {0}", # scaled in decoder
|
"preset-jetson-h265": "-r {0}", # scaled in decoder
|
||||||
|
|||||||
@@ -245,7 +245,7 @@ class GeminiClient(GenAIClient):
|
|||||||
)
|
)
|
||||||
gemini_messages.append(
|
gemini_messages.append(
|
||||||
types.Content(
|
types.Content(
|
||||||
role="user",
|
role="function",
|
||||||
parts=[
|
parts=[
|
||||||
types.Part.from_function_response(
|
types.Part.from_function_response(
|
||||||
name=msg.get("name")
|
name=msg.get("name")
|
||||||
@@ -501,7 +501,7 @@ class GeminiClient(GenAIClient):
|
|||||||
)
|
)
|
||||||
gemini_messages.append(
|
gemini_messages.append(
|
||||||
types.Content(
|
types.Content(
|
||||||
role="user",
|
role="function",
|
||||||
parts=[
|
parts=[
|
||||||
types.Part.from_function_response(
|
types.Part.from_function_response(
|
||||||
name=msg.get("name")
|
name=msg.get("name")
|
||||||
|
|||||||
+65
-121
@@ -262,6 +262,10 @@ def get_tool_definitions(
|
|||||||
`attribute` parameter is exposed for filtering by their labels. When the
|
`attribute` parameter is exposed for filtering by their labels. When the
|
||||||
embeddings model only understands English (JinaV1), the `semantic_query`
|
embeddings model only understands English (JinaV1), the `semantic_query`
|
||||||
description instructs the model to write the query in English.
|
description instructs the model to write the query in English.
|
||||||
|
|
||||||
|
Descriptions here stay mechanical: which tool to reach for, and how the
|
||||||
|
filters relate to each other, is stated once in the system prompt so the
|
||||||
|
guidance is not paid for twice on every request.
|
||||||
"""
|
"""
|
||||||
search_objects_properties: dict[str, Any] = {
|
search_objects_properties: dict[str, Any] = {
|
||||||
"camera": {
|
"camera": {
|
||||||
@@ -270,26 +274,13 @@ def get_tool_definitions(
|
|||||||
},
|
},
|
||||||
"label": {
|
"label": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": (
|
"description": "Tracked object class to filter by.",
|
||||||
"Generic object class to filter by — one of the tracked detector "
|
|
||||||
"labels such as 'person', 'package', 'car', 'dog', 'bird'. Use "
|
|
||||||
"this for broad queries like 'show me all cars today'. Combine "
|
|
||||||
"with semantic_query when the user also describes appearance or "
|
|
||||||
"behavior (e.g. label='person', semantic_query='riding a lawn "
|
|
||||||
"mower')."
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
"sub_label": {
|
"sub_label": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": (
|
"description": (
|
||||||
"Filter by a DISCRETE NAMED entity recognized in the detection. "
|
"Name recognized in the detection: a person, delivery company, "
|
||||||
"Use this for: a known person's name ('John'), a delivery "
|
"animal species or breed, or license plate."
|
||||||
"company ('Amazon', 'UPS'), a recognized animal species or "
|
|
||||||
"breed ('blue jay', 'cardinal', 'golden retriever'), or a "
|
|
||||||
"license plate string. When filtering by a specific name, set "
|
|
||||||
"only sub_label and leave label unset. Do NOT use sub_label "
|
|
||||||
"for descriptions of appearance, clothing, or actions — those "
|
|
||||||
"belong in semantic_query."
|
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
"after": {
|
"after": {
|
||||||
@@ -313,20 +304,11 @@ def get_tool_definitions(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if attribute_classifications:
|
if attribute_classifications:
|
||||||
model_outline = "; ".join(
|
|
||||||
f"{m['name']} (applies to {', '.join(m['objects']) or 'any object'})"
|
|
||||||
for m in attribute_classifications
|
|
||||||
)
|
|
||||||
search_objects_properties["attribute"] = {
|
search_objects_properties["attribute"] = {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": (
|
"description": (
|
||||||
"Filter by a classification attribute label produced by a "
|
"Attribute label produced by a configured classification model "
|
||||||
"configured attribute classification model. Use this INSTEAD "
|
"(case-sensitive)."
|
||||||
"of semantic_query when the user's request matches one of "
|
|
||||||
"these classifications. Configured models: "
|
|
||||||
f"{model_outline}. "
|
|
||||||
"Set the value to the attribute label that matches the user's "
|
|
||||||
"phrasing (case-sensitive)."
|
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,29 +316,12 @@ def get_tool_definitions(
|
|||||||
search_objects_properties["semantic_query"] = {
|
search_objects_properties["semantic_query"] = {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": (
|
"description": (
|
||||||
"Optional natural-language description of a PHYSICAL "
|
"Description of an appearance or activity, used to semantically "
|
||||||
"CHARACTERISTIC, APPEARANCE, or ACTIVITY the user mentioned, "
|
"narrow results."
|
||||||
"used to semantically narrow results. Only set this when the "
|
|
||||||
"user describes something beyond what label and sub_label can "
|
|
||||||
"express on their own.\n"
|
|
||||||
"USE for descriptive phrases like: 'riding a lawn mower', "
|
|
||||||
"'wearing a red jacket', 'carrying a package', 'walking a "
|
|
||||||
"dog', 'on a bicycle', 'holding an umbrella'.\n"
|
|
||||||
"DO NOT USE for:\n"
|
|
||||||
"- specific named people, pets, or delivery companies → use sub_label\n"
|
|
||||||
"- animal species or breed names like 'blue jay', 'cardinal', "
|
|
||||||
"'golden retriever' → use sub_label\n"
|
|
||||||
"- license plate strings → use sub_label\n"
|
|
||||||
"- generic object queries like 'all cars today' or 'every "
|
|
||||||
"person' → use label alone with no semantic_query\n"
|
|
||||||
"When set, combine with label/time/camera/zone filters as "
|
|
||||||
"usual (e.g. label='person', semantic_query='riding a lawn "
|
|
||||||
"mower', after='2024-05-01T00:00:00Z')."
|
|
||||||
+ (
|
+ (
|
||||||
" The configured embeddings model only understands "
|
" The configured embeddings model only understands English, so "
|
||||||
"English, so always write semantic_query in English, "
|
"always write this in English, translating the user's "
|
||||||
"translating the user's description if they phrased it "
|
"description if they phrased it in another language."
|
||||||
"in another language."
|
|
||||||
if embeddings_language == "english"
|
if embeddings_language == "english"
|
||||||
else ""
|
else ""
|
||||||
)
|
)
|
||||||
@@ -364,26 +329,10 @@ def get_tool_definitions(
|
|||||||
}
|
}
|
||||||
|
|
||||||
search_objects_description = (
|
search_objects_description = (
|
||||||
"Search the historical record of detected objects in Frigate. "
|
"Search the historical record of tracked detections. Use this ONLY for "
|
||||||
"Use this ONLY for questions about the PAST — e.g. 'did anyone come by today?', "
|
"questions about the PAST, e.g. 'did anyone come by today?', 'when was the "
|
||||||
"'when was the last car?', 'show me detections from yesterday'. "
|
"last car?'. For alerting on future events use start_camera_watch instead."
|
||||||
"Do NOT use this for monitoring or alerting requests about future events — "
|
|
||||||
"use start_camera_watch instead for those. "
|
|
||||||
"An 'object' in Frigate represents a tracked detection (e.g., a person, package, car).\n\n"
|
|
||||||
"Choose filters based on what the user is asking for:\n"
|
|
||||||
"- Generic class query ('show me all cars today'): set `label` only.\n"
|
|
||||||
"- Specific NAMED entity (known person, delivery company, animal "
|
|
||||||
"species/breed like 'blue jay' or 'golden retriever', license "
|
|
||||||
"plate): set `sub_label` only and leave `label` unset.\n"
|
|
||||||
)
|
)
|
||||||
if semantic_search_enabled:
|
|
||||||
search_objects_description += (
|
|
||||||
"- Physical CHARACTERISTIC, APPEARANCE, or ACTIVITY that is not a "
|
|
||||||
"discrete name ('person riding a lawn mower', 'someone in a red "
|
|
||||||
"jacket', 'person carrying a package'): set `semantic_query` with "
|
|
||||||
"the descriptive phrase, optionally alongside `label` for the "
|
|
||||||
"object class. Do NOT put descriptive phrases in sub_label."
|
|
||||||
)
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
@@ -398,20 +347,30 @@ def get_tool_definitions(
|
|||||||
"required": [],
|
"required": [],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": "get_categorized_object_names",
|
||||||
|
"description": (
|
||||||
|
"Every name that can be attached as a sub_label, grouped by object "
|
||||||
|
"type: recognized faces, named license plates, classification "
|
||||||
|
"categories, and delivery logos. Takes no arguments and always "
|
||||||
|
"returns the complete map."
|
||||||
|
),
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "find_similar_objects",
|
"name": "find_similar_objects",
|
||||||
"description": (
|
"description": (
|
||||||
"Find tracked objects that are visually and semantically similar "
|
"Find tracked objects visually and semantically similar to a "
|
||||||
"to a specific past event. Use this when the user references a "
|
"specific past event. Requires semantic search to be enabled."
|
||||||
"particular object they have seen and wants to find other "
|
|
||||||
"sightings of the same or similar one ('that green car', 'the "
|
|
||||||
"person in the red jacket', 'the package that was delivered'). "
|
|
||||||
"Prefer this over search_objects whenever the user's intent is "
|
|
||||||
"'find more like this specific one.' Use search_objects first "
|
|
||||||
"only if you need to locate the anchor event. Requires semantic "
|
|
||||||
"search to be enabled."
|
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -473,9 +432,8 @@ def get_tool_definitions(
|
|||||||
"function": {
|
"function": {
|
||||||
"name": "set_camera_state",
|
"name": "set_camera_state",
|
||||||
"description": (
|
"description": (
|
||||||
"Change a camera's feature state (e.g., turn detection on/off, enable/disable recordings). "
|
"Change a camera's feature state, e.g. turn detection on or off. "
|
||||||
"Use camera='*' to apply to all cameras at once. "
|
"Only call this when the user explicitly asks to change a setting. "
|
||||||
"Only call this tool when the user explicitly asks to change a camera setting. "
|
|
||||||
"Requires admin privileges."
|
"Requires admin privileges."
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
@@ -510,14 +468,14 @@ def get_tool_definitions(
|
|||||||
],
|
],
|
||||||
"description": (
|
"description": (
|
||||||
"The feature to change. Most features accept ON or OFF. "
|
"The feature to change. Most features accept ON or OFF. "
|
||||||
"birdseye_mode accepts CONTINUOUS, MOTION, or OBJECTS. "
|
"birdseye_mode accepts CONTINUOUS, MOTION, OBJECTS, STATIONARY_OBJECTS, or a comma-separated combination. "
|
||||||
"motion_contour_area and motion_threshold accept a number. "
|
"motion_contour_area and motion_threshold accept a number. "
|
||||||
"profile accepts a profile name or 'none' to deactivate (requires camera='*')."
|
"profile accepts a profile name or 'none' to deactivate (requires camera='*')."
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
"value": {
|
"value": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "The value to set. ON or OFF for toggles, a number for thresholds, a profile name or 'none' for profile.",
|
"description": "The value to set, as accepted by the chosen feature.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"required": ["camera", "feature", "value"],
|
"required": ["camera", "feature", "value"],
|
||||||
@@ -529,11 +487,9 @@ def get_tool_definitions(
|
|||||||
"function": {
|
"function": {
|
||||||
"name": "get_live_context",
|
"name": "get_live_context",
|
||||||
"description": (
|
"description": (
|
||||||
"Get the current live image and detection information for a single camera: objects being tracked, "
|
"Current live image and detections (tracked objects, zones, "
|
||||||
"zones, timestamps. Use this to understand what is visible in the live view. "
|
"timestamps) for one camera. Use this for questions about what is "
|
||||||
"Call this when answering questions about what is happening right now on a specific camera. "
|
"happening right now. Call it again for each additional camera."
|
||||||
"Operates on one camera at a time; call the tool again for each additional camera. "
|
|
||||||
"Wildcards and empty values are not accepted."
|
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -541,8 +497,8 @@ def get_tool_definitions(
|
|||||||
"camera": {
|
"camera": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": (
|
"description": (
|
||||||
"Exact name of a single camera to get live context for. "
|
"Exact name of a single camera. Wildcards (e.g. '*', "
|
||||||
"Wildcards (e.g. '*', 'all') and empty strings are not accepted."
|
"'all') and empty strings are not accepted."
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -555,10 +511,9 @@ def get_tool_definitions(
|
|||||||
"function": {
|
"function": {
|
||||||
"name": "start_camera_watch",
|
"name": "start_camera_watch",
|
||||||
"description": (
|
"description": (
|
||||||
"Start a continuous VLM watch job that monitors a camera and sends a notification "
|
"Start a continuous watch job that monitors a camera and notifies "
|
||||||
"when a specified condition is met. Use this when the user wants to be alerted about "
|
"the user when a condition is met, e.g. 'tell me when guests "
|
||||||
"a future event, e.g. 'tell me when guests arrive' or 'notify me when the package is picked up'. "
|
"arrive'. Only one watch job can run at a time. Returns a job ID."
|
||||||
"Only one watch job can run at a time. Returns a job ID."
|
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -598,10 +553,7 @@ def get_tool_definitions(
|
|||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "stop_camera_watch",
|
"name": "stop_camera_watch",
|
||||||
"description": (
|
"description": "Cancel the currently running watch job.",
|
||||||
"Cancel the currently running VLM watch job. Use this when the user wants to "
|
|
||||||
"stop a previously started watch, e.g. 'stop watching the front door'."
|
|
||||||
),
|
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {},
|
"properties": {},
|
||||||
@@ -614,11 +566,9 @@ def get_tool_definitions(
|
|||||||
"function": {
|
"function": {
|
||||||
"name": "get_profile_status",
|
"name": "get_profile_status",
|
||||||
"description": (
|
"description": (
|
||||||
"Get the current profile status including the active profile and "
|
"Get the active profile and when each profile was last activated. "
|
||||||
"timestamps of when each profile was last activated. Use this to "
|
"Call this before get_recap to derive the time window for requests "
|
||||||
"determine time periods for recap requests — e.g. when the user asks "
|
"like 'what happened while I was away?'."
|
||||||
"'what happened while I was away?', call this first to find the relevant "
|
|
||||||
"time window based on profile activation history."
|
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -632,11 +582,9 @@ def get_tool_definitions(
|
|||||||
"function": {
|
"function": {
|
||||||
"name": "get_recap",
|
"name": "get_recap",
|
||||||
"description": (
|
"description": (
|
||||||
"Get a recap of all activity (alerts and detections) for a given time period. "
|
"Get all activity (alerts and detections) for a time period, as a "
|
||||||
"Use this after calling get_profile_status to retrieve what happened during "
|
"chronological list with camera, objects, zones, and descriptions "
|
||||||
"a specific window — e.g. 'what happened while I was away?'. Returns a "
|
"when available. Summarize the results for the user."
|
||||||
"chronological list of activity with camera, objects, zones, and GenAI-generated "
|
|
||||||
"descriptions when available. Summarize the results for the user."
|
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -723,14 +671,13 @@ def build_chat_system_prompt(
|
|||||||
)
|
)
|
||||||
speed_units_section = f"\n\nReport object speeds to the user in {speed_unit}."
|
speed_units_section = f"\n\nReport object speeds to the user in {speed_unit}."
|
||||||
|
|
||||||
semantic_search_section = ""
|
filter_routing_section = (
|
||||||
|
"\n\nWhen routing a search_objects call, pick filters by the shape of the user's request:\n"
|
||||||
|
"- Generic class ('show me all cars today'): set `label` only.\n"
|
||||||
|
"- Specific named entity — a known person ('John'), delivery company ('Amazon'), animal species/breed ('blue jay', 'golden retriever'), or license plate: set `sub_label` only and leave `label` unset. Call get_categorized_object_names first and use the exact spelling it returns; a guessed spelling matches nothing. If the name is absent, say it is not configured rather than searching for it."
|
||||||
|
)
|
||||||
if semantic_search_enabled:
|
if semantic_search_enabled:
|
||||||
semantic_search_section = (
|
filter_routing_section += "\n- Physical characteristic, appearance, or activity that is NOT a discrete name ('riding a lawn mower', 'someone in a red jacket'): set `semantic_query` with the descriptive phrase, optionally combined with `label`. Never put descriptive phrases in `sub_label`."
|
||||||
"\n\nWhen routing a search_objects call, pick filters by the shape of the user's request:\n"
|
|
||||||
"- Generic class ('show me all cars today'): set `label` only.\n"
|
|
||||||
"- Specific named entity — a known person ('John'), delivery company ('Amazon'), animal species/breed ('blue jay', 'cardinal', 'golden retriever'), or license plate: set `sub_label` only and leave `label` unset.\n"
|
|
||||||
"- Physical characteristic, appearance, or activity that is NOT a discrete name ('find me people riding a lawn mower', 'someone in a red jacket', 'a person carrying a package'): set `semantic_query` with the descriptive phrase, optionally combined with `label` for the object class. Never put descriptive phrases in `sub_label`."
|
|
||||||
)
|
|
||||||
|
|
||||||
attribute_classification_section = ""
|
attribute_classification_section = ""
|
||||||
if attribute_classifications:
|
if attribute_classifications:
|
||||||
@@ -739,9 +686,9 @@ def build_chat_system_prompt(
|
|||||||
for m in attribute_classifications
|
for m in attribute_classifications
|
||||||
)
|
)
|
||||||
attribute_classification_section = (
|
attribute_classification_section = (
|
||||||
"\n\nAttribute classification models are configured for the following object types:\n"
|
"\n\nConfigured attribute classification models:\n"
|
||||||
f"{model_lines}\n"
|
f"{model_lines}\n"
|
||||||
"When the user's request matches one of these classifications, set the search_objects `attribute` field to the matching label rather than using `semantic_query`. Reserve `semantic_query` for descriptive phrases that fall outside the configured attribute labels."
|
"When the user's request matches one of these classifications, set the search_objects `attribute` field to the matching label (case-sensitive) rather than using `semantic_query`. Reserve `semantic_query` for descriptive phrases outside the configured attribute labels."
|
||||||
)
|
)
|
||||||
|
|
||||||
return f"""You are a helpful assistant for Frigate, a security camera NVR system. You help users answer questions about their cameras, detected objects, and events.
|
return f"""You are a helpful assistant for Frigate, a security camera NVR system. You help users answer questions about their cameras, detected objects, and events.
|
||||||
@@ -750,9 +697,6 @@ Current server local date and time: {current_date_str} at {current_time_str}
|
|||||||
|
|
||||||
Do not start your response with phrases like "I will check...", "Let me see...", or "Let me look...". Answer directly.
|
Do not start your response with phrases like "I will check...", "Let me see...", or "Let me look...". Answer directly.
|
||||||
|
|
||||||
Always present times to the user in the server's local timezone. When tool results include start_time_local and end_time_local, use those exact strings when listing or describing detection times—do not convert or invent timestamps. Do not use UTC or ISO format with Z for the user-facing answer unless the tool result only provides Unix timestamps without local time fields.
|
Always present times in the server's local timezone. When tool results include start_time_local and end_time_local, quote those strings exactly; never convert or invent timestamps, and fall back to UTC or ISO format only when a result has no local time fields. Resolve relative dates like "today" or "this week" against the current date above, and pass dates to tools in ISO 8601 (e.g. {current_date_str}T00:00:00Z for the start of today).
|
||||||
When users ask about "today", "yesterday", "this week", etc., use the current date above as reference.
|
|
||||||
When searching for objects or events, use ISO 8601 format for dates (e.g., {current_date_str}T00:00:00Z for the start of today).
|
|
||||||
Always be accurate with time calculations based on the current date provided.
|
|
||||||
|
|
||||||
When a user refers to a specific object they have seen or describe with identifying details ("that green car", "the person in the red jacket", "a package left today"), prefer the find_similar_objects tool over search_objects. Use search_objects first only to locate the anchor event, then pass its id to find_similar_objects. For generic queries like "show me all cars today", keep using search_objects. If a user message begins with [attached_event:<id>], treat that event id as the anchor for any similarity or "tell me more" request in the same message and call find_similar_objects with that id.{semantic_search_section}{attribute_classification_section}{cameras_section}{speed_units_section}"""
|
When the user refers to a specific object they have seen ("that green car", "the person in the red jacket", "a package left today"), prefer find_similar_objects over search_objects, using search_objects only to locate the anchor event and passing its id along. Keep search_objects for generic queries like "show me all cars today". If a user message begins with [attached_event:<id>], treat that id as the anchor for any similarity or "tell me more" request in the same message.{filter_routing_section}{attribute_classification_section}{cameras_section}{speed_units_section}"""
|
||||||
|
|||||||
@@ -115,10 +115,6 @@ def query_recordings(source_camera: str, start_ts: float, end_ts: float) -> Mode
|
|||||||
return cast(ModelSelect, query)
|
return cast(ModelSelect, query)
|
||||||
|
|
||||||
|
|
||||||
class NoRecordingsError(ValueError):
|
|
||||||
"""Raised when no recordings exist in the requested time range."""
|
|
||||||
|
|
||||||
|
|
||||||
class DebugReplaySource(ABC):
|
class DebugReplaySource(ABC):
|
||||||
"""Abstract source for a debug replay session.
|
"""Abstract source for a debug replay session.
|
||||||
|
|
||||||
@@ -191,7 +187,7 @@ class RecordingDebugReplaySource(DebugReplaySource):
|
|||||||
raise ValueError("End time must be after start time")
|
raise ValueError("End time must be after start time")
|
||||||
|
|
||||||
if not query_recordings(self._camera, self._start_ts, self._end_ts).count():
|
if not query_recordings(self._camera, self._start_ts, self._end_ts).count():
|
||||||
raise NoRecordingsError(
|
raise ValueError(
|
||||||
f"No recordings found for camera '{self._camera}' in the specified time range"
|
f"No recordings found for camera '{self._camera}' in the specified time range"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+138
-125
@@ -9,6 +9,7 @@ import queue
|
|||||||
import subprocess as sp
|
import subprocess as sp
|
||||||
import threading
|
import threading
|
||||||
import traceback
|
import traceback
|
||||||
|
from dataclasses import dataclass
|
||||||
from multiprocessing.synchronize import Event as MpEvent
|
from multiprocessing.synchronize import Event as MpEvent
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@@ -16,7 +17,7 @@ import cv2
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from frigate.comms.inter_process import InterProcessRequestor
|
from frigate.comms.inter_process import InterProcessRequestor
|
||||||
from frigate.config import BirdseyeModeEnum, FfmpegConfig, FrigateConfig
|
from frigate.config import BirdseyeModeConfig, FfmpegConfig, FrigateConfig
|
||||||
from frigate.const import BASE_DIR, BIRDSEYE_PIPE, INSTALL_DIR, UPDATE_BIRDSEYE_LAYOUT
|
from frigate.const import BASE_DIR, BIRDSEYE_PIPE, INSTALL_DIR, UPDATE_BIRDSEYE_LAYOUT
|
||||||
from frigate.output.ws_auth import ws_has_camera_access
|
from frigate.output.ws_auth import ws_has_camera_access
|
||||||
from frigate.util.image import (
|
from frigate.util.image import (
|
||||||
@@ -28,6 +29,15 @@ from frigate.util.image import (
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class BirdseyeActivity:
|
||||||
|
"""Activity signals used to decide whether a camera is shown in Birdseye."""
|
||||||
|
|
||||||
|
has_active_object: bool
|
||||||
|
has_stationary_object: bool
|
||||||
|
has_motion: bool
|
||||||
|
|
||||||
|
|
||||||
def get_standard_aspect_ratio(width: int, height: int) -> tuple[int, int]:
|
def get_standard_aspect_ratio(width: int, height: int) -> tuple[int, int]:
|
||||||
"""Ensure that only standard aspect ratios are used."""
|
"""Ensure that only standard aspect ratios are used."""
|
||||||
# it is important that all ratios have the same scale
|
# it is important that all ratios have the same scale
|
||||||
@@ -409,18 +419,16 @@ class BirdsEyeFrameManager:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def camera_active(
|
def camera_active(
|
||||||
self, mode: Any, object_box_count: int, motion_box_count: int
|
self,
|
||||||
|
mode: BirdseyeModeConfig,
|
||||||
|
activity: BirdseyeActivity,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
if mode == BirdseyeModeEnum.continuous:
|
return (
|
||||||
return True
|
mode.continuous
|
||||||
|
or (mode.motion and activity.has_motion)
|
||||||
if mode == BirdseyeModeEnum.motion and motion_box_count > 0:
|
or (mode.objects and activity.has_active_object)
|
||||||
return True
|
or (mode.stationary_objects and activity.has_stationary_object)
|
||||||
|
)
|
||||||
if mode == BirdseyeModeEnum.objects and object_box_count > 0:
|
|
||||||
return True
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
def get_camera_coordinates(self) -> dict[str, dict[str, int]]:
|
def get_camera_coordinates(self) -> dict[str, dict[str, int]]:
|
||||||
"""Return the coordinates of each camera in the current layout."""
|
"""Return the coordinates of each camera in the current layout."""
|
||||||
@@ -604,112 +612,92 @@ class BirdsEyeFrameManager:
|
|||||||
) -> list[list[Any]] | None:
|
) -> list[list[Any]] | None:
|
||||||
"""Calculate the optimal layout for 2+ cameras."""
|
"""Calculate the optimal layout for 2+ cameras."""
|
||||||
|
|
||||||
def map_layout(
|
def find_available_x(
|
||||||
camera_layout: list[list[Any]], row_height: int
|
current_x: int,
|
||||||
) -> tuple[int, int, list[list[Any]] | None]:
|
width: int,
|
||||||
"""Map the calculated layout."""
|
reserved_ranges: list[tuple[int, int]],
|
||||||
candidate_layout = []
|
max_width: int,
|
||||||
starting_x = 0
|
) -> int | None:
|
||||||
x = 0
|
"""Find the first horizontal slot that does not collide with reservations."""
|
||||||
max_width = 0
|
x = current_x
|
||||||
y = 0
|
|
||||||
|
|
||||||
for row in camera_layout:
|
for reserved_start, reserved_end in sorted(reserved_ranges):
|
||||||
final_row = []
|
if x >= reserved_end:
|
||||||
max_width = max(max_width, x)
|
continue
|
||||||
x = starting_x
|
|
||||||
for cameras in row:
|
|
||||||
camera_dims = self.cameras[cameras[0]]["dimensions"].copy()
|
|
||||||
camera_aspect = cameras[1]
|
|
||||||
|
|
||||||
if camera_dims[1] > camera_dims[0]:
|
if x + width <= reserved_start:
|
||||||
scaled_height = int(row_height * 2)
|
return x
|
||||||
scaled_width = int(scaled_height * camera_aspect)
|
|
||||||
starting_x = scaled_width
|
|
||||||
else:
|
|
||||||
scaled_height = row_height
|
|
||||||
scaled_width = int(scaled_height * camera_aspect)
|
|
||||||
|
|
||||||
# layout is too large
|
x = max(x, reserved_end)
|
||||||
if (
|
|
||||||
x + scaled_width > self.canvas.width
|
|
||||||
or y + scaled_height > self.canvas.height
|
|
||||||
):
|
|
||||||
return x + scaled_width, y + scaled_height, None
|
|
||||||
|
|
||||||
final_row.append((cameras[0], (x, y, scaled_width, scaled_height)))
|
if x + width <= max_width:
|
||||||
x += scaled_width
|
return x
|
||||||
|
|
||||||
y += row_height
|
|
||||||
candidate_layout.append(final_row)
|
|
||||||
|
|
||||||
if max_width == 0:
|
|
||||||
max_width = x
|
|
||||||
|
|
||||||
return max_width, y, candidate_layout
|
|
||||||
|
|
||||||
canvas_aspect_x, canvas_aspect_y = self.canvas.get_aspect(coefficient)
|
|
||||||
camera_layout: list[list[Any]] = []
|
|
||||||
camera_layout.append([])
|
|
||||||
starting_x = 0
|
|
||||||
x = starting_x
|
|
||||||
y = 0
|
|
||||||
y_i = 0
|
|
||||||
max_y = 0
|
|
||||||
for camera in cameras_to_add:
|
|
||||||
camera_dims = self.cameras[camera]["dimensions"].copy()
|
|
||||||
camera_aspect_x, camera_aspect_y = self.canvas.get_camera_aspect(
|
|
||||||
camera, camera_dims[0], camera_dims[1]
|
|
||||||
)
|
|
||||||
|
|
||||||
if camera_dims[1] > camera_dims[0]:
|
|
||||||
portrait = True
|
|
||||||
else:
|
|
||||||
portrait = False
|
|
||||||
|
|
||||||
if (x + camera_aspect_x) <= canvas_aspect_x:
|
|
||||||
# insert if camera can fit on current row
|
|
||||||
camera_layout[y_i].append(
|
|
||||||
(
|
|
||||||
camera,
|
|
||||||
camera_aspect_x / camera_aspect_y,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
if portrait:
|
|
||||||
starting_x = camera_aspect_x
|
|
||||||
else:
|
|
||||||
max_y = max(
|
|
||||||
max_y,
|
|
||||||
camera_aspect_y,
|
|
||||||
)
|
|
||||||
|
|
||||||
x += camera_aspect_x
|
|
||||||
else:
|
|
||||||
# move on to the next row and insert
|
|
||||||
y += max_y
|
|
||||||
y_i += 1
|
|
||||||
camera_layout.append([])
|
|
||||||
x = starting_x
|
|
||||||
|
|
||||||
if x + camera_aspect_x > canvas_aspect_x:
|
|
||||||
return None
|
|
||||||
|
|
||||||
camera_layout[y_i].append(
|
|
||||||
(
|
|
||||||
camera,
|
|
||||||
camera_aspect_x / camera_aspect_y,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
x += camera_aspect_x
|
|
||||||
|
|
||||||
if y + max_y > canvas_aspect_y:
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
row_height = int(self.canvas.height / coefficient)
|
def map_layout(row_height: int) -> tuple[int, int, list[list[Any]] | None]:
|
||||||
total_width, total_height, standard_candidate_layout = map_layout(
|
"""Lay out cameras row by row while reserving portrait spans for the next row."""
|
||||||
camera_layout, row_height
|
candidate_layout: list[list[Any]] = []
|
||||||
)
|
reserved_ranges: dict[int, list[tuple[int, int]]] = {}
|
||||||
|
current_row: list[Any] = []
|
||||||
|
row_index = 0
|
||||||
|
row_y = 0
|
||||||
|
row_x = 0
|
||||||
|
max_width = 0
|
||||||
|
max_height = 0
|
||||||
|
|
||||||
|
for camera in cameras_to_add:
|
||||||
|
camera_dims = self.cameras[camera]["dimensions"].copy()
|
||||||
|
camera_aspect_x, camera_aspect_y = self.canvas.get_camera_aspect(
|
||||||
|
camera, camera_dims[0], camera_dims[1]
|
||||||
|
)
|
||||||
|
portrait = camera_dims[1] > camera_dims[0]
|
||||||
|
scaled_height = row_height * 2 if portrait else row_height
|
||||||
|
scaled_width = int(scaled_height * (camera_aspect_x / camera_aspect_y))
|
||||||
|
|
||||||
|
while True:
|
||||||
|
x = find_available_x(
|
||||||
|
row_x,
|
||||||
|
scaled_width,
|
||||||
|
reserved_ranges.get(row_index, []),
|
||||||
|
self.canvas.width,
|
||||||
|
)
|
||||||
|
|
||||||
|
if x is not None and row_y + scaled_height <= self.canvas.height:
|
||||||
|
current_row.append(
|
||||||
|
(camera, (x, row_y, scaled_width, scaled_height))
|
||||||
|
)
|
||||||
|
row_x = x + scaled_width
|
||||||
|
max_width = max(max_width, row_x)
|
||||||
|
max_height = max(max_height, row_y + scaled_height)
|
||||||
|
|
||||||
|
if portrait:
|
||||||
|
reserved_ranges.setdefault(row_index + 1, []).append(
|
||||||
|
(x, row_x)
|
||||||
|
)
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
if current_row:
|
||||||
|
candidate_layout.append(current_row)
|
||||||
|
current_row = []
|
||||||
|
|
||||||
|
row_index += 1
|
||||||
|
row_y = row_index * row_height
|
||||||
|
row_x = 0
|
||||||
|
|
||||||
|
if row_y + scaled_height > self.canvas.height:
|
||||||
|
overflow_width = max(max_width, scaled_width)
|
||||||
|
overflow_height = row_y + scaled_height
|
||||||
|
return overflow_width, overflow_height, None
|
||||||
|
|
||||||
|
if current_row:
|
||||||
|
candidate_layout.append(current_row)
|
||||||
|
|
||||||
|
return max_width, max_height, candidate_layout
|
||||||
|
|
||||||
|
row_height = max(1, int(self.canvas.height / coefficient))
|
||||||
|
total_width, total_height, standard_candidate_layout = map_layout(row_height)
|
||||||
|
|
||||||
if not standard_candidate_layout:
|
if not standard_candidate_layout:
|
||||||
# if standard layout didn't work
|
# if standard layout didn't work
|
||||||
@@ -718,9 +706,9 @@ class BirdsEyeFrameManager:
|
|||||||
total_width / self.canvas.width,
|
total_width / self.canvas.width,
|
||||||
total_height / self.canvas.height,
|
total_height / self.canvas.height,
|
||||||
)
|
)
|
||||||
row_height = int(row_height / scale_down_percent)
|
row_height = max(1, int(row_height / scale_down_percent))
|
||||||
total_width, total_height, standard_candidate_layout = map_layout(
|
total_width, total_height, standard_candidate_layout = map_layout(
|
||||||
camera_layout, row_height
|
row_height
|
||||||
)
|
)
|
||||||
|
|
||||||
if not standard_candidate_layout:
|
if not standard_candidate_layout:
|
||||||
@@ -734,8 +722,8 @@ class BirdsEyeFrameManager:
|
|||||||
1 / (total_width / self.canvas.width),
|
1 / (total_width / self.canvas.width),
|
||||||
1 / (total_height / self.canvas.height),
|
1 / (total_height / self.canvas.height),
|
||||||
)
|
)
|
||||||
row_height = int(row_height * scale_up_percent)
|
row_height = max(1, int(row_height * scale_up_percent))
|
||||||
_, _, scaled_layout = map_layout(camera_layout, row_height)
|
_, _, scaled_layout = map_layout(row_height)
|
||||||
|
|
||||||
if scaled_layout:
|
if scaled_layout:
|
||||||
return scaled_layout
|
return scaled_layout
|
||||||
@@ -745,8 +733,7 @@ class BirdsEyeFrameManager:
|
|||||||
def update(
|
def update(
|
||||||
self,
|
self,
|
||||||
camera: str,
|
camera: str,
|
||||||
object_count: int,
|
activity: BirdseyeActivity,
|
||||||
motion_count: int,
|
|
||||||
frame_time: float,
|
frame_time: float,
|
||||||
frame: np.ndarray,
|
frame: np.ndarray,
|
||||||
) -> tuple[bool, bool]:
|
) -> tuple[bool, bool]:
|
||||||
@@ -760,22 +747,29 @@ class BirdsEyeFrameManager:
|
|||||||
return False, False
|
return False, False
|
||||||
|
|
||||||
force_update = False
|
force_update = False
|
||||||
|
camera_state = self.cameras.get(camera)
|
||||||
|
|
||||||
|
if camera_state is None:
|
||||||
|
return False, False
|
||||||
|
|
||||||
# disabling birdseye is a little tricky
|
# disabling birdseye is a little tricky
|
||||||
if not camera_config.birdseye.enabled or not camera_config.enabled:
|
if not camera_config.birdseye.enabled or not camera_config.enabled:
|
||||||
# if we've rendered a frame (we have a value for last_active_frame)
|
# if we've rendered a frame (we have a value for last_active_frame)
|
||||||
# then we need to set it to zero
|
# then we need to set it to zero
|
||||||
if self.cameras[camera]["last_active_frame"] > 0:
|
if camera_state["last_active_frame"] > 0:
|
||||||
self.cameras[camera]["last_active_frame"] = 0
|
camera_state["last_active_frame"] = 0
|
||||||
force_update = True
|
force_update = True
|
||||||
else:
|
else:
|
||||||
return False, False
|
return False, False
|
||||||
|
|
||||||
# update the last active frame for the camera
|
# update the last active frame for the camera
|
||||||
self.cameras[camera]["current_frame"] = frame.copy()
|
camera_state["current_frame"] = frame.copy()
|
||||||
self.cameras[camera]["current_frame_time"] = frame_time
|
camera_state["current_frame_time"] = frame_time
|
||||||
if self.camera_active(camera_config.birdseye.mode, object_count, motion_count):
|
if self.camera_active(
|
||||||
self.cameras[camera]["last_active_frame"] = frame_time
|
camera_config.birdseye.mode,
|
||||||
|
activity,
|
||||||
|
):
|
||||||
|
camera_state["last_active_frame"] = frame_time
|
||||||
|
|
||||||
now = datetime.datetime.now().timestamp()
|
now = datetime.datetime.now().timestamp()
|
||||||
|
|
||||||
@@ -882,10 +876,29 @@ class Birdseye:
|
|||||||
frame_time: float,
|
frame_time: float,
|
||||||
frame: np.ndarray,
|
frame: np.ndarray,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
has_active_object = False
|
||||||
|
has_stationary_object = False
|
||||||
|
for tracked_object in current_tracked_objects:
|
||||||
|
if tracked_object["stationary"]:
|
||||||
|
if not tracked_object["false_positive"]:
|
||||||
|
has_stationary_object = True
|
||||||
|
else:
|
||||||
|
# Preserve the existing objects activity behavior, which includes
|
||||||
|
# non-stationary trackers before they are confirmed.
|
||||||
|
has_active_object = True
|
||||||
|
|
||||||
|
if has_active_object and has_stationary_object:
|
||||||
|
break
|
||||||
|
|
||||||
|
activity = BirdseyeActivity(
|
||||||
|
has_active_object=has_active_object,
|
||||||
|
has_stationary_object=has_stationary_object,
|
||||||
|
has_motion=bool(motion_boxes),
|
||||||
|
)
|
||||||
|
|
||||||
frame_changed, frame_layout_changed = self.birdseye_manager.update(
|
frame_changed, frame_layout_changed = self.birdseye_manager.update(
|
||||||
camera,
|
camera,
|
||||||
len([o for o in current_tracked_objects if not o["stationary"]]),
|
activity,
|
||||||
len(motion_boxes),
|
|
||||||
frame_time,
|
frame_time,
|
||||||
frame,
|
frame,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -51,8 +51,12 @@ def check_disabled_camera_update(
|
|||||||
|
|
||||||
for camera, last_update in write_times.items():
|
for camera, last_update in write_times.items():
|
||||||
offline_time = now - last_update
|
offline_time = now - last_update
|
||||||
|
camera_config = config.cameras.get(camera)
|
||||||
|
|
||||||
if config.cameras[camera].enabled:
|
if camera_config is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if camera_config.enabled:
|
||||||
has_enabled_camera = True
|
has_enabled_camera = True
|
||||||
else:
|
else:
|
||||||
# flag camera as offline when it is disabled
|
# flag camera as offline when it is disabled
|
||||||
@@ -62,8 +66,8 @@ def check_disabled_camera_update(
|
|||||||
# last camera update was more than 1 second ago
|
# last camera update was more than 1 second ago
|
||||||
# need to send empty data to birdseye because current
|
# need to send empty data to birdseye because current
|
||||||
# frame is now out of date
|
# frame is now out of date
|
||||||
cam_width = config.cameras[camera].detect.width
|
cam_width = camera_config.detect.width
|
||||||
cam_height = config.cameras[camera].detect.height
|
cam_height = camera_config.detect.height
|
||||||
|
|
||||||
if cam_width is None or cam_height is None:
|
if cam_width is None or cam_height is None:
|
||||||
raise ValueError(f"Camera {camera} detect dimensions not configured")
|
raise ValueError(f"Camera {camera} detect dimensions not configured")
|
||||||
@@ -309,10 +313,11 @@ class OutputProcess(FrigateProcess):
|
|||||||
regions,
|
regions,
|
||||||
) = data
|
) = data
|
||||||
|
|
||||||
frame = frame_manager.get(
|
camera_config = self.config.cameras.get(camera)
|
||||||
frame_name, self.config.cameras[camera].frame_shape_yuv
|
|
||||||
)
|
if camera_config is not None:
|
||||||
frame_manager.close(frame_name)
|
frame_manager.get(frame_name, camera_config.frame_shape_yuv)
|
||||||
|
frame_manager.close(frame_name)
|
||||||
|
|
||||||
detection_subscriber.stop()
|
detection_subscriber.stop()
|
||||||
|
|
||||||
|
|||||||
+21
-20
@@ -799,14 +799,24 @@ class PtzAutoTracker:
|
|||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# both are popped when the camera is deleted, so resolve them once
|
||||||
|
# here and use the locals for the rest of the move; a move already
|
||||||
|
# in flight then finishes against valid objects
|
||||||
|
metrics = self.ptz_metrics.get(camera)
|
||||||
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
|
if metrics is None or camera_config is None:
|
||||||
|
logger.debug("%s: Dropping queued move, camera was removed", camera)
|
||||||
|
continue
|
||||||
|
|
||||||
async with self.move_queue_locks[camera]:
|
async with self.move_queue_locks[camera]:
|
||||||
frame_time, pan, tilt, zoom = move_data
|
frame_time, pan, tilt, zoom = move_data
|
||||||
|
|
||||||
# if we're receiving move requests during a PTZ move, ignore them
|
# if we're receiving move requests during a PTZ move, ignore them
|
||||||
if ptz_moving_at_frame_time(
|
if ptz_moving_at_frame_time(
|
||||||
frame_time,
|
frame_time,
|
||||||
self.ptz_metrics[camera].start_time.value,
|
metrics.start_time.value,
|
||||||
self.ptz_metrics[camera].stop_time.value,
|
metrics.stop_time.value,
|
||||||
):
|
):
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera}: Move queue: PTZ moving, dequeueing move request - frame time: {frame_time}, final pan: {pan}, final tilt: {tilt}, final zoom: {zoom}"
|
f"{camera}: Move queue: PTZ moving, dequeueing move request - frame time: {frame_time}, final pan: {pan}, final tilt: {tilt}, final zoom: {zoom}"
|
||||||
@@ -815,7 +825,7 @@ class PtzAutoTracker:
|
|||||||
|
|
||||||
else:
|
else:
|
||||||
if (
|
if (
|
||||||
self.config.cameras[camera].onvif.autotracking.zooming
|
camera_config.onvif.autotracking.zooming
|
||||||
== ZoomingModeEnum.relative
|
== ZoomingModeEnum.relative
|
||||||
):
|
):
|
||||||
await self.onvif._move_relative(camera, pan, tilt, zoom, 1)
|
await self.onvif._move_relative(camera, pan, tilt, zoom, 1)
|
||||||
@@ -824,25 +834,22 @@ class PtzAutoTracker:
|
|||||||
await self.onvif._move_relative(camera, pan, tilt, 0, 1)
|
await self.onvif._move_relative(camera, pan, tilt, 0, 1)
|
||||||
|
|
||||||
# Wait until the camera finishes moving
|
# Wait until the camera finishes moving
|
||||||
while not self.ptz_metrics[camera].motor_stopped.is_set():
|
while not metrics.motor_stopped.is_set():
|
||||||
await self.onvif.get_camera_status(camera)
|
await self.onvif.get_camera_status(camera)
|
||||||
|
|
||||||
if (
|
if zoom > 0 and metrics.zoom_level.value != zoom:
|
||||||
zoom > 0
|
|
||||||
and self.ptz_metrics[camera].zoom_level.value != zoom
|
|
||||||
):
|
|
||||||
await self.onvif._zoom_absolute(camera, zoom, 1)
|
await self.onvif._zoom_absolute(camera, zoom, 1)
|
||||||
|
|
||||||
# Wait until the camera finishes moving
|
# Wait until the camera finishes moving
|
||||||
while not self.ptz_metrics[camera].motor_stopped.is_set():
|
while not metrics.motor_stopped.is_set():
|
||||||
await self.onvif.get_camera_status(camera)
|
await self.onvif.get_camera_status(camera)
|
||||||
|
|
||||||
if self.config.cameras[camera].onvif.autotracking.movement_weights:
|
if camera_config.onvif.autotracking.movement_weights:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera}: Predicted movement time: {self._predict_movement_time(camera, pan, tilt)}"
|
f"{camera}: Predicted movement time: {self._predict_movement_time(camera, pan, tilt)}"
|
||||||
)
|
)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera}: Actual movement time: {self.ptz_metrics[camera].stop_time.value - self.ptz_metrics[camera].start_time.value}"
|
f"{camera}: Actual movement time: {metrics.stop_time.value - metrics.start_time.value}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# save metrics for better estimate calculations
|
# save metrics for better estimate calculations
|
||||||
@@ -851,21 +858,15 @@ class PtzAutoTracker:
|
|||||||
and len(self.move_metrics[camera])
|
and len(self.move_metrics[camera])
|
||||||
< AUTOTRACKING_MAX_MOVE_METRICS
|
< AUTOTRACKING_MAX_MOVE_METRICS
|
||||||
and (pan != 0 or tilt != 0)
|
and (pan != 0 or tilt != 0)
|
||||||
and self.config.cameras[
|
and camera_config.onvif.autotracking.calibrate_on_startup
|
||||||
camera
|
|
||||||
].onvif.autotracking.calibrate_on_startup
|
|
||||||
):
|
):
|
||||||
logger.debug(f"{camera}: Adding new values to move metrics")
|
logger.debug(f"{camera}: Adding new values to move metrics")
|
||||||
self.move_metrics[camera].append(
|
self.move_metrics[camera].append(
|
||||||
{
|
{
|
||||||
"pan": pan,
|
"pan": pan,
|
||||||
"tilt": tilt,
|
"tilt": tilt,
|
||||||
"start_timestamp": self.ptz_metrics[
|
"start_timestamp": metrics.start_time.value,
|
||||||
camera
|
"end_timestamp": metrics.stop_time.value,
|
||||||
].start_time.value,
|
|
||||||
"end_timestamp": self.ptz_metrics[
|
|
||||||
camera
|
|
||||||
].stop_time.value,
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+65
-55
@@ -180,6 +180,11 @@ class OnvifController:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
async def _init_onvif(self, camera_name: str) -> bool:
|
async def _init_onvif(self, camera_name: str) -> bool:
|
||||||
|
camera_config = self.config.cameras.get(camera_name)
|
||||||
|
|
||||||
|
if camera_config is None:
|
||||||
|
return False
|
||||||
|
|
||||||
onvif: ONVIFCamera = self.cams[camera_name]["onvif"]
|
onvif: ONVIFCamera = self.cams[camera_name]["onvif"]
|
||||||
try:
|
try:
|
||||||
await onvif.update_xaddrs()
|
await onvif.update_xaddrs()
|
||||||
@@ -235,7 +240,7 @@ class OnvifController:
|
|||||||
p.token,
|
p.token,
|
||||||
)
|
)
|
||||||
|
|
||||||
configured_profile = self.config.cameras[camera_name].onvif.profile
|
configured_profile = camera_config.onvif.profile
|
||||||
profile = None
|
profile = None
|
||||||
|
|
||||||
if configured_profile is not None:
|
if configured_profile is not None:
|
||||||
@@ -339,7 +344,7 @@ class OnvifController:
|
|||||||
except (AttributeError, TypeError):
|
except (AttributeError, TypeError):
|
||||||
fov_space_id = None
|
fov_space_id = None
|
||||||
|
|
||||||
autotracking_config = self.config.cameras[camera_name].onvif.autotracking
|
autotracking_config = camera_config.onvif.autotracking
|
||||||
autotracking_enabled = (
|
autotracking_enabled = (
|
||||||
autotracking_config.enabled_in_config and autotracking_config.enabled
|
autotracking_config.enabled_in_config and autotracking_config.enabled
|
||||||
)
|
)
|
||||||
@@ -614,6 +619,11 @@ class OnvifController:
|
|||||||
logger.error(f"{camera_name} does not support ONVIF RelativeMove (FOV).")
|
logger.error(f"{camera_name} does not support ONVIF RelativeMove (FOV).")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
metrics = self.ptz_metrics.get(camera_name)
|
||||||
|
|
||||||
|
if metrics is None:
|
||||||
|
return
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera_name} called RelativeMove: pan: {pan} tilt: {tilt} zoom: {zoom}"
|
f"{camera_name} called RelativeMove: pan: {pan} tilt: {tilt} zoom: {zoom}"
|
||||||
)
|
)
|
||||||
@@ -627,15 +637,11 @@ class OnvifController:
|
|||||||
self.cams[camera_name]["active"] = True
|
self.cams[camera_name]["active"] = True
|
||||||
|
|
||||||
# only track start_time for autotracking
|
# only track start_time for autotracking
|
||||||
if self.ptz_metrics[camera_name].autotracker_enabled.value:
|
if metrics.autotracker_enabled.value:
|
||||||
self.ptz_metrics[camera_name].motor_stopped.clear()
|
metrics.motor_stopped.clear()
|
||||||
logger.debug(
|
logger.debug(f"{camera_name}: PTZ start time: {metrics.frame_time.value}")
|
||||||
f"{camera_name}: PTZ start time: {self.ptz_metrics[camera_name].frame_time.value}"
|
metrics.start_time.value = metrics.frame_time.value
|
||||||
)
|
metrics.stop_time.value = 0
|
||||||
self.ptz_metrics[camera_name].start_time.value = self.ptz_metrics[
|
|
||||||
camera_name
|
|
||||||
].frame_time.value
|
|
||||||
self.ptz_metrics[camera_name].stop_time.value = 0
|
|
||||||
|
|
||||||
move_request = self.cams[camera_name]["relative_move_request"]
|
move_request = self.cams[camera_name]["relative_move_request"]
|
||||||
|
|
||||||
@@ -697,9 +703,14 @@ class OnvifController:
|
|||||||
logger.error(f"{preset} is not a valid preset for {camera_name}")
|
logger.error(f"{preset} is not a valid preset for {camera_name}")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
metrics = self.ptz_metrics.get(camera_name)
|
||||||
|
|
||||||
|
if metrics is None:
|
||||||
|
return
|
||||||
|
|
||||||
self.cams[camera_name]["active"] = True
|
self.cams[camera_name]["active"] = True
|
||||||
self.ptz_metrics[camera_name].start_time.value = 0
|
metrics.start_time.value = 0
|
||||||
self.ptz_metrics[camera_name].stop_time.value = 0
|
metrics.stop_time.value = 0
|
||||||
move_request = self.cams[camera_name]["move_request"]
|
move_request = self.cams[camera_name]["move_request"]
|
||||||
preset_token = self.cams[camera_name]["presets"][preset]
|
preset_token = self.cams[camera_name]["presets"][preset]
|
||||||
|
|
||||||
@@ -738,6 +749,11 @@ class OnvifController:
|
|||||||
logger.error(f"{camera_name} does not support ONVIF AbsoluteMove zooming.")
|
logger.error(f"{camera_name} does not support ONVIF AbsoluteMove zooming.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
metrics = self.ptz_metrics.get(camera_name)
|
||||||
|
|
||||||
|
if metrics is None:
|
||||||
|
return
|
||||||
|
|
||||||
logger.debug(f"{camera_name} called AbsoluteMove: zoom: {zoom}")
|
logger.debug(f"{camera_name} called AbsoluteMove: zoom: {zoom}")
|
||||||
|
|
||||||
if self.cams[camera_name]["active"]:
|
if self.cams[camera_name]["active"]:
|
||||||
@@ -747,14 +763,10 @@ class OnvifController:
|
|||||||
return
|
return
|
||||||
|
|
||||||
self.cams[camera_name]["active"] = True
|
self.cams[camera_name]["active"] = True
|
||||||
self.ptz_metrics[camera_name].motor_stopped.clear()
|
metrics.motor_stopped.clear()
|
||||||
logger.debug(
|
logger.debug(f"{camera_name}: PTZ start time: {metrics.frame_time.value}")
|
||||||
f"{camera_name}: PTZ start time: {self.ptz_metrics[camera_name].frame_time.value}"
|
metrics.start_time.value = metrics.frame_time.value
|
||||||
)
|
metrics.stop_time.value = 0
|
||||||
self.ptz_metrics[camera_name].start_time.value = self.ptz_metrics[
|
|
||||||
camera_name
|
|
||||||
].frame_time.value
|
|
||||||
self.ptz_metrics[camera_name].stop_time.value = 0
|
|
||||||
move_request = self.cams[camera_name]["absolute_move_request"]
|
move_request = self.cams[camera_name]["absolute_move_request"]
|
||||||
|
|
||||||
# function takes in 0 to 1 for zoom, interpolate to the values of the camera.
|
# function takes in 0 to 1 for zoom, interpolate to the values of the camera.
|
||||||
@@ -875,16 +887,18 @@ class OnvifController:
|
|||||||
|
|
||||||
Returns camera details including features and presets if available.
|
Returns camera details including features and presets if available.
|
||||||
"""
|
"""
|
||||||
if not self.config.cameras[camera_name].enabled:
|
camera_config = self.config.cameras.get(camera_name)
|
||||||
|
|
||||||
|
if camera_config is None:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
if not camera_config.enabled:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Camera {camera_name} disabled, won't try to initialize ONVIF"
|
f"Camera {camera_name} disabled, won't try to initialize ONVIF"
|
||||||
)
|
)
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
if camera_name not in self.cams.keys() and (
|
if camera_name not in self.cams.keys() and (not camera_config.onvif.host):
|
||||||
camera_name not in self.config.cameras
|
|
||||||
or not self.config.cameras[camera_name].onvif.host
|
|
||||||
):
|
|
||||||
logger.debug(f"ONVIF is not configured for {camera_name}")
|
logger.debug(f"ONVIF is not configured for {camera_name}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
@@ -985,6 +999,12 @@ class OnvifController:
|
|||||||
logger.error(f"ONVIF is not configured for {camera_name}")
|
logger.error(f"ONVIF is not configured for {camera_name}")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
metrics = self.ptz_metrics.get(camera_name)
|
||||||
|
camera_config = self.config.cameras.get(camera_name)
|
||||||
|
|
||||||
|
if metrics is None or camera_config is None:
|
||||||
|
return
|
||||||
|
|
||||||
if not self.cams[camera_name]["init"]:
|
if not self.cams[camera_name]["init"]:
|
||||||
if not await self._init_onvif(camera_name):
|
if not await self._init_onvif(camera_name):
|
||||||
return
|
return
|
||||||
@@ -1023,36 +1043,29 @@ class OnvifController:
|
|||||||
zoom_status is None or zoom_status == "IDLE"
|
zoom_status is None or zoom_status == "IDLE"
|
||||||
):
|
):
|
||||||
self.cams[camera_name]["active"] = False
|
self.cams[camera_name]["active"] = False
|
||||||
if not self.ptz_metrics[camera_name].motor_stopped.is_set():
|
if not metrics.motor_stopped.is_set():
|
||||||
self.ptz_metrics[camera_name].motor_stopped.set()
|
metrics.motor_stopped.set()
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera_name}: PTZ stop time: {self.ptz_metrics[camera_name].frame_time.value}"
|
f"{camera_name}: PTZ stop time: {metrics.frame_time.value}"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.ptz_metrics[camera_name].stop_time.value = self.ptz_metrics[
|
metrics.stop_time.value = metrics.frame_time.value
|
||||||
camera_name
|
|
||||||
].frame_time.value
|
|
||||||
else:
|
else:
|
||||||
self.cams[camera_name]["active"] = True
|
self.cams[camera_name]["active"] = True
|
||||||
if self.ptz_metrics[camera_name].motor_stopped.is_set():
|
if metrics.motor_stopped.is_set():
|
||||||
self.ptz_metrics[camera_name].motor_stopped.clear()
|
metrics.motor_stopped.clear()
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera_name}: PTZ start time: {self.ptz_metrics[camera_name].frame_time.value}"
|
f"{camera_name}: PTZ start time: {metrics.frame_time.value}"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.ptz_metrics[camera_name].start_time.value = self.ptz_metrics[
|
metrics.start_time.value = metrics.frame_time.value
|
||||||
camera_name
|
metrics.stop_time.value = 0
|
||||||
].frame_time.value
|
|
||||||
self.ptz_metrics[camera_name].stop_time.value = 0
|
|
||||||
|
|
||||||
if (
|
if camera_config.onvif.autotracking.zooming != ZoomingModeEnum.disabled:
|
||||||
self.config.cameras[camera_name].onvif.autotracking.zooming
|
|
||||||
!= ZoomingModeEnum.disabled
|
|
||||||
):
|
|
||||||
# store absolute zoom level as 0 to 1 interpolated from the values of the camera
|
# store absolute zoom level as 0 to 1 interpolated from the values of the camera
|
||||||
self.ptz_metrics[camera_name].zoom_level.value = numpy.interp(
|
metrics.zoom_level.value = numpy.interp(
|
||||||
round(status.Position.Zoom.x, 2),
|
round(status.Position.Zoom.x, 2),
|
||||||
[
|
[
|
||||||
self.cams[camera_name]["absolute_zoom_range"]["XRange"]["Min"],
|
self.cams[camera_name]["absolute_zoom_range"]["XRange"]["Min"],
|
||||||
@@ -1061,25 +1074,22 @@ class OnvifController:
|
|||||||
[0, 1],
|
[0, 1],
|
||||||
)
|
)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{camera_name}: Camera zoom level: {self.ptz_metrics[camera_name].zoom_level.value}"
|
f"{camera_name}: Camera zoom level: {metrics.zoom_level.value}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# some hikvision cams won't update MoveStatus, so warn if it hasn't changed
|
# some hikvision cams won't update MoveStatus, so warn if it hasn't changed
|
||||||
if (
|
if (
|
||||||
not self.ptz_metrics[camera_name].motor_stopped.is_set()
|
not metrics.motor_stopped.is_set()
|
||||||
and not self.ptz_metrics[camera_name].reset.is_set()
|
and not metrics.reset.is_set()
|
||||||
and self.ptz_metrics[camera_name].start_time.value != 0
|
and metrics.start_time.value != 0
|
||||||
and self.ptz_metrics[camera_name].frame_time.value
|
and metrics.frame_time.value > (metrics.start_time.value + 10)
|
||||||
> (self.ptz_metrics[camera_name].start_time.value + 10)
|
and metrics.stop_time.value == 0
|
||||||
and self.ptz_metrics[camera_name].stop_time.value == 0
|
|
||||||
):
|
):
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Start time: {self.ptz_metrics[camera_name].start_time.value}, Stop time: {self.ptz_metrics[camera_name].stop_time.value}, Frame time: {self.ptz_metrics[camera_name].frame_time.value}"
|
f"Start time: {metrics.start_time.value}, Stop time: {metrics.stop_time.value}, Frame time: {metrics.frame_time.value}"
|
||||||
)
|
)
|
||||||
# set the stop time so we don't come back into this again and spam the logs
|
# set the stop time so we don't come back into this again and spam the logs
|
||||||
self.ptz_metrics[camera_name].stop_time.value = self.ptz_metrics[
|
metrics.stop_time.value = metrics.frame_time.value
|
||||||
camera_name
|
|
||||||
].frame_time.value
|
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Camera {camera_name} is still in ONVIF 'MOVING' status."
|
f"Camera {camera_name} is still in ONVIF 'MOVING' status."
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -36,9 +36,8 @@ from frigate.util.time import is_current_hour
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_TIME_LAPSE_FFMPEG_INPUT_ARGS = "-an"
|
|
||||||
DEFAULT_TIME_LAPSE_FFMPEG_ARGS = "-vf setpts=0.04*PTS -r 30"
|
DEFAULT_TIME_LAPSE_FFMPEG_ARGS = "-vf setpts=0.04*PTS -r 30"
|
||||||
TIMELAPSE_DATA_INPUT_ARGS = "-skip_frame nokey"
|
TIMELAPSE_DATA_INPUT_ARGS = "-an -skip_frame nokey"
|
||||||
|
|
||||||
# Matches the setpts factor used in timelapse exports (e.g. setpts=0.04*PTS).
|
# Matches the setpts factor used in timelapse exports (e.g. setpts=0.04*PTS).
|
||||||
# Captures the floating-point factor so we can scale expected duration.
|
# Captures the floating-point factor so we can scale expected duration.
|
||||||
@@ -738,7 +737,7 @@ class RecordingExporter(threading.Thread):
|
|||||||
parse_preset_hardware_acceleration_encode(
|
parse_preset_hardware_acceleration_encode(
|
||||||
self.config.ffmpeg.ffmpeg_path,
|
self.config.ffmpeg.ffmpeg_path,
|
||||||
hwaccel_args,
|
hwaccel_args,
|
||||||
f"{self.ffmpeg_input_args} {ffmpeg_input}".strip(),
|
f"{self.ffmpeg_input_args} -an {ffmpeg_input}".strip(),
|
||||||
f"{self.ffmpeg_output_args} -movflags +faststart".strip(),
|
f"{self.ffmpeg_output_args} -movflags +faststart".strip(),
|
||||||
EncodeTypeEnum.timelapse,
|
EncodeTypeEnum.timelapse,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -388,22 +388,6 @@ class RecordingMaintainer(threading.Thread):
|
|||||||
RecordingsDataTypeEnum.valid.value,
|
RecordingsDataTypeEnum.valid.value,
|
||||||
)
|
)
|
||||||
|
|
||||||
# assume that empty means the relevant recording info has not been received yet
|
|
||||||
camera_info = self.object_recordings_info[camera]
|
|
||||||
most_recently_processed_frame_time = (
|
|
||||||
camera_info[-1][0] if len(camera_info) > 0 else 0
|
|
||||||
)
|
|
||||||
|
|
||||||
# ensure delayed segment info does not lead to lost segments, every
|
|
||||||
# retention decision below depends on complete stats for the segment
|
|
||||||
if (
|
|
||||||
datetime.datetime.fromtimestamp(
|
|
||||||
most_recently_processed_frame_time
|
|
||||||
).astimezone(datetime.UTC)
|
|
||||||
< end_time
|
|
||||||
):
|
|
||||||
return None
|
|
||||||
|
|
||||||
record_config = self.config.cameras[camera].record
|
record_config = self.config.cameras[camera].record
|
||||||
segment_stats: SegmentInfo | None = None
|
segment_stats: SegmentInfo | None = None
|
||||||
highest = None
|
highest = None
|
||||||
@@ -417,22 +401,37 @@ class RecordingMaintainer(threading.Thread):
|
|||||||
# we should first just check if this segment matches that
|
# we should first just check if this segment matches that
|
||||||
# and avoid any DB calls
|
# and avoid any DB calls
|
||||||
if highest is not None:
|
if highest is not None:
|
||||||
record_mode = (
|
# assume that empty means the relevant recording info has not been received yet
|
||||||
RetainModeEnum.all if highest == "continuous" else RetainModeEnum.motion
|
camera_info = self.object_recordings_info[camera]
|
||||||
|
most_recently_processed_frame_time = (
|
||||||
|
camera_info[-1][0] if len(camera_info) > 0 else 0
|
||||||
)
|
)
|
||||||
segment_stats = self.segment_stats(camera, start_time, end_time)
|
|
||||||
|
|
||||||
# Here we only check if we should move the segment based on non-object recording retention
|
# ensure delayed segment info does not lead to lost segments
|
||||||
# we will always want to check for overlapping review items below before dropping the segment
|
if (
|
||||||
if not segment_stats.should_discard_segment(record_mode):
|
datetime.datetime.fromtimestamp(
|
||||||
return await self.move_segment(
|
most_recently_processed_frame_time
|
||||||
camera,
|
).astimezone(datetime.UTC)
|
||||||
start_time,
|
>= end_time
|
||||||
end_time,
|
):
|
||||||
duration,
|
record_mode = (
|
||||||
cache_path,
|
RetainModeEnum.all
|
||||||
segment_stats,
|
if highest == "continuous"
|
||||||
|
else RetainModeEnum.motion
|
||||||
)
|
)
|
||||||
|
segment_stats = self.segment_stats(camera, start_time, end_time)
|
||||||
|
|
||||||
|
# Here we only check if we should move the segment based on non-object recording retention
|
||||||
|
# we will always want to check for overlapping review items below before dropping the segment
|
||||||
|
if not segment_stats.should_discard_segment(record_mode):
|
||||||
|
return await self.move_segment(
|
||||||
|
camera,
|
||||||
|
start_time,
|
||||||
|
end_time,
|
||||||
|
duration,
|
||||||
|
cache_path,
|
||||||
|
segment_stats,
|
||||||
|
)
|
||||||
|
|
||||||
# we fell through the continuous / motion check, so we need to check the review items
|
# we fell through the continuous / motion check, so we need to check the review items
|
||||||
# if the cached segment overlaps with the review items:
|
# if the cached segment overlaps with the review items:
|
||||||
@@ -488,6 +487,10 @@ class RecordingMaintainer(threading.Thread):
|
|||||||
# continuous/motion retention (either disabled or segment_stats said
|
# continuous/motion retention (either disabled or segment_stats said
|
||||||
# discard), so waiting longer just fills the cache.
|
# discard), so waiting longer just fills the cache.
|
||||||
else:
|
else:
|
||||||
|
camera_info = self.object_recordings_info[camera]
|
||||||
|
most_recently_processed_frame_time = (
|
||||||
|
camera_info[-1][0] if len(camera_info) > 0 else 0
|
||||||
|
)
|
||||||
retain_cutoff = datetime.datetime.fromtimestamp(
|
retain_cutoff = datetime.datetime.fromtimestamp(
|
||||||
most_recently_processed_frame_time - record_config.event_pre_capture
|
most_recently_processed_frame_time - record_config.event_pre_capture
|
||||||
).astimezone(datetime.UTC)
|
).astimezone(datetime.UTC)
|
||||||
@@ -742,7 +745,9 @@ class RecordingMaintainer(threading.Thread):
|
|||||||
regions,
|
regions,
|
||||||
) = data
|
) = data
|
||||||
|
|
||||||
if self.config.cameras[camera].record.enabled:
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
|
if camera_config is not None and camera_config.record.enabled:
|
||||||
self.object_recordings_info[camera].append(
|
self.object_recordings_info[camera].append(
|
||||||
(
|
(
|
||||||
frame_time,
|
frame_time,
|
||||||
@@ -759,7 +764,9 @@ class RecordingMaintainer(threading.Thread):
|
|||||||
audio_detections,
|
audio_detections,
|
||||||
) = data
|
) = data
|
||||||
|
|
||||||
if self.config.cameras[camera].record.enabled:
|
camera_config = self.config.cameras.get(camera)
|
||||||
|
|
||||||
|
if camera_config is not None and camera_config.record.enabled:
|
||||||
self.audio_recordings_info[camera].append(
|
self.audio_recordings_info[camera].append(
|
||||||
(
|
(
|
||||||
frame_time,
|
frame_time,
|
||||||
|
|||||||
@@ -418,6 +418,11 @@ class ReviewSegmentMaintainer(threading.Thread):
|
|||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def _handle_camera_removed(self, camera: str) -> None:
|
||||||
|
"""Close out a deleted camera's segment so a reused name cannot inherit it."""
|
||||||
|
self.forcibly_end_segment(camera)
|
||||||
|
self.indefinite_events.pop(camera, None)
|
||||||
|
|
||||||
def update_existing_segment(
|
def update_existing_segment(
|
||||||
self,
|
self,
|
||||||
segment: PendingReviewSegment,
|
segment: PendingReviewSegment,
|
||||||
@@ -666,6 +671,10 @@ class ReviewSegmentMaintainer(threading.Thread):
|
|||||||
for camera in updated_topics["enabled"]:
|
for camera in updated_topics["enabled"]:
|
||||||
self.forcibly_end_segment(camera)
|
self.forcibly_end_segment(camera)
|
||||||
|
|
||||||
|
if "remove" in updated_topics:
|
||||||
|
for camera in updated_topics["remove"]:
|
||||||
|
self._handle_camera_removed(camera)
|
||||||
|
|
||||||
result = self.detection_subscriber.check_for_update(timeout=1)
|
result = self.detection_subscriber.check_for_update(timeout=1)
|
||||||
|
|
||||||
if not result:
|
if not result:
|
||||||
|
|||||||
@@ -352,9 +352,8 @@ def stats_snapshot(
|
|||||||
total_camera_fps = total_process_fps = total_skipped_fps = total_detection_fps = 0
|
total_camera_fps = total_process_fps = total_skipped_fps = total_detection_fps = 0
|
||||||
|
|
||||||
stats["cameras"] = {}
|
stats["cameras"] = {}
|
||||||
for name, camera_stats in list(camera_metrics.items()):
|
for name, camera_stats in camera_metrics.items():
|
||||||
camera_config = config.cameras.get(name)
|
if name not in config.cameras:
|
||||||
if camera_config is None:
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
total_camera_fps += camera_stats.camera_fps.value
|
total_camera_fps += camera_stats.camera_fps.value
|
||||||
@@ -371,7 +370,7 @@ def stats_snapshot(
|
|||||||
# Calculate connection quality based on current state
|
# Calculate connection quality based on current state
|
||||||
# This is computed at stats-collection time so offline cameras
|
# This is computed at stats-collection time so offline cameras
|
||||||
# correctly show as unusable rather than excellent
|
# correctly show as unusable rather than excellent
|
||||||
expected_fps = camera_config.detect.fps
|
expected_fps = config.cameras[name].detect.fps
|
||||||
current_fps = camera_stats.camera_fps.value
|
current_fps = camera_stats.camera_fps.value
|
||||||
reconnects = camera_stats.reconnects_last_hour.value
|
reconnects = camera_stats.reconnects_last_hour.value
|
||||||
stalls = camera_stats.stalls_last_hour.value
|
stalls = camera_stats.stalls_last_hour.value
|
||||||
@@ -399,7 +398,7 @@ def stats_snapshot(
|
|||||||
"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),
|
||||||
"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": config.cameras[name].detect.enabled,
|
||||||
"pid": pid,
|
"pid": pid,
|
||||||
"capture_pid": capture_pid,
|
"capture_pid": capture_pid,
|
||||||
"ffmpeg_pid": ffmpeg_pid,
|
"ffmpeg_pid": ffmpeg_pid,
|
||||||
|
|||||||
@@ -144,9 +144,7 @@ class BaseTestHttp(unittest.TestCase):
|
|||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def create_app(
|
def create_app(self, stats=None, event_metadata_publisher=None):
|
||||||
self, stats=None, event_metadata_publisher=None, enforce_default_admin=False
|
|
||||||
):
|
|
||||||
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
|
||||||
|
|
||||||
app = create_fastapi_app(
|
app = create_fastapi_app(
|
||||||
@@ -160,7 +158,7 @@ class BaseTestHttp(unittest.TestCase):
|
|||||||
event_metadata_publisher,
|
event_metadata_publisher,
|
||||||
None,
|
None,
|
||||||
DebugReplayManager(),
|
DebugReplayManager(),
|
||||||
enforce_default_admin=enforce_default_admin,
|
enforce_default_admin=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Default test mocks for authentication
|
# Default test mocks for authentication
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from frigate.jobs.debug_replay import NoRecordingsError
|
|
||||||
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
|
||||||
|
|
||||||
@@ -67,32 +66,6 @@ class TestDebugReplayAPI(BaseTestHttp):
|
|||||||
# (CodeQL: information exposure through an exception).
|
# (CodeQL: information exposure through an exception).
|
||||||
self.assertEqual(body["message"], "Invalid debug replay parameters")
|
self.assertEqual(body["message"], "Invalid debug replay parameters")
|
||||||
|
|
||||||
def test_start_returns_404_when_no_recordings(self):
|
|
||||||
with patch(
|
|
||||||
"frigate.api.debug_replay.start_debug_replay_job",
|
|
||||||
side_effect=NoRecordingsError(
|
|
||||||
"No recordings found for camera 'front' in the specified time range"
|
|
||||||
),
|
|
||||||
):
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
resp = client.post(
|
|
||||||
"/debug_replay/start",
|
|
||||||
json={
|
|
||||||
"camera": "front",
|
|
||||||
"start_time": 100,
|
|
||||||
"end_time": 200,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
self.assertEqual(resp.status_code, 404)
|
|
||||||
body = resp.json()
|
|
||||||
self.assertFalse(body["success"])
|
|
||||||
# Message is hard-coded so we don't echo exception text back to clients
|
|
||||||
# (CodeQL: information exposure through an exception).
|
|
||||||
self.assertEqual(
|
|
||||||
body["message"], "No recordings found in the selected time range"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_start_returns_409_when_session_already_active(self):
|
def test_start_returns_409_when_session_already_active(self):
|
||||||
with patch(
|
with patch(
|
||||||
"frigate.api.debug_replay.start_debug_replay_job",
|
"frigate.api.debug_replay.start_debug_replay_job",
|
||||||
|
|||||||
@@ -47,25 +47,6 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json()["front_door"]["usage_percent"] == 25.0
|
assert response.json()["front_door"]["usage_percent"] == 25.0
|
||||||
|
|
||||||
def test_camera_name_collision_keeps_admin_default(self):
|
|
||||||
self.minimal_config["cameras"]["faces"] = self.minimal_config["cameras"].pop(
|
|
||||||
"front_door"
|
|
||||||
)
|
|
||||||
app = super().create_app(enforce_default_admin=True)
|
|
||||||
viewer = {"remote-user": "viewer", "remote-role": "viewer"}
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
assert client.get("/faces", headers=viewer).status_code == 403
|
|
||||||
assert client.get("/faces").status_code == 200
|
|
||||||
assert (
|
|
||||||
client.post("/faces/train/person/classify", headers=viewer).status_code
|
|
||||||
== 403
|
|
||||||
)
|
|
||||||
|
|
||||||
# Camera routes for the same name stay reachable by viewers
|
|
||||||
response = client.get("/faces/recordings/summary", headers=viewer)
|
|
||||||
assert response.status_code == 200
|
|
||||||
|
|
||||||
def test_config_set_in_memory_replaces_objects_track_list(self):
|
def test_config_set_in_memory_replaces_objects_track_list(self):
|
||||||
self.minimal_config["cameras"]["front_door"]["objects"] = {
|
self.minimal_config["cameras"]["front_door"]["objects"] = {
|
||||||
"track": ["person", "car"],
|
"track": ["person", "car"],
|
||||||
|
|||||||
@@ -440,68 +440,3 @@ class TestGo2rtcStreamAccess(BaseTestHttp):
|
|||||||
f"limited_user should be denied on alias back_door_main; "
|
f"limited_user should be denied on alias back_door_main; "
|
||||||
f"got {resp.status_code}"
|
f"got {resp.status_code}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestReviewSummaryAccess(BaseTestHttp):
|
|
||||||
"""Tests for POST /review/summarize/start/{start_ts}/end/{end_ts}.
|
|
||||||
|
|
||||||
The summary correlates each flagged event with overlapping activity on
|
|
||||||
other cameras, so it is gated on full camera access rather than scoped to
|
|
||||||
the caller's cameras. These tests pin that decision so the dependency is
|
|
||||||
not loosened without first scoping the query.
|
|
||||||
|
|
||||||
GenAI is not configured in unit tests, so an authorized request returns 400
|
|
||||||
while an unauthorized one is rejected with 403 before the handler runs.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
super().setUp([Event, ReviewSegment, Recordings])
|
|
||||||
self.minimal_config = _MULTI_CAMERA_CONFIG
|
|
||||||
self.app = super().create_app()
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
self.app.dependency_overrides.clear()
|
|
||||||
super().tearDown()
|
|
||||||
|
|
||||||
def _summarize(self, allowed_cameras: list[str]):
|
|
||||||
async def mock_cameras(request: Request):
|
|
||||||
return allowed_cameras
|
|
||||||
|
|
||||||
self.app.dependency_overrides[get_allowed_cameras_for_filter] = mock_cameras
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
return client.post("/review/summarize/start/0/end/9999999999")
|
|
||||||
|
|
||||||
def _assert_allowed(self, resp):
|
|
||||||
assert resp.status_code not in (401, 403), (
|
|
||||||
f"Caller should not be blocked; got {resp.status_code}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_partial_camera_access_blocked(self):
|
|
||||||
assert self._summarize(["front_door"]).status_code == 403
|
|
||||||
|
|
||||||
def test_no_camera_access_blocked(self):
|
|
||||||
assert self._summarize([]).status_code == 403
|
|
||||||
|
|
||||||
def test_full_camera_access_allowed(self):
|
|
||||||
# Covers admin and viewer, which always resolve to every camera, and a
|
|
||||||
# custom role whose list happens to name them all.
|
|
||||||
self._assert_allowed(self._summarize(["front_door", "back_door"]))
|
|
||||||
|
|
||||||
def _summarize_as_role(self, role: str):
|
|
||||||
"""Summarize using the real role to allowed-cameras resolution."""
|
|
||||||
self.app.dependency_overrides.pop(get_allowed_cameras_for_filter, None)
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
return client.post(
|
|
||||||
"/review/summarize/start/0/end/9999999999",
|
|
||||||
headers={"remote-user": "test", "remote-role": role},
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_viewer_role_allowed(self):
|
|
||||||
# viewer is never camera restricted, so it resolves to every camera.
|
|
||||||
self._assert_allowed(self._summarize_as_role("viewer"))
|
|
||||||
|
|
||||||
def test_admin_role_allowed(self):
|
|
||||||
self._assert_allowed(self._summarize_as_role("admin"))
|
|
||||||
|
|
||||||
def test_restricted_role_blocked(self):
|
|
||||||
assert self._summarize_as_role("limited_user").status_code == 403
|
|
||||||
|
|||||||
@@ -386,9 +386,19 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
|
|||||||
guess (mode still equals the previous global) wrongly claims a camera
|
guess (mode still equals the previous global) wrongly claims a camera
|
||||||
whose explicit yaml mode happens to match.
|
whose explicit yaml mode happens to match.
|
||||||
"""
|
"""
|
||||||
self.minimal_config["birdseye"] = {"enabled": True, "mode": "motion"}
|
self.minimal_config["birdseye"] = {
|
||||||
|
"enabled": True,
|
||||||
|
"mode": {"motion": True},
|
||||||
|
}
|
||||||
# explicit override that matches the global value being replaced
|
# explicit override that matches the global value being replaced
|
||||||
self.minimal_config["cameras"]["front_door"]["birdseye"] = {"mode": "motion"}
|
self.minimal_config["cameras"]["front_door"]["birdseye"] = {
|
||||||
|
"mode": {
|
||||||
|
"continuous": False,
|
||||||
|
"motion": True,
|
||||||
|
"objects": False,
|
||||||
|
"stationary_objects": False,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
config_path = self._write_config_file()
|
config_path = self._write_config_file()
|
||||||
mock_find_config.return_value = config_path
|
mock_find_config.return_value = config_path
|
||||||
@@ -399,7 +409,16 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
|
|||||||
resp = client.put(
|
resp = client.put(
|
||||||
"/config/set",
|
"/config/set",
|
||||||
json={
|
json={
|
||||||
"config_data": {"birdseye": {"mode": "continuous"}},
|
"config_data": {
|
||||||
|
"birdseye": {
|
||||||
|
"mode": {
|
||||||
|
"continuous": True,
|
||||||
|
"motion": False,
|
||||||
|
"objects": False,
|
||||||
|
"stationary_objects": False,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"update_topic": "config/birdseye",
|
"update_topic": "config/birdseye",
|
||||||
"requires_restart": 0,
|
"requires_restart": 0,
|
||||||
},
|
},
|
||||||
@@ -411,7 +430,7 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
|
|||||||
mock_publisher.publisher.publish.assert_called_once()
|
mock_publisher.publisher.publish.assert_called_once()
|
||||||
topic, settings = mock_publisher.publisher.publish.call_args[0]
|
topic, settings = mock_publisher.publisher.publish.call_args[0]
|
||||||
self.assertEqual(topic, "config/birdseye")
|
self.assertEqual(topic, "config/birdseye")
|
||||||
self.assertEqual(settings.mode.value, "continuous")
|
self.assertEqual(settings.mode.to_mqtt_payload(), "CONTINUOUS")
|
||||||
|
|
||||||
published = {
|
published = {
|
||||||
call[0][0].camera: call[0][1]
|
call[0][0].camera: call[0][1]
|
||||||
@@ -425,8 +444,12 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# the override survives, the inheriting camera follows global
|
# the override survives, the inheriting camera follows global
|
||||||
self.assertEqual(published["front_door"].mode.value, "motion")
|
self.assertEqual(
|
||||||
self.assertEqual(published["back_yard"].mode.value, "continuous")
|
published["front_door"].mode.to_mqtt_payload(), "MOTION"
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
published["back_yard"].mode.to_mqtt_payload(), "CONTINUOUS"
|
||||||
|
)
|
||||||
finally:
|
finally:
|
||||||
os.unlink(config_path)
|
os.unlink(config_path)
|
||||||
|
|
||||||
|
|||||||
@@ -168,29 +168,6 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
assert events[0]["id"] == id
|
assert events[0]["id"] == id
|
||||||
assert events[1]["id"] == id2
|
assert events[1]["id"] == id2
|
||||||
|
|
||||||
def test_get_event_list_offset_pages_score_sort(self):
|
|
||||||
now = datetime.now().timestamp()
|
|
||||||
scores = [0.6, 0.9, 0.7, 0.95, 0.8]
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
for i, score in enumerate(scores):
|
|
||||||
super().insert_mock_event(
|
|
||||||
f"event-{i}", start_time=now + i, data={"score": score}
|
|
||||||
)
|
|
||||||
|
|
||||||
params = {"sort": "score_desc"}
|
|
||||||
full = [e["id"] for e in client.get("/events", params=params).json()]
|
|
||||||
paged = [
|
|
||||||
e["id"]
|
|
||||||
for offset in (0, 2, 4)
|
|
||||||
for e in client.get(
|
|
||||||
"/events", params={**params, "limit": 2, "offset": offset}
|
|
||||||
).json()
|
|
||||||
]
|
|
||||||
|
|
||||||
assert full == ["event-3", "event-1", "event-4", "event-2", "event-0"]
|
|
||||||
assert paged == full
|
|
||||||
|
|
||||||
def test_get_event_list_match_multilingual_attribute(self):
|
def test_get_event_list_match_multilingual_attribute(self):
|
||||||
event_id = "123456.zh"
|
event_id = "123456.zh"
|
||||||
attribute = "中文标签"
|
attribute = "中文标签"
|
||||||
@@ -242,85 +219,6 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
assert len(events) == 1
|
assert len(events) == 1
|
||||||
assert events[0]["id"] == event_id
|
assert events[0]["id"] == event_id
|
||||||
|
|
||||||
def test_events_search_offset_pages_score_sort(self):
|
|
||||||
now = datetime.now().timestamp()
|
|
||||||
scores = [0.6, 0.9, 0.7, 0.95, 0.8]
|
|
||||||
ids = [f"event-{i}" for i in range(len(scores))]
|
|
||||||
mock_embeddings = Mock()
|
|
||||||
mock_embeddings.search_thumbnail.return_value = [
|
|
||||||
(event_id, 0.1 * i) for i, event_id in enumerate(ids)
|
|
||||||
]
|
|
||||||
|
|
||||||
self.app.frigate_config.semantic_search.enabled = True
|
|
||||||
self.app.embeddings = mock_embeddings
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
for i, score in enumerate(scores):
|
|
||||||
super().insert_mock_event(
|
|
||||||
ids[i], start_time=now + i, data={"score": score}
|
|
||||||
)
|
|
||||||
|
|
||||||
params = {
|
|
||||||
"search_type": "similarity",
|
|
||||||
"event_id": ids[0],
|
|
||||||
"sort": "score_desc",
|
|
||||||
}
|
|
||||||
paged = [
|
|
||||||
e["id"]
|
|
||||||
for offset in (0, 2, 4)
|
|
||||||
for e in client.get(
|
|
||||||
"/events/search",
|
|
||||||
params={**params, "limit": 2, "offset": offset},
|
|
||||||
).json()
|
|
||||||
]
|
|
||||||
|
|
||||||
assert paged == ["event-3", "event-1", "event-4", "event-2", "event-0"]
|
|
||||||
|
|
||||||
def test_events_search_offset_pages_orders_ties_by_id(self):
|
|
||||||
now = datetime.now().timestamp()
|
|
||||||
ids = ["event-c", "event-a", "event-b"]
|
|
||||||
mock_embeddings = Mock()
|
|
||||||
mock_embeddings.search_thumbnail.return_value = [
|
|
||||||
(event_id, 0.1) for event_id in ids
|
|
||||||
]
|
|
||||||
|
|
||||||
self.app.frigate_config.semantic_search.enabled = True
|
|
||||||
self.app.embeddings = mock_embeddings
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
for i, event_id in enumerate(ids):
|
|
||||||
super().insert_mock_event(
|
|
||||||
event_id, start_time=now + i, data={"score": 0.8}
|
|
||||||
)
|
|
||||||
|
|
||||||
for sort in ("score_desc", "relevance"):
|
|
||||||
params = {
|
|
||||||
"search_type": "similarity",
|
|
||||||
"event_id": ids[0],
|
|
||||||
"sort": sort,
|
|
||||||
}
|
|
||||||
paged = [
|
|
||||||
e["id"]
|
|
||||||
for offset in (0, 1, 2)
|
|
||||||
for e in client.get(
|
|
||||||
"/events/search",
|
|
||||||
params={**params, "limit": 1, "offset": offset},
|
|
||||||
).json()
|
|
||||||
]
|
|
||||||
|
|
||||||
assert paged == ["event-a", "event-b", "event-c"]
|
|
||||||
|
|
||||||
def test_event_list_rejects_negative_offset(self):
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
response = client.get("/events", params={"offset": -5})
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
response = client.get(
|
|
||||||
"/events/search",
|
|
||||||
params={"query": "car", "offset": -5},
|
|
||||||
)
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
def test_similarity_search_hides_unauthorized_anchor_event(self):
|
def test_similarity_search_hides_unauthorized_anchor_event(self):
|
||||||
mock_embeddings = Mock()
|
mock_embeddings = Mock()
|
||||||
self.app.frigate_config.semantic_search.enabled = True
|
self.app.frigate_config.semantic_search.enabled = True
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import io
|
|
||||||
import os
|
import os
|
||||||
import tempfile
|
import tempfile
|
||||||
import zipfile
|
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from frigate.jobs.export import (
|
from frigate.jobs.export import (
|
||||||
@@ -1433,79 +1431,3 @@ class TestHttpExport(BaseTestHttp):
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
|
|
||||||
def test_download_export_case_with_multibyte_name(self):
|
|
||||||
"""A case name outside latin-1 must not break the response headers."""
|
|
||||||
case = ExportCase.create(
|
|
||||||
id="case_multibyte",
|
|
||||||
name="テスト事案",
|
|
||||||
description="",
|
|
||||||
created_at=10,
|
|
||||||
updated_at=10,
|
|
||||||
)
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as tmpdir:
|
|
||||||
video_path = os.path.join(tmpdir, "multibyte_export.mp4")
|
|
||||||
with open(video_path, "wb") as handle:
|
|
||||||
handle.write(b"video")
|
|
||||||
|
|
||||||
Export.create(
|
|
||||||
id="export_multibyte",
|
|
||||||
camera="front_door",
|
|
||||||
name="現場カメラ",
|
|
||||||
date=100,
|
|
||||||
video_path=video_path,
|
|
||||||
thumb_path=os.path.join(tmpdir, "multibyte_export.webp"),
|
|
||||||
in_progress=False,
|
|
||||||
export_case=case,
|
|
||||||
)
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
response = client.get(f"/cases/{case.id}/download")
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
# RFC 5987/6266: the UTF-8 name rides in filename*, and a latin-1 safe
|
|
||||||
# fallback stays in filename for old clients.
|
|
||||||
assert response.headers["content-disposition"] == (
|
|
||||||
'attachment; filename="case_multibyte.zip"; '
|
|
||||||
"filename*=UTF-8''%E3%83%86%E3%82%B9%E3%83%88%E4%BA%8B%E6%A1%88.zip"
|
|
||||||
)
|
|
||||||
|
|
||||||
archive = zipfile.ZipFile(io.BytesIO(response.content))
|
|
||||||
assert archive.namelist() == ["現場カメラ.mp4"]
|
|
||||||
|
|
||||||
def test_download_export_case_with_ascii_name(self):
|
|
||||||
"""An ASCII case name still gets a plain, readable filename."""
|
|
||||||
case = ExportCase.create(
|
|
||||||
id="case_ascii",
|
|
||||||
name="Burglary 2026-08",
|
|
||||||
description="",
|
|
||||||
created_at=10,
|
|
||||||
updated_at=10,
|
|
||||||
)
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as tmpdir:
|
|
||||||
video_path = os.path.join(tmpdir, "ascii_export.mp4")
|
|
||||||
with open(video_path, "wb") as handle:
|
|
||||||
handle.write(b"video")
|
|
||||||
|
|
||||||
Export.create(
|
|
||||||
id="export_ascii",
|
|
||||||
camera="front_door",
|
|
||||||
name="Front door",
|
|
||||||
date=100,
|
|
||||||
video_path=video_path,
|
|
||||||
thumb_path=os.path.join(tmpdir, "ascii_export.webp"),
|
|
||||||
in_progress=False,
|
|
||||||
export_case=case,
|
|
||||||
)
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
response = client.get(f"/cases/{case.id}/download")
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert (
|
|
||||||
response.headers["content-disposition"]
|
|
||||||
== 'attachment; filename="Burglary 2026-08.zip"; '
|
|
||||||
"filename*=UTF-8''Burglary%202026-08.zip"
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,15 +1,73 @@
|
|||||||
"""Unit tests for recordings/media API endpoints."""
|
"""Unit tests for recordings/media API endpoints."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
import pytz
|
import pytz
|
||||||
from fastapi import Request
|
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.models import Recordings
|
from frigate.models import Recordings
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RangeCase:
|
||||||
|
"""Expected behavior for one segment relative to the requested range.
|
||||||
|
|
||||||
|
Offsets are seconds from REQUEST_START; the request ends at +100 seconds.
|
||||||
|
"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
start_offset: float
|
||||||
|
end_offset: float
|
||||||
|
included_in_recordings: bool
|
||||||
|
vod_clip_from_ms: int | None = None
|
||||||
|
vod_duration_ms: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
REQUEST_START = 1000
|
||||||
|
REQUEST_END = 1100
|
||||||
|
RANGE_CASES = (
|
||||||
|
RangeCase("before", -MAX_SEGMENT_DURATION + 1, -1, False),
|
||||||
|
RangeCase("meets_start", -10, 0, True),
|
||||||
|
RangeCase(
|
||||||
|
"overlaps_start",
|
||||||
|
-MAX_SEGMENT_DURATION + 0.5,
|
||||||
|
0.25,
|
||||||
|
True,
|
||||||
|
vod_clip_from_ms=599500,
|
||||||
|
vod_duration_ms=250,
|
||||||
|
),
|
||||||
|
RangeCase("starts_at_start", 0, 10, True, vod_duration_ms=10000),
|
||||||
|
RangeCase("inside", 20, 80, True, vod_duration_ms=60000),
|
||||||
|
RangeCase("ends_at_end", 90, 100, True, vod_duration_ms=10000),
|
||||||
|
RangeCase("matches_range", 0, 100, True, vod_duration_ms=100000),
|
||||||
|
RangeCase("starts_with_range", 0, 110, True, vod_duration_ms=100000),
|
||||||
|
RangeCase(
|
||||||
|
"covers_range",
|
||||||
|
-20,
|
||||||
|
120,
|
||||||
|
True,
|
||||||
|
vod_clip_from_ms=20000,
|
||||||
|
vod_duration_ms=100000,
|
||||||
|
),
|
||||||
|
RangeCase(
|
||||||
|
"ends_with_range",
|
||||||
|
-10,
|
||||||
|
100,
|
||||||
|
True,
|
||||||
|
vod_clip_from_ms=10000,
|
||||||
|
vod_duration_ms=100000,
|
||||||
|
),
|
||||||
|
RangeCase("overlaps_end", 95, 105, True, vod_duration_ms=5000),
|
||||||
|
RangeCase("starts_at_end", 100, 110, True),
|
||||||
|
RangeCase("after", 101, 110, False),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestHttpMedia(BaseTestHttp):
|
class TestHttpMedia(BaseTestHttp):
|
||||||
"""Test media API endpoints, particularly recordings with DST handling."""
|
"""Test media API endpoints, particularly recordings with DST handling."""
|
||||||
|
|
||||||
@@ -44,6 +102,26 @@ class TestHttpMedia(BaseTestHttp):
|
|||||||
self.app.dependency_overrides.clear()
|
self.app.dependency_overrides.clear()
|
||||||
super().tearDown()
|
super().tearDown()
|
||||||
|
|
||||||
|
def _assert_vod_response(
|
||||||
|
self,
|
||||||
|
response,
|
||||||
|
expected_clips: list[tuple[str, int | None, int]],
|
||||||
|
) -> None:
|
||||||
|
"""Assert VOD clip metadata and its derived duration fields."""
|
||||||
|
assert response.status_code == 200
|
||||||
|
vod = response.json()
|
||||||
|
assert [
|
||||||
|
(
|
||||||
|
clip["path"],
|
||||||
|
clip.get("clipFrom"),
|
||||||
|
clip["keyFrameDurations"][0],
|
||||||
|
)
|
||||||
|
for clip in vod["sequences"][0]["clips"]
|
||||||
|
] == expected_clips
|
||||||
|
expected_durations = [clip[2] for clip in expected_clips]
|
||||||
|
assert vod["durations"] == expected_durations
|
||||||
|
assert vod["segment_duration"] == max(expected_durations)
|
||||||
|
|
||||||
def test_recordings_summary_across_dst_spring_forward(self):
|
def test_recordings_summary_across_dst_spring_forward(self):
|
||||||
"""
|
"""
|
||||||
Test recordings summary across spring DST transition (spring forward).
|
Test recordings summary across spring DST transition (spring forward).
|
||||||
@@ -404,6 +482,102 @@ class TestHttpMedia(BaseTestHttp):
|
|||||||
assert "2024-03-10" in summary
|
assert "2024-03-10" in summary
|
||||||
assert summary["2024-03-10"] is True
|
assert summary["2024-03-10"] is True
|
||||||
|
|
||||||
|
def test_recordings_handles_all_range_relations(self):
|
||||||
|
"""Recordings return every interval relation that touches the range."""
|
||||||
|
with AuthTestClient(self.app) as client:
|
||||||
|
for case in RANGE_CASES:
|
||||||
|
with self.subTest(case=case.name):
|
||||||
|
Recordings.delete().execute()
|
||||||
|
super().insert_mock_recording(
|
||||||
|
case.name,
|
||||||
|
REQUEST_START + case.start_offset,
|
||||||
|
REQUEST_START + case.end_offset,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
"/front_door/recordings",
|
||||||
|
params={"after": REQUEST_START, "before": REQUEST_END},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
expected_ids = [case.name] if case.included_in_recordings else []
|
||||||
|
assert [
|
||||||
|
recording["id"] for recording in response.json()
|
||||||
|
] == expected_ids
|
||||||
|
|
||||||
|
def test_vod_handles_all_range_relations(self):
|
||||||
|
"""VOD clips every interval relation with positive playback duration."""
|
||||||
|
with (
|
||||||
|
AuthTestClient(self.app) as client,
|
||||||
|
patch(
|
||||||
|
"frigate.api.media.get_keyframe_before",
|
||||||
|
side_effect=lambda _path, offset: offset,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
for case in RANGE_CASES:
|
||||||
|
with self.subTest(case=case.name):
|
||||||
|
Recordings.delete().execute()
|
||||||
|
super().insert_mock_recording(
|
||||||
|
case.name,
|
||||||
|
REQUEST_START + case.start_offset,
|
||||||
|
REQUEST_START + case.end_offset,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
f"/vod/front_door/start/{REQUEST_START}/end/{REQUEST_END}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if case.vod_duration_ms is None:
|
||||||
|
assert response.status_code == 404
|
||||||
|
continue
|
||||||
|
|
||||||
|
self._assert_vod_response(
|
||||||
|
response,
|
||||||
|
[
|
||||||
|
(
|
||||||
|
case.name,
|
||||||
|
case.vod_clip_from_ms,
|
||||||
|
case.vod_duration_ms,
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_vod_handles_segment_ending_at_start_with_keyframe_fallbacks(self):
|
||||||
|
"""VOD keeps a boundary segment when keyframe lookup extends it."""
|
||||||
|
|
||||||
|
def keyframe_before(path: str, offset: int) -> int | None:
|
||||||
|
return offset - 1000 if path == "previous_keyframe" else None
|
||||||
|
|
||||||
|
with (
|
||||||
|
AuthTestClient(self.app) as client,
|
||||||
|
patch(
|
||||||
|
"frigate.api.media.get_keyframe_before",
|
||||||
|
side_effect=keyframe_before,
|
||||||
|
),
|
||||||
|
):
|
||||||
|
super().insert_mock_recording(
|
||||||
|
"previous_keyframe",
|
||||||
|
REQUEST_START - 10,
|
||||||
|
REQUEST_START,
|
||||||
|
)
|
||||||
|
super().insert_mock_recording(
|
||||||
|
"missing_keyframe",
|
||||||
|
REQUEST_START - 5,
|
||||||
|
REQUEST_START,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = client.get(
|
||||||
|
f"/vod/front_door/start/{REQUEST_START}/end/{REQUEST_END}"
|
||||||
|
)
|
||||||
|
|
||||||
|
self._assert_vod_response(
|
||||||
|
response,
|
||||||
|
[
|
||||||
|
("previous_keyframe", 9000, 1000),
|
||||||
|
("missing_keyframe", None, 5000),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
def test_recordings_unavailable_reports_gap_between_recordings(self):
|
def test_recordings_unavailable_reports_gap_between_recordings(self):
|
||||||
"""A gap between two recordings is reported as an unavailable segment."""
|
"""A gap between two recordings is reported as an unavailable segment."""
|
||||||
with AuthTestClient(self.app) as client:
|
with AuthTestClient(self.app) as client:
|
||||||
|
|||||||
@@ -1,113 +0,0 @@
|
|||||||
"""Tests for password change authorization."""
|
|
||||||
|
|
||||||
from fastapi import Request
|
|
||||||
|
|
||||||
from frigate.api.auth import get_current_user, hash_password, verify_password
|
|
||||||
from frigate.models import Event, Recordings, ReviewSegment, User
|
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
|
||||||
|
|
||||||
# Config carrying a custom role, which is the class of user the literal
|
|
||||||
# "viewer" check used to let through.
|
|
||||||
_CUSTOM_ROLE_CONFIG = {
|
|
||||||
"mqtt": {"host": "mqtt"},
|
|
||||||
"auth": {"roles": {"neighbor": ["front_door"]}, "hash_iterations": 10},
|
|
||||||
"cameras": {
|
|
||||||
"front_door": {
|
|
||||||
"ffmpeg": {
|
|
||||||
"inputs": [{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}]
|
|
||||||
},
|
|
||||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
ADMIN_PASSWORD = "admin-real-password"
|
|
||||||
NEW_PASSWORD = "AttackerChosenPassword123!"
|
|
||||||
|
|
||||||
|
|
||||||
class TestUpdatePasswordAccess(BaseTestHttp):
|
|
||||||
def setUp(self):
|
|
||||||
super().setUp([Event, ReviewSegment, Recordings, User])
|
|
||||||
self.minimal_config = _CUSTOM_ROLE_CONFIG
|
|
||||||
self.app = super().create_app()
|
|
||||||
User.insert(
|
|
||||||
username="admin",
|
|
||||||
password_hash=hash_password(ADMIN_PASSWORD, iterations=10),
|
|
||||||
role="admin",
|
|
||||||
notification_tokens=[],
|
|
||||||
).execute()
|
|
||||||
|
|
||||||
async def mock_get_current_user(request: Request):
|
|
||||||
return {
|
|
||||||
"username": request.headers.get("remote-user"),
|
|
||||||
"role": request.headers.get("remote-role"),
|
|
||||||
}
|
|
||||||
|
|
||||||
self.app.dependency_overrides[get_current_user] = mock_get_current_user
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
self.app.dependency_overrides.clear()
|
|
||||||
super().tearDown()
|
|
||||||
|
|
||||||
def _change_password(self, actor: str, role: str, target: str, old_password: str):
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
return client.put(
|
|
||||||
f"/users/{target}/password",
|
|
||||||
json={"password": NEW_PASSWORD, "old_password": old_password},
|
|
||||||
headers={"remote-user": actor, "remote-role": role},
|
|
||||||
)
|
|
||||||
|
|
||||||
def _admin_password_unchanged(self) -> bool:
|
|
||||||
return verify_password(ADMIN_PASSWORD, User.get_by_id("admin").password_hash)
|
|
||||||
|
|
||||||
def test_custom_role_cannot_target_another_account(self):
|
|
||||||
resp = self._change_password("neighbor", "neighbor", "admin", "wrong-guess")
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert self._admin_password_unchanged()
|
|
||||||
|
|
||||||
def test_custom_role_cannot_target_another_account_with_correct_password(self):
|
|
||||||
# The 403 must land before old_password is checked, so knowing the
|
|
||||||
# target's password is not a way through
|
|
||||||
resp = self._change_password("neighbor", "neighbor", "admin", ADMIN_PASSWORD)
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert self._admin_password_unchanged()
|
|
||||||
|
|
||||||
def test_viewer_cannot_target_another_account(self):
|
|
||||||
resp = self._change_password("viewer_user", "viewer", "admin", ADMIN_PASSWORD)
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert self._admin_password_unchanged()
|
|
||||||
|
|
||||||
def test_admin_can_target_another_account(self):
|
|
||||||
User.insert(
|
|
||||||
username="neighbor",
|
|
||||||
password_hash=hash_password("neighbor-password", iterations=10),
|
|
||||||
role="neighbor",
|
|
||||||
notification_tokens=[],
|
|
||||||
).execute()
|
|
||||||
|
|
||||||
resp = self._change_password("admin", "admin", "neighbor", "")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
|
|
||||||
def test_non_admin_can_change_own_password(self):
|
|
||||||
User.insert(
|
|
||||||
username="neighbor",
|
|
||||||
password_hash=hash_password("neighbor-password", iterations=10),
|
|
||||||
role="neighbor",
|
|
||||||
notification_tokens=[],
|
|
||||||
).execute()
|
|
||||||
|
|
||||||
resp = self._change_password(
|
|
||||||
"neighbor", "neighbor", "neighbor", "neighbor-password"
|
|
||||||
)
|
|
||||||
assert resp.status_code == 200
|
|
||||||
|
|
||||||
def test_non_admin_own_password_still_requires_old_password(self):
|
|
||||||
User.insert(
|
|
||||||
username="neighbor",
|
|
||||||
password_hash=hash_password("neighbor-password", iterations=10),
|
|
||||||
role="neighbor",
|
|
||||||
notification_tokens=[],
|
|
||||||
).execute()
|
|
||||||
|
|
||||||
resp = self._change_password("neighbor", "neighbor", "neighbor", "wrong-guess")
|
|
||||||
assert resp.status_code == 401
|
|
||||||
@@ -240,101 +240,9 @@ 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 test_get_review_with_label_filter_matches_verified(self):
|
|
||||||
"""Test that a label filter also matches the `-verified` variant."""
|
|
||||||
now = datetime.now().timestamp()
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.person", now, now + 2, data={"objects": ["person"]}
|
|
||||||
)
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.verified", now, now + 2, data={"objects": ["person-verified"]}
|
|
||||||
)
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.car", now, now + 2, data={"objects": ["car"]}
|
|
||||||
)
|
|
||||||
|
|
||||||
params = {
|
|
||||||
"labels": "person",
|
|
||||||
"after": now - 1,
|
|
||||||
"before": now + 3,
|
|
||||||
}
|
|
||||||
response = client.get("/review", params=params)
|
|
||||||
assert response.status_code == 200
|
|
||||||
response_json = response.json()
|
|
||||||
assert {r["id"] for r in response_json} == {
|
|
||||||
"123456.person",
|
|
||||||
"123456.verified",
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_get_review_with_label_filter_does_not_match_prefix(self):
|
|
||||||
"""Test that a label filter does not match labels that only share a prefix."""
|
|
||||||
now = datetime.now().timestamp()
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.carrot", now, now + 2, data={"objects": ["carrot"]}
|
|
||||||
)
|
|
||||||
|
|
||||||
params = {
|
|
||||||
"labels": "car",
|
|
||||||
"after": now - 1,
|
|
||||||
"before": now + 3,
|
|
||||||
}
|
|
||||||
response = client.get("/review", params=params)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert len(response.json()) == 0
|
|
||||||
|
|
||||||
def test_get_review_with_audio_label_filter(self):
|
|
||||||
"""Test that a label filter still matches audio labels."""
|
|
||||||
now = datetime.now().timestamp()
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.audio", now, now + 2, data={"audio": ["speech"]}
|
|
||||||
)
|
|
||||||
|
|
||||||
params = {
|
|
||||||
"labels": "speech",
|
|
||||||
"after": now - 1,
|
|
||||||
"before": now + 3,
|
|
||||||
}
|
|
||||||
response = client.get("/review", params=params)
|
|
||||||
assert response.status_code == 200
|
|
||||||
response_json = response.json()
|
|
||||||
assert len(response_json) == 1
|
|
||||||
assert response_json[0]["id"] == "123456.audio"
|
|
||||||
|
|
||||||
####################################################################################################################
|
####################################################################################################################
|
||||||
################################### GET /review/summary Endpoint #################################################
|
################################### GET /review/summary Endpoint #################################################
|
||||||
####################################################################################################################
|
####################################################################################################################
|
||||||
def test_get_review_summary_label_filter_matches_verified(self):
|
|
||||||
"""Test that the summary label filter also matches the `-verified` variant."""
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.verified", data={"objects": ["person-verified"]}
|
|
||||||
)
|
|
||||||
super().insert_mock_review_segment(
|
|
||||||
"123456.car", data={"objects": ["car"]}, severity=SeverityEnum.detection
|
|
||||||
)
|
|
||||||
|
|
||||||
params = {
|
|
||||||
"cameras": "front_door",
|
|
||||||
"labels": "person",
|
|
||||||
"zones": "all",
|
|
||||||
"timezone": "utc",
|
|
||||||
}
|
|
||||||
response = client.get("/review/summary", params=params)
|
|
||||||
assert response.status_code == 200
|
|
||||||
response_json = response.json()
|
|
||||||
assert response_json["last24Hours"]["total_alert"] == 1
|
|
||||||
assert response_json["last24Hours"]["total_detection"] == 0
|
|
||||||
|
|
||||||
today_formatted = datetime.today().strftime("%Y-%m-%d")
|
|
||||||
assert response_json[today_formatted]["total_alert"] == 1
|
|
||||||
assert response_json[today_formatted]["total_detection"] == 0
|
|
||||||
|
|
||||||
def test_get_review_summary_all_filters(self):
|
def test_get_review_summary_all_filters(self):
|
||||||
with AuthTestClient(self.app) as client:
|
with AuthTestClient(self.app) as client:
|
||||||
super().insert_mock_review_segment("123456.random")
|
super().insert_mock_review_segment("123456.random")
|
||||||
|
|||||||
@@ -1,13 +1,70 @@
|
|||||||
"""Test camera user and password cleanup."""
|
"""Tests for Birdseye canvas sizing and layout behavior."""
|
||||||
|
|
||||||
import multiprocessing as mp
|
import multiprocessing as mp
|
||||||
import unittest
|
import unittest
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
from frigate.config import FrigateConfig
|
from frigate.config import BirdseyeModeConfig, FrigateConfig
|
||||||
from frigate.output.birdseye import BirdsEyeFrameManager, get_canvas_shape
|
from frigate.output.birdseye import (
|
||||||
|
Birdseye,
|
||||||
|
BirdseyeActivity,
|
||||||
|
BirdsEyeFrameManager,
|
||||||
|
get_canvas_shape,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestBirdseye(unittest.TestCase):
|
class TestBirdseye(unittest.TestCase):
|
||||||
|
def _build_manager(
|
||||||
|
self, camera_dimensions: dict[str, tuple[int, int]]
|
||||||
|
) -> BirdsEyeFrameManager:
|
||||||
|
config = {
|
||||||
|
"mqtt": {"host": "mqtt"},
|
||||||
|
"birdseye": {"width": 1280, "height": 720},
|
||||||
|
"cameras": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
for order, (camera, dimensions) in enumerate(
|
||||||
|
camera_dimensions.items(), start=1
|
||||||
|
):
|
||||||
|
config["cameras"][camera] = {
|
||||||
|
"ffmpeg": {
|
||||||
|
"inputs": [
|
||||||
|
{
|
||||||
|
"path": f"rtsp://10.0.0.1:554/{camera}",
|
||||||
|
"roles": ["detect"],
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"detect": {
|
||||||
|
"width": dimensions[0],
|
||||||
|
"height": dimensions[1],
|
||||||
|
"fps": 5,
|
||||||
|
},
|
||||||
|
"birdseye": {"order": order},
|
||||||
|
}
|
||||||
|
|
||||||
|
return BirdsEyeFrameManager(FrigateConfig(**config), mp.Event())
|
||||||
|
|
||||||
|
def _assert_no_overlaps(
|
||||||
|
self, layout: list[list[tuple[str, tuple[int, int, int, int]]]]
|
||||||
|
):
|
||||||
|
rectangles = [position for row in layout for _, position in row]
|
||||||
|
|
||||||
|
for index, rect in enumerate(rectangles):
|
||||||
|
x1, y1, width1, height1 = rect
|
||||||
|
for other in rectangles[index + 1 :]:
|
||||||
|
x2, y2, width2, height2 = other
|
||||||
|
overlap = (
|
||||||
|
x1 < x2 + width2
|
||||||
|
and x2 < x1 + width1
|
||||||
|
and y1 < y2 + height2
|
||||||
|
and y2 < y1 + height1
|
||||||
|
)
|
||||||
|
self.assertFalse(
|
||||||
|
overlap,
|
||||||
|
msg=f"Overlapping rectangles found: {rect} and {other}",
|
||||||
|
)
|
||||||
|
|
||||||
def test_16x9(self):
|
def test_16x9(self):
|
||||||
"""Test 16x9 aspect ratio works as expected for birdseye."""
|
"""Test 16x9 aspect ratio works as expected for birdseye."""
|
||||||
width = 1280
|
width = 1280
|
||||||
@@ -48,6 +105,212 @@ class TestBirdseye(unittest.TestCase):
|
|||||||
assert canvas_width == width # width will be the same
|
assert canvas_width == width # width will be the same
|
||||||
assert canvas_height != height
|
assert canvas_height != height
|
||||||
|
|
||||||
|
def test_portrait_camera_does_not_overlap_next_row(self):
|
||||||
|
"""Portrait cameras should reserve their real horizontal position on the next row."""
|
||||||
|
manager = self._build_manager(
|
||||||
|
{
|
||||||
|
"cam_a": (1280, 720),
|
||||||
|
"cam_p": (360, 640),
|
||||||
|
"cam_b": (1280, 720),
|
||||||
|
"cam_c": (640, 480),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
layout = manager.calculate_layout(["cam_a", "cam_p", "cam_b", "cam_c"], 3)
|
||||||
|
|
||||||
|
self.assertIsNotNone(layout)
|
||||||
|
assert layout is not None
|
||||||
|
self._assert_no_overlaps(layout)
|
||||||
|
|
||||||
|
cam_c = [
|
||||||
|
position for row in layout for camera, position in row if camera == "cam_c"
|
||||||
|
][0]
|
||||||
|
self.assertEqual(cam_c[0], 0)
|
||||||
|
|
||||||
|
def test_portrait_reservation_only_applies_to_next_row(self):
|
||||||
|
"""Portrait reservations should not push later rows after the span ends."""
|
||||||
|
manager = self._build_manager(
|
||||||
|
{
|
||||||
|
"cam_a": (1280, 720),
|
||||||
|
"cam_p": (360, 640),
|
||||||
|
"cam_b": (1280, 720),
|
||||||
|
"cam_c": (1280, 720),
|
||||||
|
"cam_d": (1280, 720),
|
||||||
|
"cam_e": (1280, 720),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
layout = manager.calculate_layout(
|
||||||
|
["cam_a", "cam_p", "cam_b", "cam_c", "cam_d", "cam_e"],
|
||||||
|
3,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIsNotNone(layout)
|
||||||
|
assert layout is not None
|
||||||
|
self._assert_no_overlaps(layout)
|
||||||
|
|
||||||
|
cam_e = [
|
||||||
|
position for row in layout for camera, position in row if camera == "cam_e"
|
||||||
|
][0]
|
||||||
|
self.assertEqual(cam_e[0], 0)
|
||||||
|
|
||||||
|
def test_multiple_portraits_reserve_distinct_ranges(self):
|
||||||
|
"""Multiple portrait cameras in one row should reserve separate spans below them."""
|
||||||
|
manager = self._build_manager(
|
||||||
|
{
|
||||||
|
"cam_a": (640, 480),
|
||||||
|
"cam_p1": (360, 640),
|
||||||
|
"cam_p2": (360, 640),
|
||||||
|
"cam_b": (640, 480),
|
||||||
|
"cam_c": (1280, 720),
|
||||||
|
"cam_d": (640, 480),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
layout = manager.calculate_layout(
|
||||||
|
["cam_a", "cam_p1", "cam_p2", "cam_b", "cam_c", "cam_d"],
|
||||||
|
4,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIsNotNone(layout)
|
||||||
|
assert layout is not None
|
||||||
|
self._assert_no_overlaps(layout)
|
||||||
|
|
||||||
|
def test_two_landscapes_then_portrait_then_two_landscapes(self):
|
||||||
|
"""A portrait after two landscapes should reserve only its own tail span."""
|
||||||
|
manager = self._build_manager(
|
||||||
|
{
|
||||||
|
"cam_a": (1280, 720),
|
||||||
|
"cam_b": (1280, 720),
|
||||||
|
"cam_p": (360, 640),
|
||||||
|
"cam_c": (1280, 720),
|
||||||
|
"cam_d": (1280, 720),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
layout = manager.calculate_layout(
|
||||||
|
["cam_a", "cam_b", "cam_p", "cam_c", "cam_d"],
|
||||||
|
3,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIsNotNone(layout)
|
||||||
|
assert layout is not None
|
||||||
|
self._assert_no_overlaps(layout)
|
||||||
|
|
||||||
|
cam_c = [
|
||||||
|
position for row in layout for camera, position in row if camera == "cam_c"
|
||||||
|
][0]
|
||||||
|
cam_d = [
|
||||||
|
position for row in layout for camera, position in row if camera == "cam_d"
|
||||||
|
][0]
|
||||||
|
self.assertEqual(cam_c[0], 0)
|
||||||
|
self.assertEqual(cam_d[0], cam_c[0] + cam_c[2])
|
||||||
|
|
||||||
|
|
||||||
|
class TestBirdseyeActivity(unittest.TestCase):
|
||||||
|
"""Test which camera activity is included in each Birdseye mode."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
config = {
|
||||||
|
"mqtt": {"enabled": False},
|
||||||
|
"birdseye": {
|
||||||
|
"enabled": True,
|
||||||
|
"mode": {
|
||||||
|
"motion": True,
|
||||||
|
"objects": True,
|
||||||
|
"stationary_objects": True,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"cameras": {
|
||||||
|
"front": {
|
||||||
|
"ffmpeg": {
|
||||||
|
"inputs": [
|
||||||
|
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
self.manager = BirdsEyeFrameManager(FrigateConfig(**config), mp.Event())
|
||||||
|
|
||||||
|
def test_existing_modes_keep_their_activity_rules(self):
|
||||||
|
continuous = BirdseyeModeConfig(continuous=True)
|
||||||
|
motion = BirdseyeModeConfig(motion=True)
|
||||||
|
objects = BirdseyeModeConfig(objects=True)
|
||||||
|
|
||||||
|
no_activity = BirdseyeActivity(False, False, False)
|
||||||
|
motion_activity = BirdseyeActivity(False, False, True)
|
||||||
|
stationary_activity = BirdseyeActivity(False, True, False)
|
||||||
|
active_object_activity = BirdseyeActivity(True, False, False)
|
||||||
|
|
||||||
|
assert self.manager.camera_active(continuous, no_activity)
|
||||||
|
assert self.manager.camera_active(motion, motion_activity)
|
||||||
|
assert not self.manager.camera_active(motion, stationary_activity)
|
||||||
|
assert self.manager.camera_active(objects, active_object_activity)
|
||||||
|
assert not self.manager.camera_active(objects, stationary_activity)
|
||||||
|
|
||||||
|
def test_modes_can_be_combined(self):
|
||||||
|
mode = BirdseyeModeConfig(motion=True, stationary_objects=True)
|
||||||
|
|
||||||
|
assert self.manager.camera_active(mode, BirdseyeActivity(False, False, True))
|
||||||
|
assert self.manager.camera_active(mode, BirdseyeActivity(False, True, False))
|
||||||
|
assert not self.manager.camera_active(
|
||||||
|
mode, BirdseyeActivity(False, False, False)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stationary_objects_are_independent_from_active_objects(self):
|
||||||
|
stationary_objects = BirdseyeModeConfig(stationary_objects=True)
|
||||||
|
|
||||||
|
assert self.manager.camera_active(
|
||||||
|
stationary_objects, BirdseyeActivity(False, True, False)
|
||||||
|
)
|
||||||
|
assert not self.manager.camera_active(
|
||||||
|
stationary_objects, BirdseyeActivity(True, False, False)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_write_data_preserves_active_and_confirms_stationary_activity(self):
|
||||||
|
birdseye = Birdseye.__new__(Birdseye)
|
||||||
|
birdseye.birdseye_manager = Mock()
|
||||||
|
birdseye.birdseye_manager.update.return_value = (False, False)
|
||||||
|
birdseye._idle_interval = None
|
||||||
|
frame = Mock()
|
||||||
|
|
||||||
|
birdseye.write_data(
|
||||||
|
"front",
|
||||||
|
[
|
||||||
|
{"stationary": True, "false_positive": True},
|
||||||
|
{"stationary": False, "false_positive": True},
|
||||||
|
{"stationary": True, "false_positive": False},
|
||||||
|
],
|
||||||
|
[[0, 0, 10, 10]],
|
||||||
|
1.0,
|
||||||
|
frame,
|
||||||
|
)
|
||||||
|
|
||||||
|
birdseye.birdseye_manager.update.assert_called_once_with(
|
||||||
|
"front", BirdseyeActivity(True, True, True), 1.0, frame
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_stationary_false_positive_does_not_activate_birdseye(self):
|
||||||
|
birdseye = Birdseye.__new__(Birdseye)
|
||||||
|
birdseye.birdseye_manager = Mock()
|
||||||
|
birdseye.birdseye_manager.update.return_value = (False, False)
|
||||||
|
birdseye._idle_interval = None
|
||||||
|
frame = Mock()
|
||||||
|
|
||||||
|
birdseye.write_data(
|
||||||
|
"front",
|
||||||
|
[{"stationary": True, "false_positive": True}],
|
||||||
|
[],
|
||||||
|
1.0,
|
||||||
|
frame,
|
||||||
|
)
|
||||||
|
|
||||||
|
birdseye.birdseye_manager.update.assert_called_once_with(
|
||||||
|
"front", BirdseyeActivity(False, False, False), 1.0, frame
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestBirdseyeCameraOrder(unittest.TestCase):
|
class TestBirdseyeCameraOrder(unittest.TestCase):
|
||||||
"""Test that birdseye reacts to camera order changes without a restart."""
|
"""Test that birdseye reacts to camera order changes without a restart."""
|
||||||
@@ -55,7 +318,7 @@ class TestBirdseyeCameraOrder(unittest.TestCase):
|
|||||||
def setUp(self):
|
def setUp(self):
|
||||||
config = {
|
config = {
|
||||||
"mqtt": {"enabled": False},
|
"mqtt": {"enabled": False},
|
||||||
"birdseye": {"enabled": True, "mode": "continuous"},
|
"birdseye": {"enabled": True, "mode": {"continuous": True}},
|
||||||
"cameras": {
|
"cameras": {
|
||||||
camera: {
|
camera: {
|
||||||
"ffmpeg": {
|
"ffmpeg": {
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
"""Regression tests for runtime camera add and delete handling."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
# LicensePlatePostProcessor is imported via the maintainer rather than from
|
||||||
|
# data_processing.post.license_plate, which circularly imports back through
|
||||||
|
# frigate.embeddings before that package finishes initializing
|
||||||
|
from frigate.embeddings.maintainer import (
|
||||||
|
EmbeddingMaintainer,
|
||||||
|
LicensePlatePostProcessor,
|
||||||
|
)
|
||||||
|
from frigate.ptz.autotrack import PtzAutoTracker
|
||||||
|
from frigate.review.maintainer import ReviewSegmentMaintainer
|
||||||
|
from frigate.track.object_processing import TrackedObjectProcessor
|
||||||
|
|
||||||
|
|
||||||
|
def _make_processor() -> TrackedObjectProcessor:
|
||||||
|
"""Build a processor with no cameras, bypassing __init__."""
|
||||||
|
processor = TrackedObjectProcessor.__new__(TrackedObjectProcessor)
|
||||||
|
processor.camera_states = {}
|
||||||
|
processor.camera_states_lock = threading.Lock()
|
||||||
|
processor.config = SimpleNamespace(cameras={})
|
||||||
|
processor.event_sender = MagicMock()
|
||||||
|
processor.detection_publisher = MagicMock()
|
||||||
|
processor.ongoing_manual_events = {}
|
||||||
|
return processor
|
||||||
|
|
||||||
|
|
||||||
|
class TestObjectProcessorUnknownCamera(unittest.TestCase):
|
||||||
|
def test_save_lpr_snapshot_ignores_unknown_camera(self):
|
||||||
|
processor = _make_processor()
|
||||||
|
|
||||||
|
# 1x1 png, base64; decoding must not be what fails
|
||||||
|
payload = (
|
||||||
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||||
|
"1234.5-abcdef",
|
||||||
|
"deleted_cam",
|
||||||
|
)
|
||||||
|
|
||||||
|
processor.save_lpr_snapshot(payload)
|
||||||
|
|
||||||
|
processor.event_sender.publish.assert_not_called()
|
||||||
|
|
||||||
|
def test_create_manual_event_ignores_unknown_camera(self):
|
||||||
|
processor = _make_processor()
|
||||||
|
|
||||||
|
payload = (
|
||||||
|
1234.5,
|
||||||
|
"deleted_cam",
|
||||||
|
"person",
|
||||||
|
"1234.5-abcdef",
|
||||||
|
True,
|
||||||
|
0.9,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
"api",
|
||||||
|
False,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
|
||||||
|
processor.create_manual_event(payload)
|
||||||
|
|
||||||
|
processor.event_sender.publish.assert_not_called()
|
||||||
|
self.assertEqual(processor.ongoing_manual_events, {})
|
||||||
|
|
||||||
|
def test_create_lpr_event_ignores_unknown_camera(self):
|
||||||
|
processor = _make_processor()
|
||||||
|
|
||||||
|
payload = (
|
||||||
|
1234.5,
|
||||||
|
"deleted_cam",
|
||||||
|
"license_plate",
|
||||||
|
"1234.5-abcdef",
|
||||||
|
True,
|
||||||
|
0.9,
|
||||||
|
None,
|
||||||
|
"ABC123",
|
||||||
|
)
|
||||||
|
|
||||||
|
processor.create_lpr_event(payload)
|
||||||
|
|
||||||
|
processor.event_sender.publish.assert_not_called()
|
||||||
|
self.assertEqual(processor.ongoing_manual_events, {})
|
||||||
|
|
||||||
|
def test_create_manual_event_ignores_camera_added_but_not_yet_drained(self):
|
||||||
|
"""The add window: present in config.cameras, absent from camera_states.
|
||||||
|
|
||||||
|
debug_replay writes the camera into the shared config before publishing
|
||||||
|
add, so a guard on config.cameras passes here and falls through to
|
||||||
|
camera_states. This test fails against such a guard.
|
||||||
|
"""
|
||||||
|
processor = _make_processor()
|
||||||
|
processor.config = SimpleNamespace(
|
||||||
|
cameras={
|
||||||
|
"new_cam": SimpleNamespace(
|
||||||
|
record=SimpleNamespace(event_pre_capture=5, enabled=True)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
payload = (
|
||||||
|
1234.5,
|
||||||
|
"new_cam",
|
||||||
|
"person",
|
||||||
|
"1234.5-abcdef",
|
||||||
|
True,
|
||||||
|
0.9,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
"api",
|
||||||
|
False,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
|
||||||
|
processor.create_manual_event(payload)
|
||||||
|
|
||||||
|
processor.event_sender.publish.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestEmbeddingsUnknownCamera(unittest.TestCase):
|
||||||
|
def _make_maintainer(self) -> EmbeddingMaintainer:
|
||||||
|
maintainer = EmbeddingMaintainer.__new__(EmbeddingMaintainer)
|
||||||
|
maintainer.config = SimpleNamespace(cameras={})
|
||||||
|
maintainer.event_end_subscriber = MagicMock()
|
||||||
|
maintainer.realtime_processors = [MagicMock()]
|
||||||
|
# spec is required: the dispatch loop is a chain of isinstance checks,
|
||||||
|
# and a bare MagicMock matches none of them, so the crashing branch
|
||||||
|
# would never run and the test would pass against unfixed code
|
||||||
|
maintainer.post_processors = [MagicMock(spec=LicensePlatePostProcessor)]
|
||||||
|
maintainer.detected_license_plates = {"1234.5-abcdef": {"obj_data": {}}}
|
||||||
|
maintainer.recordings_available_through = {"deleted_cam": 1234.5}
|
||||||
|
maintainer.event_metadata_publisher = MagicMock()
|
||||||
|
return maintainer
|
||||||
|
|
||||||
|
def test_process_finalized_skips_unknown_camera(self):
|
||||||
|
maintainer = self._make_maintainer()
|
||||||
|
# updated_db=False bypasses the Event.get branch, which would hit the
|
||||||
|
# database and mask the KeyError this test is about
|
||||||
|
maintainer.event_end_subscriber.check_for_update.side_effect = [
|
||||||
|
("1234.5-abcdef", "deleted_cam", False),
|
||||||
|
None,
|
||||||
|
]
|
||||||
|
|
||||||
|
maintainer._process_finalized()
|
||||||
|
|
||||||
|
maintainer.post_processors[0].process_data.assert_not_called()
|
||||||
|
|
||||||
|
def test_process_finalized_still_expires_realtime_state(self):
|
||||||
|
"""The guard must not skip per-event cleanup, only post processing."""
|
||||||
|
maintainer = self._make_maintainer()
|
||||||
|
maintainer.event_end_subscriber.check_for_update.side_effect = [
|
||||||
|
("1234.5-abcdef", "deleted_cam", False),
|
||||||
|
None,
|
||||||
|
]
|
||||||
|
|
||||||
|
maintainer._process_finalized()
|
||||||
|
|
||||||
|
maintainer.realtime_processors[0].expire_object.assert_called_once_with(
|
||||||
|
"1234.5-abcdef", "deleted_cam"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_expire_dedicated_lpr_drops_entry_for_unknown_camera(self):
|
||||||
|
maintainer = self._make_maintainer()
|
||||||
|
maintainer.detected_license_plates = {
|
||||||
|
"1234.5-abcdef": {"camera": "deleted_cam", "last_seen": 1.0}
|
||||||
|
}
|
||||||
|
|
||||||
|
maintainer._expire_dedicated_lpr()
|
||||||
|
|
||||||
|
self.assertEqual(maintainer.detected_license_plates, {})
|
||||||
|
|
||||||
|
|
||||||
|
class TestReviewMaintainerRemoval(unittest.TestCase):
|
||||||
|
def test_camera_removal_ends_segment_and_clears_state(self):
|
||||||
|
maintainer = ReviewSegmentMaintainer.__new__(ReviewSegmentMaintainer)
|
||||||
|
maintainer.active_review_segments = {"deleted_cam": MagicMock()}
|
||||||
|
maintainer.indefinite_events = {"deleted_cam": {"1234.5-abcdef": 1.0}}
|
||||||
|
maintainer.forcibly_end_segment = MagicMock()
|
||||||
|
|
||||||
|
maintainer._handle_camera_removed("deleted_cam")
|
||||||
|
|
||||||
|
maintainer.forcibly_end_segment.assert_called_once_with("deleted_cam")
|
||||||
|
self.assertNotIn("deleted_cam", maintainer.indefinite_events)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAutotrackerMoveQueue(unittest.TestCase):
|
||||||
|
def test_move_queue_drops_move_for_removed_camera(self):
|
||||||
|
tracker = PtzAutoTracker.__new__(PtzAutoTracker)
|
||||||
|
tracker.stop_event = MagicMock()
|
||||||
|
# one pass through the loop, then stop
|
||||||
|
tracker.stop_event.is_set.side_effect = [False, True]
|
||||||
|
tracker.ptz_metrics = {}
|
||||||
|
tracker.move_queues = {"deleted_cam": asyncio.Queue()}
|
||||||
|
tracker.move_queue_locks = {"deleted_cam": asyncio.Lock()}
|
||||||
|
tracker.onvif = MagicMock()
|
||||||
|
tracker.config = SimpleNamespace(cameras={})
|
||||||
|
tracker.move_queues["deleted_cam"].put_nowait((1234.5, 0.1, 0.1, 0.0))
|
||||||
|
|
||||||
|
asyncio.run(tracker._process_move_queue("deleted_cam"))
|
||||||
|
|
||||||
|
tracker.onvif._move_relative.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class TestCameraStateAccessors(unittest.TestCase):
|
||||||
|
def test_get_camera_state_returns_none_for_unknown_camera(self):
|
||||||
|
processor = _make_processor()
|
||||||
|
|
||||||
|
self.assertIsNone(processor.get_camera_state("deleted_cam"))
|
||||||
|
|
||||||
|
def test_get_camera_states_returns_a_snapshot_not_a_view(self):
|
||||||
|
"""A live values() view raises RuntimeError if the writer pops mid-iteration."""
|
||||||
|
processor = _make_processor()
|
||||||
|
processor.camera_states = {"one": MagicMock(), "two": MagicMock()}
|
||||||
|
|
||||||
|
states = processor.get_camera_states()
|
||||||
|
processor.camera_states.pop("one")
|
||||||
|
|
||||||
|
self.assertEqual(len(states), 2)
|
||||||
|
|
||||||
|
def test_get_current_frame_time_is_zero_for_unknown_camera(self):
|
||||||
|
processor = _make_processor()
|
||||||
|
|
||||||
|
self.assertEqual(processor.get_current_frame_time("deleted_cam"), 0.0)
|
||||||
+100
-9
@@ -7,7 +7,7 @@ import numpy as np
|
|||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
from ruamel.yaml.constructor import DuplicateKeyError
|
from ruamel.yaml.constructor import DuplicateKeyError
|
||||||
|
|
||||||
from frigate.config import BirdseyeModeEnum, FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
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.util.builtin import deep_merge
|
from frigate.util.builtin import deep_merge
|
||||||
@@ -170,7 +170,7 @@ class TestConfig(unittest.TestCase):
|
|||||||
def test_override_birdseye(self):
|
def test_override_birdseye(self):
|
||||||
config = {
|
config = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
"birdseye": {"enabled": True, "mode": "continuous"},
|
"birdseye": {"enabled": True, "mode": {"continuous": True}},
|
||||||
"cameras": {
|
"cameras": {
|
||||||
"back": {
|
"back": {
|
||||||
"ffmpeg": {
|
"ffmpeg": {
|
||||||
@@ -183,19 +183,30 @@ class TestConfig(unittest.TestCase):
|
|||||||
"width": 1920,
|
"width": 1920,
|
||||||
"fps": 5,
|
"fps": 5,
|
||||||
},
|
},
|
||||||
"birdseye": {"enabled": False, "mode": "motion"},
|
"birdseye": {
|
||||||
|
"enabled": False,
|
||||||
|
"mode": {"continuous": False, "motion": True},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
frigate_config = FrigateConfig(**config)
|
frigate_config = FrigateConfig(**config)
|
||||||
assert not frigate_config.cameras["back"].birdseye.enabled
|
assert not frigate_config.cameras["back"].birdseye.enabled
|
||||||
assert frigate_config.cameras["back"].birdseye.mode is BirdseyeModeEnum.motion
|
mode = frigate_config.cameras["back"].birdseye.mode
|
||||||
|
assert mode.motion
|
||||||
|
assert not mode.continuous
|
||||||
|
assert not mode.objects
|
||||||
|
assert not mode.stationary_objects
|
||||||
|
|
||||||
def test_override_birdseye_non_inheritable(self):
|
def test_override_birdseye_non_inheritable(self):
|
||||||
config = {
|
config = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
"birdseye": {"enabled": True, "mode": "continuous", "height": 1920},
|
"birdseye": {
|
||||||
|
"enabled": True,
|
||||||
|
"mode": {"continuous": True},
|
||||||
|
"height": 1920,
|
||||||
|
},
|
||||||
"cameras": {
|
"cameras": {
|
||||||
"back": {
|
"back": {
|
||||||
"ffmpeg": {
|
"ffmpeg": {
|
||||||
@@ -218,7 +229,7 @@ class TestConfig(unittest.TestCase):
|
|||||||
def test_inherit_birdseye(self):
|
def test_inherit_birdseye(self):
|
||||||
config = {
|
config = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
"birdseye": {"enabled": True, "mode": "continuous"},
|
"birdseye": {"enabled": True, "mode": {"continuous": True}},
|
||||||
"cameras": {
|
"cameras": {
|
||||||
"back": {
|
"back": {
|
||||||
"ffmpeg": {
|
"ffmpeg": {
|
||||||
@@ -237,9 +248,89 @@ class TestConfig(unittest.TestCase):
|
|||||||
|
|
||||||
frigate_config = FrigateConfig(**config)
|
frigate_config = FrigateConfig(**config)
|
||||||
assert frigate_config.cameras["back"].birdseye.enabled
|
assert frigate_config.cameras["back"].birdseye.enabled
|
||||||
assert (
|
mode = frigate_config.cameras["back"].birdseye.mode
|
||||||
frigate_config.cameras["back"].birdseye.mode is BirdseyeModeEnum.continuous
|
assert mode.continuous
|
||||||
)
|
assert not mode.motion
|
||||||
|
assert not mode.objects
|
||||||
|
assert not mode.stationary_objects
|
||||||
|
|
||||||
|
def test_combine_birdseye_activity_types(self):
|
||||||
|
config = {
|
||||||
|
**self.minimal,
|
||||||
|
"birdseye": {
|
||||||
|
"mode": {
|
||||||
|
"motion": True,
|
||||||
|
"stationary_objects": True,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
frigate_config = FrigateConfig(**config)
|
||||||
|
mode = frigate_config.cameras["back"].birdseye.mode
|
||||||
|
assert mode.motion
|
||||||
|
assert mode.stationary_objects
|
||||||
|
assert not mode.continuous
|
||||||
|
assert not mode.objects
|
||||||
|
|
||||||
|
def test_birdseye_requires_an_activity_type(self):
|
||||||
|
config = {
|
||||||
|
**self.minimal,
|
||||||
|
"birdseye": {
|
||||||
|
"mode": {
|
||||||
|
"continuous": False,
|
||||||
|
"motion": False,
|
||||||
|
"objects": False,
|
||||||
|
"stationary_objects": False,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValidationError, "must enable at least one Birdseye activity type"
|
||||||
|
):
|
||||||
|
FrigateConfig(**config)
|
||||||
|
|
||||||
|
def test_camera_can_disable_an_inherited_activity_type(self):
|
||||||
|
config = {
|
||||||
|
**self.minimal,
|
||||||
|
"birdseye": {"mode": {"motion": True, "objects": True}},
|
||||||
|
}
|
||||||
|
config["cameras"]["back"]["birdseye"] = {"mode": {"motion": False}}
|
||||||
|
|
||||||
|
frigate_config = FrigateConfig(**config)
|
||||||
|
mode = frigate_config.cameras["back"].birdseye.mode
|
||||||
|
assert not mode.motion
|
||||||
|
assert mode.objects
|
||||||
|
|
||||||
|
def test_profile_must_leave_an_activity_type_enabled(self):
|
||||||
|
config = {
|
||||||
|
**self.minimal,
|
||||||
|
"profiles": {"away": {"friendly_name": "Away"}},
|
||||||
|
"birdseye": {"mode": {"objects": True}},
|
||||||
|
}
|
||||||
|
config["cameras"]["back"]["profiles"] = {
|
||||||
|
"away": {"birdseye": {"mode": {"objects": False}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValidationError, "must enable at least one Birdseye activity type"
|
||||||
|
):
|
||||||
|
FrigateConfig(**config)
|
||||||
|
|
||||||
|
def test_camera_birdseye_activity_types_override_global_values(self):
|
||||||
|
config = {
|
||||||
|
**self.minimal,
|
||||||
|
"birdseye": {"mode": {"motion": True, "objects": True}},
|
||||||
|
}
|
||||||
|
config["cameras"]["back"]["birdseye"] = {
|
||||||
|
"mode": {"motion": False, "stationary_objects": True}
|
||||||
|
}
|
||||||
|
|
||||||
|
frigate_config = FrigateConfig(**config)
|
||||||
|
mode = frigate_config.cameras["back"].birdseye.mode
|
||||||
|
assert not mode.motion
|
||||||
|
assert mode.objects
|
||||||
|
assert mode.stationary_objects
|
||||||
|
|
||||||
def test_override_tracked_objects(self):
|
def test_override_tracked_objects(self):
|
||||||
config = {
|
config = {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
from frigate.debug_replay import DebugReplayManager
|
from frigate.debug_replay import DebugReplayManager
|
||||||
from frigate.jobs.debug_replay import (
|
from frigate.jobs.debug_replay import (
|
||||||
DebugReplayJob,
|
DebugReplayJob,
|
||||||
NoRecordingsError,
|
|
||||||
RecordingDebugReplaySource,
|
RecordingDebugReplaySource,
|
||||||
cancel_debug_replay_job,
|
cancel_debug_replay_job,
|
||||||
get_active_runner,
|
get_active_runner,
|
||||||
@@ -130,7 +129,7 @@ class TestStartDebugReplayJob(unittest.TestCase):
|
|||||||
empty_qs = MagicMock()
|
empty_qs = MagicMock()
|
||||||
empty_qs.count.return_value = 0
|
empty_qs.count.return_value = 0
|
||||||
with patch("frigate.jobs.debug_replay.query_recordings", return_value=empty_qs):
|
with patch("frigate.jobs.debug_replay.query_recordings", return_value=empty_qs):
|
||||||
with self.assertRaises(NoRecordingsError):
|
with self.assertRaises(ValueError):
|
||||||
start_debug_replay_job(
|
start_debug_replay_job(
|
||||||
source=RecordingDebugReplaySource(
|
source=RecordingDebugReplaySource(
|
||||||
source_camera="front",
|
source_camera="front",
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
"""Tests for ONNX Runtime session option selection."""
|
|
||||||
|
|
||||||
import unittest
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import onnxruntime as ort
|
|
||||||
|
|
||||||
from frigate.detectors.detection_runners import (
|
|
||||||
CudaGraphRunner,
|
|
||||||
get_ort_session_options,
|
|
||||||
)
|
|
||||||
from frigate.detectors.detector_config import ModelTypeEnum
|
|
||||||
from frigate.embeddings.types import EnrichmentModelTypeEnum
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetOrtSessionOptions(unittest.TestCase):
|
|
||||||
def test_jina_v2_uses_extended(self):
|
|
||||||
"""jina-clip-v2 returns an identical vector for every image on the CUDA
|
|
||||||
execution provider at anything below EXTENDED."""
|
|
||||||
options = get_ort_session_options(EnrichmentModelTypeEnum.jina_v2.value)
|
|
||||||
|
|
||||||
self.assertIsNotNone(options)
|
|
||||||
self.assertEqual(
|
|
||||||
options.graph_optimization_level,
|
|
||||||
ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_jina_v1_uses_basic(self):
|
|
||||||
options = get_ort_session_options(EnrichmentModelTypeEnum.jina_v1.value)
|
|
||||||
|
|
||||||
self.assertIsNotNone(options)
|
|
||||||
self.assertEqual(
|
|
||||||
options.graph_optimization_level,
|
|
||||||
ort.GraphOptimizationLevel.ORT_ENABLE_BASIC,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_other_models_use_defaults(self):
|
|
||||||
for model_type in [
|
|
||||||
None,
|
|
||||||
EnrichmentModelTypeEnum.paddleocr.value,
|
|
||||||
EnrichmentModelTypeEnum.arcface.value,
|
|
||||||
ModelTypeEnum.rfdetr.value,
|
|
||||||
]:
|
|
||||||
with self.subTest(model_type=model_type):
|
|
||||||
self.assertIsNone(get_ort_session_options(model_type))
|
|
||||||
|
|
||||||
|
|
||||||
class TestCudaGraphRunner(unittest.TestCase):
|
|
||||||
"""CUDA graph capture fails if the arena has to allocate during capture, so
|
|
||||||
the session is warmed up with capture disabled before the first real run."""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
self.session = MagicMock()
|
|
||||||
self.session.get_outputs.return_value = [MagicMock(name="output")]
|
|
||||||
self.io_binding = self.session.io_binding.return_value
|
|
||||||
self.input = {"images": np.zeros((1, 3, 320, 320), np.float32)}
|
|
||||||
|
|
||||||
def _annotations(self) -> list[str | None]:
|
|
||||||
"""Graph annotation id passed with each run, None when unset."""
|
|
||||||
annotations = []
|
|
||||||
|
|
||||||
for call in self.session.run_with_iobinding.call_args_list:
|
|
||||||
try:
|
|
||||||
annotations.append(call.args[1].get_run_config_entry("gpu_graph_id"))
|
|
||||||
except RuntimeError:
|
|
||||||
annotations.append(None)
|
|
||||||
|
|
||||||
return annotations
|
|
||||||
|
|
||||||
def test_first_run_warms_up_with_capture_disabled(self):
|
|
||||||
with patch.object(ort.OrtValue, "ortvalue_from_numpy"):
|
|
||||||
CudaGraphRunner(self.session, 0).run(self.input)
|
|
||||||
|
|
||||||
self.assertEqual(
|
|
||||||
self._annotations(),
|
|
||||||
["-1"] * CudaGraphRunner.GRAPH_FREE_WARMUP_RUNS + [None],
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_later_runs_allow_capture(self):
|
|
||||||
with patch.object(ort.OrtValue, "ortvalue_from_numpy"):
|
|
||||||
runner = CudaGraphRunner(self.session, 0)
|
|
||||||
runner.run(self.input)
|
|
||||||
self.session.run_with_iobinding.reset_mock()
|
|
||||||
runner.run(self.input)
|
|
||||||
|
|
||||||
self.assertEqual(self._annotations(), [None])
|
|
||||||
runner._input_ortvalue.update_inplace.assert_called_once()
|
|
||||||
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
|
|||||||
from frigate.app import FrigateApp
|
from frigate.app import FrigateApp
|
||||||
from frigate.comms.dispatcher import Dispatcher
|
from frigate.comms.dispatcher import Dispatcher
|
||||||
from frigate.comms.runtime_state import RuntimeStatePersistence
|
from frigate.comms.runtime_state import RuntimeStatePersistence
|
||||||
|
from frigate.config import BirdseyeModeConfig
|
||||||
|
|
||||||
|
|
||||||
def _make_camera_mock(
|
def _make_camera_mock(
|
||||||
@@ -51,6 +52,58 @@ def _build_dispatcher(cameras: dict[str, MagicMock]) -> Dispatcher:
|
|||||||
return Dispatcher(config, config_updater, onvif, ptz_metrics, communicators)
|
return Dispatcher(config, config_updater, onvif, ptz_metrics, communicators)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBirdseyeModeCommands(unittest.TestCase):
|
||||||
|
"""Verify Birdseye mode commands use the boolean mode contract."""
|
||||||
|
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.camera = _make_camera_mock()
|
||||||
|
self.camera.birdseye.enabled = True
|
||||||
|
self.dispatcher = _build_dispatcher({"front_door": self.camera})
|
||||||
|
self.dispatcher.publish = MagicMock()
|
||||||
|
|
||||||
|
def test_combined_modes_are_accepted(self) -> None:
|
||||||
|
self.dispatcher._on_birdseye_mode_command(
|
||||||
|
"front_door", "STATIONARY_OBJECTS,MOTION"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.camera.birdseye.mode,
|
||||||
|
BirdseyeModeConfig(motion=True, stationary_objects=True),
|
||||||
|
)
|
||||||
|
self.dispatcher.config_updater.publish_update.assert_called_once()
|
||||||
|
self.dispatcher.publish.assert_called_once_with(
|
||||||
|
"front_door/birdseye_mode/state",
|
||||||
|
"MOTION,STATIONARY_OBJECTS",
|
||||||
|
retain=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_single_activity_type_is_accepted(self) -> None:
|
||||||
|
self.dispatcher._on_birdseye_mode_command("front_door", "OBJECTS")
|
||||||
|
|
||||||
|
self.assertEqual(
|
||||||
|
self.camera.birdseye.mode,
|
||||||
|
BirdseyeModeConfig(objects=True),
|
||||||
|
)
|
||||||
|
self.dispatcher.publish.assert_called_once_with(
|
||||||
|
"front_door/birdseye_mode/state", "OBJECTS", retain=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unknown_mode_is_rejected(self) -> None:
|
||||||
|
for payload in (
|
||||||
|
"UNKNOWN",
|
||||||
|
"motion",
|
||||||
|
"MOTION_OBJECTS",
|
||||||
|
"NONE",
|
||||||
|
"NONE,MOTION",
|
||||||
|
"MOTION,MOTION",
|
||||||
|
"MOTION,",
|
||||||
|
):
|
||||||
|
with self.subTest(payload=payload):
|
||||||
|
self.dispatcher._on_birdseye_mode_command("front_door", payload)
|
||||||
|
|
||||||
|
self.dispatcher.config_updater.publish_update.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
class TestRestoreRuntimeState(unittest.TestCase):
|
class TestRestoreRuntimeState(unittest.TestCase):
|
||||||
"""Verify replay routes through handlers and tolerates missing entries."""
|
"""Verify replay routes through handlers and tolerates missing entries."""
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import unittest
|
import unittest
|
||||||
|
from io import StringIO
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from frigate.util.services import get_amd_gpu_stats, get_intel_gpu_stats
|
from frigate.util.services import (
|
||||||
|
get_amd_gpu_stats,
|
||||||
|
get_intel_gpu_stats,
|
||||||
|
get_openvino_npu_stats,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestGpuStats(unittest.TestCase):
|
class TestGpuStats(unittest.TestCase):
|
||||||
@@ -17,6 +22,88 @@ class TestGpuStats(unittest.TestCase):
|
|||||||
amd_stats = get_amd_gpu_stats()
|
amd_stats = get_amd_gpu_stats()
|
||||||
assert amd_stats == {"gpu": "4.17%", "mem": "60.37%"}
|
assert amd_stats == {"gpu": "4.17%", "mem": "60.37%"}
|
||||||
|
|
||||||
|
@patch("frigate.util.services.time.sleep")
|
||||||
|
@patch("frigate.util.services.time.time", side_effect=[0.0, 1.0])
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.os.readlink",
|
||||||
|
return_value="/sys/bus/pci/drivers/intel_vpu",
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.glob.glob",
|
||||||
|
return_value=["/sys/class/accel/accel0"],
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"builtins.open",
|
||||||
|
side_effect=[StringIO("1000"), StringIO("1250")],
|
||||||
|
)
|
||||||
|
def test_openvino_npu_stats_discovers_accel0(
|
||||||
|
self, open_file, glob, readlink, time, sleep
|
||||||
|
):
|
||||||
|
assert get_openvino_npu_stats() == {"npu": "25.0", "mem": "-%"}
|
||||||
|
|
||||||
|
open_file.assert_any_call(
|
||||||
|
"/sys/class/accel/accel0/device/power/runtime_active_time"
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch("frigate.util.services.time.sleep")
|
||||||
|
@patch("frigate.util.services.time.time", side_effect=[0.0, 1.0])
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.os.readlink",
|
||||||
|
side_effect=[
|
||||||
|
"/sys/bus/pci/drivers/other",
|
||||||
|
"/sys/bus/pci/drivers/intel_vpu",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.glob.glob",
|
||||||
|
return_value=[
|
||||||
|
"/sys/class/accel/accel0",
|
||||||
|
"/sys/class/accel/accel1",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"builtins.open",
|
||||||
|
side_effect=[StringIO("1000"), StringIO("1250")],
|
||||||
|
)
|
||||||
|
def test_openvino_npu_stats_skips_non_intel_accelerator(
|
||||||
|
self, open_file, glob, readlink, time, sleep
|
||||||
|
):
|
||||||
|
assert get_openvino_npu_stats() == {"npu": "25.0", "mem": "-%"}
|
||||||
|
|
||||||
|
open_file.assert_any_call(
|
||||||
|
"/sys/class/accel/accel1/device/power/runtime_active_time"
|
||||||
|
)
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.os.readlink",
|
||||||
|
return_value="/sys/bus/pci/drivers/other",
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.glob.glob",
|
||||||
|
return_value=["/sys/class/accel/accel0"],
|
||||||
|
)
|
||||||
|
@patch("builtins.open")
|
||||||
|
def test_openvino_npu_stats_no_intel_accelerator(self, open_file, glob, readlink):
|
||||||
|
assert get_openvino_npu_stats() is None
|
||||||
|
open_file.assert_not_called()
|
||||||
|
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.os.readlink",
|
||||||
|
return_value="/sys/bus/pci/drivers/intel_vpu",
|
||||||
|
)
|
||||||
|
@patch(
|
||||||
|
"frigate.util.services.glob.glob",
|
||||||
|
return_value=["/sys/class/accel/accel0"],
|
||||||
|
)
|
||||||
|
@patch("builtins.open", side_effect=FileNotFoundError)
|
||||||
|
def test_openvino_npu_stats_runtime_counter_unavailable(
|
||||||
|
self, open_file, glob, readlink
|
||||||
|
):
|
||||||
|
assert get_openvino_npu_stats() is None
|
||||||
|
open_file.assert_called_once_with(
|
||||||
|
"/sys/class/accel/accel0/device/power/runtime_active_time"
|
||||||
|
)
|
||||||
|
|
||||||
@patch("frigate.stats.intel_gpu_info.intel_gpu_name_resolver.get_names")
|
@patch("frigate.stats.intel_gpu_info.intel_gpu_name_resolver.get_names")
|
||||||
@patch("frigate.util.services.time.sleep")
|
@patch("frigate.util.services.time.sleep")
|
||||||
@patch("frigate.util.services.time.monotonic")
|
@patch("frigate.util.services.time.monotonic")
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import sys
|
import sys
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import AsyncMock, MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
# Mock complex imports before importing maintainer, saving originals so we can
|
# Mock complex imports before importing maintainer, saving originals so we can
|
||||||
# restore them after import and avoid polluting sys.modules for other tests.
|
# restore them after import and avoid polluting sys.modules for other tests.
|
||||||
@@ -16,7 +16,7 @@ for name in _MOCKED_MODULES:
|
|||||||
sys.modules[name] = MagicMock()
|
sys.modules[name] = MagicMock()
|
||||||
|
|
||||||
# Now import the class under test
|
# Now import the class under test
|
||||||
from frigate.config import FrigateConfig, RetainModeEnum # noqa: E402
|
from frigate.config import FrigateConfig # noqa: E402
|
||||||
from frigate.record.maintainer import RecordingMaintainer # noqa: E402
|
from frigate.record.maintainer import RecordingMaintainer # noqa: E402
|
||||||
|
|
||||||
# Restore original modules (or remove mock if there was no original)
|
# Restore original modules (or remove mock if there was no original)
|
||||||
@@ -115,70 +115,6 @@ class TestMaintainer(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertIsNone(result)
|
self.assertIsNone(result)
|
||||||
maintainer.drop_segment.assert_called_once_with(cache_path)
|
maintainer.drop_segment.assert_called_once_with(cache_path)
|
||||||
|
|
||||||
async def test_defers_review_overlap_segment_until_metadata_catches_up(self):
|
|
||||||
# Regression: a segment overlapping an active_objects review must not
|
|
||||||
# be dropped while detection metadata lags behind the segment end,
|
|
||||||
# the missing frames may hold the active objects (or continuous
|
|
||||||
# retention would keep it anyway).
|
|
||||||
config = MagicMock(spec=FrigateConfig)
|
|
||||||
|
|
||||||
camera_config = MagicMock()
|
|
||||||
camera_config.record.enabled = True
|
|
||||||
camera_config.record.continuous.days = 7
|
|
||||||
camera_config.record.motion.days = 0
|
|
||||||
camera_config.record.alerts.retain.mode = RetainModeEnum.active_objects
|
|
||||||
camera_config.record.get_review_pre_capture.return_value = 5
|
|
||||||
camera_config.record.get_review_post_capture.return_value = 5
|
|
||||||
config.cameras = {"test_cam": camera_config}
|
|
||||||
|
|
||||||
stop_event = MagicMock()
|
|
||||||
maintainer = RecordingMaintainer(config, stop_event)
|
|
||||||
|
|
||||||
now = datetime.datetime.now(datetime.UTC)
|
|
||||||
start_time = now - datetime.timedelta(seconds=20)
|
|
||||||
end_time = now - datetime.timedelta(seconds=10)
|
|
||||||
cache_path = "/tmp/cache/test_cam@20260417150000+0000.mp4"
|
|
||||||
|
|
||||||
maintainer.end_time_cache = {cache_path: (end_time, 10.0)}
|
|
||||||
# Metadata has only reached partway into the segment.
|
|
||||||
maintainer.object_recordings_info["test_cam"] = [
|
|
||||||
(end_time.timestamp() - 8, [], [], [])
|
|
||||||
]
|
|
||||||
maintainer.audio_recordings_info["test_cam"] = []
|
|
||||||
|
|
||||||
maintainer.drop_segment = MagicMock()
|
|
||||||
maintainer.move_segment = AsyncMock(return_value=None)
|
|
||||||
maintainer.recordings_publisher = MagicMock()
|
|
||||||
|
|
||||||
review = MagicMock()
|
|
||||||
review.severity = "alert"
|
|
||||||
review.start_time = start_time.timestamp() - 30
|
|
||||||
review.end_time = None
|
|
||||||
|
|
||||||
result = await maintainer.validate_and_move_segment(
|
|
||||||
"test_cam",
|
|
||||||
reviews=[review],
|
|
||||||
recording={"start_time": start_time, "cache_path": cache_path},
|
|
||||||
)
|
|
||||||
|
|
||||||
self.assertIsNone(result)
|
|
||||||
maintainer.drop_segment.assert_not_called()
|
|
||||||
maintainer.move_segment.assert_not_awaited()
|
|
||||||
|
|
||||||
# Once metadata passes the segment end, continuous retention keeps it.
|
|
||||||
maintainer.object_recordings_info["test_cam"].append(
|
|
||||||
(now.timestamp(), [], [], [])
|
|
||||||
)
|
|
||||||
|
|
||||||
await maintainer.validate_and_move_segment(
|
|
||||||
"test_cam",
|
|
||||||
reviews=[review],
|
|
||||||
recording={"start_time": start_time, "cache_path": cache_path},
|
|
||||||
)
|
|
||||||
|
|
||||||
maintainer.drop_segment.assert_not_called()
|
|
||||||
maintainer.move_segment.assert_awaited_once()
|
|
||||||
|
|
||||||
async def test_expire_stale_recordings_info_drops_only_absent_cameras(self):
|
async def test_expire_stale_recordings_info_drops_only_absent_cameras(self):
|
||||||
config = MagicMock(spec=FrigateConfig)
|
config = MagicMock(spec=FrigateConfig)
|
||||||
config.cameras = {}
|
config.cameras = {}
|
||||||
|
|||||||
@@ -560,6 +560,25 @@ class TestProfileManager(unittest.TestCase):
|
|||||||
assert err is None
|
assert err is None
|
||||||
assert self.config.cameras["front"].enabled is False
|
assert self.config.cameras["front"].enabled is False
|
||||||
|
|
||||||
|
@patch.object(ProfileManager, "_persist_active_profile")
|
||||||
|
def test_profile_can_disable_inherited_birdseye_activity(self, mock_persist):
|
||||||
|
"""A false-only mode override inherits the other base activity types."""
|
||||||
|
self.config.profiles["away"] = ProfileDefinitionConfig(friendly_name="Away")
|
||||||
|
base_mode = self.config.cameras["front"].birdseye.mode
|
||||||
|
base_mode.motion = True
|
||||||
|
base_mode.objects = True
|
||||||
|
self.config.cameras["front"].profiles["away"] = CameraProfileConfig(
|
||||||
|
birdseye={"mode": {"motion": False}}
|
||||||
|
)
|
||||||
|
self.manager = ProfileManager(self.config, self.mock_updater)
|
||||||
|
|
||||||
|
err = self.manager.activate_profile("away")
|
||||||
|
|
||||||
|
assert err is None
|
||||||
|
mode = self.config.cameras["front"].birdseye.mode
|
||||||
|
assert not mode.motion
|
||||||
|
assert mode.objects
|
||||||
|
|
||||||
@patch.object(ProfileManager, "_persist_active_profile")
|
@patch.object(ProfileManager, "_persist_active_profile")
|
||||||
def test_deactivate_restores_enabled(self, mock_persist):
|
def test_deactivate_restores_enabled(self, mock_persist):
|
||||||
"""Deactivating a profile restores the camera's base enabled state."""
|
"""Deactivating a profile restores the camera's base enabled state."""
|
||||||
|
|||||||
@@ -1,24 +1,16 @@
|
|||||||
"""Tests for embedding storage and cleanup on the main Frigate database.
|
"""Tests for embedding cleanup on the main Frigate database.
|
||||||
|
|
||||||
Embeddings are deleted whether or not semantic search is currently enabled, so
|
Embeddings are deleted whether or not semantic search is currently enabled, so
|
||||||
the delete path has to tolerate databases where the vec0 tables were never
|
the delete path has to tolerate databases where the vec0 tables were never
|
||||||
created and installs where the sqlite-vec extension is unavailable.
|
created and installs where the sqlite-vec extension is unavailable.
|
||||||
|
|
||||||
The write paths need the real extension, since the behavior under test belongs
|
|
||||||
to vec0 itself, so those tests are skipped when it is not installed.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import struct
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from peewee import OperationalError
|
|
||||||
|
|
||||||
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
|
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
|
||||||
|
|
||||||
VEC_EXTENSION_PATH = "/usr/local/lib/vec0.so"
|
|
||||||
|
|
||||||
|
|
||||||
class TestDeleteEmbeddings(unittest.TestCase):
|
class TestDeleteEmbeddings(unittest.TestCase):
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
@@ -60,21 +52,6 @@ class TestDeleteEmbeddings(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertEqual(self._thumbnail_ids(), ["b"])
|
self.assertEqual(self._thumbnail_ids(), ["b"])
|
||||||
|
|
||||||
def test_delete_failure_is_logged_not_raised(self) -> None:
|
|
||||||
self._create_thumbnails_table()
|
|
||||||
self.db.execute_sql(
|
|
||||||
"""
|
|
||||||
CREATE TRIGGER vec_thumbnails_no_delete BEFORE DELETE ON vec_thumbnails
|
|
||||||
BEGIN SELECT RAISE(ABORT, 'delete blocked'); END
|
|
||||||
"""
|
|
||||||
).fetchall()
|
|
||||||
|
|
||||||
with self.assertLogs("frigate.db.sqlitevecq", level="ERROR") as logs:
|
|
||||||
self.db.delete_embeddings_thumbnail(event_ids=["a"])
|
|
||||||
|
|
||||||
self.assertIn("Failed to delete embeddings", logs.output[0])
|
|
||||||
self.assertEqual(self._thumbnail_ids(), ["a", "b"])
|
|
||||||
|
|
||||||
def test_delete_skipped_without_extension(self) -> None:
|
def test_delete_skipped_without_extension(self) -> None:
|
||||||
self._create_thumbnails_table()
|
self._create_thumbnails_table()
|
||||||
self.db.load_vec_extension = False
|
self.db.load_vec_extension = False
|
||||||
@@ -84,104 +61,3 @@ class TestDeleteEmbeddings(unittest.TestCase):
|
|||||||
|
|
||||||
# the vec0 tables cannot be written without the extension
|
# the vec0 tables cannot be written without the extension
|
||||||
self.assertEqual(self._thumbnail_ids(), ["a", "b"])
|
self.assertEqual(self._thumbnail_ids(), ["a", "b"])
|
||||||
|
|
||||||
|
|
||||||
def _vector(value: float) -> bytes:
|
|
||||||
return struct.pack("768f", *([value] * 768))
|
|
||||||
|
|
||||||
|
|
||||||
@unittest.skipUnless(
|
|
||||||
os.path.exists(VEC_EXTENSION_PATH), "sqlite-vec extension is not installed"
|
|
||||||
)
|
|
||||||
class TestEmbeddingsTableWrites(unittest.TestCase):
|
|
||||||
"""Covers the vec0 writes behind semantic search reindexing."""
|
|
||||||
|
|
||||||
def setUp(self) -> None:
|
|
||||||
self.tmp_dir = tempfile.TemporaryDirectory()
|
|
||||||
self.db = SqliteVecQueueDatabase(
|
|
||||||
os.path.join(self.tmp_dir.name, "test.db"), load_vec_extension=True
|
|
||||||
)
|
|
||||||
self.db.start()
|
|
||||||
self.db.create_embeddings_tables()
|
|
||||||
|
|
||||||
def tearDown(self) -> None:
|
|
||||||
self.db.stop()
|
|
||||||
self.db.close()
|
|
||||||
self.tmp_dir.cleanup()
|
|
||||||
|
|
||||||
def _vec_tables(self) -> list[str]:
|
|
||||||
return [
|
|
||||||
row[0]
|
|
||||||
for row in self.db.execute_sql(
|
|
||||||
"SELECT name FROM sqlite_master WHERE name LIKE 'vec_%' ORDER BY name"
|
|
||||||
)
|
|
||||||
]
|
|
||||||
|
|
||||||
def _make_legacy(self, table: str) -> None:
|
|
||||||
# sqlite-vec added the _info shadow table in 0.1.6, so tables written by
|
|
||||||
# Frigate 0.17 and earlier do not have one
|
|
||||||
self.db.execute_sql(f"DROP TABLE {table}_info").fetchall()
|
|
||||||
|
|
||||||
def _stored(self, table: str, column: str, event_id: str) -> str | None:
|
|
||||||
row = self.db.execute_sql(
|
|
||||||
f"SELECT vec_to_json({column}) FROM {table} WHERE id = ?", (event_id,)
|
|
||||||
).fetchone()
|
|
||||||
return row[0] if row else None
|
|
||||||
|
|
||||||
def test_write_error_is_raised(self) -> None:
|
|
||||||
# queued writes hide their exception in the returned cursor
|
|
||||||
with self.assertRaises(OperationalError):
|
|
||||||
self.db.execute_write("INSERT INTO vec_missing(id) VALUES ('a')")
|
|
||||||
|
|
||||||
def test_drop_tables_removes_legacy_tables(self) -> None:
|
|
||||||
self._make_legacy("vec_thumbnails")
|
|
||||||
self._make_legacy("vec_descriptions")
|
|
||||||
|
|
||||||
self.db.drop_embeddings_tables()
|
|
||||||
|
|
||||||
self.assertEqual(self._vec_tables(), [])
|
|
||||||
|
|
||||||
def test_drop_tables_without_any_tables_does_not_raise(self) -> None:
|
|
||||||
self.db.drop_embeddings_tables()
|
|
||||||
|
|
||||||
self.db.drop_embeddings_tables()
|
|
||||||
|
|
||||||
def test_upsert_replaces_existing_embedding(self) -> None:
|
|
||||||
self.db.upsert_embeddings(
|
|
||||||
"vec_thumbnails", "thumbnail_embedding", {"evt1": _vector(0.01)}
|
|
||||||
)
|
|
||||||
|
|
||||||
self.db.upsert_embeddings(
|
|
||||||
"vec_thumbnails", "thumbnail_embedding", {"evt1": _vector(0.99)}
|
|
||||||
)
|
|
||||||
|
|
||||||
stored = self._stored("vec_thumbnails", "thumbnail_embedding", "evt1")
|
|
||||||
self.assertTrue(stored.startswith("[0.990000"), stored)
|
|
||||||
|
|
||||||
def test_upsert_keeps_one_row_per_event(self) -> None:
|
|
||||||
for _ in range(3):
|
|
||||||
self.db.upsert_embeddings(
|
|
||||||
"vec_descriptions", "description_embedding", {"evt1": _vector(0.5)}
|
|
||||||
)
|
|
||||||
|
|
||||||
count = self.db.execute_sql(
|
|
||||||
"SELECT count(*) FROM vec_descriptions WHERE id = 'evt1'"
|
|
||||||
).fetchone()[0]
|
|
||||||
self.assertEqual(count, 1)
|
|
||||||
|
|
||||||
def test_reindex_cycle_rewrites_legacy_tables(self) -> None:
|
|
||||||
"""The 0.18 upgrade path: old vectors in, new vectors out."""
|
|
||||||
self.db.upsert_embeddings(
|
|
||||||
"vec_thumbnails", "thumbnail_embedding", {"evt1": _vector(0.01)}
|
|
||||||
)
|
|
||||||
self._make_legacy("vec_thumbnails")
|
|
||||||
self._make_legacy("vec_descriptions")
|
|
||||||
|
|
||||||
self.db.drop_embeddings_tables()
|
|
||||||
self.db.create_embeddings_tables()
|
|
||||||
self.db.upsert_embeddings(
|
|
||||||
"vec_thumbnails", "thumbnail_embedding", {"evt1": _vector(0.99)}
|
|
||||||
)
|
|
||||||
|
|
||||||
stored = self._stored("vec_thumbnails", "thumbnail_embedding", "evt1")
|
|
||||||
self.assertTrue(stored.startswith("[0.990000"), stored)
|
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
import unittest
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
from frigate.events.types import EventStateEnum
|
|
||||||
from frigate.models import Timeline
|
|
||||||
from frigate.timeline import TimelineProcessor
|
|
||||||
|
|
||||||
|
|
||||||
def make_event(has_clip: bool, has_snapshot: bool) -> dict:
|
|
||||||
return {
|
|
||||||
"id": "event-1",
|
|
||||||
"frame_time": 1000.0,
|
|
||||||
"box": [0, 0, 10, 10],
|
|
||||||
"region": [0, 0, 100, 100],
|
|
||||||
"label": "car",
|
|
||||||
"sub_label": None,
|
|
||||||
"score": 0.8,
|
|
||||||
"has_clip": has_clip,
|
|
||||||
"has_snapshot": has_snapshot,
|
|
||||||
"current_zones": [],
|
|
||||||
"stationary": False,
|
|
||||||
"attributes": {},
|
|
||||||
"current_attributes": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestTimelineProcessor(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
camera_config = MagicMock()
|
|
||||||
camera_config.detect.width = 1280
|
|
||||||
camera_config.detect.height = 720
|
|
||||||
config = MagicMock()
|
|
||||||
config.cameras.get.return_value = camera_config
|
|
||||||
self.processor = TimelineProcessor(config, MagicMock(), MagicMock())
|
|
||||||
|
|
||||||
@patch.object(Timeline, "insert")
|
|
||||||
def test_unsaved_event_writes_no_timeline_rows(self, insert):
|
|
||||||
event = make_event(has_clip=False, has_snapshot=False)
|
|
||||||
self.processor.handle_object_detection(
|
|
||||||
"front", EventStateEnum.start, None, event
|
|
||||||
)
|
|
||||||
self.processor.handle_object_detection(
|
|
||||||
"front", EventStateEnum.end, event, event
|
|
||||||
)
|
|
||||||
|
|
||||||
insert.assert_not_called()
|
|
||||||
self.assertEqual(self.processor.pre_event_cache, {})
|
|
||||||
|
|
||||||
@patch.object(Timeline, "insert")
|
|
||||||
def test_cached_entries_flush_when_event_is_saved(self, insert):
|
|
||||||
start = make_event(has_clip=False, has_snapshot=False)
|
|
||||||
self.processor.handle_object_detection(
|
|
||||||
"front", EventStateEnum.start, None, start
|
|
||||||
)
|
|
||||||
insert.assert_not_called()
|
|
||||||
|
|
||||||
end = make_event(has_clip=True, has_snapshot=False)
|
|
||||||
self.processor.handle_object_detection("front", EventStateEnum.end, start, end)
|
|
||||||
|
|
||||||
class_types = [c.args[0][Timeline.class_type] for c in insert.call_args_list]
|
|
||||||
self.assertEqual(class_types, ["visible", "gone"])
|
|
||||||
self.assertEqual(self.processor.pre_event_cache, {})
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -6,7 +6,7 @@ import unittest
|
|||||||
|
|
||||||
from ruamel.yaml import YAML
|
from ruamel.yaml import YAML
|
||||||
|
|
||||||
from frigate.util.builtin import clear_orphaned_comments, update_yaml_file_bulk
|
from frigate.util.builtin import update_yaml_file_bulk
|
||||||
|
|
||||||
|
|
||||||
class TestUpdateYaml(unittest.TestCase):
|
class TestUpdateYaml(unittest.TestCase):
|
||||||
@@ -178,27 +178,6 @@ class TestUpdateYaml(unittest.TestCase):
|
|||||||
assert data["cameras"]["cam1"]["detect"]["fps"] == 5
|
assert data["cameras"]["cam1"]["detect"]["fps"] == 5
|
||||||
assert "# tuned for the pi" in self._read()
|
assert "# tuned for the pi" in self._read()
|
||||||
|
|
||||||
def test_delete_only_camera_with_comment_on_cameras_key(self):
|
|
||||||
"""Deleting the only camera stays parseable when the cameras key
|
|
||||||
carries the default config's trailing comment."""
|
|
||||||
self._write(
|
|
||||||
"cameras: # No cameras defined, UI wizard should be used\n"
|
|
||||||
" cam1:\n"
|
|
||||||
" enabled: true\n"
|
|
||||||
"version: 0.18-0\n"
|
|
||||||
)
|
|
||||||
yaml = YAML()
|
|
||||||
with open(self.config_path) as f:
|
|
||||||
data = yaml.load(f)
|
|
||||||
del data["cameras"]["cam1"]
|
|
||||||
clear_orphaned_comments(data["cameras"], data, "cameras")
|
|
||||||
with open(self.config_path, "w") as f:
|
|
||||||
yaml.dump(data, f)
|
|
||||||
|
|
||||||
data = self._load()
|
|
||||||
assert data["cameras"] == {}
|
|
||||||
assert data["version"] == "0.18-0"
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main(verbosity=2)
|
unittest.main(verbosity=2)
|
||||||
|
|||||||
@@ -1,150 +0,0 @@
|
|||||||
"""Tests for push notification subscription validation."""
|
|
||||||
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
from frigate.api.notification import _validate_push_endpoint, _validate_subscription
|
|
||||||
|
|
||||||
VALID_ENDPOINTS = [
|
|
||||||
"https://fcm.googleapis.com/fcm/send/dGhpcy1pcy1hLXRva2Vu",
|
|
||||||
"https://updates.push.services.mozilla.com/wpush/v2/dGhpcy1pcy1hLXRva2Vu",
|
|
||||||
"https://web.push.apple.com/dGhpcy1pcy1hLXRva2Vu",
|
|
||||||
"https://wns2-by3p.notify.windows.com/w/?token=dGhpcy1pcy1hLXRva2Vu",
|
|
||||||
"https://fcm.googleapis.com:443/fcm/send/dGhpcy1pcy1hLXRva2Vu",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _subscription(endpoint: str) -> dict:
|
|
||||||
return {
|
|
||||||
"endpoint": endpoint,
|
|
||||||
"keys": {"p256dh": "cHVibGljLWtleQ", "auth": "YXV0aC1zZWNyZXQ"},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestValidatePushEndpoint(unittest.TestCase):
|
|
||||||
def test_accepts_real_push_service_endpoints(self):
|
|
||||||
for endpoint in VALID_ENDPOINTS:
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_http(self):
|
|
||||||
self.assertIsNotNone(
|
|
||||||
_validate_push_endpoint("http://fcm.googleapis.com/fcm/send/token")
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_rejects_non_http_schemes(self):
|
|
||||||
for endpoint in (
|
|
||||||
"file:///etc/passwd",
|
|
||||||
"ftp://example.com/token",
|
|
||||||
"//example.com/token",
|
|
||||||
):
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_localhost(self):
|
|
||||||
for endpoint in (
|
|
||||||
"https://localhost/token",
|
|
||||||
"https://localhost:443/token",
|
|
||||||
"https://127.0.0.1/token",
|
|
||||||
"https://[::1]/token",
|
|
||||||
):
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_private_addresses(self):
|
|
||||||
for endpoint in (
|
|
||||||
"https://192.168.1.10/token",
|
|
||||||
"https://10.0.0.5/token",
|
|
||||||
"https://172.16.0.1/token",
|
|
||||||
"https://169.254.169.254/token",
|
|
||||||
"https://0.0.0.0/token",
|
|
||||||
):
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_internal_hostnames(self):
|
|
||||||
for endpoint in (
|
|
||||||
"https://frigate/token",
|
|
||||||
"https://nas.local/token",
|
|
||||||
"https://push.internal/token",
|
|
||||||
"https://host.home.arpa/token",
|
|
||||||
):
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_non_default_port(self):
|
|
||||||
self.assertIsNotNone(
|
|
||||||
_validate_push_endpoint("https://fcm.googleapis.com:8080/fcm/send/token")
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_rejects_embedded_credentials(self):
|
|
||||||
self.assertIsNotNone(
|
|
||||||
_validate_push_endpoint(
|
|
||||||
"https://user:pass@fcm.googleapis.com/fcm/send/token"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_rejects_endpoint_without_path(self):
|
|
||||||
for endpoint in ("https://fcm.googleapis.com", "https://fcm.googleapis.com/"):
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_endpoint_that_breaks_audience_parsing(self):
|
|
||||||
# webpush.py locates the host by searching for a separator after index
|
|
||||||
# 10, which raises ValueError when the url has no path at all
|
|
||||||
endpoint = "https://fcm.googleapis.com"
|
|
||||||
|
|
||||||
with self.assertRaises(ValueError):
|
|
||||||
endpoint.index("/", 10)
|
|
||||||
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_missing_or_non_string_endpoint(self):
|
|
||||||
for endpoint in (None, "", 5, {"url": "https://example.com/token"}):
|
|
||||||
with self.subTest(endpoint=endpoint):
|
|
||||||
self.assertIsNotNone(_validate_push_endpoint(endpoint))
|
|
||||||
|
|
||||||
def test_rejects_overlong_endpoint(self):
|
|
||||||
self.assertIsNotNone(
|
|
||||||
_validate_push_endpoint(f"https://fcm.googleapis.com/{'a' * 4096}")
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestValidateSubscription(unittest.TestCase):
|
|
||||||
def test_accepts_valid_subscription(self):
|
|
||||||
self.assertIsNone(_validate_subscription(_subscription(VALID_ENDPOINTS[0])))
|
|
||||||
|
|
||||||
def test_accepts_extra_fields_sent_by_the_browser(self):
|
|
||||||
sub = _subscription(VALID_ENDPOINTS[0])
|
|
||||||
sub["expirationTime"] = None
|
|
||||||
self.assertIsNone(_validate_subscription(sub))
|
|
||||||
|
|
||||||
def test_rejects_non_object(self):
|
|
||||||
for sub in ("https://fcm.googleapis.com/fcm/send/token", ["endpoint"], 5):
|
|
||||||
with self.subTest(sub=sub):
|
|
||||||
self.assertIsNotNone(_validate_subscription(sub))
|
|
||||||
|
|
||||||
def test_rejects_bad_endpoint(self):
|
|
||||||
self.assertIsNotNone(
|
|
||||||
_validate_subscription(_subscription("https://localhost/t"))
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_rejects_missing_keys(self):
|
|
||||||
sub = _subscription(VALID_ENDPOINTS[0])
|
|
||||||
del sub["keys"]
|
|
||||||
self.assertIsNotNone(_validate_subscription(sub))
|
|
||||||
|
|
||||||
def test_rejects_incomplete_keys(self):
|
|
||||||
for keys in (
|
|
||||||
{"p256dh": "cHVibGljLWtleQ"},
|
|
||||||
{"auth": "YXV0aC1zZWNyZXQ"},
|
|
||||||
{"p256dh": "cHVibGljLWtleQ", "auth": ""},
|
|
||||||
{"p256dh": None, "auth": "YXV0aC1zZWNyZXQ"},
|
|
||||||
):
|
|
||||||
with self.subTest(keys=keys):
|
|
||||||
sub = _subscription(VALID_ENDPOINTS[0])
|
|
||||||
sub["keys"] = keys
|
|
||||||
self.assertIsNotNone(_validate_subscription(sub))
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -191,9 +191,6 @@ class TimelineProcessor(threading.Thread):
|
|||||||
timeline_entry[Timeline.class_type] = "gone"
|
timeline_entry[Timeline.class_type] = "gone"
|
||||||
self.insert_or_save(timeline_entry, prev_event_data, event_data)
|
self.insert_or_save(timeline_entry, prev_event_data, event_data)
|
||||||
|
|
||||||
# drop entries for events that ended without being saved
|
|
||||||
self.pre_event_cache.pop(event_id, None)
|
|
||||||
|
|
||||||
def handle_api_entry(
|
def handle_api_entry(
|
||||||
self,
|
self,
|
||||||
camera: str,
|
camera: str,
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ from frigate.comms.event_metadata_updater import (
|
|||||||
from frigate.comms.events_updater import EventEndSubscriber, EventUpdatePublisher
|
from frigate.comms.events_updater import EventEndSubscriber, EventUpdatePublisher
|
||||||
from frigate.comms.inter_process import InterProcessRequestor
|
from frigate.comms.inter_process import InterProcessRequestor
|
||||||
from frigate.config import (
|
from frigate.config import (
|
||||||
CameraConfig,
|
|
||||||
CameraMqttConfig,
|
CameraMqttConfig,
|
||||||
FrigateConfig,
|
FrigateConfig,
|
||||||
RecordConfig,
|
RecordConfig,
|
||||||
@@ -69,6 +68,7 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
self.tracked_objects_queue = tracked_objects_queue
|
self.tracked_objects_queue = tracked_objects_queue
|
||||||
self.stop_event: MpEvent = stop_event
|
self.stop_event: MpEvent = stop_event
|
||||||
self.camera_states: dict[str, CameraState] = {}
|
self.camera_states: dict[str, CameraState] = {}
|
||||||
|
self.camera_states_lock = threading.Lock()
|
||||||
self.frame_manager = SharedMemoryFrameManager()
|
self.frame_manager = SharedMemoryFrameManager()
|
||||||
self.last_motion_detected: dict[str, float] = {}
|
self.last_motion_detected: dict[str, float] = {}
|
||||||
self.ptz_autotracker_thread = ptz_autotracker_thread
|
self.ptz_autotracker_thread = ptz_autotracker_thread
|
||||||
@@ -129,10 +129,8 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def update(camera: str, obj: TrackedObject, frame_name: str) -> None:
|
def update(camera: str, obj: TrackedObject, frame_name: str) -> None:
|
||||||
obj.has_snapshot = self.should_save_snapshot(
|
obj.has_snapshot = self.should_save_snapshot(camera, obj)
|
||||||
camera_state.camera_config, obj
|
obj.has_clip = self.should_retain_recording(camera, obj)
|
||||||
)
|
|
||||||
obj.has_clip = self.should_retain_recording(camera_state.camera_config, obj)
|
|
||||||
after = obj.to_dict()
|
after = obj.to_dict()
|
||||||
message = {
|
message = {
|
||||||
"before": obj.previous,
|
"before": obj.previous,
|
||||||
@@ -156,10 +154,8 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
|
|
||||||
def end(camera: str, obj: TrackedObject, frame_name: str) -> None:
|
def end(camera: str, obj: TrackedObject, frame_name: str) -> None:
|
||||||
# populate has_snapshot
|
# populate has_snapshot
|
||||||
obj.has_snapshot = self.should_save_snapshot(
|
obj.has_snapshot = self.should_save_snapshot(camera, obj)
|
||||||
camera_state.camera_config, obj
|
obj.has_clip = self.should_retain_recording(camera, obj)
|
||||||
)
|
|
||||||
obj.has_clip = self.should_retain_recording(camera_state.camera_config, obj)
|
|
||||||
|
|
||||||
# write thumbnail to disk if it will be saved as an event
|
# write thumbnail to disk if it will be saved as an event
|
||||||
if obj.has_snapshot or obj.has_clip:
|
if obj.has_snapshot or obj.has_clip:
|
||||||
@@ -189,8 +185,8 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def snapshot(camera: str, obj: TrackedObject) -> bool:
|
def snapshot(camera: str, obj: TrackedObject) -> bool:
|
||||||
mqtt_config: CameraMqttConfig = camera_state.camera_config.mqtt
|
mqtt_config: CameraMqttConfig = self.config.cameras[camera].mqtt
|
||||||
if mqtt_config.enabled and self.should_mqtt_snapshot(mqtt_config, obj):
|
if mqtt_config.enabled and self.should_mqtt_snapshot(camera, obj):
|
||||||
jpg_bytes, _ = obj.get_img_bytes(
|
jpg_bytes, _ = obj.get_img_bytes(
|
||||||
ext="jpg",
|
ext="jpg",
|
||||||
timestamp=mqtt_config.timestamp,
|
timestamp=mqtt_config.timestamp,
|
||||||
@@ -241,15 +237,15 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
camera_state.on("end", end)
|
camera_state.on("end", end)
|
||||||
camera_state.on("snapshot", snapshot)
|
camera_state.on("snapshot", snapshot)
|
||||||
camera_state.on("camera_activity", camera_activity)
|
camera_state.on("camera_activity", camera_activity)
|
||||||
self.camera_states[camera] = camera_state
|
|
||||||
|
|
||||||
def should_save_snapshot(
|
with self.camera_states_lock:
|
||||||
self, camera_config: CameraConfig, obj: TrackedObject
|
self.camera_states[camera] = camera_state
|
||||||
) -> bool:
|
|
||||||
|
def should_save_snapshot(self, camera: str, obj: TrackedObject) -> bool:
|
||||||
if obj.false_positive:
|
if obj.false_positive:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
snapshot_config: SnapshotsConfig = camera_config.snapshots
|
snapshot_config: SnapshotsConfig = self.config.cameras[camera].snapshots
|
||||||
|
|
||||||
if not snapshot_config.enabled:
|
if not snapshot_config.enabled:
|
||||||
return False
|
return False
|
||||||
@@ -268,13 +264,11 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def should_retain_recording(
|
def should_retain_recording(self, camera: str, obj: TrackedObject) -> bool:
|
||||||
self, camera_config: CameraConfig, obj: TrackedObject
|
|
||||||
) -> bool:
|
|
||||||
if obj.false_positive:
|
if obj.false_positive:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
record_config: RecordConfig = camera_config.record
|
record_config: RecordConfig = self.config.cameras[camera].record
|
||||||
|
|
||||||
# Recording is disabled
|
# Recording is disabled
|
||||||
if not record_config.enabled:
|
if not record_config.enabled:
|
||||||
@@ -290,15 +284,13 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def should_mqtt_snapshot(
|
def should_mqtt_snapshot(self, camera: str, obj: TrackedObject) -> bool:
|
||||||
self, mqtt_config: CameraMqttConfig, obj: TrackedObject
|
|
||||||
) -> bool:
|
|
||||||
# object never changed position
|
# object never changed position
|
||||||
if obj.is_stationary():
|
if obj.is_stationary():
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# if there are required zones and there is no overlap
|
# if there are required zones and there is no overlap
|
||||||
required_zones = mqtt_config.required_zones
|
required_zones = self.config.cameras[camera].mqtt.required_zones
|
||||||
if len(required_zones) > 0 and not set(obj.entered_zones) & set(required_zones):
|
if len(required_zones) > 0 and not set(obj.entered_zones) & set(required_zones):
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Not sending mqtt for {obj.obj_data['id']} because it did not enter required zones"
|
f"Not sending mqtt for {obj.obj_data['id']} because it did not enter required zones"
|
||||||
@@ -308,11 +300,7 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
def update_mqtt_motion(
|
def update_mqtt_motion(
|
||||||
self,
|
self, camera: str, frame_time: float, motion_boxes: list
|
||||||
camera: str,
|
|
||||||
camera_config: CameraConfig,
|
|
||||||
frame_time: float,
|
|
||||||
motion_boxes: list,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
# publish if motion is currently being detected
|
# publish if motion is currently being detected
|
||||||
if motion_boxes:
|
if motion_boxes:
|
||||||
@@ -327,7 +315,7 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
# always updated latest motion
|
# always updated latest motion
|
||||||
self.last_motion_detected[camera] = frame_time
|
self.last_motion_detected[camera] = frame_time
|
||||||
elif self.last_motion_detected.get(camera, 0) > 0:
|
elif self.last_motion_detected.get(camera, 0) > 0:
|
||||||
mqtt_delay = camera_config.motion.mqtt_off_delay
|
mqtt_delay = self.config.cameras[camera].motion.mqtt_off_delay
|
||||||
|
|
||||||
# If no motion, make sure the off_delay has passed
|
# If no motion, make sure the off_delay has passed
|
||||||
if frame_time - self.last_motion_detected.get(camera, 0) >= mqtt_delay:
|
if frame_time - self.last_motion_detected.get(camera, 0) >= mqtt_delay:
|
||||||
@@ -339,9 +327,22 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
# reset the last_motion so redundant `off` commands aren't sent
|
# reset the last_motion so redundant `off` commands aren't sent
|
||||||
self.last_motion_detected[camera] = 0
|
self.last_motion_detected[camera] = 0
|
||||||
|
|
||||||
|
def get_camera_state(self, camera: str) -> CameraState | None:
|
||||||
|
"""Returns the state for a camera, or None if it does not exist."""
|
||||||
|
with self.camera_states_lock:
|
||||||
|
return self.camera_states.get(camera)
|
||||||
|
|
||||||
|
def get_camera_states(self) -> list[CameraState]:
|
||||||
|
"""Returns a snapshot of camera states that is safe to iterate."""
|
||||||
|
with self.camera_states_lock:
|
||||||
|
return list(self.camera_states.values())
|
||||||
|
|
||||||
def get_best(self, camera: str, label: str) -> dict[str, Any]:
|
def get_best(self, camera: str, label: str) -> dict[str, Any]:
|
||||||
# TODO: need a lock here
|
camera_state = self.get_camera_state(camera)
|
||||||
camera_state = self.camera_states[camera]
|
|
||||||
|
if camera_state is None:
|
||||||
|
return {}
|
||||||
|
|
||||||
if label in camera_state.best_objects:
|
if label in camera_state.best_objects:
|
||||||
best_obj = camera_state.best_objects[label]
|
best_obj = camera_state.best_objects[label]
|
||||||
|
|
||||||
@@ -365,17 +366,21 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
(self.config.birdseye.height * 3 // 2, self.config.birdseye.width),
|
(self.config.birdseye.height * 3 // 2, self.config.birdseye.width),
|
||||||
)
|
)
|
||||||
|
|
||||||
if camera not in self.camera_states:
|
camera_state = self.get_camera_state(camera)
|
||||||
|
|
||||||
|
if camera_state is None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return self.camera_states[camera].get_current_frame(draw_options)
|
return camera_state.get_current_frame(draw_options)
|
||||||
|
|
||||||
def get_current_frame_time(self, camera: str) -> float:
|
def get_current_frame_time(self, camera: str) -> float:
|
||||||
"""Returns the latest frame time for a given camera."""
|
"""Returns the latest frame time for a given camera."""
|
||||||
if camera not in self.camera_states:
|
camera_state = self.get_camera_state(camera)
|
||||||
|
|
||||||
|
if camera_state is None:
|
||||||
return 0.0
|
return 0.0
|
||||||
|
|
||||||
return self.camera_states[camera].current_frame_time
|
return camera_state.current_frame_time
|
||||||
|
|
||||||
def set_sub_label(
|
def set_sub_label(
|
||||||
self, event_id: str, sub_label: str | None, score: float | None
|
self, event_id: str, sub_label: str | None, score: float | None
|
||||||
@@ -513,14 +518,18 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
# save the snapshot image
|
# save the snapshot image
|
||||||
(frame, event_id, camera) = payload
|
(frame, event_id, camera) = payload
|
||||||
|
|
||||||
|
camera_state = self.camera_states.get(camera)
|
||||||
|
|
||||||
|
if camera_state is None:
|
||||||
|
logger.debug("Discarding LPR snapshot for unknown camera %s", camera)
|
||||||
|
return
|
||||||
|
|
||||||
img = cv2.imdecode(
|
img = cv2.imdecode(
|
||||||
np.frombuffer(base64.b64decode(frame), dtype=np.uint8),
|
np.frombuffer(base64.b64decode(frame), dtype=np.uint8),
|
||||||
cv2.IMREAD_COLOR,
|
cv2.IMREAD_COLOR,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.camera_states[camera].save_manual_event_image(
|
camera_state.save_manual_event_image(img, event_id, "license_plate", {})
|
||||||
img, event_id, "license_plate", {}
|
|
||||||
)
|
|
||||||
|
|
||||||
def create_manual_event(self, payload: tuple) -> None:
|
def create_manual_event(self, payload: tuple) -> None:
|
||||||
(
|
(
|
||||||
@@ -537,13 +546,17 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
pre_capture,
|
pre_capture,
|
||||||
) = payload
|
) = payload
|
||||||
|
|
||||||
|
camera_state = self.camera_states.get(camera_name)
|
||||||
|
|
||||||
|
if camera_state is None:
|
||||||
|
logger.debug("Discarding manual event for unknown camera %s", camera_name)
|
||||||
|
return
|
||||||
|
|
||||||
# save the snapshot image
|
# save the snapshot image
|
||||||
self.camera_states[camera_name].save_manual_event_image(
|
camera_state.save_manual_event_image(None, event_id, label, draw)
|
||||||
None, event_id, label, draw
|
|
||||||
)
|
|
||||||
end_time = frame_time + duration if duration is not None else None
|
end_time = frame_time + duration if duration is not None else None
|
||||||
start_time = (
|
start_time = (
|
||||||
frame_time - self.config.cameras[camera_name].record.event_pre_capture
|
frame_time - camera_state.camera_config.record.event_pre_capture
|
||||||
if pre_capture is None
|
if pre_capture is None
|
||||||
else frame_time - pre_capture
|
else frame_time - pre_capture
|
||||||
)
|
)
|
||||||
@@ -563,7 +576,7 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
"camera": camera_name,
|
"camera": camera_name,
|
||||||
"start_time": start_time,
|
"start_time": start_time,
|
||||||
"end_time": end_time,
|
"end_time": end_time,
|
||||||
"has_clip": self.config.cameras[camera_name].record.enabled
|
"has_clip": camera_state.camera_config.record.enabled
|
||||||
and include_recording,
|
and include_recording,
|
||||||
"has_snapshot": True,
|
"has_snapshot": True,
|
||||||
"snapshot_clean": True,
|
"snapshot_clean": True,
|
||||||
@@ -606,6 +619,12 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
plate,
|
plate,
|
||||||
) = payload
|
) = payload
|
||||||
|
|
||||||
|
camera_state = self.camera_states.get(camera_name)
|
||||||
|
|
||||||
|
if camera_state is None:
|
||||||
|
logger.debug("Discarding LPR event for unknown camera %s", camera_name)
|
||||||
|
return
|
||||||
|
|
||||||
# send event to event maintainer
|
# send event to event maintainer
|
||||||
self.event_sender.publish(
|
self.event_sender.publish(
|
||||||
(
|
(
|
||||||
@@ -620,9 +639,9 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
"score": score,
|
"score": score,
|
||||||
"camera": camera_name,
|
"camera": camera_name,
|
||||||
"start_time": frame_time
|
"start_time": frame_time
|
||||||
- self.config.cameras[camera_name].record.event_pre_capture,
|
- camera_state.camera_config.record.event_pre_capture,
|
||||||
"end_time": None,
|
"end_time": None,
|
||||||
"has_clip": self.config.cameras[camera_name].record.enabled
|
"has_clip": camera_state.camera_config.record.enabled
|
||||||
and include_recording,
|
and include_recording,
|
||||||
"has_snapshot": True,
|
"has_snapshot": True,
|
||||||
"snapshot_clean": True,
|
"snapshot_clean": True,
|
||||||
@@ -714,7 +733,10 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
camera_state.shutdown()
|
camera_state.shutdown()
|
||||||
self.camera_states.pop(camera)
|
|
||||||
|
with self.camera_states_lock:
|
||||||
|
self.camera_states.pop(camera)
|
||||||
|
|
||||||
self.camera_activity.pop(camera, None)
|
self.camera_activity.pop(camera, None)
|
||||||
self.last_motion_detected.pop(camera, None)
|
self.last_motion_detected.pop(camera, None)
|
||||||
|
|
||||||
@@ -730,8 +752,6 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
if camera_state is None:
|
if camera_state is None:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
camera_state = self.camera_states[camera]
|
|
||||||
|
|
||||||
if camera_state.prev_enabled and not current_enabled:
|
if camera_state.prev_enabled and not current_enabled:
|
||||||
logger.debug(f"Not processing objects for disabled camera {camera}")
|
logger.debug(f"Not processing objects for disabled camera {camera}")
|
||||||
self.force_end_all_events(camera, camera_state)
|
self.force_end_all_events(camera, camera_state)
|
||||||
@@ -798,7 +818,7 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
frame_name, frame_time, current_tracked_objects, motion_boxes, regions
|
frame_name, frame_time, current_tracked_objects, motion_boxes, regions
|
||||||
)
|
)
|
||||||
|
|
||||||
self.update_mqtt_motion(camera, camera_config, frame_time, motion_boxes)
|
self.update_mqtt_motion(camera, frame_time, motion_boxes)
|
||||||
|
|
||||||
tracked_objects = [
|
tracked_objects = [
|
||||||
o.to_dict() for o in camera_state.tracked_objects.values()
|
o.to_dict() for o in camera_state.tracked_objects.values()
|
||||||
@@ -827,7 +847,11 @@ class TrackedObjectProcessor(threading.Thread):
|
|||||||
break
|
break
|
||||||
|
|
||||||
event_id, camera, _ = update
|
event_id, camera, _ = update
|
||||||
self.camera_states[camera].finished(event_id)
|
camera_state = self.camera_states.get(camera)
|
||||||
|
|
||||||
|
# the camera may have been removed while its event was pending
|
||||||
|
if camera_state is not None:
|
||||||
|
camera_state.finished(event_id)
|
||||||
|
|
||||||
# shut down camera states
|
# shut down camera states
|
||||||
for state in self.camera_states.values():
|
for state in self.camera_states.values():
|
||||||
|
|||||||
@@ -54,11 +54,6 @@ class TrackedObject:
|
|||||||
self.obj_data = obj_data
|
self.obj_data = obj_data
|
||||||
self.colormap = model_config.colormap
|
self.colormap = model_config.colormap
|
||||||
self.logos = model_config.all_attribute_logos
|
self.logos = model_config.all_attribute_logos
|
||||||
self.thumbnail_attributes = [
|
|
||||||
attr
|
|
||||||
for attr in model_config.attributes_map.get(obj_data["label"], [])
|
|
||||||
if attr in model_config.non_logo_attributes
|
|
||||||
]
|
|
||||||
self.camera_config = camera_config
|
self.camera_config = camera_config
|
||||||
self.ui_config = ui_config
|
self.ui_config = ui_config
|
||||||
self.frame_cache = frame_cache
|
self.frame_cache = frame_cache
|
||||||
@@ -154,7 +149,7 @@ class TrackedObject:
|
|||||||
if not self.false_positive and has_valid_frame:
|
if not self.false_positive and has_valid_frame:
|
||||||
# determine if this frame is a better thumbnail
|
# determine if this frame is a better thumbnail
|
||||||
if self.thumbnail_data is None or is_better_thumbnail(
|
if self.thumbnail_data is None or is_better_thumbnail(
|
||||||
self.thumbnail_attributes,
|
self.obj_data["label"],
|
||||||
self.thumbnail_data,
|
self.thumbnail_data,
|
||||||
obj_data,
|
obj_data,
|
||||||
self.camera_config.frame_shape,
|
self.camera_config.frame_shape,
|
||||||
|
|||||||
+45
-2
@@ -20,7 +20,7 @@ from frigate.util.services import get_video_properties
|
|||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
CURRENT_CONFIG_VERSION = "0.18-0"
|
CURRENT_CONFIG_VERSION = "0.19-0"
|
||||||
DEFAULT_CONFIG_FILE = os.path.join(CONFIG_DIR, "config.yml")
|
DEFAULT_CONFIG_FILE = os.path.join(CONFIG_DIR, "config.yml")
|
||||||
|
|
||||||
|
|
||||||
@@ -93,6 +93,7 @@ def migrate_frigate_config(config_file: str):
|
|||||||
|
|
||||||
logger.info("copying config as backup...")
|
logger.info("copying config as backup...")
|
||||||
shutil.copy(config_file, os.path.join(CONFIG_DIR, "backup_config.yaml"))
|
shutil.copy(config_file, os.path.join(CONFIG_DIR, "backup_config.yaml"))
|
||||||
|
new_config = config
|
||||||
|
|
||||||
if previous_version < "0.14":
|
if previous_version < "0.14":
|
||||||
logger.info(f"Migrating frigate config from {previous_version} to 0.14...")
|
logger.info(f"Migrating frigate config from {previous_version} to 0.14...")
|
||||||
@@ -147,6 +148,13 @@ def migrate_frigate_config(config_file: str):
|
|||||||
yaml.dump(new_config, f)
|
yaml.dump(new_config, f)
|
||||||
previous_version = "0.18-0"
|
previous_version = "0.18-0"
|
||||||
|
|
||||||
|
if previous_version < "0.19-0":
|
||||||
|
logger.info(f"Migrating frigate config from {previous_version} to 0.19-0...")
|
||||||
|
new_config = migrate_019_0(new_config)
|
||||||
|
with open(config_file, "w") as f:
|
||||||
|
yaml.dump(new_config, f)
|
||||||
|
previous_version = "0.19-0"
|
||||||
|
|
||||||
logger.info("Finished frigate config migration...")
|
logger.info("Finished frigate config migration...")
|
||||||
|
|
||||||
|
|
||||||
@@ -525,6 +533,21 @@ def _convert_legacy_mask_to_dict(
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _migrate_birdseye_mode(birdseye: dict[str, Any] | None) -> None:
|
||||||
|
"""Convert a scalar Birdseye mode to composable activity types."""
|
||||||
|
if not birdseye or not isinstance(birdseye.get("mode"), str):
|
||||||
|
return
|
||||||
|
|
||||||
|
legacy_mode = birdseye["mode"]
|
||||||
|
activity_types = ("continuous", "motion", "objects", "stationary_objects")
|
||||||
|
if legacy_mode not in activity_types:
|
||||||
|
return
|
||||||
|
|
||||||
|
birdseye["mode"] = {
|
||||||
|
activity_type: activity_type == legacy_mode for activity_type in activity_types
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||||
"""Handle migrating frigate config to 0.18-0"""
|
"""Handle migrating frigate config to 0.18-0"""
|
||||||
new_config = config.copy()
|
new_config = config.copy()
|
||||||
@@ -533,7 +556,7 @@ def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]
|
|||||||
genai = new_config.get("genai")
|
genai = new_config.get("genai")
|
||||||
|
|
||||||
if genai and genai.get("provider"):
|
if genai and genai.get("provider"):
|
||||||
genai["roles"] = ["descriptions", "chat"]
|
genai["roles"] = ["embeddings", "descriptions", "chat"]
|
||||||
new_config["genai"] = {"default": genai}
|
new_config["genai"] = {"default": genai}
|
||||||
|
|
||||||
# Remove deprecated sync_recordings from global record config
|
# Remove deprecated sync_recordings from global record config
|
||||||
@@ -658,6 +681,26 @@ def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]
|
|||||||
return new_config
|
return new_config
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_019_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||||
|
"""Handle migrating Frigate config to 0.19-0."""
|
||||||
|
new_config = config.copy()
|
||||||
|
|
||||||
|
_migrate_birdseye_mode(new_config.get("birdseye"))
|
||||||
|
|
||||||
|
for name, camera in new_config.get("cameras", {}).items():
|
||||||
|
camera_config: dict[str, dict[str, Any]] = camera.copy()
|
||||||
|
_migrate_birdseye_mode(camera_config.get("birdseye"))
|
||||||
|
|
||||||
|
for profile in camera_config.get("profiles", {}).values():
|
||||||
|
if isinstance(profile, dict):
|
||||||
|
_migrate_birdseye_mode(profile.get("birdseye"))
|
||||||
|
|
||||||
|
new_config["cameras"][name] = camera_config
|
||||||
|
|
||||||
|
new_config["version"] = "0.19-0"
|
||||||
|
return new_config
|
||||||
|
|
||||||
|
|
||||||
def get_relative_coordinates(
|
def get_relative_coordinates(
|
||||||
mask: str | list | None,
|
mask: str | list | None,
|
||||||
frame_shape: tuple[int, int],
|
frame_shape: tuple[int, int],
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user