Settings rework (#11613)

* refactor settings to be consistent with other page structure

* Implement non auto live

* Adjust missing view

* Quick fix

* Clarify settings options

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>

* Update naming and config restarts

* Rename

---------

Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com>
This commit is contained in:
Nicolas Mowen
2024-05-29 08:01:39 -06:00
committed by GitHub
parent d5f6decd30
commit 6dd9660ecd
11 changed files with 128 additions and 85 deletions

View File

@@ -50,6 +50,7 @@ export default function LiveDashboardView({
const containerRef = useRef<HTMLDivElement>(null);
// recent events
const { payload: eventUpdate } = useFrigateReviews();
const { data: allEvents, mutate: updateEvents } = useSWR<ReviewSegment[]>([
"review",
@@ -92,6 +93,7 @@ export default function LiveDashboardView({
// camera live views
const [autoLiveView] = usePersistence("autoLiveView", true);
const [windowVisible, setWindowVisible] = useState(true);
const visibilityListener = useCallback(() => {
setWindowVisible(document.visibilityState == "visible");
@@ -261,6 +263,7 @@ export default function LiveDashboardView({
}
cameraConfig={camera}
preferredLiveMode={isSafari ? "webrtc" : "mse"}
autoLive={autoLiveView}
onClick={() => onSelectCamera(camera.name)}
/>
);

View File

@@ -0,0 +1,170 @@
import { useCallback, useEffect, useState } from "react";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import { FrigateConfig } from "@/types/frigateConfig";
import { Toaster } from "@/components/ui/sonner";
import useSWR from "swr";
import Heading from "@/components/ui/heading";
import { User } from "@/types/user";
import { Button } from "@/components/ui/button";
import SetPasswordDialog from "@/components/overlay/SetPasswordDialog";
import axios from "axios";
import CreateUserDialog from "@/components/overlay/CreateUserDialog";
import { toast } from "sonner";
import DeleteUserDialog from "@/components/overlay/DeleteUserDialog";
import { Card } from "@/components/ui/card";
import { HiTrash } from "react-icons/hi";
import { FaUserEdit } from "react-icons/fa";
import { LuPlus } from "react-icons/lu";
export default function AuthenticationView() {
const { data: config } = useSWR<FrigateConfig>("config");
const { data: users, mutate: mutateUsers } = useSWR<User[]>("users");
const [showSetPassword, setShowSetPassword] = useState(false);
const [showCreate, setShowCreate] = useState(false);
const [showDelete, setShowDelete] = useState(false);
const [selectedUser, setSelectedUser] = useState<string>();
useEffect(() => {
document.title = "Authentication Settings - Frigate";
}, []);
const onSavePassword = useCallback((user: string, password: string) => {
axios
.put(`users/${user}/password`, {
password: password,
})
.then((response) => {
if (response.status == 200) {
setShowSetPassword(false);
}
})
.catch((_error) => {
toast.error("Error setting password", {
position: "top-center",
});
});
}, []);
const onCreate = async (user: string, password: string) => {
try {
await axios.post("users", {
username: user,
password: password,
});
setShowCreate(false);
mutateUsers((users) => {
users?.push({ username: user });
return users;
}, false);
} catch (error) {
toast.error("Error creating user. Check server logs.", {
position: "top-center",
});
}
};
const onDelete = async (user: string) => {
try {
await axios.delete(`users/${user}`);
setShowDelete(false);
mutateUsers((users) => {
return users?.filter((u) => {
return u.username !== user;
});
}, false);
} catch (error) {
toast.error("Error deleting user. Check server logs.", {
position: "top-center",
});
}
};
if (!config || !users) {
return <ActivityIndicator />;
}
return (
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="order-last mb-10 mt-2 flex h-full w-full flex-col overflow-y-auto rounded-lg border-[1px] border-secondary-foreground bg-background_alt p-2 md:order-none md:mb-0 md:mr-2 md:mt-0">
<div className="flex flex-row items-center justify-between gap-2">
<Heading as="h3" className="my-2">
Users
</Heading>
<Button
className="flex items-center gap-1"
variant="default"
onClick={() => {
setShowCreate(true);
}}
>
<LuPlus className="text-secondary-foreground" />
Add User
</Button>
</div>
<div className="mt-3 space-y-3">
{users.map((u) => (
<Card key={u.username} className="mb-1 p-2">
<div className="flex items-center gap-3">
<div className="ml-3 flex flex-none shrink overflow-hidden text-ellipsis align-middle text-lg">
{u.username}
</div>
<div className="flex flex-1 justify-end space-x-2">
<Button
className="flex items-center gap-1"
variant="secondary"
onClick={() => {
setShowSetPassword(true);
setSelectedUser(u.username);
}}
>
<FaUserEdit />
<div className="hidden md:block">Update Password</div>
</Button>
<Button
className="flex items-center gap-1"
variant="destructive"
onClick={() => {
setShowDelete(true);
setSelectedUser(u.username);
}}
>
<HiTrash />
<div className="hidden md:block">Delete</div>
</Button>
</div>
</div>
</Card>
))}
</div>
</div>
<SetPasswordDialog
show={showSetPassword}
onCancel={() => {
setShowSetPassword(false);
}}
onSave={(password) => {
onSavePassword(selectedUser!, password);
}}
/>
<DeleteUserDialog
show={showDelete}
onCancel={() => {
setShowDelete(false);
}}
onDelete={() => {
onDelete(selectedUser!);
}}
/>
<CreateUserDialog
show={showCreate}
onCreate={onCreate}
onCancel={() => {
setShowCreate(false);
}}
/>
</div>
);
}

View File

@@ -0,0 +1,150 @@
import Heading from "@/components/ui/heading";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useCallback, useEffect } from "react";
import { Toaster } from "sonner";
import { toast } from "sonner";
import { Separator } from "../../components/ui/separator";
import { Button } from "../../components/ui/button";
import useSWR from "swr";
import { FrigateConfig } from "@/types/frigateConfig";
import { del as delData } from "idb-keyval";
import { usePersistence } from "@/hooks/use-persistence";
import { isSafari } from "react-device-detect";
import {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectTrigger,
} from "../../components/ui/select";
const PLAYBACK_RATE_DEFAULT = isSafari ? [0.5, 1, 2] : [0.5, 1, 2, 4, 8, 16];
export default function GeneralSettingsView() {
const { data: config } = useSWR<FrigateConfig>("config");
const clearStoredLayouts = useCallback(() => {
if (!config) {
return [];
}
Object.entries(config.camera_groups).forEach(async (value) => {
await delData(`${value[0]}-draggable-layout`)
.then(() => {
toast.success(`Cleared stored layout for ${value[0]}`, {
position: "top-center",
});
})
.catch((error) => {
toast.error(
`Failed to clear stored layout: ${error.response.data.message}`,
{ position: "top-center" },
);
});
});
}, [config]);
useEffect(() => {
document.title = "General Settings - Frigate";
}, []);
// settings
const [autoLive, setAutoLive] = usePersistence("autoLiveView", true);
const [playbackRate, setPlaybackRate] = usePersistence("playbackRate", 1);
return (
<>
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="order-last mb-10 mt-2 flex h-full w-full flex-col overflow-y-auto rounded-lg border-[1px] border-secondary-foreground bg-background_alt p-2 md:order-none md:mb-0 md:mr-2 md:mt-0">
<Heading as="h3" className="my-2">
General Settings
</Heading>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
Live Dashboard
</Heading>
<div className="mt-2 space-y-6">
<div className="space-y-3">
<div className="flex flex-row items-center justify-start gap-2">
<Switch
id="auto-live"
checked={autoLive}
onCheckedChange={setAutoLive}
/>
<Label className="cursor-pointer" htmlFor="auto-live">
Automatic Live View
</Label>
</div>
<div className="my-2 text-sm text-muted-foreground">
<p>
Automatically switch to a camera's live view when activity is
detected. Disabling this option causes static camera images on
the Live dashboard to only update once per minute.
</p>
</div>
</div>
</div>
<div className="my-3 flex w-full flex-col space-y-6">
<div className="mt-2 space-y-6">
<div className="space-y-0.5">
<div className="text-md">Stored Layouts</div>
<div className="my-2 text-sm text-muted-foreground">
<p>
The layout of cameras in a camera group can be
dragged/resized. The positions are stored in your browser's
local storage.
</p>
</div>
</div>
<Button onClick={clearStoredLayouts}>Clear All Layouts</Button>
</div>
<Separator className="my-2 flex bg-secondary" />
<Heading as="h4" className="my-2">
Recordings Viewer
</Heading>
<div className="mt-2 space-y-6">
<div className="space-y-0.5">
<div className="text-md">Default Playback Rate</div>
<div className="my-2 text-sm text-muted-foreground">
<p>Default playback rate for recordings playback.</p>
</div>
</div>
</div>
<Select
value={playbackRate?.toString()}
onValueChange={(value) => setPlaybackRate(parseFloat(value))}
>
<SelectTrigger className="w-20">
{`${playbackRate}x`}
</SelectTrigger>
<SelectContent>
<SelectGroup>
{PLAYBACK_RATE_DEFAULT.map((rate) => (
<SelectItem
key={rate}
className="cursor-pointer"
value={rate.toString()}
>
{rate}x
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
<Separator className="my-2 flex bg-secondary" />
</div>
</div>
</div>
</>
);
}

View File

@@ -0,0 +1,663 @@
import { FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { PolygonCanvas } from "@/components/settings/PolygonCanvas";
import { Polygon, PolygonType } from "@/types/canvas";
import { interpolatePoints, parseCoordinates } from "@/utils/canvasUtil";
import { Skeleton } from "@/components/ui/skeleton";
import { useResizeObserver } from "@/hooks/resize-observer";
import { LuExternalLink, LuPlus } from "react-icons/lu";
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@/components/ui/hover-card";
import copy from "copy-to-clipboard";
import { toast } from "sonner";
import { Toaster } from "@/components/ui/sonner";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import Heading from "@/components/ui/heading";
import ZoneEditPane from "@/components/settings/ZoneEditPane";
import MotionMaskEditPane from "@/components/settings/MotionMaskEditPane";
import ObjectMaskEditPane from "@/components/settings/ObjectMaskEditPane";
import PolygonItem from "@/components/settings/PolygonItem";
import { Link } from "react-router-dom";
import { isDesktop } from "react-device-detect";
import { StatusBarMessagesContext } from "@/context/statusbar-provider";
type MasksAndZoneViewProps = {
selectedCamera: string;
selectedZoneMask?: PolygonType[];
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
};
export default function MasksAndZonesView({
selectedCamera,
selectedZoneMask,
setUnsavedChanges,
}: MasksAndZoneViewProps) {
const { data: config } = useSWR<FrigateConfig>("config");
const [allPolygons, setAllPolygons] = useState<Polygon[]>([]);
const [editingPolygons, setEditingPolygons] = useState<Polygon[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [activePolygonIndex, setActivePolygonIndex] = useState<
number | undefined
>(undefined);
const [hoveredPolygonIndex, setHoveredPolygonIndex] = useState<number | null>(
null,
);
const containerRef = useRef<HTMLDivElement | null>(null);
const [editPane, setEditPane] = useState<PolygonType | undefined>(undefined);
const { addMessage } = useContext(StatusBarMessagesContext)!;
const cameraConfig = useMemo(() => {
if (config && selectedCamera) {
return config.cameras[selectedCamera];
}
}, [config, selectedCamera]);
const [{ width: containerWidth, height: containerHeight }] =
useResizeObserver(containerRef);
const aspectRatio = useMemo(() => {
if (!config) {
return undefined;
}
const camera = config.cameras[selectedCamera];
if (!camera) {
return undefined;
}
return camera.detect.width / camera.detect.height;
}, [config, selectedCamera]);
const detectHeight = useMemo(() => {
if (!config) {
return undefined;
}
const camera = config.cameras[selectedCamera];
if (!camera) {
return undefined;
}
return camera.detect.height;
}, [config, selectedCamera]);
const stretch = true;
const fitAspect = useMemo(
() => (isDesktop ? containerWidth / containerHeight : 3 / 4),
[containerWidth, containerHeight],
);
const scaledHeight = useMemo(() => {
if (containerRef.current && aspectRatio && detectHeight) {
const scaledHeight =
aspectRatio < (fitAspect ?? 0)
? Math.floor(
Math.min(containerHeight, containerRef.current?.clientHeight),
)
: isDesktop || aspectRatio > fitAspect
? Math.floor(containerWidth / aspectRatio)
: Math.floor(containerWidth / aspectRatio) / 1.5;
const finalHeight = stretch
? scaledHeight
: Math.min(scaledHeight, detectHeight);
if (finalHeight > 0) {
return finalHeight;
}
}
}, [
aspectRatio,
containerWidth,
containerHeight,
fitAspect,
detectHeight,
stretch,
]);
const scaledWidth = useMemo(() => {
if (aspectRatio && scaledHeight) {
return Math.ceil(scaledHeight * aspectRatio);
}
}, [scaledHeight, aspectRatio]);
const handleNewPolygon = (type: PolygonType) => {
if (!cameraConfig) {
return;
}
setActivePolygonIndex(allPolygons.length);
let polygonColor = [128, 128, 0];
if (type == "motion_mask") {
polygonColor = [0, 0, 220];
}
if (type == "object_mask") {
polygonColor = [128, 128, 128];
}
setEditingPolygons([
...(allPolygons || []),
{
points: [],
isFinished: false,
type,
typeIndex: 9999,
name: "",
objects: [],
camera: selectedCamera,
color: polygonColor,
},
]);
};
const handleCancel = useCallback(() => {
setEditPane(undefined);
setEditingPolygons([...allPolygons]);
setActivePolygonIndex(undefined);
setHoveredPolygonIndex(null);
setUnsavedChanges(false);
document.title = "Mask and Zone Editor - Frigate";
}, [allPolygons, setUnsavedChanges]);
const handleSave = useCallback(() => {
setAllPolygons([...(editingPolygons ?? [])]);
setHoveredPolygonIndex(null);
setUnsavedChanges(false);
addMessage(
"masks_zones",
"Restart required (masks/zones changed)",
undefined,
"masks_zones",
);
}, [editingPolygons, setUnsavedChanges, addMessage]);
useEffect(() => {
if (isLoading) {
return;
}
if (!isLoading && editPane !== undefined) {
setActivePolygonIndex(undefined);
setEditPane(undefined);
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoading]);
const handleCopyCoordinates = useCallback(
(index: number) => {
if (allPolygons && scaledWidth && scaledHeight) {
const poly = allPolygons[index];
copy(
interpolatePoints(poly.points, scaledWidth, scaledHeight, 1, 1)
.map((point) => `${point[0]},${point[1]}`)
.join(","),
);
toast.success(`Copied coordinates for ${poly.name} to clipboard.`);
} else {
toast.error("Could not copy coordinates to clipboard.");
}
},
[allPolygons, scaledHeight, scaledWidth],
);
useEffect(() => {
if (cameraConfig && containerRef.current && scaledWidth && scaledHeight) {
const zones = Object.entries(cameraConfig.zones).map(
([name, zoneData], index) => ({
type: "zone" as PolygonType,
typeIndex: index,
camera: cameraConfig.name,
name,
objects: zoneData.objects,
points: interpolatePoints(
parseCoordinates(zoneData.coordinates),
1,
1,
scaledWidth,
scaledHeight,
),
isFinished: true,
color: zoneData.color,
}),
);
let motionMasks: Polygon[] = [];
let globalObjectMasks: Polygon[] = [];
let objectMasks: Polygon[] = [];
// this can be an array or a string
motionMasks = (
Array.isArray(cameraConfig.motion.mask)
? cameraConfig.motion.mask
: cameraConfig.motion.mask
? [cameraConfig.motion.mask]
: []
).map((maskData, index) => ({
type: "motion_mask" as PolygonType,
typeIndex: index,
camera: cameraConfig.name,
name: `Motion Mask ${index + 1}`,
objects: [],
points: interpolatePoints(
parseCoordinates(maskData),
1,
1,
scaledWidth,
scaledHeight,
),
isFinished: true,
color: [0, 0, 255],
}));
const globalObjectMasksArray = Array.isArray(cameraConfig.objects.mask)
? cameraConfig.objects.mask
: cameraConfig.objects.mask
? [cameraConfig.objects.mask]
: [];
globalObjectMasks = globalObjectMasksArray.map((maskData, index) => ({
type: "object_mask" as PolygonType,
typeIndex: index,
camera: cameraConfig.name,
name: `Object Mask ${index + 1} (all objects)`,
objects: [],
points: interpolatePoints(
parseCoordinates(maskData),
1,
1,
scaledWidth,
scaledHeight,
),
isFinished: true,
color: [128, 128, 128],
}));
const globalObjectMasksCount = globalObjectMasks.length;
let index = 0;
objectMasks = Object.entries(cameraConfig.objects.filters)
.filter(([, { mask }]) => mask || Array.isArray(mask))
.flatMap(([objectName, { mask }]): Polygon[] => {
const maskArray = Array.isArray(mask) ? mask : mask ? [mask] : [];
return maskArray.flatMap((maskItem, subIndex) => {
const maskItemString = maskItem;
const newMask = {
type: "object_mask" as PolygonType,
typeIndex: subIndex,
camera: cameraConfig.name,
name: `Object Mask ${globalObjectMasksCount + index + 1} (${objectName})`,
objects: [objectName],
points: interpolatePoints(
parseCoordinates(maskItem),
1,
1,
scaledWidth,
scaledHeight,
),
isFinished: true,
color: [128, 128, 128],
};
index++;
if (
globalObjectMasksArray.some(
(globalMask) => globalMask === maskItemString,
)
) {
index--;
return [];
} else {
return [newMask];
}
});
});
setAllPolygons([
...zones,
...motionMasks,
...globalObjectMasks,
...objectMasks,
]);
setEditingPolygons([
...zones,
...motionMasks,
...globalObjectMasks,
...objectMasks,
]);
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cameraConfig, containerRef, scaledHeight, scaledWidth]);
useEffect(() => {
if (editPane === undefined) {
setEditingPolygons([...allPolygons]);
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [setEditingPolygons, allPolygons]);
useEffect(() => {
if (selectedCamera) {
setActivePolygonIndex(undefined);
setEditPane(undefined);
}
}, [selectedCamera]);
useEffect(() => {
document.title = "Mask and Zone Editor - Frigate";
}, []);
if (!cameraConfig && !selectedCamera) {
return <ActivityIndicator />;
}
return (
<>
{cameraConfig && editingPolygons && (
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="order-last mb-10 mt-2 flex h-full w-full flex-col overflow-y-auto rounded-lg border-[1px] border-secondary-foreground bg-background_alt p-2 md:order-none md:mb-0 md:mr-2 md:mt-0 md:w-3/12">
{editPane == "zone" && (
<ZoneEditPane
polygons={editingPolygons}
setPolygons={setEditingPolygons}
activePolygonIndex={activePolygonIndex}
scaledWidth={scaledWidth}
scaledHeight={scaledHeight}
isLoading={isLoading}
setIsLoading={setIsLoading}
onCancel={handleCancel}
onSave={handleSave}
/>
)}
{editPane == "motion_mask" && (
<MotionMaskEditPane
polygons={editingPolygons}
setPolygons={setEditingPolygons}
activePolygonIndex={activePolygonIndex}
scaledWidth={scaledWidth}
scaledHeight={scaledHeight}
isLoading={isLoading}
setIsLoading={setIsLoading}
onCancel={handleCancel}
onSave={handleSave}
/>
)}
{editPane == "object_mask" && (
<ObjectMaskEditPane
polygons={editingPolygons}
setPolygons={setEditingPolygons}
activePolygonIndex={activePolygonIndex}
scaledWidth={scaledWidth}
scaledHeight={scaledHeight}
isLoading={isLoading}
setIsLoading={setIsLoading}
onCancel={handleCancel}
onSave={handleSave}
/>
)}
{editPane === undefined && (
<>
<Heading as="h3" className="my-2">
Masks / Zones
</Heading>
<div className="flex w-full flex-col">
{(selectedZoneMask === undefined ||
selectedZoneMask.includes("zone" as PolygonType)) && (
<div className="mt-0 pt-0 last:border-b-[1px] last:border-secondary last:pb-3">
<div className="my-3 flex flex-row items-center justify-between">
<HoverCard>
<HoverCardTrigger asChild>
<div className="text-md cursor-default">Zones</div>
</HoverCardTrigger>
<HoverCardContent>
<div className="my-2 flex flex-col gap-2 text-sm text-primary-variant">
<p>
Zones allow you to define a specific area of the
frame so you can determine whether or not an
object is within a particular area.
</p>
<div className="flex items-center text-primary">
<Link
to="https://docs.frigate.video/configuration/zones"
target="_blank"
rel="noopener noreferrer"
className="inline"
>
Documentation{" "}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
</HoverCardContent>
</HoverCard>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
onClick={() => {
setEditPane("zone");
handleNewPolygon("zone");
}}
>
<LuPlus />
</Button>
</TooltipTrigger>
<TooltipContent>Add Zone</TooltipContent>
</Tooltip>
</div>
{allPolygons
.flatMap((polygon, index) =>
polygon.type === "zone" ? [{ polygon, index }] : [],
)
.map(({ polygon, index }) => (
<PolygonItem
key={index}
polygon={polygon}
index={index}
hoveredPolygonIndex={hoveredPolygonIndex}
setHoveredPolygonIndex={setHoveredPolygonIndex}
setActivePolygonIndex={setActivePolygonIndex}
setEditPane={setEditPane}
handleCopyCoordinates={handleCopyCoordinates}
/>
))}
</div>
)}
{(selectedZoneMask === undefined ||
selectedZoneMask.includes(
"motion_mask" as PolygonType,
)) && (
<div className="mt-3 border-t-[1px] border-secondary pt-3 first:mt-0 first:border-transparent first:pt-0 last:border-b-[1px] last:pb-3">
<div className="my-3 flex flex-row items-center justify-between">
<HoverCard>
<HoverCardTrigger asChild>
<div className="text-md cursor-default">
Motion Masks
</div>
</HoverCardTrigger>
<HoverCardContent>
<div className="my-2 flex flex-col gap-2 text-sm text-primary-variant">
<p>
Motion masks are used to prevent unwanted types
of motion from triggering detection. Over
masking will make it more difficult for objects
to be tracked.
</p>
<div className="flex items-center text-primary">
<Link
to="https://docs.frigate.video/configuration/masks#motion-masks"
target="_blank"
rel="noopener noreferrer"
className="inline"
>
Documentation{" "}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
</HoverCardContent>
</HoverCard>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
onClick={() => {
setEditPane("motion_mask");
handleNewPolygon("motion_mask");
}}
>
<LuPlus />
</Button>
</TooltipTrigger>
<TooltipContent>Add Motion Mask</TooltipContent>
</Tooltip>
</div>
{allPolygons
.flatMap((polygon, index) =>
polygon.type === "motion_mask"
? [{ polygon, index }]
: [],
)
.map(({ polygon, index }) => (
<PolygonItem
key={index}
polygon={polygon}
index={index}
hoveredPolygonIndex={hoveredPolygonIndex}
setHoveredPolygonIndex={setHoveredPolygonIndex}
setActivePolygonIndex={setActivePolygonIndex}
setEditPane={setEditPane}
handleCopyCoordinates={handleCopyCoordinates}
/>
))}
</div>
)}
{(selectedZoneMask === undefined ||
selectedZoneMask.includes(
"object_mask" as PolygonType,
)) && (
<div className="mt-3 border-t-[1px] border-secondary pt-3 first:mt-0 first:border-transparent first:pt-0 last:border-b-[1px] last:pb-3">
<div className="my-3 flex flex-row items-center justify-between">
<HoverCard>
<HoverCardTrigger asChild>
<div className="text-md cursor-default">
Object Masks
</div>
</HoverCardTrigger>
<HoverCardContent>
<div className="my-2 flex flex-col gap-2 text-sm text-primary-variant">
<p>
Object filter masks are used to filter out false
positives for a given object type based on
location.
</p>
<div className="flex items-center text-primary">
<Link
to="https://docs.frigate.video/configuration/masks#object-filter-masks"
target="_blank"
rel="noopener noreferrer"
className="inline"
>
Documentation{" "}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
</HoverCardContent>
</HoverCard>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="secondary"
className="size-6 rounded-md bg-secondary-foreground p-1 text-background"
onClick={() => {
setEditPane("object_mask");
handleNewPolygon("object_mask");
}}
>
<LuPlus />
</Button>
</TooltipTrigger>
<TooltipContent>Add Object Mask</TooltipContent>
</Tooltip>
</div>
{allPolygons
.flatMap((polygon, index) =>
polygon.type === "object_mask"
? [{ polygon, index }]
: [],
)
.map(({ polygon, index }) => (
<PolygonItem
key={index}
polygon={polygon}
index={index}
hoveredPolygonIndex={hoveredPolygonIndex}
setHoveredPolygonIndex={setHoveredPolygonIndex}
setActivePolygonIndex={setActivePolygonIndex}
setEditPane={setEditPane}
handleCopyCoordinates={handleCopyCoordinates}
/>
))}
</div>
)}
</div>
</>
)}
</div>
<div
ref={containerRef}
className="flex max-h-[50%] md:h-dvh md:max-h-full md:w-7/12 md:grow"
>
<div className="mx-auto flex size-full flex-row justify-center">
{cameraConfig &&
scaledWidth &&
scaledHeight &&
editingPolygons ? (
<PolygonCanvas
containerRef={containerRef}
camera={cameraConfig.name}
width={scaledWidth}
height={scaledHeight}
polygons={editingPolygons}
setPolygons={setEditingPolygons}
activePolygonIndex={activePolygonIndex}
hoveredPolygonIndex={hoveredPolygonIndex}
selectedZoneMask={selectedZoneMask}
/>
) : (
<Skeleton className="size-full" />
)}
</div>
</div>
</div>
)}
</>
);
}

View File

@@ -0,0 +1,326 @@
import Heading from "@/components/ui/heading";
import { FrigateConfig } from "@/types/frigateConfig";
import useSWR from "swr";
import axios from "axios";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import AutoUpdatingCameraImage from "@/components/camera/AutoUpdatingCameraImage";
import { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { Slider } from "@/components/ui/slider";
import { Label } from "@/components/ui/label";
import {
useImproveContrast,
useMotionContourArea,
useMotionThreshold,
} from "@/api/ws";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Toaster } from "@/components/ui/sonner";
import { toast } from "sonner";
import { Separator } from "@/components/ui/separator";
import { Link } from "react-router-dom";
import { LuExternalLink } from "react-icons/lu";
import { StatusBarMessagesContext } from "@/context/statusbar-provider";
type MotionTunerViewProps = {
selectedCamera: string;
setUnsavedChanges: React.Dispatch<React.SetStateAction<boolean>>;
};
type MotionSettings = {
threshold?: number;
contour_area?: number;
improve_contrast?: boolean;
};
export default function MotionTunerView({
selectedCamera,
setUnsavedChanges,
}: MotionTunerViewProps) {
const { data: config, mutate: updateConfig } =
useSWR<FrigateConfig>("config");
const [changedValue, setChangedValue] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const { addMessage, removeMessage } = useContext(StatusBarMessagesContext)!;
const { send: sendMotionThreshold } = useMotionThreshold(selectedCamera);
const { send: sendMotionContourArea } = useMotionContourArea(selectedCamera);
const { send: sendImproveContrast } = useImproveContrast(selectedCamera);
const [motionSettings, setMotionSettings] = useState<MotionSettings>({
threshold: undefined,
contour_area: undefined,
improve_contrast: undefined,
});
const [origMotionSettings, setOrigMotionSettings] = useState<MotionSettings>({
threshold: undefined,
contour_area: undefined,
improve_contrast: undefined,
});
const cameraConfig = useMemo(() => {
if (config && selectedCamera) {
return config.cameras[selectedCamera];
}
}, [config, selectedCamera]);
useEffect(() => {
if (cameraConfig) {
setMotionSettings({
threshold: cameraConfig.motion.threshold,
contour_area: cameraConfig.motion.contour_area,
improve_contrast: cameraConfig.motion.improve_contrast,
});
setOrigMotionSettings({
threshold: cameraConfig.motion.threshold,
contour_area: cameraConfig.motion.contour_area,
improve_contrast: cameraConfig.motion.improve_contrast,
});
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedCamera]);
useEffect(() => {
if (!motionSettings.threshold) return;
sendMotionThreshold(motionSettings.threshold);
}, [motionSettings.threshold, sendMotionThreshold]);
useEffect(() => {
if (!motionSettings.contour_area) return;
sendMotionContourArea(motionSettings.contour_area);
}, [motionSettings.contour_area, sendMotionContourArea]);
useEffect(() => {
if (motionSettings.improve_contrast === undefined) return;
sendImproveContrast(motionSettings.improve_contrast ? "ON" : "OFF");
}, [motionSettings.improve_contrast, sendImproveContrast]);
const handleMotionConfigChange = (newConfig: Partial<MotionSettings>) => {
setMotionSettings((prevConfig) => ({ ...prevConfig, ...newConfig }));
setUnsavedChanges(true);
setChangedValue(true);
};
const saveToConfig = useCallback(async () => {
setIsLoading(true);
axios
.put(
`config/set?cameras.${selectedCamera}.motion.threshold=${motionSettings.threshold}&cameras.${selectedCamera}.motion.contour_area=${motionSettings.contour_area}&cameras.${selectedCamera}.motion.improve_contrast=${motionSettings.improve_contrast}`,
{ requires_restart: 1 },
)
.then((res) => {
if (res.status === 200) {
toast.success("Motion settings have been saved.", {
position: "top-center",
});
setChangedValue(false);
updateConfig();
} else {
toast.error(`Failed to save config changes: ${res.statusText}`, {
position: "top-center",
});
}
})
.catch((error) => {
toast.error(
`Failed to save config changes: ${error.response.data.message}`,
{ position: "top-center" },
);
})
.finally(() => {
setIsLoading(false);
});
}, [
updateConfig,
motionSettings.threshold,
motionSettings.contour_area,
motionSettings.improve_contrast,
selectedCamera,
]);
const onCancel = useCallback(() => {
setMotionSettings(origMotionSettings);
setChangedValue(false);
removeMessage("motion_tuner", `motion_tuner_${selectedCamera}`);
}, [origMotionSettings, removeMessage, selectedCamera]);
useEffect(() => {
if (changedValue) {
addMessage(
"motion_tuner",
`Unsaved motion tuner changes (${selectedCamera})`,
undefined,
`motion_tuner_${selectedCamera}`,
);
} else {
removeMessage("motion_tuner", `motion_tuner_${selectedCamera}`);
}
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [changedValue, selectedCamera]);
useEffect(() => {
document.title = "Motion Tuner - Frigate";
}, []);
if (!cameraConfig && !selectedCamera) {
return <ActivityIndicator />;
}
return (
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="order-last mb-10 mt-2 flex h-full w-full flex-col overflow-y-auto rounded-lg border-[1px] border-secondary-foreground bg-background_alt p-2 md:order-none md:mb-0 md:mr-2 md:mt-0 md:w-3/12">
<Heading as="h3" className="my-2">
Motion Detection Tuner
</Heading>
<div className="my-3 space-y-3 text-sm text-muted-foreground">
<p>
Frigate uses motion detection as a first line check to see if there
is anything happening in the frame worth checking with object
detection.
</p>
<div className="flex items-center text-primary">
<Link
to="https://docs.frigate.video/configuration/motion_detection"
target="_blank"
rel="noopener noreferrer"
className="inline"
>
Read the Motion Tuning Guide{" "}
<LuExternalLink className="ml-2 inline-flex size-3" />
</Link>
</div>
</div>
<Separator className="my-2 flex bg-secondary" />
<div className="flex w-full flex-col space-y-6">
<div className="mt-2 space-y-6">
<div className="space-y-0.5">
<Label htmlFor="motion-threshold" className="text-md">
Threshold
</Label>
<div className="my-2 text-sm text-muted-foreground">
<p>
The threshold value dictates how much of a change in a pixel's
luminance is required to be considered motion.{" "}
<em>Default: 30</em>
</p>
</div>
</div>
<div className="flex flex-row justify-between">
<Slider
id="motion-threshold"
className="w-full"
disabled={motionSettings.threshold === undefined}
value={[motionSettings.threshold ?? 0]}
min={5}
max={80}
step={1}
onValueChange={(value) => {
handleMotionConfigChange({ threshold: value[0] });
}}
/>
<div className="align-center ml-6 mr-2 flex text-lg">
{motionSettings.threshold}
</div>
</div>
</div>
<div className="mt-2 space-y-6">
<div className="space-y-0.5">
<Label htmlFor="motion-threshold" className="text-md">
Contour Area
</Label>
<div className="my-2 text-sm text-muted-foreground">
<p>
The contour area value is used to decide which groups of
changed pixels qualify as motion. <em>Default: 10</em>
</p>
</div>
</div>
<div className="flex flex-row justify-between">
<Slider
id="motion-contour-area"
className="w-full"
disabled={motionSettings.contour_area === undefined}
value={[motionSettings.contour_area ?? 0]}
min={5}
max={100}
step={1}
onValueChange={(value) => {
handleMotionConfigChange({ contour_area: value[0] });
}}
/>
<div className="align-center ml-6 mr-2 flex text-lg">
{motionSettings.contour_area}
</div>
</div>
</div>
<Separator className="my-2 flex bg-secondary" />
<div className="flex flex-row items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="improve-contrast">Improve Contrast</Label>
<div className="text-sm text-muted-foreground">
Improve contrast for darker scenes. <em>Default: ON</em>
</div>
</div>
<Switch
id="improve-contrast"
className="ml-3"
disabled={motionSettings.improve_contrast === undefined}
checked={motionSettings.improve_contrast === true}
onCheckedChange={(isChecked) => {
handleMotionConfigChange({ improve_contrast: isChecked });
}}
/>
</div>
</div>
<div className="flex flex-1 flex-col justify-end">
<div className="flex flex-row gap-2 pt-5">
<Button className="flex flex-1" onClick={onCancel}>
Reset
</Button>
<Button
variant="select"
disabled={!changedValue || isLoading}
className="flex flex-1"
onClick={saveToConfig}
>
{isLoading ? (
<div className="flex flex-row items-center gap-2">
<ActivityIndicator />
<span>Saving...</span>
</div>
) : (
"Save"
)}
</Button>
</div>
</div>
</div>
{cameraConfig ? (
<div className="flex md:h-dvh md:max-h-full md:w-7/12 md:grow">
<div className="size-full min-h-10">
<AutoUpdatingCameraImage
camera={cameraConfig.name}
searchParams={new URLSearchParams([["motion", "1"]])}
showFps={false}
className="size-full"
cameraClasses="relative w-full h-full flex flex-col justify-start"
/>
</div>
</div>
) : (
<Skeleton className="size-full rounded-lg md:rounded-2xl" />
)}
</div>
);
}

View File

@@ -0,0 +1,284 @@
import { useCallback, useEffect, useMemo } from "react";
import ActivityIndicator from "@/components/indicators/activity-indicator";
import AutoUpdatingCameraImage from "@/components/camera/AutoUpdatingCameraImage";
import { CameraConfig, FrigateConfig } from "@/types/frigateConfig";
import { Toaster } from "@/components/ui/sonner";
import { Label } from "@/components/ui/label";
import useSWR from "swr";
import Heading from "@/components/ui/heading";
import { Switch } from "@/components/ui/switch";
import { usePersistence } from "@/hooks/use-persistence";
import { Skeleton } from "@/components/ui/skeleton";
import { useCameraActivity } from "@/hooks/use-camera-activity";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ObjectType } from "@/types/ws";
import useDeepMemo from "@/hooks/use-deep-memo";
import { Card } from "@/components/ui/card";
import { getIconForLabel } from "@/utils/iconUtil";
import { capitalizeFirstLetter } from "@/utils/stringUtil";
type ObjectSettingsViewProps = {
selectedCamera?: string;
};
type Options = { [key: string]: boolean };
const emptyObject = Object.freeze({});
export default function ObjectSettingsView({
selectedCamera,
}: ObjectSettingsViewProps) {
const { data: config } = useSWR<FrigateConfig>("config");
const DEBUG_OPTIONS = [
{
param: "bbox",
title: "Bounding boxes",
description: "Show bounding boxes around detected objects",
},
{
param: "timestamp",
title: "Timestamp",
description: "Overlay a timestamp on the image",
},
{
param: "zones",
title: "Zones",
description: "Show an outline of any defined zones",
},
{
param: "mask",
title: "Motion masks",
description: "Show motion mask polygons",
},
{
param: "motion",
title: "Motion boxes",
description: "Show boxes around areas where motion is detected",
},
{
param: "regions",
title: "Regions",
description:
"Show a box of the region of interest sent to the object detector",
},
];
const [options, setOptions, optionsLoaded] = usePersistence<Options>(
`${selectedCamera}-feed`,
emptyObject,
);
const handleSetOption = useCallback(
(id: string, value: boolean) => {
const newOptions = { ...options, [id]: value };
setOptions(newOptions);
},
[options, setOptions],
);
const cameraConfig = useMemo(() => {
if (config && selectedCamera) {
return config.cameras[selectedCamera];
}
}, [config, selectedCamera]);
const { objects } = useCameraActivity(cameraConfig ?? ({} as CameraConfig));
const memoizedObjects = useDeepMemo(objects);
const searchParams = useMemo(() => {
if (!optionsLoaded) {
return new URLSearchParams();
}
const params = new URLSearchParams(
Object.keys(options || {}).reduce((memo, key) => {
//@ts-expect-error we know this is correct
memo.push([key, options[key] === true ? "1" : "0"]);
return memo;
}, []),
);
return params;
}, [options, optionsLoaded]);
useEffect(() => {
document.title = "Object Settings - Frigate";
}, []);
if (!cameraConfig) {
return <ActivityIndicator />;
}
return (
<div className="flex size-full flex-col md:flex-row">
<Toaster position="top-center" closeButton={true} />
<div className="order-last mb-10 mt-2 flex h-full w-full flex-col overflow-y-auto rounded-lg border-[1px] border-secondary-foreground bg-background_alt p-2 md:order-none md:mb-0 md:mr-2 md:mt-0 md:w-3/12">
<Heading as="h3" className="my-2">
Debug
</Heading>
<div className="mb-5 space-y-3 text-sm text-muted-foreground">
<p>
Frigate uses your detectors{" "}
{config
? "(" +
Object.keys(config?.detectors)
.map((detector) => capitalizeFirstLetter(detector))
.join(",") +
")"
: ""}{" "}
to detect objects in your camera's video stream.
</p>
<p>
Debugging view shows a real-time view of detected objects and their
statistics. The object list shows a time-delayed summary of detected
objects.
</p>
</div>
<Tabs defaultValue="debug" className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="debug">Debugging</TabsTrigger>
<TabsTrigger value="objectlist">Object List</TabsTrigger>
</TabsList>
<TabsContent value="debug">
<div className="flex w-full flex-col space-y-6">
<div className="mt-2 space-y-6">
<div className="my-2.5 flex flex-col gap-2.5">
{DEBUG_OPTIONS.map(({ param, title, description }) => (
<div
key={param}
className="flex w-full flex-row items-center justify-between"
>
<div className="mb-2 flex flex-col">
<Label
className="mb-2 w-full cursor-pointer capitalize text-primary"
htmlFor={param}
>
{title}
</Label>
<div className="text-xs text-muted-foreground">
{description}
</div>
</div>
<Switch
key={param}
className="ml-1"
id={param}
checked={options && options[param]}
onCheckedChange={(isChecked) => {
handleSetOption(param, isChecked);
}}
/>
</div>
))}
</div>
</div>
</div>
</TabsContent>
<TabsContent value="objectlist">
{ObjectList(memoizedObjects)}
</TabsContent>
</Tabs>
</div>
{cameraConfig ? (
<div className="flex md:h-dvh md:max-h-full md:w-7/12 md:grow">
<div className="size-full min-h-10">
<AutoUpdatingCameraImage
camera={cameraConfig.name}
searchParams={searchParams}
showFps={false}
className="size-full"
cameraClasses="relative w-full h-full flex flex-col justify-start"
/>
</div>
</div>
) : (
<Skeleton className="size-full rounded-lg md:rounded-2xl" />
)}
</div>
);
}
function ObjectList(objects?: ObjectType[]) {
const { data: config } = useSWR<FrigateConfig>("config");
const colormap = useMemo(() => {
if (!config) {
return;
}
return config.model?.colormap;
}, [config]);
const getColorForObjectName = useCallback(
(objectName: string) => {
return colormap && colormap[objectName]
? `rgb(${colormap[objectName][2]}, ${colormap[objectName][1]}, ${colormap[objectName][0]})`
: "rgb(128, 128, 128)";
},
[colormap],
);
return (
<div className="flex w-full flex-col overflow-y-auto">
{objects && objects.length > 0 ? (
objects.map((obj) => {
return (
<Card className="mb-1 p-2 text-sm" key={obj.id}>
<div className="flex flex-row items-center gap-3 pb-1">
<div className="flex flex-1 flex-row items-center justify-start p-3 pl-1">
<div
className="rounded-lg p-2"
style={{
backgroundColor: obj.stationary
? "rgb(110,110,110)"
: getColorForObjectName(obj.label),
}}
>
{getIconForLabel(obj.label, "size-5 text-white")}
</div>
<div className="ml-3 text-lg">
{capitalizeFirstLetter(obj.label)}
</div>
</div>
<div className="flex w-8/12 flex-row items-end justify-end">
<div className="text-md mr-2 w-1/3">
<div className="flex flex-col items-end justify-end">
<p className="mb-1.5 text-sm text-primary-variant">
Score
</p>
{obj.score
? (obj.score * 100).toFixed(1).toString()
: "-"}
%
</div>
</div>
<div className="text-md mr-2 w-1/3">
<div className="flex flex-col items-end justify-end">
<p className="mb-1.5 text-sm text-primary-variant">
Ratio
</p>
{obj.ratio ? obj.ratio.toFixed(2).toString() : "-"}
</div>
</div>
<div className="text-md mr-2 w-1/3">
<div className="flex flex-col items-end justify-end">
<p className="mb-1.5 text-sm text-primary-variant">
Area
</p>
{obj.area ? obj.area.toString() : "-"}
</div>
</div>
</div>
</div>
</Card>
);
})
) : (
<div className="p-3 text-center">No objects</div>
)}
</div>
);
}