Compare commits

..
Author SHA1 Message Date
Josh HawkinsandGitHub f2c1dda2fd Add Apple compatibility switch to the camera wizard (#24115)
* add apple compatibility switch to the camera wizard

* don't require every record stream to be h265
2026-08-27 17:14:37 -06:00
Josh HawkinsandGitHub 95f2e41725 Add onboarding wizard for new installations (#24102)
* add onboarding wizard for new users

* resolve hwaccel per camera and clarify recording retention

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

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

* clean up

* add light/dark mode icon switcher

* use yml as default config file extension when not found

* i18n tweaks

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

* render setup wizard steps by key

* share the setup wizard e2e helpers and mock users

* add an account step to the setup wizard

* add setup wizard account step e2e coverage

* cover the account step's restart behavior

* button consistency

* fix test

* docs

* fixes
2026-08-27 07:49:11 -06:00
Josh HawkinsandGitHub 9466cf632f Fix 500 when an event thumbnail file is empty (#24110)
* fix 500 when an event thumbnail file is empty

* fix test
2026-08-27 07:04:49 -06:00
Josh HawkinsandGitHub 8d6fff61e9 Fix inconsistent export download filenames (#24111)
* fix inconsistent export download filenames

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

* cap filename length and catch duplicate names

* fix export rename and stop blocking the event loop

* move the rename rollback off the event loop

* no awaits
2026-08-27 07:02:37 -06:00
41 changed files with 3678 additions and 319 deletions
+3 -1
View File
@@ -22,7 +22,9 @@ The following ports are available to access the Frigate web UI.
## Onboarding
On startup, an admin user and password are generated and printed in the logs. It is recommended to set a new password for the admin account after logging in for the first time under Settings > Users.
On startup, an admin user and password are generated and printed in the logs. It is recommended to set a new password for the admin account after logging in for the first time.
On a new install the [setup wizard](../guides/getting_started.md#configuring-frigate) offers this as its first step, along with creating accounts for anyone else who needs access. You can also do both at any time under <NavPath path="Settings > Users" />.
## Resetting admin password
+1 -1
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
## Adding a camera with the Add Camera Wizard
The Add Camera Wizard is the recommended way to add a camera. Click **Add Camera** in <NavPath path="Settings > Global configuration > Camera management" />. The wizard connects to your camera, tests each stream, and writes the camera's configuration for you, including the [go2rtc](go2rtc.md) restream and the live view stream mapping, so a standard setup needs no hand-written YAML.
The Add Camera Wizard is the recommended way to add a camera. Click **Add Camera** in <NavPath path="Settings > Global configuration > Camera management" />, or use it from the [setup wizard](../guides/getting_started.md#configuring-frigate) on a new install. The wizard connects to your camera, tests each stream, and writes the camera's configuration for you, including the [go2rtc](go2rtc.md) restream and the live view stream mapping, so a standard setup needs no hand-written YAML.
### Step 1: Name and connection
+59 -8
View File
@@ -4,6 +4,7 @@ title: Getting started
---
import ConfigTabs from "@site/src/components/ConfigTabs";
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import NavPath from "@site/src/components/NavPath";
@@ -132,21 +133,68 @@ services:
- "8554:8554" # RTSP feeds
```
Now you should be able to start Frigate by running `docker compose up -d` from within the folder containing `docker-compose.yml`. On startup, an admin user and password will be created and outputted in the logs. You can see this by running `docker logs frigate`. Frigate should now be accessible at `https://server_ip:8971` where you can login with the `admin` user and finish configuration using the Settings UI.
Now you should be able to start Frigate by running `docker compose up -d` from within the folder containing `docker-compose.yml`. On startup, an admin user and password will be created and outputted in the logs. You can see this by running `docker logs frigate`. Frigate should now be accessible at `https://server_ip:8971` where you can login with the `admin` user. With no cameras configured yet, the setup wizard runs on first login and walks you through the rest.
## Configuring Frigate
This section assumes that you already have an environment setup as described in [Installation](../frigate/installation.md). You should also configure your cameras according to the [camera setup guide](/frigate/camera_setup). Pay particular attention to the section on choosing a detect resolution.
### Step 1: Start Frigate
<Tabs
groupId="setup-method"
defaultValue="wizard"
values={[
{ label: "Setup wizard", value: "wizard" },
{ label: "Manual", value: "manual" },
]}
> <TabItem value="wizard">
The first time you open Frigate with no cameras configured, the setup wizard walks you through the basics. Every step can be skipped, everything it sets can be changed later in Settings, and once you finish or dismiss it, it doesn't come back.
:::note
Frigate only sees hardware that has been passed into the container. If you plan to use a GPU, a Coral, or another accelerator, add the device to your `docker-compose.yml` and restart before running the wizard, otherwise it won't appear in the detection or hardware acceleration steps. The Manual tab shows the device entries for an Intel or AMD GPU and for a Coral, and the [hardware acceleration](../configuration/hardware_acceleration_video.md) and [object detectors](../configuration/object_detectors.md) docs cover the rest.
:::
**Account**
Set a password for the `admin` account to replace the generated one from the logs, and add accounts for anyone else who needs access. This step is hidden if you have turned authentication off.
**Add a camera**
Opens the [Add Camera Wizard](../configuration/cameras.md#adding-a-camera-with-the-add-camera-wizard), which connects to the camera, tests each stream, and writes its configuration for you. You can add more than one before moving on.
**Object detection**
Lists the detection hardware Frigate found on your system, such as a Coral, an Intel GPU or NPU, or a discrete GPU, and configures the one you pick. NVIDIA and AMD GPUs need a model before detection can start, so the wizard offers your Frigate+ models if you have them, or lets you finish setup and add one later under <NavPath path="Settings > System > Detection models" />.
**Hardware acceleration**
Offers only the decoding methods your hardware supports. Auto picks one based on that hardware and the codec your camera sends, so a mixed h264 and h265 setup gets the right preset per camera.
**Recording**
Choose whether to record only when something is detected or around the clock, and how long to keep it.
The last screen summarizes what was set up. If a step changed something that needs a restart, the button restarts Frigate and returns you to the Live view once it is back.
The wizard configures the essentials only. Motion masks are not included and should be set up afterward, once you can identify the areas of the frame that trigger unwanted motion. See the [masks documentation](../configuration/masks.md). Zones, tracked object types, notifications, and MQTT are also configured in Settings.
</TabItem>
<TabItem value="manual">
On a new install the setup wizard opens first. Click **Skip setup and configure manually** on its welcome screen to dismiss it, and the steps below apply. The wizard won't come back once dismissed.
**Step 1: Start Frigate**
At this point you should be able to start Frigate and a basic config will be created automatically.
### Step 2: Add a camera
**Step 2: Add a camera**
Click the **Add Camera** button in <NavPath path="Settings > Global configuration > Camera management" /> to use the camera setup wizard to get your first camera added into Frigate. See [Adding a camera with the Add Camera Wizard](../configuration/cameras.md#adding-a-camera-with-the-add-camera-wizard) for a walkthrough of each step.
### Step 3: Configure hardware acceleration (recommended)
**Step 3: Configure hardware acceleration (recommended)**
Now that you have a working camera configuration, set up hardware acceleration to minimize the CPU required to decode your video streams. See the [hardware acceleration](../configuration/hardware_acceleration_video.md) docs for examples applicable to your hardware.
@@ -190,7 +238,7 @@ cameras:
</TabItem>
</ConfigTabs>
### Step 4: Configure detectors
**Step 4: Configure detectors**
By default, Frigate will use a single OpenVINO detector running on the CPU.
@@ -299,7 +347,7 @@ More details on available detectors can be found [here](../configuration/object_
Restart Frigate and you should start seeing detections for `person`. If you want to track other objects, they can be configured in <NavPath path="Settings > Global configuration > Objects" /> or via the [configuration file reference](../configuration/advanced/reference.md).
### Step 5: Setup motion masks
**Step 5: Setup motion masks**
Now that you have optimized your configuration for decoding the video stream, you will want to check to see where to implement motion masks. Click on the camera from the main dashboard, then select the gear icon in the top right, enable the [Debug view](/usage/live#the-single-camera-view), and finally enable the switch for Motion Boxes. Watch for areas that continuously trigger unwanted motion to be detected. Common areas to mask include camera timestamps and trees that frequently blow in the wind. The goal is to avoid wasting object detection cycles looking at these areas.
@@ -336,7 +384,7 @@ cameras:
coordinates: "0,461,3,0,1919,0,1919,843,1699,492,1344,458,1346,336,973,317,869,375,866,432"
```
### Step 6: Enable recordings
**Step 6: Enable recordings**
In order to review activity in the Frigate UI, recordings need to be enabled.
@@ -385,7 +433,10 @@ If you only plan to use Frigate for recording, it is still recommended to define
By default, Frigate will retain video of all tracked objects for 10 days. The full set of options for recording can be found [here](../configuration/advanced/reference.md).
### Step 7: Complete config
</TabItem>
</Tabs>
### Complete config
At this point you have a complete config with basic functionality.
+92 -5
View File
@@ -1476,12 +1476,10 @@ paths:
- Classification
summary: Get custom classification attributes
description: |-
**Access:** Any authenticated user.
**Access:** Admin role required.
Returns custom classification attributes for a given object type.
Only includes models with classification_type set to 'attribute'.
Callers without access to every camera only receive values that have been
recorded on the cameras they can access.
By default returns a flat sorted list of all attribute labels.
If group_by_model is true, returns attributes grouped by model name.
operationId: get_custom_attributes_classification_attributes_get
@@ -1512,8 +1510,8 @@ paths:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateUserAuth: []
x-required-role: any
- frigateAdminAuth: []
x-required-role: admin
/classification/{name}/train:
get:
tags:
@@ -4055,6 +4053,58 @@ paths:
security:
- frigateAdminAuth: []
x-required-role: admin
/hardware/hwaccel:
get:
tags:
- Hardware
summary: Hwaccel Recommendation
description: |-
**Access:** Admin role required.
Get the hardware decoding this system can do.
Args:
detector: Hardware key of the detection hardware in use, which biases
the recommendation toward that hardware's GPU
codecs: Comma separated codecs of the streams that will be decoded,
used to drop families that cannot decode one of them
Returns:
The recommended family (empty when none fits) and every usable family
operationId: hwaccel_recommendation_hardware_hwaccel_get
parameters:
- name: detector
in: query
required: false
schema:
anyOf:
- type: string
- type: 'null'
title: Detector
- name: codecs
in: query
required: false
schema:
anyOf:
- type: string
- type: 'null'
title: Codecs
responses:
'200':
description: Successful Response
content:
application/json:
schema:
$ref: '#/components/schemas/HwaccelRecommendation'
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateAdminAuth: []
x-required-role: admin
/events:
get:
tags:
@@ -8672,6 +8722,43 @@ components:
- label
title: HardwareUnit
description: One physical piece of hardware.
HwaccelFamily:
properties:
key:
type: string
title: Family key
description: Stable identifier for this kind of hardware decoding.
presets:
additionalProperties:
type: string
type: object
title: Presets
description: The ffmpeg preset for each codec this family decodes, or
a single 'any' preset when it decodes every codec.
type: object
required:
- key
- presets
title: HwaccelFamily
description: A kind of hardware decoding, and the presets that drive it.
HwaccelRecommendation:
properties:
recommended:
type: string
title: Recommended family
description: Key of the family that fits this system best, or an empty
string when none does.
available:
items:
$ref: '#/components/schemas/HwaccelFamily'
type: array
title: Available families
description: Every family this system's hardware can use, best first.
type: object
required:
- recommended
title: HwaccelRecommendation
description: The hardware decoding this system can do.
Last24HoursReview:
properties:
reviewed_alert:
-1
View File
@@ -86,7 +86,6 @@ def require_admin_by_default():
"/categorized_object_names",
"/plus/models",
"/recognized_license_plates",
"/classification/attributes",
"/timeline",
"/timeline/hourly",
"/recordings/storage",
+3 -96
View File
@@ -11,14 +11,10 @@ from typing import Any
import cv2
from fastapi import APIRouter, Depends, Request, UploadFile
from fastapi.responses import JSONResponse
from peewee import DoesNotExist, fn
from peewee import DoesNotExist
from playhouse.shortcuts import model_to_dict
from frigate.api.auth import (
allow_any_authenticated,
get_allowed_cameras_for_filter,
require_role,
)
from frigate.api.auth import require_role
from frigate.api.defs.request.classification_body import (
AudioTranscriptionBody,
DeleteFaceImagesBody,
@@ -743,81 +739,18 @@ def get_classification_dataset(name: str):
)
def get_observed_attributes(
model_attributes: dict[str, list[str]],
object_labels: set[str],
allowed_cameras: list[str],
) -> dict[str, set[str]]:
"""Get the attribute values recorded on the given cameras.
Args:
model_attributes: Labels each attribute model can emit, keyed by model name
object_labels: Object types those models run on
allowed_cameras: Cameras the caller has access to
Returns:
Values seen for each model, keyed by model name
"""
if not model_attributes or not object_labels or not allowed_cameras:
return {}
model_names = list(model_attributes.keys())
query = (
Event.select(
*[
fn.json_extract(Event.data, f'$."{model_name}"')
for model_name in model_names
]
)
.where(
(Event.camera << allowed_cameras) & (Event.label << sorted(object_labels))
)
.distinct()
.tuples()
)
targets = {
model_name: set(attributes)
for model_name, attributes in model_attributes.items()
}
observed: dict[str, set[str]] = {model_name: set() for model_name in model_names}
for row in query.iterator():
found = False
for model_name, value in zip(model_names, row):
if isinstance(value, str) and value not in observed[model_name]:
observed[model_name].add(value)
found = True
if found and all(
observed[model_name] >= targets[model_name] for model_name in model_names
):
break
return observed
@router.get(
"/classification/attributes",
dependencies=[Depends(allow_any_authenticated())],
summary="Get custom classification attributes",
description="""Returns custom classification attributes for a given object type.
Only includes models with classification_type set to 'attribute'.
Callers without access to every camera only receive values that have been
recorded on the cameras they can access.
By default returns a flat sorted list of all attribute labels.
If group_by_model is true, returns attributes grouped by model name.""",
)
def get_custom_attributes(
request: Request,
object_type: str = None,
group_by_model: bool = False,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
request: Request, object_type: str = None, group_by_model: bool = False
):
models_with_attributes = {}
objects_by_model = {}
for (
model_key,
@@ -848,32 +781,6 @@ def get_custom_attributes(
if attributes:
model_name = model_config.name or model_key
models_with_attributes[model_name] = sorted(attributes)
objects_by_model[model_name] = model_objects
# the dataset holds every label a model can emit, including ones never
# applied to an event, so callers without full camera access are limited to
# the values actually recorded on the cameras they can see
all_cameras = set(request.app.frigate_config.cameras.keys())
if models_with_attributes and not all_cameras.issubset(allowed_cameras):
observed = get_observed_attributes(
models_with_attributes,
set().union(*objects_by_model.values()),
allowed_cameras,
)
models_with_attributes = {
model_name: [
attribute
for attribute in attributes
if attribute in observed.get(model_name, set())
]
for model_name, attributes in models_with_attributes.items()
}
models_with_attributes = {
model_name: attributes
for model_name, attributes in models_with_attributes.items()
if attributes
}
if group_by_model:
return JSONResponse(content=models_with_attributes)
+64 -7
View File
@@ -1,7 +1,9 @@
"""Export apis."""
import contextlib
import datetime
import logging
import os
import random
import string
import time
@@ -14,7 +16,7 @@ import psutil
from fastapi import APIRouter, Depends, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pathvalidate import sanitize_filename
from peewee import DoesNotExist
from peewee import DatabaseError, DoesNotExist, IntegrityError
from playhouse.shortcuts import model_to_dict
from frigate.api.auth import (
@@ -70,6 +72,7 @@ from frigate.record.export import (
DEFAULT_TIME_LAPSE_FFMPEG_ARGS,
ChaptersEnum,
PlaybackSourceEnum,
export_video_path,
validate_ffmpeg_args,
)
from frigate.util.path import sanitize_contained_path
@@ -403,14 +406,17 @@ class _StreamingZipBuffer:
def _unique_archive_name(export: Export, used: set[str]) -> str:
base = sanitize_filename(export.name) if export.name else None
if not base:
base = f"{export.camera}_{int(export.date)}"
"""Zip entry name for an export, de-duplicated within the archive.
The on-disk name is the one the user sees either way: renaming an export
renames its file, so a zip entry and an individual download can't drift.
"""
source = Path(export.video_path)
candidate = source.name
candidate = f"{base}.mp4"
counter = 1
while candidate in used:
candidate = f"{base}_{counter}.mp4"
candidate = f"{source.stem}_{counter}{source.suffix}"
counter += 1
used.add(candidate)
@@ -908,8 +914,59 @@ async def export_rename(event_id: str, body: ExportRenameBody, request: Request)
status_code=404,
)
if export.in_progress:
return JSONResponse(
content={
"success": False,
"message": "Export is still being written and can't be renamed yet.",
},
status_code=400,
)
new_path = export_video_path(body.name, export.id)
old_path = export.video_path
moved = new_path != old_path
# move the file first so a rename that can't happen leaves the row alone
if moved:
try:
os.rename(old_path, new_path)
except OSError:
logger.exception("Failed to rename export file for %s", event_id)
return JSONResponse(
content={"success": False, "message": "Failed to rename export."},
status_code=500,
)
export.name = body.name
export.save()
export.video_path = new_path
try:
export.save()
except DatabaseError as err:
# the queue database has no transactions, so undo the move by hand
if moved:
with contextlib.suppress(OSError):
os.rename(new_path, old_path)
if isinstance(err, IntegrityError):
logger.warning(
"Export %s cannot be renamed, %s is taken", event_id, new_path
)
return JSONResponse(
content={
"success": False,
"message": "Another export already uses that name.",
},
status_code=409,
)
logger.exception("Failed to save renamed export %s", event_id)
return JSONResponse(
content={"success": False, "message": "Failed to rename export."},
status_code=500,
)
return JSONResponse(
content=(
{
+27
View File
@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends
from frigate.api.auth import require_role
from frigate.api.defs.tags import Tags
from frigate.detectors.hardware import DetectionHardware, hardware_prober
from frigate.util.hwaccel import HwaccelRecommendation, hwaccel_options
logger = logging.getLogger(__name__)
@@ -28,3 +29,29 @@ def probe_hardware(refresh: bool = False) -> list[DetectionHardware]:
Every kind of detection hardware that was found
"""
return hardware_prober.probe(refresh=refresh)
@router.get(
"/hardware/hwaccel",
response_model=HwaccelRecommendation,
dependencies=[Depends(require_role(["admin"]))],
)
def hwaccel_recommendation(
detector: str | None = None, codecs: str | None = None
) -> HwaccelRecommendation:
"""Get the hardware decoding this system can do.
Args:
detector: Hardware key of the detection hardware in use, which biases
the recommendation toward that hardware's GPU
codecs: Comma separated codecs of the streams that will be decoded,
used to drop families that cannot decode one of them
Returns:
The recommended family (empty when none fits) and every usable family
"""
wanted = {
codec.strip().lower() for codec in (codecs or "").split(",") if codec.strip()
}
recommended, available = hwaccel_options(detector, wanted)
return HwaccelRecommendation(recommended=recommended, available=available)
+9 -2
View File
@@ -1060,7 +1060,7 @@ async def event_thumbnail(
except DoesNotExist:
thumbnail_bytes = None
if thumbnail_bytes is None:
if not thumbnail_bytes:
# see if the object is currently being tracked
try:
camera_states = request.app.detected_frames_processor.get_camera_states()
@@ -1076,7 +1076,7 @@ async def event_thumbnail(
status_code=404,
)
if thumbnail_bytes is None:
if not thumbnail_bytes:
return JSONResponse(
content={"success": False, "message": "Event not found"},
status_code=404,
@@ -1085,6 +1085,13 @@ async def event_thumbnail(
img_as_np = np.frombuffer(thumbnail_bytes, dtype=np.uint8)
img = cv2.imdecode(img_as_np, flags=1)
if img is None:
# thumbnail on disk is truncated or corrupt
return JSONResponse(
content={"success": False, "message": "Event not found"},
status_code=404,
)
# android notifications prefer a 2:1 ratio
if format == "android":
img = cv2.copyMakeBorder(
+22 -1
View File
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import Any
import pytz # type: ignore[import-untyped]
from pathvalidate import sanitize_filename
from peewee import DoesNotExist
from frigate.config import FfmpegConfig, FrigateConfig
@@ -204,6 +205,22 @@ class PlaybackSourceEnum(str, Enum):
preview = "preview"
EXPORT_FILE_NAME_MAX_BYTES = 255
def export_video_path(name: str, export_id: str) -> str:
"""Path an export's video is stored at once the user has named it.
The id suffix keeps the path unique when two exports share a name, and
keeps the result a single path component whatever the user typed.
"""
suffix = f"_{export_id.split('_')[-1]}.mp4"
budget = EXPORT_FILE_NAME_MAX_BYTES - len(suffix.encode())
stem = sanitize_filename(name).encode()[:budget].decode(errors="ignore")
return os.path.join(EXPORT_DIR, f"{stem.strip('. ') or 'export'}{suffix}")
class RecordingExporter(threading.Thread):
"""Exports a specific set of recordings for a camera to storage as a single file."""
@@ -917,7 +934,11 @@ class RecordingExporter(threading.Thread):
"%Y%m%d_%H%M%S"
)
cleaned_export_id = self.export_id.split("_")[-1]
video_path = f"{EXPORT_DIR}/{self.camera}_{filename_start_datetime}-{filename_end_datetime}_{cleaned_export_id}.mp4"
if self.user_provided_name:
video_path = export_video_path(self.user_provided_name, self.export_id)
else:
video_path = f"{EXPORT_DIR}/{self.camera}_{filename_start_datetime}-{filename_end_datetime}_{cleaned_export_id}.mp4"
thumb_path = self.save_thumbnail(self.export_id)
export_values = {
@@ -1,189 +0,0 @@
"""Tests for GET /classification/attributes."""
import os
import shutil
import unittest
from frigate.api.auth import get_allowed_cameras_for_filter
from frigate.const import CLIPS_DIR
from frigate.models import Event, Recordings, ReviewSegment
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
# "limited_user" only reaches front_door, so it never sees the values that were
# recorded on back_door.
_CONFIG = {
"mqtt": {"host": "mqtt"},
"auth": {"roles": {"limited_user": ["front_door"]}},
"classification": {
"custom": {
"delivery_service": {
"enabled": True,
"object_config": {
"objects": ["car"],
"classification_type": "attribute",
},
}
}
},
"cameras": {
"front_door": {
"ffmpeg": {
"inputs": [{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
},
"back_door": {
"ffmpeg": {
"inputs": [{"path": "rtsp://10.0.0.2:554/video", "roles": ["detect"]}]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
},
},
}
class TestClassificationAttributesAccess(BaseTestHttp):
"""The attribute list is read from the training dataset on disk, which holds
every label a model can emit regardless of which camera recorded it. Callers
without full camera access are cut back to the values on their own cameras,
so these tests pin that scoping.
"""
def setUp(self):
super().setUp([Event, ReviewSegment, Recordings])
self.minimal_config = _CONFIG
self.app = super().create_app()
self.model_dir = os.path.join(CLIPS_DIR, "delivery_service")
for category in ("DHL", "Amazon", "Hermes", "none"):
os.makedirs(
os.path.join(self.model_dir, "dataset", category), exist_ok=True
)
def tearDown(self):
shutil.rmtree(self.model_dir, ignore_errors=True)
self.app.dependency_overrides.clear()
super().tearDown()
def _insert_event(self, event_id: str, camera: str, attribute: str | None):
data = {"type": "object", "score": 0.9}
if attribute is not None:
data["delivery_service"] = attribute
Event.insert(
id=event_id,
label="car",
camera=camera,
start_time=100,
end_time=200,
top_score=0.9,
score=0.9,
false_positive=False,
zones=[],
thumbnail="",
has_clip=True,
has_snapshot=True,
region=[],
box=[],
area=0,
retain_indefinitely=False,
ratio=1.0,
plus_id=None,
model_hash="",
detector_type="cpu",
model_type="ssd",
data=data,
).execute()
def _get(self, role: str, **params):
# the base class resolves every camera by default, so drop the override
# to exercise the real role to allowed-cameras resolution
self.app.dependency_overrides.pop(get_allowed_cameras_for_filter, None)
with AuthTestClient(self.app) as client:
return client.get(
"/classification/attributes",
params=params,
headers={"remote-user": "test", "remote-role": role},
)
def _insert_split_events(self):
self._insert_event("front", "front_door", "DHL")
self._insert_event("back", "back_door", "Amazon")
def test_admin_gets_every_trained_label(self):
self._insert_split_events()
assert self._get("admin").json() == ["Amazon", "DHL", "Hermes"]
def test_viewer_gets_every_trained_label(self):
self._insert_split_events()
assert self._get("viewer").json() == ["Amazon", "DHL", "Hermes"]
def test_restricted_role_only_gets_its_own_cameras(self):
self._insert_split_events()
assert self._get("limited_user").json() == ["DHL"]
def test_restricted_role_grouped_by_model(self):
self._insert_split_events()
assert self._get("limited_user", group_by_model="true").json() == {
"delivery_service": ["DHL"]
}
def test_restricted_role_with_no_recorded_values(self):
self._insert_event("back", "back_door", "Amazon")
assert self._get("limited_user").json() == []
assert self._get("limited_user", group_by_model="true").json() == {}
def test_restricted_role_ignores_events_without_the_attribute(self):
self._insert_event("front", "front_door", None)
assert self._get("limited_user").json() == []
def test_restricted_role_with_a_dotted_model_name(self):
# model names are unrestricted config keys, and an unquoted "." in the
# json path would be read as a nested lookup and match nothing
self.app.frigate_config.classification.custom["delivery.service"] = (
self.app.frigate_config.classification.custom.pop("delivery_service")
)
self.app.frigate_config.classification.custom[
"delivery.service"
].name = "delivery.service"
os.rename(self.model_dir, os.path.join(CLIPS_DIR, "delivery.service"))
self.model_dir = os.path.join(CLIPS_DIR, "delivery.service")
data = {"type": "object", "score": 0.9, "delivery.service": "DHL"}
Event.insert(
id="front",
label="car",
camera="front_door",
start_time=100,
end_time=200,
top_score=0.9,
score=0.9,
false_positive=False,
zones=[],
thumbnail="",
has_clip=True,
has_snapshot=True,
region=[],
box=[],
area=0,
retain_indefinitely=False,
ratio=1.0,
plus_id=None,
model_hash="",
detector_type="cpu",
model_type="ssd",
data=data,
).execute()
assert self._get("limited_user").json() == ["DHL"]
def test_object_type_filters_out_unrelated_models(self):
self._insert_split_events()
assert self._get("limited_user", object_type="person").json() == []
assert self._get("limited_user", object_type="car").json() == ["DHL"]
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -366,6 +366,91 @@ class TestHttpExport(BaseTestHttp):
assert response.status_code == 200
assert response.json() == [queued_job.to_dict()]
def test_rename_export_moves_the_file(self):
with tempfile.TemporaryDirectory() as tmpdir:
video = os.path.join(tmpdir, "front_door_20260823_020615_abc123.mp4")
thumb = os.path.join(tmpdir, "front_door_abc123.webp")
for path, data in ((video, b"video"), (thumb, b"thumb")):
with open(path, "wb") as handle:
handle.write(data)
Export.create(
id="front_door_abc123",
camera="front_door",
name="front door 2026-08-23 02:06:15 2026-08-23 02:07:34",
date=100,
video_path=video,
thumb_path=thumb,
in_progress=False,
)
with patch("frigate.record.export.EXPORT_DIR", tmpdir):
with AuthTestClient(self.app) as client:
response = client.patch(
"/export/front_door_abc123/rename",
json={"name": "Package thief"},
)
assert response.status_code == 200
renamed = Export.get(Export.id == "front_door_abc123")
assert renamed.name == "Package thief"
assert os.path.basename(renamed.video_path) == "Package thief_abc123.mp4"
assert os.path.exists(renamed.video_path)
assert not os.path.exists(video)
def test_rename_export_rejected_while_in_progress(self):
with tempfile.TemporaryDirectory() as tmpdir:
video = os.path.join(tmpdir, "front_door_abc123.mp4")
with open(video, "wb") as handle:
handle.write(b"video")
Export.create(
id="front_door_running",
camera="front_door",
name="front door export",
date=100,
video_path=video,
thumb_path=os.path.join(tmpdir, "t.webp"),
in_progress=True,
)
with AuthTestClient(self.app) as client:
response = client.patch(
"/export/front_door_running/rename",
json={"name": "Package thief"},
)
assert response.status_code == 400
assert Export.get(Export.id == "front_door_running").video_path == video
def test_rename_export_missing_file_leaves_the_row_alone(self):
with tempfile.TemporaryDirectory() as tmpdir:
video = os.path.join(tmpdir, "front_door_gone_abc123.mp4")
Export.create(
id="front_door_gone",
camera="front_door",
name="front door export",
date=100,
video_path=video,
thumb_path=os.path.join(tmpdir, "t.webp"),
in_progress=False,
)
with patch("frigate.record.export.EXPORT_DIR", tmpdir):
with AuthTestClient(self.app) as client:
response = client.patch(
"/export/front_door_gone/rename",
json={"name": "Package thief"},
)
assert response.status_code == 500
unchanged = Export.get(Export.id == "front_door_gone")
assert unchanged.name == "front door export"
assert unchanged.video_path == video
def test_reap_stale_exports_deletes_rows_with_no_file(self):
with tempfile.TemporaryDirectory() as tmpdir:
stale_video = os.path.join(tmpdir, "stale.mp4")
+81 -1
View File
@@ -1,6 +1,9 @@
import unittest
from pathlib import Path
from frigate.record.export import validate_ffmpeg_args
from frigate.api.export import _unique_archive_name
from frigate.models import Export
from frigate.record.export import export_video_path, validate_ffmpeg_args
class TestValidateFfmpegArgs(unittest.TestCase):
@@ -128,5 +131,82 @@ class TestValidateFfmpegArgs(unittest.TestCase):
self.assertRejected("-metadata comment=x")
class TestExportVideoPath(unittest.TestCase):
"""Tests for the file path an export takes once the user names it."""
EXPORT_ID = "front_door_abc123"
def test_uses_the_name_the_user_gave(self):
self.assertEqual(
export_video_path("Package thief", self.EXPORT_ID),
"/media/frigate/exports/Package thief_abc123.mp4",
)
def test_id_suffix_keeps_shared_names_apart(self):
self.assertNotEqual(
export_video_path("clip", "front_door_abc123"),
export_video_path("clip", "front_door_def456"),
)
def test_long_names_fit_the_filesystem_limit(self):
# Names are capped in bytes, not characters: 244 CJK characters is
# under any character cap and still 732 bytes on disk.
for name in ("A" * 256, "\u76e3" * 256, "\U0001f3a5" * 100):
file_name = Path(export_video_path(name, self.EXPORT_ID)).name
self.assertLessEqual(len(file_name.encode()), 255)
def test_truncation_keeps_the_name_decodable(self):
file_name = Path(export_video_path("\u76e3" * 256, self.EXPORT_ID)).name
self.assertTrue(file_name.endswith("_abc123.mp4"))
self.assertNotIn("\ufffd", file_name)
def test_stays_inside_the_export_dir(self):
for name in ("../../etc/passwd", "..", "a/b", "...", ""):
path = Path(export_video_path(name, self.EXPORT_ID))
self.assertEqual(str(path.parent), "/media/frigate/exports")
class TestUniqueArchiveName(unittest.TestCase):
"""Tests for zip entry names in a case download.
Entries use the on-disk file name, which is also what an individual
download produces, so the two can't drift.
"""
def build_export(self, video_path: str) -> Export:
return Export(
id="front_door_abc123",
camera="front_door",
name="whatever the display name is",
date=1756000000.0,
video_path=video_path,
thumb_path=video_path.replace(".mp4", ".webp"),
in_progress=False,
)
def test_uses_the_on_disk_file_name(self):
export = self.build_export(
"/media/frigate/exports/front_door_20260823_020615-20260823_020734_abc123.mp4"
)
self.assertEqual(
_unique_archive_name(export, set()),
"front_door_20260823_020615-20260823_020734_abc123.mp4",
)
def test_follows_a_renamed_file(self):
export = self.build_export("/media/frigate/exports/Package thief_abc123.mp4")
self.assertEqual(
_unique_archive_name(export, set()), "Package thief_abc123.mp4"
)
def test_entries_are_deduplicated(self):
export = self.build_export("/media/frigate/exports/Package thief_abc123.mp4")
used: set[str] = set()
self.assertEqual(_unique_archive_name(export, used), "Package thief_abc123.mp4")
self.assertEqual(
_unique_archive_name(export, used), "Package thief_abc123_1.mp4"
)
if __name__ == "__main__":
unittest.main()
+16
View File
@@ -70,3 +70,19 @@ class TestFileUtils(TestCase):
assert rendered_image is not None
assert rendered_image.shape[0] == 40
assert rendered_image.max() > 0
def test_get_event_thumbnail_bytes_ignores_empty_file(self):
"""Verify empty thumbnail files are treated as missing."""
event = SimpleNamespace(id="empty-thumb", camera="front_door", thumbnail=None)
with (
tempfile.TemporaryDirectory() as thumb_dir,
patch.object(file_util, "THUMB_DIR", thumb_dir),
):
camera_dir = os.path.join(thumb_dir, event.camera)
os.makedirs(camera_dir)
with open(os.path.join(camera_dir, f"{event.id}.webp"), "wb"):
pass
assert file_util.get_event_thumbnail_bytes(event) is None
+225
View File
@@ -0,0 +1,225 @@
"""Tests for the hardware decoding recommendation."""
import os
import tempfile
import unittest
from unittest.mock import patch
from frigate.detectors.hardware import DetectionHardware
from frigate.util import hwaccel
def found(key: str) -> DetectionHardware:
"""A probe result carrying only the fields the recommendation reads."""
return DetectionHardware(
key=key,
detector=key.partition(":")[0],
name=key,
units=[],
count=0,
unlimited=True,
)
class HwaccelRecommendationTestCase(unittest.TestCase):
"""Points every read at an empty fixture tree, so nothing is found by default."""
def setUp(self):
self.root = tempfile.TemporaryDirectory()
self.addCleanup(self.root.cleanup)
self.proc_root = os.path.join(self.root.name, "proc")
os.makedirs(self.proc_root)
patcher = patch.object(hwaccel, "PROC_ROOT", self.proc_root)
patcher.start()
self.addCleanup(patcher.stop)
drm = patch.object(hwaccel, "enumerate_drm_devices", return_value={})
self.drm = drm.start()
self.addCleanup(drm.stop)
def options(self, keys=(), detector_key=None, codecs=None):
"""Run the recommendation against a fixed set of hardware keys."""
with patch.object(
hwaccel.hardware_prober,
"probe",
return_value=[found(key) for key in keys],
):
return hwaccel.hwaccel_options(detector_key, codecs)
def recommend(self, keys=(), detector_key=None, codecs=None) -> str:
"""The recommended family key."""
return self.options(keys, detector_key, codecs)[0]
def available(self, keys=(), detector_key=None, codecs=None) -> list[str]:
"""The keys of the usable families, best first."""
return [family.key for family in self.options(keys, detector_key, codecs)[1]]
def presets(self, keys=(), detector_key=None, codecs=None) -> dict:
"""The presets each usable family provides."""
return {
family.key: family.presets
for family in self.options(keys, detector_key, codecs)[1]
}
def write_cpuinfo(self, model_name: str) -> None:
with open(os.path.join(self.proc_root, "cpuinfo"), "w") as f:
f.write(f"processor\t: 0\nmodel name\t: {model_name}\n")
def write_device_tree(self) -> None:
os.makedirs(os.path.join(self.proc_root, "device-tree"), exist_ok=True)
with open(os.path.join(self.proc_root, "device-tree", "compatible"), "w") as f:
f.write("raspberrypi,5-model-b\x00brcm,bcm2712\x00")
class TestPriority(HwaccelRecommendationTestCase):
def test_nothing_found_recommends_nothing(self):
self.assertEqual(self.recommend(), "")
def test_nvidia_wins_over_intel(self):
self.assertEqual(self.recommend(["onnx:nvidia", "openvino:GPU"]), "nvidia")
def test_a_jetson_uses_its_own_family(self):
self.assertEqual(self.recommend(["tensorrt"]), "jetson")
def test_a_rockchip_uses_rkmpp(self):
self.assertEqual(self.recommend(["rknn"]), "rkmpp")
def test_an_amd_gpu_uses_vaapi(self):
self.assertEqual(self.recommend(["onnx:amd"]), "vaapi")
class TestDetectorBias(HwaccelRecommendationTestCase):
def test_a_chosen_intel_gpu_beats_a_present_nvidia(self):
self.assertEqual(
self.recommend(["onnx:nvidia", "openvino:GPU"], "openvino:GPU"), "vaapi"
)
def test_a_chosen_npu_decodes_through_the_igpu(self):
self.assertEqual(
self.recommend(["openvino:NPU", "openvino:GPU"], "openvino:NPU"), "vaapi"
)
def test_an_npu_without_an_igpu_falls_through(self):
self.assertEqual(self.recommend(["openvino:NPU"], "openvino:NPU"), "")
def test_a_cpu_choice_still_recommends_the_present_gpu(self):
self.assertEqual(self.recommend(["cpu", "openvino:GPU"], "cpu"), "vaapi")
class TestIntelGeneration(HwaccelRecommendationTestCase):
def test_the_xe_driver_prefers_qsv(self):
self.drm.return_value = {"0000:00:02.0": "xe"}
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "intel-qsv")
def test_gen13_prefers_qsv(self):
self.write_cpuinfo("13th Gen Intel(R) Core(TM) i5-13500")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "intel-qsv")
def test_a_core_ultra_prefers_qsv(self):
self.write_cpuinfo("Intel(R) Core(TM) Ultra 7 155H")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "intel-qsv")
def test_gen13_prefers_qsv_for_mixed_codecs(self):
# each camera resolves the family to its own codec
self.write_cpuinfo("13th Gen Intel(R) Core(TM) i5-13500")
self.assertEqual(
self.recommend(["openvino:GPU"], codecs={"h264", "h265"}), "intel-qsv"
)
def test_gen12_prefers_vaapi(self):
self.write_cpuinfo("12th Gen Intel(R) Core(TM) i5-12400")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "vaapi")
def test_gen12_still_offers_qsv(self):
self.write_cpuinfo("12th Gen Intel(R) Core(TM) i5-12400")
self.assertEqual(self.available(["openvino:GPU"]), ["vaapi", "intel-qsv"])
def test_an_older_model_string_prefers_vaapi(self):
self.write_cpuinfo("Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz")
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "vaapi")
def test_missing_cpuinfo_prefers_vaapi(self):
self.assertEqual(self.recommend(["openvino:GPU"], codecs={"h264"}), "vaapi")
def test_qsv_is_not_offered_before_gen8(self):
self.write_cpuinfo("7th Gen Intel(R) Core(TM) i5-7500")
self.assertEqual(self.available(["openvino:GPU"]), ["vaapi"])
class TestUnknownCodecs(HwaccelRecommendationTestCase):
def test_a_codec_agnostic_family_wins_when_no_codec_is_known(self):
# a qsv preset would have to guess a codec for cameras added later
self.drm.return_value = {"0000:00:02.0": "xe"}
self.assertEqual(self.recommend(["openvino:GPU"]), "vaapi")
def test_hardware_with_no_agnostic_family_still_recommends(self):
self.assertEqual(self.recommend(["tensorrt"]), "jetson")
class TestAvailableFamilies(HwaccelRecommendationTestCase):
def test_nothing_found_offers_nothing(self):
self.assertEqual(self.available(), [])
def test_only_families_the_hardware_can_use_are_offered(self):
self.assertEqual(self.available(["onnx:nvidia"]), ["nvidia"])
def test_a_pi_does_not_offer_desktop_gpu_families(self):
self.write_device_tree()
self.assertEqual(self.available(), ["rpi"])
def test_an_intel_system_does_not_offer_the_pi_family(self):
offered = self.available(["openvino:GPU"])
self.assertIn("vaapi", offered)
self.assertNotIn("rpi", offered)
self.assertNotIn("nvidia", offered)
def test_every_gpu_present_is_offered(self):
offered = self.available(["onnx:nvidia", "openvino:GPU"])
self.assertEqual(offered[0], "nvidia")
self.assertIn("vaapi", offered)
def test_a_gpu_wins_over_the_pi_fallback(self):
self.write_device_tree()
self.assertEqual(self.recommend(["onnx:nvidia"]), "nvidia")
def test_the_recommendation_is_always_offered(self):
recommended, families = self.options(["openvino:GPU"], codecs={"h264"})
self.assertIn(recommended, [family.key for family in families])
class TestCodecCoverage(HwaccelRecommendationTestCase):
def test_a_family_carries_a_preset_per_codec(self):
self.assertEqual(
self.presets(["tensorrt"])["jetson"],
{"h264": "preset-jetson-h264", "h265": "preset-jetson-h265"},
)
def test_a_codec_agnostic_family_carries_one_preset(self):
self.assertEqual(
self.presets(["onnx:nvidia"])["nvidia"], {"any": "preset-nvidia"}
)
def test_hevc_is_treated_as_h265(self):
self.assertEqual(self.available(["tensorrt"], codecs={"hevc"}), ["jetson"])
def test_a_family_that_cannot_decode_a_codec_is_dropped(self):
# a jetson decodes h264 and h265 only, so an mjpeg camera rules it out
self.assertEqual(self.available(["tensorrt"], codecs={"mjpeg"}), [])
def test_codec_agnostic_families_survive_any_codec(self):
self.assertEqual(
self.available(["onnx:nvidia"], codecs={"mjpeg", "h265"}), ["nvidia"]
)
def test_a_dropped_family_hands_off_to_the_next_hardware(self):
self.assertEqual(
self.recommend(["tensorrt", "onnx:nvidia"], codecs={"mjpeg"}), "nvidia"
)
if __name__ == "__main__":
unittest.main()
+11 -1
View File
@@ -79,10 +79,20 @@ def redact_credential(obj: dict[str, Any], key: str) -> None:
def find_config_file() -> str:
"""Return the path of the config file to use.
Both .yml and .yaml are supported, so fall back to the other extension when
the configured path does not exist. If neither exists the configured path is
returned so a new config is created with the default .yml extension.
"""
config_path = os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE)
if not os.path.isfile(config_path):
config_path = config_path.replace("yml", "yaml")
base, ext = os.path.splitext(config_path)
alternate = f"{base}.yaml" if ext == ".yml" else f"{base}.yml"
if os.path.isfile(alternate):
return alternate
return config_path
+3 -2
View File
@@ -20,14 +20,15 @@ logger = logging.getLogger(__name__)
def get_event_thumbnail_bytes(event: Event) -> bytes | None:
# callers treat empty bytes as a valid image, so normalize them to None
if event.thumbnail:
return base64.b64decode(event.thumbnail)
return base64.b64decode(event.thumbnail) or None
else:
try:
with open(
os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp"), "rb"
) as f:
return f.read()
return f.read() or None
except Exception:
return None
+273
View File
@@ -0,0 +1,273 @@
"""Recommendation of ffmpeg hwaccel presets from the hardware on the system.
Every check is a filesystem read, like the detection hardware probes, so this
is cheap enough to serve from the API process.
Presets are grouped into families because some of them only decode the codec
they name. A family hides that: callers pick the family their hardware needs
and resolve it per camera against that camera's detect stream.
"""
import logging
import re
from pydantic import BaseModel, Field
from frigate.const import (
FFMPEG_HWACCEL_NVIDIA,
FFMPEG_HWACCEL_RKMPP,
FFMPEG_HWACCEL_VAAPI,
)
from frigate.detectors.hardware import hardware_prober
from frigate.util.services import enumerate_drm_devices
logger = logging.getLogger(__name__)
# root the /proc reads use, so tests can point them at a fixture tree
PROC_ROOT = "/proc"
ANY_CODEC = "any"
# a Raspberry Pi has no detection hardware of its own, so it gets a key here
RASPBERRY_PI = "raspberrypi"
# ffprobe names h265 streams hevc
CODEC_ALIASES = {"hevc": "h265"}
# e.g. "13th Gen Intel(R) Core(TM) i5-13500"
INTEL_GEN_PATTERN = re.compile(r"(\d+)th Gen")
# Core Ultra dropped the generation prefix and is newer than all of them
INTEL_ULTRA_PATTERN = re.compile(r"Core\(TM\) Ultra")
INTEL_GEN_LATEST = 99
# per the hwaccel docs, gen13+ and Arc prefer qsv while older is safest on
# vaapi, and qsv is not supported at all before gen8
INTEL_QSV_MIN_GEN = 13
INTEL_QSV_SUPPORTED_GEN = 8
# decode capable detection hardware, in recommendation priority order
DECODE_HARDWARE = (
"onnx:nvidia",
"tensorrt",
"rknn",
"openvino:GPU",
"onnx:amd",
RASPBERRY_PI,
)
class HwaccelFamily(BaseModel):
"""A kind of hardware decoding, and the presets that drive it."""
key: str = Field(
title="Family key",
description="Stable identifier for this kind of hardware decoding.",
)
presets: dict[str, str] = Field(
title="Presets",
description="The ffmpeg preset for each codec this family decodes, or a single 'any' preset when it decodes every codec.",
)
class HwaccelRecommendation(BaseModel):
"""The hardware decoding this system can do."""
recommended: str = Field(
title="Recommended family",
description="Key of the family that fits this system best, or an empty string when none does.",
)
available: list[HwaccelFamily] = Field(
default_factory=list,
title="Available families",
description="Every family this system's hardware can use, best first.",
)
FAMILY_NVIDIA = HwaccelFamily(key="nvidia", presets={ANY_CODEC: FFMPEG_HWACCEL_NVIDIA})
FAMILY_VAAPI = HwaccelFamily(key="vaapi", presets={ANY_CODEC: FFMPEG_HWACCEL_VAAPI})
FAMILY_RKMPP = HwaccelFamily(key="rkmpp", presets={ANY_CODEC: FFMPEG_HWACCEL_RKMPP})
FAMILY_QSV = HwaccelFamily(
key="intel-qsv",
presets={"h264": "preset-intel-qsv-h264", "h265": "preset-intel-qsv-h265"},
)
FAMILY_JETSON = HwaccelFamily(
key="jetson",
presets={"h264": "preset-jetson-h264", "h265": "preset-jetson-h265"},
)
FAMILY_RPI = HwaccelFamily(
key="rpi",
presets={"h264": "preset-rpi-64-h264", "h265": "preset-rpi-64-h265"},
)
def _read(path: str) -> str | None:
"""Read a small file, returning None if it cannot be read."""
try:
with open(path) as f:
return f.read().strip()
except OSError:
return None
def _intel_generation() -> int | None:
"""The Intel platform generation, or None when it cannot be determined."""
# the xe driver only binds to the newest platforms (Arc and later iGPUs)
if "xe" in enumerate_drm_devices().values():
return INTEL_GEN_LATEST
cpuinfo = _read(f"{PROC_ROOT}/cpuinfo") or ""
for line in cpuinfo.splitlines():
if not line.startswith("model name"):
continue
match = INTEL_GEN_PATTERN.search(line)
if match:
return int(match.group(1))
if INTEL_ULTRA_PATTERN.search(line):
return INTEL_GEN_LATEST
break
return None
def _is_raspberry_pi() -> bool:
compatible = _read(f"{PROC_ROOT}/device-tree/compatible") or ""
return "raspberrypi" in compatible
def _intel_families(generation: int | None) -> list[HwaccelFamily]:
"""vaapi drives every Intel GPU, qsv only those from gen8 on."""
if generation is not None and generation < INTEL_QSV_SUPPORTED_GEN:
return [FAMILY_VAAPI]
if generation is not None and generation >= INTEL_QSV_MIN_GEN:
return [FAMILY_QSV, FAMILY_VAAPI]
return [FAMILY_VAAPI, FAMILY_QSV]
def _families(key: str, generation: int | None) -> list[HwaccelFamily]:
"""Every family that can decode on this hardware, best first."""
if key == "onnx:nvidia":
return [FAMILY_NVIDIA]
if key == "tensorrt":
return [FAMILY_JETSON]
if key == "rknn":
return [FAMILY_RKMPP]
if key == "onnx:amd":
return [FAMILY_VAAPI]
if key == RASPBERRY_PI:
return [FAMILY_RPI]
if key == "openvino:GPU":
return _intel_families(generation)
return []
def _decodes(family: HwaccelFamily, codecs: set[str]) -> bool:
"""Whether a family can decode every codec that is in use."""
if ANY_CODEC in family.presets:
return True
return all(codec in family.presets for codec in codecs)
def _decode_hardware(detector_key: str | None) -> list[str]:
"""Decode capable hardware on this system, best first.
Args:
detector_key: Hardware key of the detection hardware in use, whose GPU
is preferred over any other
Returns:
The hardware keys that can decode video, in recommendation order
"""
present = {found.key for found in hardware_prober.probe()}
if _is_raspberry_pi():
present.add(RASPBERRY_PI)
# an Intel NPU decodes through the iGPU next to it
if detector_key == "openvino:NPU":
detector_key = "openvino:GPU"
ordered = [key for key in DECODE_HARDWARE if key in present]
if detector_key in ordered:
ordered.remove(detector_key)
ordered.insert(0, detector_key)
return ordered
def hwaccel_options(
detector_key: str | None = None, codecs: set[str] | None = None
) -> tuple[str, list[HwaccelFamily]]:
"""Get the hardware decoding this system can do.
Args:
detector_key: Hardware key of the detection hardware in use, which
biases the recommendation toward that hardware's GPU
codecs: Codecs of the streams that will be decoded, used to drop
families that cannot decode one of them
Returns:
The recommended family key (empty when none fits) and every usable
family, best first
"""
wanted = {CODEC_ALIASES.get(codec, codec) for codec in codecs or set()}
hardware = _decode_hardware(detector_key)
generation = _intel_generation() if "openvino:GPU" in hardware else None
available: list[HwaccelFamily] = []
recommended = ""
for key in hardware:
usable = [
family for family in _families(key, generation) if _decodes(family, wanted)
]
if usable and not recommended:
recommended = _recommend(usable, bool(wanted))
for family in usable:
if family.key not in {entry.key for entry in available}:
available.append(family)
return recommended, available
def _recommend(families: list[HwaccelFamily], codecs_known: bool) -> str:
"""Pick the family to default to out of the ones this hardware can use."""
if not codecs_known:
# a codec specific family would have to guess a codec for cameras
# that do not exist yet
for family in families:
if ANY_CODEC in family.presets:
return family.key
return families[0].key
def recommend_hwaccel(
detector_key: str | None = None, codecs: set[str] | None = None
) -> str:
"""Recommend a hardware decoding family for this system.
Args:
detector_key: Hardware key of the detection hardware in use
codecs: Codecs of the streams that will be decoded
Returns:
The key of the family that fits, or an empty string when none does
"""
return hwaccel_options(detector_key, codecs)[0]
+26
View File
@@ -43,6 +43,11 @@ export interface ApiMockOverrides {
configRaw?: string;
configSchema?: Record<string, unknown>;
hardware?: unknown[];
hwaccel?: {
recommended: string;
available?: { key: string; presets: Record<string, string> }[];
};
users?: { username: string; role: string }[];
}
export class ApiMocker {
@@ -185,6 +190,27 @@ export class ApiMocker {
route.fulfill({ json: overrides?.hardware ?? DETECTION_HARDWARE }),
);
// Hwaccel preset recommendation
await this.page.route("**/api/hardware/hwaccel**", (route) =>
route.fulfill({
json: {
recommended: "",
available: [],
...(overrides?.hwaccel ?? {}),
},
}),
);
// Users. GET lists them; POST/PUT (create, password) just succeed, so
// tests assert on the intercepted request body instead of a response.
await this.page.route("**/api/users**", (route) =>
route.request().method() === "GET"
? route.fulfill({
json: overrides?.users ?? [{ username: "admin", role: "admin" }],
})
: route.fulfill({ json: { message: "ok" } }),
);
// Go2RTC streams
await this.page.route("**/api/go2rtc/streams**", (route) =>
route.fulfill({ json: {} }),
+51
View File
@@ -0,0 +1,51 @@
/**
* Shared setup-wizard e2e helpers.
*
* The wizard shows when config has no cameras, so a first run is mocked by
* serving a camera-less config until the returned callback is fired. Firing
* it is only needed by tests that care what the rest of the app sees; the
* wizard itself tracks added cameras from the camera dialog's own callback.
*/
import type { Page } from "@playwright/test";
import { expect } from "../fixtures/frigate-test";
import { configFactory } from "../fixtures/mock-data/config";
import type { ApiMockOverrides } from "./api-mocker";
export async function installFirstRun(
frigateApp: { installDefaults: (o?: ApiMockOverrides) => Promise<void> },
page: Page,
overrides?: ApiMockOverrides,
): Promise<() => void> {
await frigateApp.installDefaults(overrides);
const full = configFactory(overrides?.config);
let cameras: unknown = {};
await page.route("**/api/config", (route) => {
if (route.request().method() === "GET") {
return route.fulfill({ json: { ...full, cameras } });
}
return route.fulfill({ json: { success: true } });
});
return () => {
cameras = full.cameras;
};
}
export async function gotoDetectorStep(page: Page) {
await page.getByRole("button", { name: "Get Started" }).click();
// the account step sits between welcome and camera whenever auth is on,
// which the default mock config has it
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Object Detection")).toBeVisible();
}
@@ -0,0 +1,353 @@
/**
* Add-camera wizard - Apple/HEVC compatibility switch on Step 3.
*
* It writes the camera-level `ffmpeg.apple_compatibility` and starts on for
* Apple browsers. That default is user-agent driven, so the second describe
* pins an explicit Safari and Chrome UA instead of relying on the project's
* own.
*
* The save tests drive Step 4, which registers go2rtc streams and renders MSE
* previews; they mock those and assert only the captured config/set body.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page, Locator } from "@playwright/test";
const MAIN_URI = "rtsp://admin:pw@192.168.1.100:554/stream1";
const SUB_URI = "rtsp://admin:pw@192.168.1.100:554/stream2";
const SAFARI_UA =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15";
const CHROME_UA =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const APPLE_TITLE = "Improve playback on Apple devices";
const PROBE = {
success: true,
host: "192.168.1.100",
port: 80,
manufacturer: "Acme",
model: "Cam-1",
firmware_version: "1.0",
profiles_count: 2,
ptz_supported: false,
pan_tilt_supported: false,
presets_count: 0,
autotrack_supported: false,
rtsp_candidates: [
{ source: "GetStreamUri", profile_token: "profile_1", uri: MAIN_URI },
{ source: "GetStreamUri", profile_token: "profile_2", uri: SUB_URI },
],
};
function ffprobeJson(codec: string) {
return [
{
return_code: 0,
stderr: [],
stdout: {
streams: [
{
codec_type: "video",
codec_name: codec,
width: 1920,
height: 1080,
avg_frame_rate: "15/1",
},
{ codec_type: "audio", codec_name: "aac" },
],
},
},
];
}
/** Mock ffprobe per stream URL; a null codec makes that probe fail. */
async function mockFfprobe(
page: Page,
codecByUri: Record<string, string | null>,
) {
await page.route("**/api/ffprobe**", (route) => {
const paths = new URL(route.request().url()).searchParams.get("paths");
const match = Object.keys(codecByUri).find((uri) => paths?.includes(uri));
const codec = match ? codecByUri[match] : null;
return route.fulfill({
json: codec
? ffprobeJson(codec)
: [{ return_code: 1, stderr: ["probe failed"], stdout: "" }],
});
});
}
/** Open the wizard and drive Step 1 -> Step 2 -> Step 3. */
async function gotoStep3(page: Page) {
await page.route("**/api/onvif/probe**", (route) =>
route.fulfill({ json: PROBE }),
);
await page.getByRole("button", { name: /Add New Camera/i }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
await dialog.getByPlaceholder(/front_door/i).fill("hevc_test_camera");
await dialog.getByPlaceholder("192.168.1.100").fill("192.168.1.100");
await dialog.getByRole("button", { name: /^Continue$/i }).click();
const next = dialog.getByRole("button", { name: /^Next$/i });
await expect(next).toBeEnabled({ timeout: 10_000 });
await next.click();
await expect(
dialog.getByRole("button", { name: /Add Another Stream/i }),
).toBeVisible();
return dialog;
}
/** The role toggle for `role` on the nth stream card (0-based). */
function roleSwitch(dialog: Locator, role: string, streamIndex = 0) {
return dialog
.locator("span.capitalize", { hasText: new RegExp(`^${role}$`) })
.nth(streamIndex)
.locator("xpath=..")
.getByRole("switch");
}
/** Run "Test Connection" on the nth stream card and wait for the result. */
async function testStream(dialog: Locator, streamIndex = 0) {
await dialog
.getByRole("button", { name: /Test Connection/i })
.nth(streamIndex)
.click();
await expect(
dialog.getByText("Connected", { exact: true }).nth(streamIndex),
).toBeVisible();
}
/** Run "Test Connection" on the nth stream card and wait for it to fail. */
async function failStream(dialog: Locator, streamIndex: number) {
await dialog
.getByRole("button", { name: /Test Connection/i })
.nth(streamIndex)
.click();
await expect(dialog.getByText("Test Failed", { exact: true })).toBeVisible();
}
function appleSwitch(dialog: Locator) {
return dialog
.locator("div.items-start.justify-between", { hasText: APPLE_TITLE })
.getByRole("switch");
}
async function openCameraManagement(frigateApp: {
page: Page;
goto: (path: string) => Promise<void>;
}) {
// not in the default mock; unmocked it 500s and trips the error collector
await frigateApp.page.route("**/api/config/raw_paths", (route) =>
route.fulfill({ json: {} }),
);
await frigateApp.goto("/settings?page=cameraManagement");
await expect(
frigateApp.page.getByRole("heading", { name: /Manage Cameras/i }),
).toBeVisible();
}
test.describe("Camera wizard Apple compatibility @medium @mobile", () => {
test.beforeEach(async ({ frigateApp }) => {
await openCameraManagement(frigateApp);
});
test("appears only once the record stream is probed as H.265", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "hevc" });
const dialog = await gotoStep3(frigateApp.page);
// the probe leaves the stream untested, so the codec is unknown
await roleSwitch(dialog, "record").click();
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(0);
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toBeVisible();
});
test("stays hidden for an H.264 record stream", async ({ frigateApp }) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "h264" });
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(0);
});
test("stays hidden for an H.265 stream with no recording role", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "hevc" });
const dialog = await gotoStep3(frigateApp.page);
// detect is assigned by default; no record or record_sub role
await testStream(dialog);
await expect(roleSwitch(dialog, "detect")).toBeChecked();
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(0);
});
test("appears for an H.265 record_sub stream", async ({ frigateApp }) => {
await mockFfprobe(frigateApp.page, { [MAIN_URI]: "hevc" });
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record_sub").click();
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toBeVisible();
});
test("renders once when only one recording stream is H.265", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, {
[MAIN_URI]: "hevc",
[SUB_URI]: "h264",
});
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await dialog.getByRole("button", { name: /Add Another Stream/i }).click();
await roleSwitch(dialog, "record_sub", 1).click();
await testStream(dialog, 1);
// ffmpeg drops the tag on the H.264 output, so the H.265 one still wins
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(1);
});
test("stays visible when another recording stream fails to probe", async ({
frigateApp,
}) => {
await mockFfprobe(frigateApp.page, {
[MAIN_URI]: "hevc",
[SUB_URI]: null,
});
const dialog = await gotoStep3(frigateApp.page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await expect(dialog.getByText(APPLE_TITLE)).toBeVisible();
await dialog.getByRole("button", { name: /Add Another Stream/i }).click();
await roleSwitch(dialog, "record_sub", 1).click();
await failStream(dialog, 1);
await expect(dialog.getByText(APPLE_TITLE)).toHaveCount(1);
});
});
test.describe("Camera wizard Apple compatibility default @medium @mobile", () => {
test.describe("on an Apple browser", () => {
test.use({ userAgent: SAFARI_UA });
test.beforeEach(async ({ frigateApp }) => {
await openCameraManagement(frigateApp);
});
test("starts on for an H.265 record stream and is saved", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: true,
toggle: false,
});
expect(ffmpeg.apple_compatibility).toBe(true);
});
test("can still be turned off, which omits it from the save", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: true,
toggle: true,
});
expect(ffmpeg).not.toHaveProperty("apple_compatibility");
});
});
test.describe("on a non-Apple browser", () => {
test.use({ userAgent: CHROME_UA });
test.beforeEach(async ({ frigateApp }) => {
await openCameraManagement(frigateApp);
});
test("starts off and is omitted so the global applies", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: false,
toggle: false,
});
expect(ffmpeg).not.toHaveProperty("apple_compatibility");
});
test("can be turned on, which writes it at camera level", async ({
frigateApp,
}) => {
const ffmpeg = await saveHevcCamera(frigateApp.page, {
startsOn: false,
toggle: true,
});
expect(ffmpeg.apple_compatibility).toBe(true);
});
});
});
/**
* Drive the whole wizard for an H.265 record stream, asserting the switch's
* starting state and optionally toggling it, then return the `ffmpeg` section
* of the camera that config/set received.
*/
async function saveHevcCamera(
page: Page,
{ startsOn, toggle }: { startsOn: boolean; toggle: boolean },
) {
await mockFfprobe(page, { [MAIN_URI]: "hevc" });
const saved: Record<string, unknown>[] = [];
await page.route("**/api/config/set", (route) => {
saved.push(route.request().postDataJSON());
return route.fulfill({ json: { success: true, require_restart: false } });
});
const dialog = await gotoStep3(page);
await roleSwitch(dialog, "record").click();
await testStream(dialog);
await expect(appleSwitch(dialog)).toBeChecked({ checked: startsOn });
if (toggle) {
await appleSwitch(dialog).click();
await expect(appleSwitch(dialog)).toBeChecked({ checked: !startsOn });
}
await dialog.getByRole("button", { name: /^Next$/i }).click();
const save = dialog.getByRole("button", { name: /Save New Camera/i });
await expect(save).toBeEnabled({ timeout: 15_000 });
await save.click();
// the camera PUT is the one carrying update_topic; go2rtc follows without it
await expect
.poll(() => saved.some((body) => "update_topic" in body), {
timeout: 15_000,
})
.toBe(true);
const cameraSave = saved.find((body) => "update_topic" in body) as {
update_topic: string;
config_data: {
cameras: Record<string, { ffmpeg: { apple_compatibility?: boolean } }>;
};
};
expect(cameraSave.update_topic).toBe("config/cameras/hevc_test_camera/add");
return cameraSave.config_data.cameras.hevc_test_camera.ffmpeg;
}
+196
View File
@@ -0,0 +1,196 @@
/**
* Setup wizard account step -- HIGH tier.
*
* Covers the step's placement and gating, the password and user payloads it
* sends, the copy it shows when nobody is signed in (the internal port), and
* that skipping it writes nothing.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page } from "@playwright/test";
import { installFirstRun } from "../../helpers/setup-wizard";
type Sent = {
method: string;
url: string;
body: Record<string, unknown> | null;
};
async function captureUserCalls(page: Page): Promise<Sent[]> {
const sent: Sent[] = [];
await page.route("**/api/users**", (route) => {
const request = route.request();
if (request.method() === "GET") {
return route.fulfill({ json: [{ username: "admin", role: "admin" }] });
}
sent.push({
method: request.method(),
url: request.url(),
body: request.postDataJSON(),
});
return route.fulfill({ json: { message: "ok" } });
});
return sent;
}
async function gotoAccountStep(page: Page) {
await page.getByRole("button", { name: "Get Started" }).click();
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeVisible();
}
test.describe("setup wizard account @high @mobile", () => {
test("sets the admin password without an old password", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Change password" }).click();
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
// the dialog is in set-password mode, so it asks for no current password
await expect(
dialog.getByPlaceholder("Enter your current password"),
).toBeHidden();
await dialog
.getByPlaceholder("Enter new password", { exact: true })
.fill("a-long-enough-password");
await dialog
.getByPlaceholder("Re-enter new password")
.fill("a-long-enough-password");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Password set")).toBeVisible();
const passwordCall = sent.find((call) => call.method === "PUT");
expect(passwordCall?.url).toContain("/users/admin/password");
// admins are exempt from the current-password check, so it must not be sent
expect(passwordCall?.body).toEqual({ password: "a-long-enough-password" });
});
test("creates a user with a role", async ({ frigateApp, page }) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Add user" }).click();
await page.getByPlaceholder("Enter username").fill("family");
await page
.getByPlaceholder("Enter password")
.fill("a-long-enough-password");
await page
.getByPlaceholder("Confirm Password")
.fill("a-long-enough-password");
await page.getByRole("button", { name: "Save" }).click();
const createCall = sent.find((call) => call.method === "POST");
expect(createCall?.body).toEqual({
username: "family",
password: "a-long-enough-password",
role: "viewer",
});
});
test("shows anonymous copy when nobody is signed in", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
profile: { username: "anonymous", role: "admin", allowed_cameras: null },
});
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await expect(page.getByText("doesn't require a login")).toBeVisible();
await expect(page.getByText("You're signed in as")).toBeHidden();
});
test("is absent when native auth is disabled", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
config: { auth: { enabled: false } } as never,
});
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await page.getByRole("button", { name: "Get Started" }).click();
// straight from welcome to the camera step, with no gap in the indicator
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await expect(
page.getByRole("heading", { name: "Secure your account" }),
).toBeHidden();
});
test("skipping sends nothing", async ({ frigateApp, page }) => {
await installFirstRun(frigateApp, page);
const sent = await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
expect(sent).toHaveLength(0);
});
test("an account change alone needs no restart", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
await captureUserCalls(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoAccountStep(page);
await page.getByRole("button", { name: "Change password" }).click();
const dialog = page.getByRole("dialog");
await dialog
.getByPlaceholder("Enter new password", { exact: true })
.fill("a-long-enough-password");
await dialog
.getByPlaceholder("Re-enter new password")
.fill("a-long-enough-password");
await dialog.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Password set")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Add Your First Camera")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
// every remaining step is passed without writing config: Skip on the
// detector, then Auto on hwaccel, which has nothing to derive and so
// saves nothing, then Skip on recording
await expect(page.getByText("Object Detection")).toBeVisible();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByRole("button", { name: "Go to Live View" }),
).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeHidden();
});
});
+255
View File
@@ -0,0 +1,255 @@
/**
* Setup wizard hardware tests -- HIGH tier.
*
* Covers the detector step's probed radio list and the models: payload it
* writes, the model-required deferral for onnx hardware, the hwaccel step's
* Auto option writing the preset derived from the chosen hardware, and the
* completion screen only restarting when a saved step requires it.
*/
import { test, expect } from "../../fixtures/frigate-test";
import type { Page } from "@playwright/test";
import { gotoDetectorStep, installFirstRun } from "../../helpers/setup-wizard";
const NVIDIA_HARDWARE = [
{
key: "onnx:nvidia",
detector: "onnx",
name: "NVIDIA GeForce RTX 3060",
units: [{ device: "onnx:0", label: "NVIDIA GeForce RTX 3060" }],
count: 1,
unlimited: true,
},
{
key: "cpu",
detector: "cpu",
name: "CPU",
units: [{ device: "cpu", label: "CPU" }],
count: 1,
unlimited: true,
},
];
type SavedConfig = {
config_data?: {
models?: { devices: string[]; path?: string }[];
detect?: { enabled?: boolean };
ffmpeg?: { hwaccel_args?: string | string[] };
};
};
async function captureSaves(page: Page): Promise<SavedConfig[]> {
const saves: SavedConfig[] = [];
await page.route("**/api/config/set**", (route) => {
saves.push(route.request().postDataJSON() as SavedConfig);
return route.fulfill({ json: { success: true, require_restart: true } });
});
return saves;
}
async function captureRestarts(page: Page): Promise<string[]> {
const calls: string[] = [];
await page.route("**/api/restart", (route) => {
calls.push(route.request().url());
return route.fulfill({ json: { success: true, message: "Restarting" } });
});
return calls;
}
test.describe("setup wizard hardware @high @mobile", () => {
test("lists probed hardware and writes a models config", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hwaccel: {
recommended: "vaapi",
available: [
{ key: "vaapi", presets: { any: "preset-vaapi" } },
{
key: "intel-qsv",
presets: {
h264: "preset-intel-qsv-h264",
h265: "preset-intel-qsv-h265",
},
},
],
},
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
// the default hardware mock reports two Corals, an Intel GPU, and the CPU
await expect(
page.getByRole("radio", { name: /Coral EdgeTPU \(PCIe\) \(2\)/ }),
).toBeChecked();
await expect(page.getByText("Recommended")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
const detectorSave = saves.find((save) => save.config_data?.models);
expect(detectorSave?.config_data?.models).toEqual([
{ devices: ["edgetpu:pci:0"] },
]);
expect(detectorSave?.config_data?.detect).toEqual({ enabled: true });
// VAAPI decodes any codec, so one global value covers every camera
await expect(page.getByText("Will use VAAPI (Intel/AMD)")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
const hwaccelSave = saves.find((save) => save.config_data?.ffmpeg);
expect(hwaccelSave?.config_data?.ffmpeg).toEqual({
hwaccel_args: "preset-vaapi",
});
// the saved steps only take effect after a restart
const restarts = await captureRestarts(page);
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeVisible();
await page.getByRole("button", { name: "Apply & Restart" }).click();
await expect(page.getByText("Starting Frigate...")).toBeVisible();
expect(restarts).toHaveLength(1);
});
test("defers model setup for onnx hardware without Frigate+", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hardware: NVIDIA_HARDWARE,
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await expect(
page.getByRole("radio", { name: /NVIDIA GeForce RTX 3060/ }),
).toBeChecked();
await page
.getByRole("button", { name: "Continue without detection" })
.click();
// advances without touching the config
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
expect(saves.filter((save) => save.config_data?.models)).toHaveLength(0);
// nothing derived and nothing saved, so finishing needs no restart
const restarts = await captureRestarts(page);
await expect(page.getByText("No supported video card found")).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
await page.getByRole("button", { name: "Skip" }).click();
await expect(page.getByText("You're done!")).toBeVisible();
await expect(
page.getByText("Frigate needs to restart to apply your settings"),
).toBeHidden();
await page.getByRole("button", { name: "Go to Live View" }).click();
// hands off without restarting, and the wizard does not come back
await expect(page.getByText("Welcome to Frigate")).toBeHidden();
expect(restarts).toHaveLength(0);
});
test("offers only the presets the hardware supports", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hardware: NVIDIA_HARDWARE,
hwaccel: {
recommended: "nvidia",
available: [{ key: "nvidia", presets: { any: "preset-nvidia" } }],
},
});
await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await page
.getByRole("button", { name: "Continue without detection" })
.click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
// an NVIDIA box has no business being offered Rockchip or Pi decoding
await expect(
page.getByRole("radio", { name: "CUDA (NVIDIA)" }),
).toBeVisible();
await expect(
page.getByRole("radio", { name: /Raspberry Pi/ }),
).toBeHidden();
await expect(page.getByRole("radio", { name: /Rockchip/ })).toBeHidden();
// Auto and None are always available
await expect(page.getByRole("radio", { name: "Auto" })).toBeVisible();
await expect(
page.getByRole("radio", { name: "None (software decoding)" }),
).toBeVisible();
});
test("a codec specific family falls back to h264 with no cameras", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page, {
hwaccel: {
recommended: "jetson",
available: [
{
key: "jetson",
presets: {
h264: "preset-jetson-h264",
h265: "preset-jetson-h265",
},
},
],
},
});
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await expect(
page.getByRole("radio", { name: "NVIDIA Jetson" }),
).toBeVisible();
await page.getByRole("button", { name: "Next" }).click();
// no camera was added, so there is no codec to match
const hwaccelSave = saves.find((save) => save.config_data?.ffmpeg);
expect(hwaccelSave?.config_data?.ffmpeg).toEqual({
hwaccel_args: "preset-jetson-h264",
});
});
test("None writes an explicit empty hwaccel list", async ({
frigateApp,
page,
}) => {
await installFirstRun(frigateApp, page);
const saves = await captureSaves(page);
await frigateApp.gotoAndWait("/", "text=Welcome to Frigate");
await gotoDetectorStep(page);
await page.getByRole("button", { name: "Next" }).click();
await expect(page.getByText("Hardware Acceleration")).toBeVisible();
await page.getByRole("radio", { name: "None (software decoding)" }).click();
await page.getByRole("button", { name: "Next" }).click();
const hwaccelSave = saves.find((save) => save.config_data?.ffmpeg);
expect(hwaccelSave?.config_data?.ffmpeg).toEqual({ hwaccel_args: [] });
});
});
@@ -427,6 +427,10 @@
"notConnected": "Not Connected",
"featuresTitle": "Features",
"go2rtc": "Reduce connections to camera",
"appleCompatibility": {
"title": "Improve playback on Apple devices",
"description": "Turn this on if you watch recordings in Safari or on an iPhone, iPad, or Mac."
},
"detectRoleWarning": "At least one stream must have the \"detect\" role to proceed.",
"rolesPopover": {
"title": "Stream Roles",
+114
View File
@@ -0,0 +1,114 @@
{
"setupWizard": {
"steps": {
"welcome": "Welcome",
"account": "Account",
"camera": "Add Camera",
"hwaccel": "Acceleration",
"detector": "Detection",
"recording": "Recording",
"complete": "Done"
},
"welcome": {
"title": "Welcome to Frigate",
"description": "Let's get your security cameras set up. We'll walk through camera connection, hardware settings, and recording.",
"getStarted": "Get Started",
"skipSetup": "Skip setup and configure manually"
},
"account": {
"title": "Secure your account",
"descriptionSignedIn": "You're signed in as {{username}} using the temporary password from the Frigate logs. Set one you'll remember.",
"descriptionAnonymous": "You're accessing Frigate on a port that doesn't require a login. Set a password for the admin account so you can sign in on the secured port.",
"passwordSet": "Password set",
"changePassword": "Change password",
"addUser": "Add user",
"usersFailed": "Could not load the user list. You can still set the admin password.",
"userFailed": "Failed to add the user. Please try again."
},
"camera": {
"title": "Add Your First Camera",
"description": "Connect a camera to start monitoring. You can also add more cameras later in Settings.",
"addCamera": "Add Camera",
"addAnother": "Add Another Camera",
"cameraAdded": "Camera added successfully",
"retry": "Try Again"
},
"hwaccel": {
"title": "Hardware Acceleration",
"description": "Speed up video decoding with your GPU.",
"detecting": "Checking your hardware...",
"auto": "Auto",
"autoResolved": "Will use {{family}} for your cameras.",
"autoNone": "No supported video card found. Frigate will decide at startup.",
"recommendFailed": "Hardware detection is unavailable. Frigate will decide at startup.",
"families": {
"nvidia": "CUDA (NVIDIA)",
"vaapi": "VAAPI (Intel/AMD)",
"intel-qsv": "QuickSync (Intel)",
"rkmpp": "RKMPP (Rockchip)",
"jetson": "NVIDIA Jetson",
"rpi": "V4L2 (Raspberry Pi)",
"none": "None (software decoding)"
}
},
"detector": {
"title": "Object Detection",
"description": "Choose the hardware Frigate uses to detect people and objects.",
"detecting": "Checking for detection hardware...",
"probeFailed": "Hardware detection is unavailable. You can configure detection later in Settings.",
"recommended": "Recommended",
"modelRequired": "{{name}} needs a detection model before it can run. Pick a Frigate+ model, or finish setup and add one under Settings > Detection models.",
"plusModelPlaceholder": "Select a Frigate+ model",
"continueWithout": "Continue without detection"
},
"recording": {
"title": "Recordings",
"description": "Save video from your cameras so you can watch it later.",
"enableRecording": "Enable recordings",
"retentionDays": "Keep recordings for (days)",
"storageEstimate": "With {{free}} GB free, {{cameras}} camera(s) recording around the clock fills the disk in roughly {{days}} days.",
"noCameras": "You haven't added cameras yet. Recording will apply when you add cameras in Settings.",
"modeLabel": "What to record",
"modes": {
"events": {
"label": "Only when something is detected",
"description": "Saves video around people, cars, and other objects Frigate detects. Uses far less disk space."
},
"continuous": {
"label": "All the time",
"description": "Saves video around the clock, so you can go back to any moment. Uses much more disk space."
}
},
"retentionHint": {
"events": "Video of anything Frigate detects is kept this long, then deleted automatically.",
"continuous": "All video is kept this long, then deleted automatically."
}
},
"complete": {
"title": "You're done!",
"description": "Your Frigate system is configured. Here's what we set up:",
"configured": "Configured",
"notConfigured": "Not configured",
"configureInSettings": "Configure in Settings",
"camera": "Camera",
"hwaccel": "Hardware Acceleration",
"detector": "Object Detection",
"recording": "Recording",
"goToLiveView": "Go to Live View",
"applyAndRestart": "Apply & Restart",
"restartNotice": "Frigate needs to restart to apply your settings. This takes about 30 seconds.",
"nextSteps": "Next steps: Set up motion masks, zones, and notifications in Settings.",
"restarting": "Starting Frigate...",
"restartingDescription": "This takes about 30 seconds."
},
"actions": {
"next": "Next",
"back": "Back",
"skip": "Skip",
"saving": "Saving..."
},
"errors": {
"saveFailed": "Failed to save configuration. Please try again."
}
}
}
+38 -1
View File
@@ -6,7 +6,7 @@ import Sidebar from "@/components/navigation/Sidebar";
import { isDesktop, isMobile } from "react-device-detect";
import Statusbar from "./components/Statusbar";
import Bottombar from "./components/navigation/Bottombar";
import { Suspense, lazy } from "react";
import { Suspense, lazy, useContext, useEffect, useState } from "react";
import { Redirect } from "./components/navigation/Redirect";
import { cn } from "./lib/utils";
import { isPWA } from "./utils/isPWA";
@@ -15,6 +15,9 @@ import useSWR from "swr";
import { FrigateConfig } from "./types/frigateConfig";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { isRedirectingToLogin } from "@/api/auth-redirect";
import { AuthContext } from "@/context/auth-context";
import { useIsAdmin } from "@/hooks/use-is-admin";
import { isSetupDismissed } from "@/utils/setupWizard";
const Live = lazy(() => import("@/pages/Live"));
const Events = lazy(() => import("@/pages/Events"));
@@ -30,6 +33,7 @@ const Chat = lazy(() => import("@/pages/Chat"));
const Logs = lazy(() => import("@/pages/Logs"));
const AccessDenied = lazy(() => import("@/pages/AccessDenied"));
const Replay = lazy(() => import("@/pages/Replay"));
const SetupWizard = lazy(() => import("@/pages/SetupWizard"));
function App() {
const { data: config } = useSWR<FrigateConfig>("config", {
@@ -52,6 +56,24 @@ function DefaultAppView() {
revalidateOnFocus: false,
});
// decided once per load: adding the first camera part way through the
// wizard must not pull the wizard out from under the user
const [showWizard, setShowWizard] = useState<boolean>();
const { auth } = useContext(AuthContext);
const isAdmin = useIsAdmin();
useEffect(() => {
// every step writes through admin only endpoints, and the role isn't
// known until the profile resolves
if (config && !auth.isLoading && showWizard === undefined) {
setShowWizard(
isAdmin &&
Object.keys(config.cameras ?? {}).length === 0 &&
!isSetupDismissed(),
);
}
}, [config, auth.isLoading, isAdmin, showWizard]);
// Compute required roles for main routes, ensuring we have config first
// to prevent race condition where custom roles are temporarily unavailable
const mainRouteRoles = config?.auth?.roles
@@ -68,6 +90,21 @@ function DefaultAppView() {
);
}
// Show setup wizard for first-time users
if (showWizard) {
return (
<div className="size-full overflow-hidden">
<Suspense
fallback={
<ActivityIndicator className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" />
}
>
<SetupWizard />
</Suspense>
</div>
);
}
return (
<div className="size-full overflow-hidden">
{isDesktop && <Sidebar />}
@@ -23,6 +23,7 @@ import type {
import {
processCameraName,
calculateDetectDimensions,
hevcRecordingStreamId,
} from "@/utils/cameraUtil";
import { cn } from "@/lib/utils";
@@ -74,11 +75,14 @@ const STEPS = [
type CameraWizardDialogProps = {
open: boolean;
onClose: () => void;
// lets callers reuse what was probed here instead of probing again
onCameraAdded?: (camera: { name: string; detectCodec?: string }) => void;
};
export default function CameraWizardDialog({
open,
onClose,
onCameraAdded,
}: CameraWizardDialogProps) {
const { t } = useTranslation(["views/settings"]);
const { mutate: updateConfig } = useSWR("config");
@@ -182,6 +186,11 @@ export default function CameraWizardDialog({
wizardData.cameraName,
);
// re-checked here: roles and codecs may have changed since it was set
const appleCompatibility =
!!wizardData.appleCompatibility &&
!!hevcRecordingStreamId(wizardData.streams);
// Convert wizard data to Frigate config format
const configData: CameraConfigData = {
cameras: {
@@ -189,6 +198,7 @@ export default function CameraWizardDialog({
enabled: true,
...(friendlyName && { friendly_name: friendlyName }),
ffmpeg: {
...(appleCompatibility && { apple_compatibility: true }),
inputs: wizardData.streams.map((stream, index) => {
if (stream.restream) {
const go2rtcStreamName =
@@ -271,6 +281,13 @@ export default function CameraWizardDialog({
.put("config/set", requestBody)
.then((response) => {
if (response.status === 200) {
onCameraAdded?.({
name: finalCameraName,
detectCodec: wizardData.streams?.find((stream) =>
stream.roles.includes("detect"),
)?.testResult?.videoCodec,
});
// Configure go2rtc streams for all streams
if (wizardData.streams && wizardData.streams.length > 0) {
const go2rtcStreams: Record<string, string[]> = {};
@@ -393,7 +410,7 @@ export default function CameraWizardDialog({
setIsLoading(false);
});
},
[updateConfig, t, onClose],
[updateConfig, t, onClose, onCameraAdded],
);
return (
@@ -26,7 +26,7 @@ import {
PopoverTrigger,
} from "@/components/ui/popover";
import { Drawer, DrawerContent, DrawerTrigger } from "@/components/ui/drawer";
import { isMobile } from "react-device-detect";
import { isIOS, isMobile, isSafari } from "react-device-detect";
import {
LuInfo,
LuExternalLink,
@@ -53,6 +53,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { hevcRecordingStreamId } from "@/utils/cameraUtil";
// Recording the sub stream from the same stream as record would just
// re-record the main stream, so the two roles are mutually exclusive.
@@ -389,6 +390,22 @@ export default function Step3StreamConfig({
const hasDetectRole = streams.some((s) => s.roles.includes("detect"));
const appleCompatibilityStreamId = useMemo(
() => hevcRecordingStreamId(streams),
[streams],
);
useEffect(() => {
// undefined, not false: a deliberate toggle-off must not be re-seeded
if (
(isSafari || isIOS) &&
appleCompatibilityStreamId &&
wizardData.appleCompatibility === undefined
) {
onUpdate({ appleCompatibility: true });
}
}, [appleCompatibilityStreamId, wizardData.appleCompatibility, onUpdate]);
return (
<div className="space-y-6">
<div className="text-sm text-secondary-foreground">
@@ -778,7 +795,7 @@ export default function Step3StreamConfig({
</PopoverContent>
</Popover>
</div>
<div className="rounded-lg bg-background p-3">
<div className="space-y-3 rounded-lg bg-background p-3">
<div className="flex items-center justify-between">
<span className="text-sm">
{t("cameraWizard.step3.go2rtc")}
@@ -788,6 +805,27 @@ export default function Step3StreamConfig({
onCheckedChange={() => setRestream(stream.id)}
/>
</div>
{appleCompatibilityStreamId === stream.id && (
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<div className="text-sm">
{t("cameraWizard.step3.appleCompatibility.title")}
</div>
<p className="text-xs text-muted-foreground">
{t(
"cameraWizard.step3.appleCompatibility.description",
)}
</p>
</div>
<Switch
checked={wizardData.appleCompatibility ?? false}
onCheckedChange={(checked) =>
onUpdate({ appleCompatibility: checked })
}
/>
</div>
)}
</div>
</div>
</CardContent>
@@ -268,6 +268,7 @@ export default function Step4Validation({
customUrl: wizardData.customUrl,
streams: wizardData.streams,
hasBackchannel: wizardData.hasBackchannel,
appleCompatibility: wizardData.appleCompatibility,
onvif: wizardData.onvif,
};
+194
View File
@@ -0,0 +1,194 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import CreateUserDialog from "@/components/overlay/CreateUserDialog";
import SetPasswordDialog from "@/components/overlay/SetPasswordDialog";
import { Button } from "@/components/ui/button";
import { AuthContext } from "@/context/auth-context";
import axios from "axios";
import { useCallback, useContext, useState } from "react";
import { useTranslation } from "react-i18next";
import { FaCircleCheck } from "react-icons/fa6";
import { toast } from "sonner";
import useSWR from "swr";
type User = {
username: string;
role: string;
};
type SetupAccountProps = {
onNext: () => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupAccount({
onNext,
onBack,
onSkip,
}: SetupAccountProps) {
const { t } = useTranslation(["views/setup"]);
const { auth } = useContext(AuthContext);
const {
data: users,
isLoading,
error: usersError,
mutate: mutateUsers,
} = useSWR<User[]>("users", { revalidateOnFocus: false });
// the internal port has no signed in user, so the built-in admin is the
// account being secured
const adminUsername = auth.isAuthenticated
? (auth.user?.username ?? "admin")
: "admin";
const [showPassword, setShowPassword] = useState(false);
const [passwordError, setPasswordError] = useState<string | null>(null);
const [passwordSaving, setPasswordSaving] = useState(false);
const [passwordSet, setPasswordSet] = useState(false);
const [showCreate, setShowCreate] = useState(false);
const handleSavePassword = useCallback(
(password: string) => {
setPasswordSaving(true);
axios
.put(`users/${adminUsername}/password`, { password })
.then(() => {
setShowPassword(false);
setPasswordError(null);
setPasswordSet(true);
})
.catch((error) => {
setPasswordError(
error.response?.data?.message ||
error.response?.data?.detail ||
t("setupWizard.errors.saveFailed"),
);
})
.finally(() => setPasswordSaving(false));
},
[adminUsername, t],
);
const handleCreateUser = useCallback(
(username: string, password: string, role: string) =>
axios
.post("users", { username, password, role })
.then(() => {
setShowCreate(false);
mutateUsers();
})
.catch((error) => {
toast.error(
error.response?.data?.message ||
error.response?.data?.detail ||
t("setupWizard.account.userFailed"),
);
}),
[mutateUsers, t],
);
const otherUsers = (users ?? []).filter(
(user) => user.username !== adminUsername,
);
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.account.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{auth.isAuthenticated
? t("setupWizard.account.descriptionSignedIn", {
username: adminUsername,
})
: t("setupWizard.account.descriptionAnonymous")}
</p>
</div>
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between rounded-md border p-3">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium">{adminUsername}</span>
{passwordSet && (
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<FaCircleCheck className="size-3 text-success" />
{t("setupWizard.account.passwordSet")}
</span>
)}
</div>
<Button
type="button"
variant="outline"
onClick={() => setShowPassword(true)}
>
{t("setupWizard.account.changePassword")}
</Button>
</div>
{otherUsers.map((user) => (
<div
key={user.username}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{user.username}</span>
<span className="text-xs text-muted-foreground">{user.role}</span>
</div>
))}
</div>
{isLoading && <ActivityIndicator />}
{usersError && (
<p className="rounded-md bg-muted p-3 text-xs text-muted-foreground">
{t("setupWizard.account.usersFailed")}
</p>
)}
<div className="flex flex-col items-center gap-3 py-4">
<Button
variant="select"
className="w-full"
onClick={() => setShowCreate(true)}
>
{t("setupWizard.account.addUser")}
</Button>
</div>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button type="button" variant="select" onClick={onNext}>
{t("setupWizard.actions.next")}
</Button>
</div>
</div>
{/* no username prop: passing one puts the dialog in current-password
mode, which the admin is exempt from and an anonymous internal port
user has no way to satisfy */}
<SetPasswordDialog
show={showPassword}
initialError={passwordError}
isLoading={passwordSaving}
onSave={handleSavePassword}
onCancel={() => {
setShowPassword(false);
setPasswordError(null);
}}
/>
<CreateUserDialog
show={showCreate}
onCreate={handleCreateUser}
onCancel={() => setShowCreate(false)}
/>
</div>
);
}
+109
View File
@@ -0,0 +1,109 @@
import CameraWizardDialog from "@/components/settings/CameraWizardDialog";
import { Button } from "@/components/ui/button";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { FaCircleCheck } from "react-icons/fa6";
type SetupCameraProps = {
onNext: (
cameraNames?: string[],
detectCodecs?: Record<string, string>,
) => void;
onBack: () => void;
};
export default function SetupCamera({ onNext, onBack }: SetupCameraProps) {
const { t } = useTranslation(["views/setup"]);
const [showWizard, setShowWizard] = useState(false);
const [addedCameras, setAddedCameras] = useState<string[]>([]);
const [detectCodecs, setDetectCodecs] = useState<Record<string, string>>({});
const handleClose = useCallback(() => {
setShowWizard(false);
}, []);
// the dialog fires this once its config write has succeeded, which is the
// only reliable signal that a camera was added
const handleCameraAdded = useCallback(
({ name, detectCodec }: { name: string; detectCodec?: string }) => {
setAddedCameras((previous) =>
previous.includes(name) ? previous : [...previous, name],
);
if (detectCodec) {
setDetectCodecs((previous) => ({ ...previous, [name]: detectCodec }));
}
},
[],
);
const handleNext = useCallback(() => {
onNext(addedCameras, detectCodecs);
}, [onNext, addedCameras, detectCodecs]);
const handleSkip = useCallback(() => {
onNext();
}, [onNext]);
return (
<>
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.camera.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.camera.description")}
</p>
</div>
{addedCameras.length > 0 && (
<div className="flex flex-col gap-2">
{addedCameras.map((name) => (
<div
key={name}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{name}</span>
<FaCircleCheck className="size-4 text-success" />
</div>
))}
</div>
)}
<div className="flex flex-col items-center gap-3 py-4">
<Button
variant="select"
className="w-full"
onClick={() => setShowWizard(true)}
>
{addedCameras.length > 0
? t("setupWizard.camera.addAnother")
: t("setupWizard.camera.addCamera")}
</Button>
</div>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
{addedCameras.length > 0 ? (
<Button type="button" variant="select" onClick={handleNext}>
{t("setupWizard.actions.next")}
</Button>
) : (
<Button type="button" variant="outline" onClick={handleSkip}>
{t("setupWizard.actions.skip")}
</Button>
)}
</div>
</div>
</div>
<CameraWizardDialog
open={showWizard}
onClose={handleClose}
onCameraAdded={handleCameraAdded}
/>
</>
);
}
+209
View File
@@ -0,0 +1,209 @@
import Logo from "@/components/Logo";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { Button } from "@/components/ui/button";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import axios from "axios";
import { FaCircleCheck } from "react-icons/fa6";
import { dismissSetup } from "@/utils/setupWizard";
type ConfiguredItem = {
key: string;
label: string;
value: string | null;
};
type SetupCompleteProps = {
cameraNames: string[];
configuredSteps: {
camera: boolean;
hwaccel: boolean;
detector: boolean;
recording: boolean;
};
restartRequired: boolean;
onBack: () => void;
};
export default function SetupComplete({
cameraNames,
configuredSteps,
restartRequired,
onBack,
}: SetupCompleteProps) {
const { t } = useTranslation(["views/setup"]);
const [restarting, setRestarting] = useState(false);
const [finishing, setFinishing] = useState(false);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const cameraItems: ConfiguredItem[] =
configuredSteps.camera && cameraNames.length > 0
? cameraNames.map((name) => ({
key: `camera-${name}`,
label: t("setupWizard.complete.camera"),
value: name,
}))
: [
{
key: "camera",
label: t("setupWizard.complete.camera"),
value: null,
},
];
const items: ConfiguredItem[] = [
...cameraItems,
{
key: "hwaccel",
label: t("setupWizard.complete.hwaccel"),
value: configuredSteps.hwaccel
? t("setupWizard.complete.configured")
: null,
},
{
key: "detector",
label: t("setupWizard.complete.detector"),
value: configuredSteps.detector
? t("setupWizard.complete.configured")
: null,
},
{
key: "recording",
label: t("setupWizard.complete.recording"),
value: configuredSteps.recording
? t("setupWizard.complete.configured")
: null,
},
];
useEffect(() => {
return () => {
if (pollRef.current) {
clearInterval(pollRef.current);
}
};
}, []);
const handleFinish = useCallback(async () => {
setFinishing(true);
dismissSetup();
try {
// camera adds were applied live, so nothing is waiting on a restart
if (!restartRequired) {
window.location.href = window.baseUrl || "/";
return;
}
setRestarting(true);
await axios.post("restart");
let retries = 0;
const maxRetries = 60; // 2 minutes max
pollRef.current = setInterval(async () => {
retries++;
if (retries > maxRetries) {
if (pollRef.current) {
clearInterval(pollRef.current);
}
window.location.href = window.baseUrl || "/";
return;
}
try {
const resp = await axios.get("version", { timeout: 2000 });
if (resp.status === 200) {
if (pollRef.current) {
clearInterval(pollRef.current);
}
window.location.href = window.baseUrl || "/";
}
} catch {
// not back yet
}
}, 2000);
} catch {
setRestarting(false);
setFinishing(false);
toast.error(t("setupWizard.errors.saveFailed"));
}
}, [restartRequired, t]);
if (restarting) {
return (
<div className="flex flex-col items-center gap-6 py-12">
<Logo className="h-12 w-12" />
<ActivityIndicator />
<div className="text-center">
<p className="font-semibold">
{t("setupWizard.complete.restarting")}
</p>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.complete.restartingDescription")}
</p>
</div>
</div>
);
}
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.complete.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.complete.description")}
</p>
</div>
<div className="flex flex-col gap-2">
{items.map((item) => (
<div
key={item.key}
className="flex items-center justify-between rounded-md border p-3"
>
<span className="text-sm font-medium">{item.label}</span>
<div className="flex items-center gap-2">
{item.value && <FaCircleCheck className="size-4 text-success" />}
<span
className={`text-sm ${item.value ? "" : "text-muted-foreground"}`}
>
{item.value ?? t("setupWizard.complete.notConfigured")}
</span>
</div>
</div>
))}
</div>
<p className="text-sm text-muted-foreground">
{t("setupWizard.complete.nextSteps")}
</p>
{restartRequired && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.complete.restartNotice")}
</p>
)}
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end">
<Button
type="button"
variant="select"
onClick={handleFinish}
disabled={finishing}
>
{restartRequired
? t("setupWizard.complete.applyAndRestart")
: t("setupWizard.complete.goToLiveView")}
</Button>
</div>
</div>
</div>
);
}
+273
View File
@@ -0,0 +1,273 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import type { FrigatePlusModel } from "@/components/config-form/theme/fields/ModelSourcePicker";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { useDocDomain } from "@/hooks/use-doc-domain";
import type { FrigateConfig } from "@/types/frigateConfig";
import type { DetectionHardware } from "@/types/hardware";
import { recommendedDetectorCount } from "@/utils/detectionHardware";
import axios from "axios";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { LuExternalLink } from "react-icons/lu";
import { toast } from "sonner";
import useSWR from "swr";
// these ship no default model, so configuring one without a model leaves the
// detector unable to start
const MODEL_REQUIRED_DETECTORS = ["onnx", "tensorrt"];
const CPU_FALLBACK: DetectionHardware[] = [
{
key: "cpu",
detector: "cpu",
name: "CPU",
units: [{ device: "cpu", label: "CPU" }],
count: 1,
unlimited: true,
},
];
type SetupDetectorProps = {
cameraCount: number;
onNext: (hardwareKey: string) => void;
onBack: () => void;
onSkip: (hardwareKey?: string) => void;
};
export default function SetupDetector({
cameraCount,
onNext,
onBack,
onSkip,
}: SetupDetectorProps) {
const { t } = useTranslation(["views/setup", "common"]);
const { getLocaleDocUrl } = useDocDomain();
const {
data: hardware,
isLoading,
error: probeError,
} = useSWR<DetectionHardware[]>("hardware/probe", {
revalidateOnFocus: false,
});
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
const plusEnabled = Boolean(config?.plus?.enabled);
// the cpu is always probed, so an empty list means the probe failed
const options = useMemo(
() => (hardware && hardware.length > 0 ? hardware : CPU_FALLBACK),
[hardware],
);
// the prober orders accelerators ahead of the cpu
const recommendedKey = options[0].key;
const [selectedKey, setSelectedKey] = useState<string>();
const selected =
options.find((entry) => entry.key === (selectedKey ?? recommendedKey)) ??
options[0];
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
plusEnabled && needsModel ? "/plus/models" : null,
{
fetcher: async (url) => {
const res = await axios.get(url, { withCredentials: true });
return res.data;
},
},
);
const [plusModelId, setPlusModelId] = useState("");
const compatiblePlusModels = useMemo(
() =>
(plusModels ?? []).filter((model) =>
model.supportedDetectors.includes(selected.detector),
),
[plusModels, selected.detector],
);
const [saving, setSaving] = useState(false);
const buildDevices = useCallback(
(entry: DetectionHardware): string[] => {
const first = entry.units[0]?.device;
if (!first) {
return [];
}
if (!entry.unlimited) {
return [first];
}
// repeating a device runs an extra inference process on it
const count = recommendedDetectorCount(Math.max(cameraCount, 1));
return Array.from({ length: count }, () => first);
},
[cameraCount],
);
const handleSave = useCallback(async () => {
if (needsModel && !plusModelId) {
onSkip(selected.key);
return;
}
setSaving(true);
try {
const model: Record<string, unknown> = {
devices: buildDevices(selected),
};
if (needsModel) {
model.path = `plus://${plusModelId}`;
}
await axios.put("config/set", {
config_data: {
models: [model],
detect: { enabled: true },
},
requires_restart: 1,
});
onNext(selected.key);
} catch {
toast.error(t("setupWizard.errors.saveFailed"));
} finally {
setSaving(false);
}
}, [needsModel, plusModelId, selected, buildDevices, onNext, onSkip, t]);
if (isLoading) {
return (
<div className="flex flex-col items-center gap-4 py-12">
<ActivityIndicator />
<p className="text-sm text-muted-foreground">
{t("setupWizard.detector.detecting")}
</p>
</div>
);
}
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.detector.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.detector.description")}
</p>
</div>
{probeError && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.detector.probeFailed")}
</p>
)}
<RadioGroup
value={selected.key}
onValueChange={(value) => {
setSelectedKey(value);
setPlusModelId("");
}}
>
{options.map((entry) => (
<div key={entry.key} className="flex items-center space-x-2">
<RadioGroupItem
value={entry.key}
id={`detector-${entry.key}`}
className={
selected.key === entry.key
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
/>
<label
htmlFor={`detector-${entry.key}`}
className="cursor-pointer text-sm font-medium"
>
{entry.name}
{entry.count > 1 ? ` (${entry.count})` : ""}
{entry.key === recommendedKey && entry.key !== "cpu" && (
<span className="ml-2 text-xs text-selected">
{t("setupWizard.detector.recommended")}
</span>
)}
</label>
</div>
))}
</RadioGroup>
{needsModel && (
<div className="flex flex-col gap-3 rounded-md bg-muted p-3 text-sm">
<p>
{t("setupWizard.detector.modelRequired", { name: selected.name })}
</p>
{plusEnabled ? (
<Select value={plusModelId} onValueChange={setPlusModelId}>
<SelectTrigger className="max-w-xs">
<SelectValue
placeholder={t("setupWizard.detector.plusModelPlaceholder")}
/>
</SelectTrigger>
<SelectContent>
{compatiblePlusModels.map((model) => (
<SelectItem key={model.id} value={model.id}>
{`${model.name} (${model.width}x${model.height})`}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<a
href={getLocaleDocUrl("configuration/object_detectors")}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center text-primary"
>
{t("readTheDocumentation", { ns: "common" })}
<LuExternalLink className="ml-2 size-3" />
</a>
)}
</div>
)}
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={() => onSkip(selected.key)}>
{t("setupWizard.actions.skip")}
</Button>
<Button
type="button"
variant="select"
onClick={handleSave}
disabled={saving}
>
{saving
? t("setupWizard.actions.saving")
: needsModel && !plusModelId
? t("setupWizard.detector.continueWithout")
: t("setupWizard.actions.next")}
</Button>
</div>
</div>
</div>
);
}
+258
View File
@@ -0,0 +1,258 @@
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import type { HwaccelFamily, HwaccelRecommendation } from "@/types/hardware";
import axios from "axios";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import useSWR from "swr";
const AUTO = "auto";
const NONE = "none";
const ANY_CODEC = "any";
// ffprobe names h265 streams hevc
const CODEC_ALIASES: Record<string, string> = { hevc: "h265" };
function normalizeCodec(codec: string): string {
const lower = codec.toLowerCase();
return CODEC_ALIASES[lower] ?? lower;
}
type SetupHwAccelProps = {
detectorHardwareKey?: string;
// camera name -> detect stream codec, the only stream hwaccel applies to
detectCodecs: Record<string, string>;
// saved tells the wizard whether finishing needs a restart
onNext: (saved: boolean) => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupHwAccel({
detectorHardwareKey,
detectCodecs,
onNext,
onBack,
onSkip,
}: SetupHwAccelProps) {
const { t } = useTranslation(["views/setup"]);
const cameraCodecs = useMemo(
() =>
Object.entries(detectCodecs).map(([camera, codec]) => ({
camera,
codec: normalizeCodec(codec),
})),
[detectCodecs],
);
const query = useMemo(() => {
const params = new URLSearchParams();
if (detectorHardwareKey) {
params.set("detector", detectorHardwareKey);
}
const codecs = [...new Set(cameraCodecs.map((entry) => entry.codec))];
if (codecs.length > 0) {
params.set("codecs", codecs.join(","));
}
return params.toString();
}, [detectorHardwareKey, cameraCodecs]);
const {
data: recommendation,
isLoading,
error: recommendError,
} = useSWR<HwaccelRecommendation>(
query ? `hardware/hwaccel?${query}` : "hardware/hwaccel",
{ revalidateOnFocus: false },
);
const [selected, setSelected] = useState<string>(AUTO);
const [saving, setSaving] = useState(false);
const families = useMemo(
() => recommendation?.available ?? [],
[recommendation],
);
const derived = recommendation?.recommended ?? "";
/** The config a family should be saved as, or null when it writes nothing. */
const configFor = useCallback(
(family: HwaccelFamily | undefined): Record<string, unknown> | null => {
if (!family) {
return null;
}
const shared = family.presets[ANY_CODEC];
if (shared) {
return { ffmpeg: { hwaccel_args: shared } };
}
const perCamera = cameraCodecs
.map((entry) => ({ ...entry, preset: family.presets[entry.codec] }))
.filter((entry) => entry.preset);
if (perCamera.length === 0) {
const fallback = Object.values(family.presets)[0];
return fallback ? { ffmpeg: { hwaccel_args: fallback } } : null;
}
const presets = new Set(perCamera.map((entry) => entry.preset));
if (presets.size === 1 && perCamera.length === cameraCodecs.length) {
return { ffmpeg: { hwaccel_args: [...presets][0] } };
}
// the global stays on auto so cameras added later resolve at startup
// instead of inheriting one camera's codec
return {
cameras: Object.fromEntries(
perCamera.map((entry) => [
entry.camera,
{ ffmpeg: { hwaccel_args: entry.preset } },
]),
),
};
},
[cameraCodecs],
);
const handleSave = useCallback(async () => {
const key = selected === AUTO ? derived : selected;
const configData =
selected === NONE
? // an empty string would make config/set delete the key, reviving
// the "auto" default
{ ffmpeg: { hwaccel_args: [] } }
: configFor(families.find((family) => family.key === key));
// nothing to write leaves the config default of "auto" in place
if (!configData) {
onNext(false);
return;
}
setSaving(true);
try {
await axios.put("config/set", {
config_data: configData,
requires_restart: 1,
});
onNext(true);
} catch {
toast.error(t("setupWizard.errors.saveFailed"));
} finally {
setSaving(false);
}
}, [selected, derived, families, configFor, onNext, t]);
if (isLoading) {
return (
<div className="flex flex-col items-center gap-4 py-12">
<ActivityIndicator />
<p className="text-sm text-muted-foreground">
{t("setupWizard.hwaccel.detecting")}
</p>
</div>
);
}
const radioClass = (value: string) =>
selected === value
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary";
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.hwaccel.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.hwaccel.description")}
</p>
</div>
<RadioGroup value={selected} onValueChange={setSelected}>
<div className="flex flex-col gap-0.5">
<div className="flex items-center space-x-2">
<RadioGroupItem
value={AUTO}
id="hwaccel-auto"
className={radioClass(AUTO)}
/>
<label htmlFor="hwaccel-auto" className="cursor-pointer text-sm">
{t("setupWizard.hwaccel.auto")}
</label>
</div>
<p className="ml-6 text-xs text-muted-foreground">
{derived
? t("setupWizard.hwaccel.autoResolved", {
family: t(`setupWizard.hwaccel.families.${derived}`),
})
: recommendError
? t("setupWizard.hwaccel.recommendFailed")
: t("setupWizard.hwaccel.autoNone")}
</p>
</div>
{families.map((family) => (
<div key={family.key} className="flex items-center space-x-2">
<RadioGroupItem
value={family.key}
id={`hwaccel-${family.key}`}
className={radioClass(family.key)}
/>
<label
htmlFor={`hwaccel-${family.key}`}
className="cursor-pointer text-sm"
>
{t(`setupWizard.hwaccel.families.${family.key}`)}
</label>
</div>
))}
<div className="flex items-center space-x-2">
<RadioGroupItem
value={NONE}
id="hwaccel-none"
className={radioClass(NONE)}
/>
<label htmlFor="hwaccel-none" className="cursor-pointer text-sm">
{t("setupWizard.hwaccel.families.none")}
</label>
</div>
</RadioGroup>
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button
type="button"
variant="select"
onClick={handleSave}
disabled={saving}
>
{saving
? t("setupWizard.actions.saving")
: t("setupWizard.actions.next")}
</Button>
</div>
</div>
</div>
);
}
+189
View File
@@ -0,0 +1,189 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Switch } from "@/components/ui/switch";
import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import axios from "axios";
import useSWR from "swr";
const EVENTS = "events";
const CONTINUOUS = "continuous";
const MODES = [EVENTS, CONTINUOUS] as const;
type SetupRecordingProps = {
cameraNames: string[];
onNext: () => void;
onBack: () => void;
onSkip: () => void;
};
export default function SetupRecording({
cameraNames,
onNext,
onBack,
onSkip,
}: SetupRecordingProps) {
const { t } = useTranslation(["views/setup"]);
const [enabled, setEnabled] = useState(true);
const [mode, setMode] = useState<string>(EVENTS);
const [retentionDays, setRetentionDays] = useState(10);
const [saving, setSaving] = useState(false);
const { data: stats } = useSWR("stats", { revalidateOnFocus: false });
const storageInfo = stats?.service?.storage?.["/tmp/frigate/recordings"];
const freeGb = storageInfo ? Math.round(storageInfo.free / 1024) : null;
const cameraCount = cameraNames.length;
// Rough estimate: ~2 Mbps per camera continuous recording
const estimatedDays =
freeGb && cameraCount > 0
? Math.round((freeGb * 1024) / ((2 * 0.125 * 86400) / 1024) / cameraCount)
: null;
const handleSave = useCallback(async () => {
setSaving(true);
try {
const record: Record<string, unknown> = { enabled };
if (enabled) {
record.alerts = { retain: { days: retentionDays } };
record.detections = { retain: { days: retentionDays } };
// written even when off, so switching modes back turns it off again
record.continuous = { days: mode === CONTINUOUS ? retentionDays : 0 };
}
await axios.put("config/set", {
config_data: { record },
requires_restart: 1,
});
onNext();
} catch {
toast.error(t("setupWizard.errors.saveFailed"));
} finally {
setSaving(false);
}
}, [enabled, mode, retentionDays, onNext, t]);
return (
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="text-xl font-semibold">
{t("setupWizard.recording.title")}
</h2>
<p className="mt-1 text-sm text-muted-foreground">
{t("setupWizard.recording.description")}
</p>
</div>
{cameraCount === 0 && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.recording.noCameras")}
</p>
)}
<div className="flex items-center justify-between rounded-md border p-4">
<Label htmlFor="recording-toggle" className="font-medium">
{t("setupWizard.recording.enableRecording")}
</Label>
<Switch
id="recording-toggle"
checked={enabled}
onCheckedChange={setEnabled}
/>
</div>
{enabled && (
<>
<div className="flex flex-col gap-2">
<Label>{t("setupWizard.recording.modeLabel")}</Label>
<RadioGroup value={mode} onValueChange={setMode}>
{MODES.map((option) => (
<div key={option} className="flex flex-col gap-0.5">
<div className="flex items-center space-x-2">
<RadioGroupItem
value={option}
id={`recording-mode-${option}`}
className={
mode === option
? "bg-selected from-selected/50 to-selected/90 text-selected"
: "bg-secondary from-secondary/50 to-secondary/90 text-secondary"
}
/>
<label
htmlFor={`recording-mode-${option}`}
className="cursor-pointer text-sm font-medium"
>
{t(`setupWizard.recording.modes.${option}.label`)}
</label>
</div>
<p className="ml-6 text-xs text-muted-foreground">
{t(`setupWizard.recording.modes.${option}.description`)}
</p>
</div>
))}
</RadioGroup>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="retention-days">
{t("setupWizard.recording.retentionDays")}
</Label>
<Input
id="retention-days"
type="number"
min={1}
max={365}
value={retentionDays}
// drop the spinner arrows; typing and arrow keys still work
className="[appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
onChange={(e) =>
setRetentionDays(Math.max(1, parseInt(e.target.value) || 1))
}
/>
<p className="text-xs text-muted-foreground">
{t(`setupWizard.recording.retentionHint.${mode}`)}
</p>
</div>
{mode === CONTINUOUS &&
freeGb !== null &&
estimatedDays !== null &&
cameraCount > 0 && (
<p className="rounded-md bg-muted p-3 text-sm text-muted-foreground">
{t("setupWizard.recording.storageEstimate", {
free: freeGb,
days: estimatedDays,
cameras: cameraCount,
})}
</p>
)}
</>
)}
<div className="flex flex-col gap-3 pt-6 sm:flex-row sm:justify-end sm:gap-4">
<Button type="button" onClick={onBack}>
{t("setupWizard.actions.back")}
</Button>
<div className="flex flex-1 justify-end gap-3">
<Button type="button" onClick={onSkip}>
{t("setupWizard.actions.skip")}
</Button>
<Button
type="button"
variant="select"
onClick={handleSave}
disabled={saving}
>
{saving
? t("setupWizard.actions.saving")
: t("setupWizard.actions.next")}
</Button>
</div>
</div>
</div>
);
}
+37
View File
@@ -0,0 +1,37 @@
import Logo from "@/components/Logo";
import { Button } from "@/components/ui/button";
import { useTranslation } from "react-i18next";
type SetupWelcomeProps = {
onNext: () => void;
onSkip: () => void;
};
export default function SetupWelcome({ onNext, onSkip }: SetupWelcomeProps) {
const { t } = useTranslation(["views/setup"]);
return (
<div className="flex flex-col items-center gap-6 py-4">
<Logo className="h-16 w-16" />
<div className="text-center">
<h2 className="text-2xl font-semibold">
{t("setupWizard.welcome.title")}
</h2>
<p className="mt-2 text-muted-foreground">
{t("setupWizard.welcome.description")}
</p>
</div>
<div className="flex w-full flex-col gap-3 pt-4">
<Button variant="select" className="w-full" onClick={onNext}>
{t("setupWizard.welcome.getStarted")}
</Button>
<button
className="text-sm text-muted-foreground hover:text-primary"
onClick={onSkip}
>
{t("setupWizard.welcome.skipSetup")}
</button>
</div>
</div>
);
}
+284
View File
@@ -0,0 +1,284 @@
import StepIndicator from "@/components/indicators/StepIndicator";
import SetupAccount from "@/components/setup/SetupAccount";
import SetupCamera from "@/components/setup/SetupCamera";
import SetupComplete from "@/components/setup/SetupComplete";
import SetupDetector from "@/components/setup/SetupDetector";
import SetupHwAccel from "@/components/setup/SetupHwAccel";
import SetupRecording from "@/components/setup/SetupRecording";
import SetupWelcome from "@/components/setup/SetupWelcome";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { useTheme } from "@/context/theme-provider";
import { FrigateConfig } from "@/types/frigateConfig";
import { dismissSetup } from "@/utils/setupWizard";
import { useCallback, useMemo, useReducer } from "react";
import { useTranslation } from "react-i18next";
import { LuMoon, LuSun } from "react-icons/lu";
import useSWR from "swr";
type StepKey =
| "welcome"
| "account"
| "camera"
| "detector"
| "hwaccel"
| "recording"
| "complete";
const STEP_KEYS: StepKey[] = [
"welcome",
"account",
"camera",
"detector",
"hwaccel",
"recording",
"complete",
];
type WizardState = {
currentStep: number;
cameraNames: string[];
detectorHardwareKey?: string;
// camera name -> detect stream codec
detectCodecs: Record<string, string>;
// camera adds apply live, so they don't count toward needing a restart
restartRequired: boolean;
configuredSteps: {
camera: boolean;
hwaccel: boolean;
detector: boolean;
recording: boolean;
};
};
type WizardAction =
| { type: "NEXT_STEP" }
| { type: "PREV_STEP" }
| {
type: "CAMERAS_ADDED";
cameraNames: string[];
detectCodecs: Record<string, string>;
}
| {
type: "STEP_CONFIGURED";
step: keyof WizardState["configuredSteps"];
savedConfig: boolean;
}
| { type: "DETECTOR_DONE"; configured: boolean; hardwareKey?: string }
| { type: "SKIP_STEP" };
const initialState: WizardState = {
currentStep: 0,
cameraNames: [],
detectCodecs: {},
restartRequired: false,
configuredSteps: {
camera: false,
hwaccel: false,
detector: false,
recording: false,
},
};
function wizardReducer(state: WizardState, action: WizardAction): WizardState {
switch (action.type) {
case "NEXT_STEP":
return { ...state, currentStep: state.currentStep + 1 };
case "PREV_STEP":
return {
...state,
currentStep: Math.max(0, state.currentStep - 1),
};
case "CAMERAS_ADDED":
return {
...state,
currentStep: state.currentStep + 1,
cameraNames: action.cameraNames,
detectCodecs: action.detectCodecs,
configuredSteps: { ...state.configuredSteps, camera: true },
};
case "STEP_CONFIGURED":
return {
...state,
currentStep: state.currentStep + 1,
restartRequired: state.restartRequired || action.savedConfig,
configuredSteps: { ...state.configuredSteps, [action.step]: true },
};
case "DETECTOR_DONE":
return {
...state,
currentStep: state.currentStep + 1,
detectorHardwareKey: action.hardwareKey ?? state.detectorHardwareKey,
restartRequired: state.restartRequired || action.configured,
configuredSteps: {
...state.configuredSteps,
detector: state.configuredSteps.detector || action.configured,
},
};
case "SKIP_STEP":
return { ...state, currentStep: state.currentStep + 1 };
default:
return state;
}
}
export default function SetupWizard() {
const { t } = useTranslation(["views/setup", "common"]);
const [state, dispatch] = useReducer(wizardReducer, initialState);
const { theme, systemTheme, setTheme } = useTheme();
const { data: config } = useSWR<FrigateConfig>("config", {
revalidateOnFocus: false,
});
// with native auth off there are no users to manage, so the step would lie
const steps = useMemo(
() =>
config?.auth?.enabled === false
? STEP_KEYS.filter((key) => key !== "account")
: STEP_KEYS,
[config],
);
const stepLabels = useMemo(
() => steps.map((key) => `setupWizard.steps.${key}`),
[steps],
);
const isDark = (theme === "system" ? systemTheme : theme) === "dark";
const handleSkipSetup = useCallback(() => {
dismissSetup();
window.location.href = window.baseUrl || "/";
}, []);
const handleCameraNext = useCallback(
(cameraNames?: string[], detectCodecs?: Record<string, string>) => {
if (cameraNames && cameraNames.length > 0) {
dispatch({
type: "CAMERAS_ADDED",
cameraNames,
detectCodecs: detectCodecs ?? {},
});
} else {
dispatch({ type: "SKIP_STEP" });
}
},
[],
);
const handleHwAccelNext = useCallback((saved: boolean) => {
dispatch({ type: "STEP_CONFIGURED", step: "hwaccel", savedConfig: saved });
}, []);
const handleDetectorNext = useCallback((hardwareKey: string) => {
dispatch({ type: "DETECTOR_DONE", configured: true, hardwareKey });
}, []);
const handleDetectorSkip = useCallback((hardwareKey?: string) => {
dispatch({ type: "DETECTOR_DONE", configured: false, hardwareKey });
}, []);
const handleRecordingNext = useCallback(() => {
dispatch({ type: "STEP_CONFIGURED", step: "recording", savedConfig: true });
}, []);
const handleBack = useCallback(() => {
dispatch({ type: "PREV_STEP" });
}, []);
const handleSkipStep = useCallback(() => {
dispatch({ type: "SKIP_STEP" });
}, []);
const renderStep = () => {
switch (steps[state.currentStep]) {
case "welcome":
return (
<SetupWelcome
onNext={() => dispatch({ type: "NEXT_STEP" })}
onSkip={handleSkipSetup}
/>
);
case "account":
return (
<SetupAccount
onNext={handleSkipStep}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "camera":
return <SetupCamera onNext={handleCameraNext} onBack={handleBack} />;
case "detector":
return (
<SetupDetector
cameraCount={state.cameraNames.length}
onNext={handleDetectorNext}
onBack={handleBack}
onSkip={handleDetectorSkip}
/>
);
case "hwaccel":
return (
<SetupHwAccel
detectorHardwareKey={state.detectorHardwareKey}
detectCodecs={state.detectCodecs}
onNext={handleHwAccelNext}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "recording":
return (
<SetupRecording
cameraNames={state.cameraNames}
onNext={handleRecordingNext}
onBack={handleBack}
onSkip={handleSkipStep}
/>
);
case "complete":
return (
<SetupComplete
cameraNames={state.cameraNames}
configuredSteps={state.configuredSteps}
restartRequired={state.restartRequired}
onBack={handleBack}
/>
);
default:
return null;
}
};
return (
<div className="flex min-h-dvh items-center justify-center bg-background p-4">
<Button
type="button"
variant="ghost"
size="icon"
className="fixed right-4 top-4 text-muted-foreground hover:text-primary"
aria-label={t(isDark ? "menu.darkMode.light" : "menu.darkMode.dark", {
ns: "common",
})}
onClick={() => setTheme(isDark ? "light" : "dark")}
>
{isDark ? <LuSun className="size-4" /> : <LuMoon className="size-4" />}
</Button>
<Card className="w-full max-w-lg bg-background_alt">
<CardContent className="p-6">
<StepIndicator
steps={stepLabels}
currentStep={state.currentStep}
variant="dots"
translationNameSpace="views/setup"
className="mb-4 justify-start"
/>
<div className="fade-in">{renderStep()}</div>
</CardContent>
</Card>
</div>
);
}
+2
View File
@@ -119,6 +119,7 @@ export type WizardFormData = {
probeCandidates?: string[]; // candidate URLs from probe
candidateTests?: CandidateTestMap; // test results for candidates
hasBackchannel?: boolean; // true if camera supports backchannel audio
appleCompatibility?: boolean; // camera level, covers both recording outputs
onvif?: {
enabled: boolean;
host: string;
@@ -163,6 +164,7 @@ export type CameraConfigData = {
enabled: boolean;
friendly_name?: string;
ffmpeg: {
apple_compatibility?: boolean;
inputs: {
path: string;
roles: string[];
+11
View File
@@ -11,3 +11,14 @@ export type DetectionHardware = {
count: number;
unlimited: boolean;
};
export type HwaccelFamily = {
key: string;
// keyed by codec, or a single "any" preset when it decodes every codec
presets: Record<string, string>;
};
export type HwaccelRecommendation = {
recommended: string;
available: HwaccelFamily[];
};
+23
View File
@@ -1,6 +1,7 @@
import { baseUrl } from "@/api/baseUrl";
import { generateFixedHash, isValidId } from "./stringUtil";
import type { LiveStreamMetadata } from "@/types/live";
import type { StreamConfig } from "@/types/cameraWizard";
/**
* Processes a user-entered camera name and returns both the final camera name
@@ -205,3 +206,25 @@ const REPLAY_CAMERA_PREFIX = "_replay_";
export function isReplayCamera(name: string): boolean {
return name.startsWith(REPLAY_CAMERA_PREFIX);
}
const HEVC_CODEC_NAMES = ["hevc", "h265"];
function isHevcCodec(codec?: string): boolean {
return HEVC_CODEC_NAMES.includes((codec ?? "").trim().toLowerCase());
}
function isRecordingStream(stream: StreamConfig): boolean {
return stream.roles.includes("record") || stream.roles.includes("record_sub");
}
/**
* First recording stream probed as H.265. The other record output's codec
* doesn't matter: ffmpeg drops `-tag:v hvc1` on anything that isn't HEVC.
*/
export function hevcRecordingStreamId(
streams: StreamConfig[],
): string | undefined {
return streams.find(
(s) => isRecordingStream(s) && isHevcCodec(s.testResult?.videoCodec),
)?.id;
}
+19
View File
@@ -0,0 +1,19 @@
// dismissing the setup wizard is per-device UI state, so it lives in the
// browser rather than in the config the wizard exists to write
const DISMISSED_KEY = "frigate-setup-dismissed";
export function isSetupDismissed(): boolean {
try {
return localStorage.getItem(DISMISSED_KEY) === "true";
} catch {
return false;
}
}
export function dismissSetup(): void {
try {
localStorage.setItem(DISMISSED_KEY, "true");
} catch {
// storage can be unavailable; showing the wizard again beats failing here
}
}