Camera profile support (#22482)

* add CameraProfileConfig model for named config overrides

* add profiles field to CameraConfig

* add active_profile field to FrigateConfig

Runtime-only field excluded from YAML serialization, tracks which
profile is currently active.

* add ProfileManager for profile activation and persistence

Handles snapshotting base configs, applying profile overrides via
deep_merge + apply_section_update, publishing ZMQ updates, and
persisting active profile to /config/.active_profile.

* add profile API endpoints (GET /profiles, GET/PUT /profile)

* add MQTT and dispatcher integration for profiles

- Subscribe to frigate/profile/set MQTT topic
- Publish profile/state and profiles/available on connect
- Add _on_profile_command handler to dispatcher
- Broadcast active profile state on WebSocket connect

* wire ProfileManager into app startup and FastAPI

- Create ProfileManager after dispatcher init
- Restore persisted profile on startup
- Pass dispatcher and profile_manager to FastAPI app

* add tests for invalid profile values and keys

Tests that Pydantic rejects: invalid field values (fps: "not_a_number"),
unknown section keys (ffmpeg in profile), invalid nested values, and
invalid profiles in full config parsing.

* formatting

* fix CameraLiveConfig JSON serialization error on profile activation

refactor _publish_updates to only publish ZMQ updates for
sections that actually changed, not all sections on affected cameras.

* consolidate

* add enabled field to camera profiles for enabling/disabling cameras

* add zones support to camera profiles

* add frontend profile types, color utility, and config save support

* add profile state management and save preview support

* add profileName prop to BaseSection for profile-aware config editing

* add profile section dropdown and wire into camera settings pages

* add per-profile camera enable/disable to Camera Management view

* add profiles summary page with card-based layout and fix backend zone comparison bug

* add active profile badge to settings toolbar

* i18n

* add red dot for any pending changes including profiles

* profile support for mask and zone editor

* fix hidden field validation errors caused by lodash wildcard and schema gaps

lodash unset does not support wildcard (*) segments, so hidden fields like
filters.*.mask were never stripped from form data, leaving null raw_coordinates
that fail RJSF anyOf validation. Add unsetWithWildcard helper and also strip
hidden fields from the JSON schema itself as defense-in-depth.

* add face_recognition and lpr to profile-eligible sections

* move profile dropdown from section panes to settings header

* add profiles enable toggle and improve empty state

* formatting

* tweaks

* tweak colors and switch

* fix profile save diff, masksAndZones delete, and config sync

* ui tweaks

* ensure profile manager gets updated config

* rename profile settings to ui settings

* refactor profilesview and add dots/border colors when overridden

* implement an update_config method for profile manager

* fix mask deletion

* more unique colors

* add top-level profiles config section with friendly names

* implement profile friendly names and improve profile UI

- Add ProfileDefinitionConfig type and profiles field to FrigateConfig
- Use ProfilesApiResponse type with friendly_name support throughout
- Replace Record<string, unknown> with proper JsonObject/JsonValue types
- Add profile creation form matching zone pattern (Zod + NameAndIdFields)
- Add pencil icon for renaming profile friendly names in ProfilesView
- Move Profiles menu item to first under Camera Configuration
- Add activity indicators on save/rename/delete buttons
- Display friendly names in CameraManagementView profile selector
- Fix duplicate colored dots in management profile dropdown
- Fix i18n namespace for overridden base config tooltips
- Move profile override deletion from dropdown trash icon to footer
  button with confirmation dialog, matching Reset to Global pattern
- Remove Add Profile from section header dropdown to prevent saving
  camera overrides before top-level profile definition exists
- Clean up newProfiles state after API profile deletion
- Refresh profiles SWR cache after saving profile definitions

* remove profile badge in settings and add profiles to main menu

* use icon only on mobile

* change color order

* docs

* show activity indicator on trash icon while deleting a profile

* tweak language

* immediately create profiles on backend instead of deferring to Save All

* hide restart-required fields when editing a profile section

fields that require a restart cannot take effect via profile switching,
so they are merged into hiddenFields when profileName is set

* show active profile indicator in desktop status bar

* fix profile config inheritance bug where Pydantic defaults override base values

The /config API was dumping profile overrides with model_dump() which included
all Pydantic defaults. When the frontend merged these over
the camera's base config, explicitly-set base values were
lost. Now profile overrides are re-dumped with exclude_unset=True so only
user-specified fields are returned.

Also fixes the Save All path generating spurious deletion markers for
restart-required fields that are hidden during profile
editing but not excluded from the raw data sanitization in
prepareSectionSavePayload.

* docs tweaks

* docs tweak

* formatting

* formatting

* fix typing

* fix test pollution

test_maintainer was injecting MagicMock() into sys.modules["frigate.config.camera.updater"] at module load time and never restoring it. When the profile tests later imported CameraConfigUpdateEnum and CameraConfigUpdateTopic from that module, they got mock objects instead of the real dataclass/enum, so equality comparisons always failed

* remove

* fix settings showing profile-merged values when editing base config

When a profile is active, the in-memory config contains effective
(profile-merged) values. The settings UI was displaying these merged
values even when the "Base Config" view was selected.

Backend: snapshot pre-profile base configs in ProfileManager and expose
them via a `base_config` key in the /api/config camera response when a
profile is active. The top-level sections continue to reflect the
effective running config.

Frontend: read from `base_config` when available in BaseSection,
useConfigOverride, useAllCameraOverrides, and prepareSectionSavePayload.
Include formData labels in Object/Audio switches widgets so that labels
added only by a profile override remain visible when editing that profile.

* use rasterized_mask as field

makes it easier to exclude from the schema with exclude=True
prevents leaking of the field when using model_dump for profiles

* fix zones

- Fix zone colors not matching across profiles by falling back to base zone color when profile zone data lacks a color field
- Use base_config for base-layer values in masks/zones view so profile-merged values don't pollute the base config editing view
- Handle zones separately in profile manager snapshot/restore since ZoneConfig requires special serialization (color as private attr, contour generation)
- Inherit base zone color and generate contours for profile zone overrides in profile manager

* formatting

* don't require restart for camera enabled change for profiles

* publish camera state when changing profiles

* formatting

* remove available profiles from mqtt

* improve typing
This commit is contained in:
Josh Hawkins
2026-03-19 09:47:57 -05:00
committed by GitHub
parent a05f35c747
commit c93dad9bd9
47 changed files with 4591 additions and 458 deletions
+312 -40
View File
@@ -1,4 +1,4 @@
import { FrigateConfig } from "@/types/frigateConfig";
import { CameraConfig, FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -35,17 +35,19 @@ import { useTranslation } from "react-i18next";
import { useDocDomain } from "@/hooks/use-doc-domain";
import { cn } from "@/lib/utils";
import { ProfileState } from "@/types/profile";
type MasksAndZoneViewProps = {
selectedCamera: string;
selectedZoneMask?: PolygonType[];
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
profileState?: ProfileState;
};
export default function MasksAndZonesView({
selectedCamera,
selectedZoneMask,
setUnsavedChanges,
profileState,
}: MasksAndZoneViewProps) {
const { t } = useTranslation(["views/settings"]);
const { getLocaleDocUrl } = useDocDomain();
@@ -70,6 +72,10 @@ export default function MasksAndZonesView({
const [activeLine, setActiveLine] = useState<number | undefined>();
const [snapPoints, setSnapPoints] = useState(false);
// Profile state
const currentEditingProfile =
profileState?.editingProfile[selectedCamera] ?? null;
const cameraConfig = useMemo(() => {
if (config && selectedCamera) {
return config.cameras[selectedCamera];
@@ -228,18 +234,94 @@ export default function MasksAndZonesView({
[allPolygons, scaledHeight, scaledWidth, t],
);
// Helper to dim colors for base polygons in profile mode
const dimColor = useCallback(
(color: number[]): number[] => {
if (!currentEditingProfile) return color;
return color.map((c) => Math.round(c * 0.4 + 153 * 0.6));
},
[currentEditingProfile],
);
useEffect(() => {
if (cameraConfig && containerRef.current && scaledWidth && scaledHeight) {
const zones = Object.entries(cameraConfig.zones).map(
([name, zoneData], index) => ({
const profileData = currentEditingProfile
? cameraConfig.profiles?.[currentEditingProfile]
: undefined;
// When a profile is active, the top-level sections contain
// effective (profile-merged) values. Use base_config for the
// original base values so the "Base Config" view is accurate and
// the base layer for profile merging is correct.
const baseMotion = (cameraConfig.base_config?.motion ??
cameraConfig.motion) as typeof cameraConfig.motion;
const baseObjects = (cameraConfig.base_config?.objects ??
cameraConfig.objects) as typeof cameraConfig.objects;
const baseZones = (cameraConfig.base_config?.zones ??
cameraConfig.zones) as typeof cameraConfig.zones;
// Build base zone names set for source tracking
const baseZoneNames = new Set(Object.keys(baseZones));
const profileZoneNames = new Set(Object.keys(profileData?.zones ?? {}));
const baseMotionMaskNames = new Set(Object.keys(baseMotion.mask || {}));
const profileMotionMaskNames = new Set(
Object.keys(profileData?.motion?.mask ?? {}),
);
const baseGlobalObjectMaskNames = new Set(
Object.keys(baseObjects.mask || {}),
);
const profileGlobalObjectMaskNames = new Set(
Object.keys(profileData?.objects?.mask ?? {}),
);
// Merge zones: profile zones override base zones with same name
const mergedZones = new Map<
string,
{
data: CameraConfig["zones"][string];
source: "base" | "profile" | "override";
}
>();
for (const [name, zoneData] of Object.entries(baseZones)) {
if (currentEditingProfile && profileZoneNames.has(name)) {
// Profile overrides this base zone
mergedZones.set(name, {
data: profileData!.zones![name]!,
source: "override",
});
} else {
mergedZones.set(name, {
data: zoneData,
source: currentEditingProfile ? "base" : "base",
});
}
}
// Add profile-only zones
if (profileData?.zones) {
for (const [name, zoneData] of Object.entries(profileData.zones)) {
if (!baseZoneNames.has(name)) {
mergedZones.set(name, { data: zoneData!, source: "profile" });
}
}
}
let zoneIndex = 0;
const zones: Polygon[] = [];
for (const [name, { data: zoneData, source }] of mergedZones) {
const isBase = source === "base" && !!currentEditingProfile;
const baseColor = zoneData.color ??
baseZones[name]?.color ?? [128, 128, 0];
zones.push({
type: "zone" as PolygonType,
typeIndex: index,
typeIndex: zoneIndex,
camera: cameraConfig.name,
name,
friendly_name: zoneData.friendly_name,
enabled: zoneData.enabled,
enabled_in_config: zoneData.enabled_in_config,
objects: zoneData.objects,
objects: zoneData.objects ?? [],
points: interpolatePoints(
parseCoordinates(zoneData.coordinates),
1,
@@ -248,21 +330,60 @@ export default function MasksAndZonesView({
scaledHeight,
),
distances:
zoneData.distances?.map((distance) => parseFloat(distance)) ?? [],
zoneData.distances?.map((distance: string) =>
parseFloat(distance),
) ?? [],
isFinished: true,
color: zoneData.color,
}),
);
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
});
zoneIndex++;
}
let motionMasks: Polygon[] = [];
let globalObjectMasks: Polygon[] = [];
let objectMasks: Polygon[] = [];
// Merge motion masks
const mergedMotionMasks = new Map<
string,
{
data: CameraConfig["motion"]["mask"][string];
source: "base" | "profile" | "override";
}
>();
// Motion masks are a dict with mask_id as key
motionMasks = Object.entries(cameraConfig.motion.mask || {}).map(
([maskId, maskData], index) => ({
for (const [maskId, maskData] of Object.entries(baseMotion.mask || {})) {
if (currentEditingProfile && profileMotionMaskNames.has(maskId)) {
mergedMotionMasks.set(maskId, {
data: profileData!.motion!.mask![maskId],
source: "override",
});
} else {
mergedMotionMasks.set(maskId, {
data: maskData,
source: currentEditingProfile ? "base" : "base",
});
}
}
if (profileData?.motion?.mask) {
for (const [maskId, maskData] of Object.entries(
profileData.motion.mask,
)) {
if (!baseMotionMaskNames.has(maskId)) {
mergedMotionMasks.set(maskId, {
data: maskData,
source: "profile",
});
}
}
}
let motionMaskIndex = 0;
const motionMasks: Polygon[] = [];
for (const [maskId, { data: maskData, source }] of mergedMotionMasks) {
const isBase = source === "base" && !!currentEditingProfile;
const baseColor = [0, 0, 255];
motionMasks.push({
type: "motion_mask" as PolygonType,
typeIndex: index,
typeIndex: motionMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
@@ -278,15 +399,59 @@ export default function MasksAndZonesView({
),
distances: [],
isFinished: true,
color: [0, 0, 255],
}),
);
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
});
motionMaskIndex++;
}
// Global object masks are a dict with mask_id as key
globalObjectMasks = Object.entries(cameraConfig.objects.mask || {}).map(
([maskId, maskData], index) => ({
// Merge global object masks
const mergedGlobalObjectMasks = new Map<
string,
{
data: CameraConfig["objects"]["mask"][string];
source: "base" | "profile" | "override";
}
>();
for (const [maskId, maskData] of Object.entries(baseObjects.mask || {})) {
if (currentEditingProfile && profileGlobalObjectMaskNames.has(maskId)) {
mergedGlobalObjectMasks.set(maskId, {
data: profileData!.objects!.mask![maskId],
source: "override",
});
} else {
mergedGlobalObjectMasks.set(maskId, {
data: maskData,
source: currentEditingProfile ? "base" : "base",
});
}
}
if (profileData?.objects?.mask) {
for (const [maskId, maskData] of Object.entries(
profileData.objects.mask,
)) {
if (!baseGlobalObjectMaskNames.has(maskId)) {
mergedGlobalObjectMasks.set(maskId, {
data: maskData,
source: "profile",
});
}
}
}
let objectMaskIndex = 0;
const globalObjectMasks: Polygon[] = [];
for (const [
maskId,
{ data: maskData, source },
] of mergedGlobalObjectMasks) {
const isBase = source === "base" && !!currentEditingProfile;
const baseColor = [128, 128, 128];
globalObjectMasks.push({
type: "object_mask" as PolygonType,
typeIndex: index,
typeIndex: objectMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
@@ -302,13 +467,41 @@ export default function MasksAndZonesView({
),
distances: [],
isFinished: true,
color: [128, 128, 128],
}),
);
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
});
objectMaskIndex++;
}
let objectMaskIndex = globalObjectMasks.length;
objectMaskIndex = globalObjectMasks.length;
objectMasks = Object.entries(cameraConfig.objects.filters)
// Build per-object filter mask names for profile tracking
const baseFilterMaskNames = new Set<string>();
for (const [, filterConfig] of Object.entries(
baseObjects.filters || {},
)) {
for (const maskId of Object.keys(filterConfig.mask || {})) {
if (!maskId.startsWith("global_")) {
baseFilterMaskNames.add(maskId);
}
}
}
const profileFilterMaskNames = new Set<string>();
if (profileData?.objects?.filters) {
for (const [, filterConfig] of Object.entries(
profileData.objects.filters,
)) {
if (filterConfig?.mask) {
for (const maskId of Object.keys(filterConfig.mask)) {
profileFilterMaskNames.add(maskId);
}
}
}
}
// Per-object filter masks (base)
const objectMasks: Polygon[] = Object.entries(baseObjects.filters || {})
.filter(
([, filterConfig]) =>
filterConfig.mask && Object.keys(filterConfig.mask).length > 0,
@@ -316,22 +509,36 @@ export default function MasksAndZonesView({
.flatMap(([objectName, filterConfig]): Polygon[] => {
return Object.entries(filterConfig.mask || {}).flatMap(
([maskId, maskData]) => {
// Skip if this mask is a global mask (prefixed with "global_")
if (maskId.startsWith("global_")) {
return [];
}
const newMask = {
const source: "base" | "override" = currentEditingProfile
? profileFilterMaskNames.has(maskId)
? "override"
: "base"
: "base";
const isBase = source === "base" && !!currentEditingProfile;
// If override, use profile data
const finalData =
source === "override" && profileData?.objects?.filters
? (profileData.objects.filters[objectName]?.mask?.[maskId] ??
maskData)
: maskData;
const baseColor = [128, 128, 128];
const newMask: Polygon = {
type: "object_mask" as PolygonType,
typeIndex: objectMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
enabled: maskData.enabled,
enabled_in_config: maskData.enabled_in_config,
friendly_name: finalData.friendly_name,
enabled: finalData.enabled,
enabled_in_config: finalData.enabled_in_config,
objects: [objectName],
points: interpolatePoints(
parseCoordinates(maskData.coordinates),
parseCoordinates(finalData.coordinates),
1,
1,
scaledWidth,
@@ -339,7 +546,8 @@ export default function MasksAndZonesView({
),
distances: [],
isFinished: true,
color: [128, 128, 128],
color: isBase ? dimColor(baseColor) : baseColor,
polygonSource: currentEditingProfile ? source : undefined,
};
objectMaskIndex++;
return [newMask];
@@ -347,6 +555,45 @@ export default function MasksAndZonesView({
);
});
// Add profile-only per-object filter masks
if (profileData?.objects?.filters) {
for (const [objectName, filterConfig] of Object.entries(
profileData.objects.filters,
)) {
if (filterConfig?.mask) {
for (const [maskId, maskData] of Object.entries(
filterConfig.mask,
)) {
if (!baseFilterMaskNames.has(maskId) && maskData) {
const baseColor = [128, 128, 128];
objectMasks.push({
type: "object_mask" as PolygonType,
typeIndex: objectMaskIndex,
camera: cameraConfig.name,
name: maskId,
friendly_name: maskData.friendly_name,
enabled: maskData.enabled,
enabled_in_config: maskData.enabled_in_config,
objects: [objectName],
points: interpolatePoints(
parseCoordinates(maskData.coordinates),
1,
1,
scaledWidth,
scaledHeight,
),
distances: [],
isFinished: true,
color: baseColor,
polygonSource: "profile",
});
objectMaskIndex++;
}
}
}
}
}
setAllPolygons([
...zones,
...motionMasks,
@@ -386,7 +633,14 @@ export default function MasksAndZonesView({
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cameraConfig, containerRef, scaledHeight, scaledWidth]);
}, [
cameraConfig,
containerRef,
scaledHeight,
scaledWidth,
currentEditingProfile,
dimColor,
]);
useEffect(() => {
if (editPane === undefined) {
@@ -403,6 +657,15 @@ export default function MasksAndZonesView({
}
}, [selectedCamera]);
// Cancel editing when profile selection changes
useEffect(() => {
if (editPaneRef.current !== undefined) {
handleCancel();
}
// we only want to react to profile changes
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentEditingProfile]);
useSearchEffect("object_mask", (coordinates: string) => {
if (!scaledWidth || !scaledHeight || isLoading) {
return false;
@@ -473,6 +736,7 @@ export default function MasksAndZonesView({
setActiveLine={setActiveLine}
snapPoints={snapPoints}
setSnapPoints={setSnapPoints}
editingProfile={currentEditingProfile}
/>
)}
{editPane == "motion_mask" && (
@@ -488,6 +752,7 @@ export default function MasksAndZonesView({
onSave={handleSave}
snapPoints={snapPoints}
setSnapPoints={setSnapPoints}
editingProfile={currentEditingProfile}
/>
)}
{editPane == "object_mask" && (
@@ -503,13 +768,14 @@ export default function MasksAndZonesView({
onSave={handleSave}
snapPoints={snapPoints}
setSnapPoints={setSnapPoints}
editingProfile={currentEditingProfile}
/>
)}
{editPane === undefined && (
<>
<Heading as="h4" className="mb-2">
{t("menu.masksAndZones")}
</Heading>
<div className="mb-2 flex items-center justify-between">
<Heading as="h4">{t("menu.masksAndZones")}</Heading>
</div>
<div className="flex w-full flex-col">
{(selectedZoneMask === undefined ||
selectedZoneMask.includes("zone" as PolygonType)) && (
@@ -575,6 +841,8 @@ export default function MasksAndZonesView({
setIsLoading={setIsLoading}
loadingPolygonIndex={loadingPolygonIndex}
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
/>
))}
</div>
@@ -649,6 +917,8 @@ export default function MasksAndZonesView({
setIsLoading={setIsLoading}
loadingPolygonIndex={loadingPolygonIndex}
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
/>
))}
</div>
@@ -723,6 +993,8 @@ export default function MasksAndZonesView({
setIsLoading={setIsLoading}
loadingPolygonIndex={loadingPolygonIndex}
setLoadingPolygonIndex={setLoadingPolygonIndex}
editingProfile={currentEditingProfile}
allProfileNames={profileState?.allProfileNames}
/>
))}
</div>