Compare commits
220 Commits
v0.11.0-be
...
v0.12.0-be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf2466c8c1 | ||
|
|
6b123675c4 | ||
|
|
ddcae2d4aa | ||
|
|
731db8fb8f | ||
|
|
cb0c5c2587 | ||
|
|
1643b4d108 | ||
|
|
acd1fb9e3e | ||
|
|
ddde477770 | ||
|
|
3edbb8dc41 | ||
|
|
581c2591ae | ||
|
|
d49359e26a | ||
|
|
e79eab711a | ||
|
|
5b7cd9ce64 | ||
|
|
3cb96091ec | ||
|
|
fdd2cc972e | ||
|
|
61243ad34b | ||
|
|
5f4c439f57 | ||
|
|
1f963ec5aa | ||
|
|
bcbf0061ff | ||
|
|
57dce4ec38 | ||
|
|
0dbf909ca6 | ||
|
|
47ac5ed522 | ||
|
|
ec7aaa18ab | ||
|
|
bee965df06 | ||
|
|
543cad5497 | ||
|
|
d9c45a76fe | ||
|
|
417a42b0b3 | ||
|
|
8ac3114f9a | ||
|
|
740d932848 | ||
|
|
e645c8e007 | ||
|
|
9ee367d9e9 | ||
|
|
8410788e99 | ||
|
|
12235acd75 | ||
|
|
ba5cffac55 | ||
|
|
64ab6580dc | ||
|
|
0a3295aa5c | ||
|
|
ffa98a138b | ||
|
|
5e71d95cb1 | ||
|
|
9fd13aad11 | ||
|
|
ebef38e408 | ||
|
|
b6592c67d1 | ||
|
|
d547680116 | ||
|
|
bc5aa1141a | ||
|
|
ea7d1aabba | ||
|
|
760d65b214 | ||
|
|
ceab294840 | ||
|
|
abc40f2581 | ||
|
|
dc738e9be7 | ||
|
|
53d39a1373 | ||
|
|
cee52e9cfd | ||
|
|
9c6193b9b5 | ||
|
|
e4a79b12eb | ||
|
|
5eac767758 | ||
|
|
b6ad287ef2 | ||
|
|
f4991b46f8 | ||
|
|
ecc7b93dc0 | ||
|
|
ff56262c6e | ||
|
|
da1b7c2e28 | ||
|
|
76bbd838f7 | ||
|
|
a8e81a255d | ||
|
|
fee48e555e | ||
|
|
59b52f3879 | ||
|
|
d6731b17a4 | ||
|
|
3f05f74ecb | ||
|
|
e3ec292528 | ||
|
|
63260119fb | ||
|
|
ffd637cc0c | ||
|
|
be2408b366 | ||
|
|
6e519e0071 | ||
|
|
f3e0ced1cd | ||
|
|
368c07cc34 | ||
|
|
d999575832 | ||
|
|
06bc9bb4dc | ||
|
|
161991df1f | ||
|
|
e3e03ec12f | ||
|
|
c85df9c691 | ||
|
|
7953d131ae | ||
|
|
c6f0abf732 | ||
|
|
49f70b9563 | ||
|
|
369299315f | ||
|
|
9b99ba81e5 | ||
|
|
499866bf94 | ||
|
|
420bcd7aa0 | ||
|
|
43c2761308 | ||
|
|
b1ec56de29 | ||
|
|
45c43d7cf5 | ||
|
|
037f3761e7 | ||
|
|
739a267462 | ||
|
|
ba3fbc99ba | ||
|
|
cd9f6b074e | ||
|
|
964bcc0733 | ||
|
|
4f79ca1bf0 | ||
|
|
bc52fc1e79 | ||
|
|
fee3418e60 | ||
|
|
2a5ab77637 | ||
|
|
6abc0ce921 | ||
|
|
7888059c9f | ||
|
|
97161310a5 | ||
|
|
2651bc18cd | ||
|
|
87e2810725 | ||
|
|
007fa75294 | ||
|
|
94a2b6bb88 | ||
|
|
e5fe323aca | ||
|
|
4523c9b06d | ||
|
|
5ad391977e | ||
|
|
25a7c4ee81 | ||
|
|
87144cd572 | ||
|
|
69560c8bde | ||
|
|
aaedd24f37 | ||
|
|
3cb6d43fac | ||
|
|
68248cc274 | ||
|
|
047c2408d2 | ||
|
|
91982c4f7e | ||
|
|
4e5512e35d | ||
|
|
1f4ce6ff1e | ||
|
|
c497e83a54 | ||
|
|
93f94a7afb | ||
|
|
6c0978498d | ||
|
|
370276a7b6 | ||
|
|
f4187d6b83 | ||
|
|
c4d442450b | ||
|
|
82432a78b7 | ||
|
|
ebdf36e0b9 | ||
|
|
65825040a3 | ||
|
|
253061ee5f | ||
|
|
a46c37018f | ||
|
|
2e81c94d8e | ||
|
|
a04fa105ef | ||
|
|
ad3f6fc551 | ||
|
|
53045de1c2 | ||
|
|
410cea71f1 | ||
|
|
cc27c94e03 | ||
|
|
a9d95b89e1 | ||
|
|
4eb3e98076 | ||
|
|
664e04836d | ||
|
|
a1b21a87a1 | ||
|
|
e718d09c79 | ||
|
|
c97aac6c94 | ||
|
|
9c9220979e | ||
|
|
42bc372d6e | ||
|
|
47c1985c26 | ||
|
|
9e31873520 | ||
|
|
8665a24560 | ||
|
|
2b842468ad | ||
|
|
8cddf87f9e | ||
|
|
573fdae37f | ||
|
|
9b5c6bea56 | ||
|
|
40cb5102b0 | ||
|
|
95343b6094 | ||
|
|
e15b2627fc | ||
|
|
02caeb9f87 | ||
|
|
4383b883c0 | ||
|
|
bcc26dd86a | ||
|
|
1bc9efd529 | ||
|
|
11624d4759 | ||
|
|
94e2a500c7 | ||
|
|
552638d000 | ||
|
|
8163afce79 | ||
|
|
2a36a1b980 | ||
|
|
d8123d2497 | ||
|
|
86268b99fb | ||
|
|
b4d4adb75b | ||
|
|
3c01dbed7d | ||
|
|
2eada219cd | ||
|
|
8dd367efa9 | ||
|
|
66dc8c772b | ||
|
|
68cdd9b94c | ||
|
|
65c211bb6d | ||
|
|
60ad38261b | ||
|
|
c02100ee6f | ||
|
|
8669c29e3d | ||
|
|
10783fec49 | ||
|
|
3bed4611f1 | ||
|
|
f0e836e5b6 | ||
|
|
a1ae5b67d8 | ||
|
|
53f7190d42 | ||
|
|
3846a13805 | ||
|
|
7c60753ab0 | ||
|
|
df40b96b44 | ||
|
|
faf583451f | ||
|
|
be7b858cbd | ||
|
|
a6a0e4d1de | ||
|
|
14faf0b2f6 | ||
|
|
bdfe4a961a | ||
|
|
1bc8d94312 | ||
|
|
7e9f913ff6 | ||
|
|
0882e4a454 | ||
|
|
699bd3748a | ||
|
|
2ca59f0abe | ||
|
|
64b1b8e15c | ||
|
|
b6f799e641 | ||
|
|
c461c9e700 | ||
|
|
9df415b3f2 | ||
|
|
f7c5e02a35 | ||
|
|
656e6a2a89 | ||
|
|
afefa3ec02 | ||
|
|
8c45dab9b8 | ||
|
|
0d6dd1ed0f | ||
|
|
911d6fdfa7 | ||
|
|
0cf759acad | ||
|
|
7c57c8c2da | ||
|
|
89c04acdff | ||
|
|
05d5f13f0e | ||
|
|
4682af81fb | ||
|
|
e649a1eb98 | ||
|
|
01482d791b | ||
|
|
6e2e297aeb | ||
|
|
5577ef081f | ||
|
|
2d5d3bdaf4 | ||
|
|
3376e85be6 | ||
|
|
7a1215d581 | ||
|
|
a94297ac93 | ||
|
|
37325c70ba | ||
|
|
e68f80b44a | ||
|
|
653c2274e1 | ||
|
|
93cd973e59 | ||
|
|
53bf3cd2e6 | ||
|
|
f59871a189 | ||
|
|
2dda7608bb | ||
|
|
10db9faff9 |
@@ -1,16 +1,50 @@
|
||||
{
|
||||
"name": "Frigate Dev",
|
||||
"name": "Frigate Devcontainer",
|
||||
"dockerComposeFile": "../docker-compose.yml",
|
||||
"service": "dev",
|
||||
"workspaceFolder": "/lab/frigate",
|
||||
"service": "devcontainer",
|
||||
"workspaceFolder": "/workspace/frigate",
|
||||
"initializeCommand": ".devcontainer/initialize.sh",
|
||||
"postCreateCommand": ".devcontainer/post_create.sh",
|
||||
"overrideCommand": false,
|
||||
"remoteUser": "vscode",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/common-utils:1": {}
|
||||
},
|
||||
"forwardPorts": [5000, 5001, 5173, 1935, 8554, 8555],
|
||||
"portsAttributes": {
|
||||
"5000": {
|
||||
"label": "NGINX",
|
||||
"onAutoForward": "silent"
|
||||
},
|
||||
"5001": {
|
||||
"label": "Frigate API",
|
||||
"onAutoForward": "silent"
|
||||
},
|
||||
"5173": {
|
||||
"label": "Vite Server",
|
||||
"onAutoForward": "silent"
|
||||
},
|
||||
"1935": {
|
||||
"label": "RTMP",
|
||||
"onAutoForward": "silent"
|
||||
},
|
||||
"8554": {
|
||||
"label": "gortc RTSP",
|
||||
"onAutoForward": "silent"
|
||||
},
|
||||
"8555": {
|
||||
"label": "go2rtc WebRTC",
|
||||
"onAutoForward": "silent"
|
||||
}
|
||||
},
|
||||
"extensions": [
|
||||
"ms-python.vscode-pylance",
|
||||
"ms-python.python",
|
||||
"visualstudioexptteam.vscodeintellicode",
|
||||
"mhutchie.git-graph",
|
||||
"ms-azuretools.vscode-docker",
|
||||
"streetsidesoftware.code-spell-checker",
|
||||
"esbenp.prettier-vscode",
|
||||
"ms-python.vscode-pylance",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"mikestead.dotenv",
|
||||
"csstools.postcss",
|
||||
@@ -18,6 +52,7 @@
|
||||
"bradlc.vscode-tailwindcss"
|
||||
],
|
||||
"settings": {
|
||||
"remote.autoForwardPorts": false,
|
||||
"python.linting.pylintEnabled": true,
|
||||
"python.linting.enabled": true,
|
||||
"python.formatting.provider": "black",
|
||||
@@ -25,6 +60,9 @@
|
||||
"editor.formatOnPaste": false,
|
||||
"editor.formatOnSave": true,
|
||||
"editor.formatOnType": true,
|
||||
"python.testing.pytestEnabled": false,
|
||||
"python.testing.unittestEnabled": true,
|
||||
"python.testing.unittestArgs": ["-v", "-s", "./frigate/test"],
|
||||
"files.trimTrailingWhitespace": true,
|
||||
"eslint.workingDirectories": ["./web"],
|
||||
"[json][jsonc]": {
|
||||
|
||||
13
.devcontainer/initialize.sh
Executable file
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# These folders needs to be created and owned by the host user
|
||||
mkdir -p debug web/dist
|
||||
|
||||
if [[ -f "config/config.yml" ]]; then
|
||||
echo "config/config.yml already exists, skipping initialization" >&2
|
||||
else
|
||||
echo "initializing config/config.yml" >&2
|
||||
cp -fv config/config.yml.example config/config.yml
|
||||
fi
|
||||
17
.devcontainer/post_create.sh
Executable file
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
# Frigate normal container runs as root, so it have permission to create
|
||||
# the folders. But the devcontainer runs as the host user, so we need to
|
||||
# create the folders and give the host user permission to write to them.
|
||||
sudo mkdir -p /media/frigate
|
||||
sudo chown -R "$(id -u):$(id -g)" /media/frigate
|
||||
|
||||
make version
|
||||
|
||||
cd web
|
||||
|
||||
npm install
|
||||
|
||||
npm run build
|
||||
@@ -9,4 +9,8 @@ core
|
||||
*.mp4
|
||||
*.jpg
|
||||
*.db
|
||||
*.ts
|
||||
*.ts
|
||||
|
||||
web/dist/
|
||||
web/node_modules/
|
||||
web/.npm
|
||||
|
||||
2
.github/FUNDING.yml
vendored
@@ -1,3 +1,3 @@
|
||||
github:
|
||||
- blakeblackshear
|
||||
- paularmstrong
|
||||
- NickM-27
|
||||
|
||||
84
.github/ISSUE_TEMPLATE/edgetpu_support_request.yml
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
name: EdgeTpu Support Request
|
||||
description: Support for setting up EdgeTPU in Frigate
|
||||
title: "[EdgeTPU Support]: "
|
||||
labels: ["support", "triage"]
|
||||
assignees: []
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Describe the problem you are having
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: Visible on the Debug page in the Web UI
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: config
|
||||
attributes:
|
||||
label: Frigate config file
|
||||
description: This will be automatically formatted into code, so no need for backticks.
|
||||
render: yaml
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: docker
|
||||
attributes:
|
||||
label: docker-compose file or Docker CLI command
|
||||
description: This will be automatically formatted into code, so no need for backticks.
|
||||
render: yaml
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||
render: shell
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating system
|
||||
options:
|
||||
- HassOS
|
||||
- Debian
|
||||
- Other Linux
|
||||
- Proxmox
|
||||
- UNRAID
|
||||
- Windows
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: install-method
|
||||
attributes:
|
||||
label: Install method
|
||||
options:
|
||||
- HassOS Addon
|
||||
- Docker Compose
|
||||
- Docker CLI
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: coral
|
||||
attributes:
|
||||
label: Coral version
|
||||
options:
|
||||
- USB
|
||||
- PCIe
|
||||
- M.2
|
||||
- Dev Board
|
||||
- Other
|
||||
- CPU (no coral)
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: other
|
||||
attributes:
|
||||
label: Any other information that may be helpful
|
||||
96
.github/ISSUE_TEMPLATE/hwaccel_support_request.yml
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
name: Hardware Acceleration Support Request
|
||||
description: Support for setting up GPU hardware acceleration in Frigate
|
||||
title: "[HW Accel Support]: "
|
||||
labels: ["support", "triage"]
|
||||
assignees: []
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Describe the problem you are having
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
description: Visible on the Debug page in the Web UI
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: config
|
||||
attributes:
|
||||
label: Frigate config file
|
||||
description: This will be automatically formatted into code, so no need for backticks.
|
||||
render: yaml
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: docker
|
||||
attributes:
|
||||
label: docker-compose file or Docker CLI command
|
||||
description: This will be automatically formatted into code, so no need for backticks.
|
||||
render: yaml
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Relevant log output
|
||||
description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks.
|
||||
render: shell
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: ffprobe
|
||||
attributes:
|
||||
label: FFprobe output from your camera
|
||||
description: Run `ffprobe <camera_url>` and provide output below
|
||||
render: shell
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating system
|
||||
options:
|
||||
- HassOS
|
||||
- Debian
|
||||
- Other Linux
|
||||
- Proxmox
|
||||
- UNRAID
|
||||
- Windows
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: install-method
|
||||
attributes:
|
||||
label: Install method
|
||||
options:
|
||||
- HassOS Addon
|
||||
- Docker Compose
|
||||
- Docker CLI
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: network
|
||||
attributes:
|
||||
label: Network connection
|
||||
options:
|
||||
- Wired
|
||||
- Wireless
|
||||
- Mixed
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: camera
|
||||
attributes:
|
||||
label: Camera make and model
|
||||
description: Dahua, hikvision, amcrest, reolink, etc and model number
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: other
|
||||
attributes:
|
||||
label: Any other information that may be helpful
|
||||
32
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
target-branch: dev
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/docker"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
target-branch: dev
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
target-branch: dev
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/web"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
target-branch: dev
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/docs"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
target-branch: dev
|
||||
17
.github/stale.yml
vendored
@@ -1,17 +0,0 @@
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 30
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 3
|
||||
# Issues with these labels will never be considered stale
|
||||
exemptLabels:
|
||||
- pinned
|
||||
- security
|
||||
# Label to use when marking an issue as stale
|
||||
staleLabel: stale
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
53
.github/workflows/ci.yml
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
- master
|
||||
|
||||
env:
|
||||
PYTHON_VERSION: 3.9
|
||||
|
||||
jobs:
|
||||
multi_arch_build:
|
||||
runs-on: ubuntu-latest
|
||||
name: Image Build
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v3
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@f4ef78c080cd8ba55a85445d5b36e214a81df20a
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Create version file
|
||||
run: make version
|
||||
- name: Create short sha
|
||||
run: echo "SHORT_SHA=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
target: frigate
|
||||
tags: |
|
||||
ghcr.io/blakeblackshear/frigate:${{ github.ref_name }}-${{ env.SHORT_SHA }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
- name: Build and push TensorRT
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
platforms: linux/amd64
|
||||
target: frigate-tensorrt
|
||||
tags: |
|
||||
ghcr.io/blakeblackshear/frigate:${{ github.ref_name }}-${{ env.SHORT_SHA }}-tensorrt
|
||||
cache-from: type=gha
|
||||
42
.github/workflows/pull_request.yml
vendored
@@ -6,11 +6,35 @@ env:
|
||||
DEFAULT_PYTHON: 3.9
|
||||
|
||||
jobs:
|
||||
build_devcontainer:
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Devcontainer
|
||||
# The Dockerfile contains features that requires buildkit, and since the
|
||||
# devcontainer cli uses docker-compose to build the image, the only way to
|
||||
# ensure docker-compose uses buildkit is to explicitly enable it.
|
||||
env:
|
||||
DOCKER_BUILDKIT: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@master
|
||||
with:
|
||||
node-version: 16.x
|
||||
- name: Install devcontainer cli
|
||||
run: npm install --global @devcontainers/cli
|
||||
- name: Build devcontainer
|
||||
run: devcontainer build --workspace-folder .
|
||||
# It would be nice to also test the following commands, but for some
|
||||
# reason they don't work even though in VS Code devcontainer works.
|
||||
# - name: Start devcontainer
|
||||
# run: devcontainer up --workspace-folder .
|
||||
# - name: Run devcontainer scripts
|
||||
# run: devcontainer run-user-commands --workspace-folder .
|
||||
|
||||
web_lint:
|
||||
name: Web - Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@master
|
||||
with:
|
||||
node-version: 16.x
|
||||
@@ -24,7 +48,7 @@ jobs:
|
||||
name: Web - Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@master
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@master
|
||||
with:
|
||||
node-version: 16.x
|
||||
@@ -36,12 +60,12 @@ jobs:
|
||||
|
||||
python_checks:
|
||||
runs-on: ubuntu-latest
|
||||
name: Python checks
|
||||
name: Python Checks
|
||||
steps:
|
||||
- name: Check out the repository
|
||||
uses: actions/checkout@v2.3.4
|
||||
uses: actions/checkout@v3
|
||||
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
|
||||
uses: actions/setup-python@v2.2.2
|
||||
uses: actions/setup-python@v4.4.0
|
||||
with:
|
||||
python-version: ${{ env.DEFAULT_PYTHON }}
|
||||
- name: Install requirements
|
||||
@@ -57,7 +81,7 @@ jobs:
|
||||
name: Python Tests
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@master
|
||||
with:
|
||||
node-version: 16.x
|
||||
@@ -67,11 +91,9 @@ jobs:
|
||||
run: npm run build
|
||||
working-directory: ./web
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v1
|
||||
uses: docker/setup-qemu-action@v2
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
- name: Create Version Module
|
||||
run: make version
|
||||
uses: docker/setup-buildx-action@v2
|
||||
- name: Build
|
||||
run: make
|
||||
- name: Run mypy
|
||||
|
||||
26
.github/workflows/stale.yml
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
# Close Stale Issues
|
||||
# Warns and then closes issues and PRs that have had no activity for a specified amount of time.
|
||||
# https://github.com/actions/stale
|
||||
|
||||
name: "Stalebot"
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0 * * *" # run stalebot once a day
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@main
|
||||
id: stale
|
||||
with:
|
||||
stale-issue-message: "This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions."
|
||||
close-issue-message: ""
|
||||
days-before-stale: 30
|
||||
days-before-close: 3
|
||||
exempt-draft-pr: true
|
||||
exempt-issue-labels: "pinned,security"
|
||||
exempt-pr-labels: "pinned,security,dependencies"
|
||||
operations-per-run: 120
|
||||
- name: Print outputs
|
||||
run: echo ${{ join(steps.stale.outputs.*, ',') }}
|
||||
4
.gitignore
vendored
@@ -2,7 +2,8 @@
|
||||
*.pyc
|
||||
*.swp
|
||||
debug
|
||||
.vscode
|
||||
.vscode/*
|
||||
!.vscode/launch.json
|
||||
config/config.yml
|
||||
models
|
||||
*.mp4
|
||||
@@ -15,3 +16,4 @@ web/node_modules
|
||||
web/coverage
|
||||
core
|
||||
!/web/**/*.ts
|
||||
.idea/*
|
||||
12
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Python: Launch Frigate",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"module": "frigate",
|
||||
"justMyCode": true
|
||||
}
|
||||
]
|
||||
}
|
||||
278
Dockerfile
Normal file
@@ -0,0 +1,278 @@
|
||||
# syntax=docker/dockerfile:1.2
|
||||
|
||||
# https://askubuntu.com/questions/972516/debian-frontend-environment-variable
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
FROM debian:11 AS base
|
||||
|
||||
FROM --platform=linux/amd64 debian:11 AS base_amd64
|
||||
|
||||
FROM debian:11-slim AS slim-base
|
||||
|
||||
FROM slim-base AS wget
|
||||
ARG DEBIAN_FRONTEND
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y wget xz-utils \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /rootfs
|
||||
|
||||
FROM base AS nginx
|
||||
ARG DEBIAN_FRONTEND
|
||||
|
||||
# bind /var/cache/apt to tmpfs to speed up nginx build
|
||||
RUN --mount=type=tmpfs,target=/tmp --mount=type=tmpfs,target=/var/cache/apt \
|
||||
--mount=type=bind,source=docker/build_nginx.sh,target=/deps/build_nginx.sh \
|
||||
/deps/build_nginx.sh
|
||||
|
||||
FROM wget AS go2rtc
|
||||
ARG TARGETARCH
|
||||
WORKDIR /rootfs/usr/local/go2rtc/bin
|
||||
RUN wget -qO go2rtc "https://github.com/AlexxIT/go2rtc/releases/download/v0.1-rc.7/go2rtc_linux_${TARGETARCH}" \
|
||||
&& chmod +x go2rtc
|
||||
|
||||
|
||||
####
|
||||
#
|
||||
# OpenVino Support
|
||||
#
|
||||
# 1. Download and convert a model from Intel's Public Open Model Zoo
|
||||
# 2. Build libUSB without udev to handle NCS2 enumeration
|
||||
#
|
||||
####
|
||||
# Download and Convert OpenVino model
|
||||
FROM base_amd64 AS ov-converter
|
||||
ARG DEBIAN_FRONTEND
|
||||
|
||||
# Install OpenVino Runtime and Dev library
|
||||
COPY requirements-ov.txt /requirements-ov.txt
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install -y wget python3 python3-distutils \
|
||||
&& wget -q https://bootstrap.pypa.io/get-pip.py -O get-pip.py \
|
||||
&& python3 get-pip.py "pip" \
|
||||
&& pip install -r /requirements-ov.txt
|
||||
|
||||
# Get OpenVino Model
|
||||
RUN mkdir /models \
|
||||
&& cd /models && omz_downloader --name ssdlite_mobilenet_v2 \
|
||||
&& cd /models && omz_converter --name ssdlite_mobilenet_v2 --precision FP16
|
||||
|
||||
|
||||
# libUSB - No Udev
|
||||
FROM wget as libusb-build
|
||||
ARG TARGETARCH
|
||||
ARG DEBIAN_FRONTEND
|
||||
|
||||
# Build libUSB without udev. Needed for Openvino NCS2 support
|
||||
WORKDIR /opt
|
||||
RUN apt-get update && apt-get install -y unzip build-essential automake libtool
|
||||
RUN wget -q https://github.com/libusb/libusb/archive/v1.0.25.zip -O v1.0.25.zip && \
|
||||
unzip v1.0.25.zip && cd libusb-1.0.25 && \
|
||||
./bootstrap.sh && \
|
||||
./configure --disable-udev --enable-shared && \
|
||||
make -j $(nproc --all)
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends libusb-1.0-0-dev && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /opt/libusb-1.0.25/libusb
|
||||
RUN /bin/mkdir -p '/usr/local/lib' && \
|
||||
/bin/bash ../libtool --mode=install /usr/bin/install -c libusb-1.0.la '/usr/local/lib' && \
|
||||
/bin/mkdir -p '/usr/local/include/libusb-1.0' && \
|
||||
/usr/bin/install -c -m 644 libusb.h '/usr/local/include/libusb-1.0' && \
|
||||
/bin/mkdir -p '/usr/local/lib/pkgconfig' && \
|
||||
cd /opt/libusb-1.0.25/ && \
|
||||
/usr/bin/install -c -m 644 libusb-1.0.pc '/usr/local/lib/pkgconfig' && \
|
||||
ldconfig
|
||||
|
||||
FROM wget AS models
|
||||
|
||||
# Get model and labels
|
||||
RUN wget -qO edgetpu_model.tflite https://github.com/google-coral/test_data/raw/release-frogfish/ssdlite_mobiledet_coco_qat_postprocess_edgetpu.tflite
|
||||
RUN wget -qO cpu_model.tflite https://github.com/google-coral/test_data/raw/release-frogfish/ssdlite_mobiledet_coco_qat_postprocess.tflite
|
||||
COPY labelmap.txt .
|
||||
# Copy OpenVino model
|
||||
COPY --from=ov-converter /models/public/ssdlite_mobilenet_v2/FP16 openvino-model
|
||||
RUN wget -q https://github.com/openvinotoolkit/open_model_zoo/raw/master/data/dataset_classes/coco_91cl_bkgr.txt -O openvino-model/coco_91cl_bkgr.txt && \
|
||||
sed -i 's/truck/car/g' openvino-model/coco_91cl_bkgr.txt
|
||||
|
||||
|
||||
|
||||
FROM wget AS s6-overlay
|
||||
ARG TARGETARCH
|
||||
RUN --mount=type=bind,source=docker/install_s6_overlay.sh,target=/deps/install_s6_overlay.sh \
|
||||
/deps/install_s6_overlay.sh
|
||||
|
||||
|
||||
FROM base AS wheels
|
||||
ARG DEBIAN_FRONTEND
|
||||
ARG TARGETARCH
|
||||
|
||||
# Use a separate container to build wheels to prevent build dependencies in final image
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install -y \
|
||||
apt-transport-https \
|
||||
gnupg \
|
||||
wget \
|
||||
&& apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 9165938D90FDDD2E \
|
||||
&& echo "deb http://raspbian.raspberrypi.org/raspbian/ bullseye main contrib non-free rpi" | tee /etc/apt/sources.list.d/raspi.list \
|
||||
&& apt-get -qq update \
|
||||
&& apt-get -qq install -y \
|
||||
python3 \
|
||||
python3-dev \
|
||||
wget \
|
||||
# opencv dependencies
|
||||
build-essential cmake git pkg-config libgtk-3-dev \
|
||||
libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
|
||||
libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
|
||||
gfortran openexr libatlas-base-dev libssl-dev\
|
||||
libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
|
||||
libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev \
|
||||
# scipy dependencies
|
||||
gcc gfortran libopenblas-dev liblapack-dev && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN wget -q https://bootstrap.pypa.io/get-pip.py -O get-pip.py \
|
||||
&& python3 get-pip.py "pip"
|
||||
|
||||
RUN if [ "${TARGETARCH}" = "arm" ]; \
|
||||
then echo "[global]" > /etc/pip.conf \
|
||||
&& echo "extra-index-url=https://www.piwheels.org/simple" >> /etc/pip.conf; \
|
||||
fi
|
||||
|
||||
COPY requirements.txt /requirements.txt
|
||||
RUN pip3 install -r requirements.txt
|
||||
|
||||
COPY requirements-wheels.txt /requirements-wheels.txt
|
||||
RUN pip3 wheel --wheel-dir=/wheels -r requirements-wheels.txt
|
||||
|
||||
# Make this a separate target so it can be built/cached optionally
|
||||
FROM wheels as trt-wheels
|
||||
ARG DEBIAN_FRONTEND
|
||||
ARG TARGETARCH
|
||||
|
||||
# Add TensorRT wheels to another folder
|
||||
COPY requirements-tensorrt.txt /requirements-tensorrt.txt
|
||||
RUN mkdir -p /trt-wheels && pip3 wheel --wheel-dir=/trt-wheels -r requirements-tensorrt.txt
|
||||
|
||||
|
||||
# Collect deps in a single layer
|
||||
FROM scratch AS deps-rootfs
|
||||
COPY --from=nginx /usr/local/nginx/ /usr/local/nginx/
|
||||
COPY --from=go2rtc /rootfs/ /
|
||||
COPY --from=libusb-build /usr/local/lib /usr/local/lib
|
||||
COPY --from=s6-overlay /rootfs/ /
|
||||
COPY --from=models /rootfs/ /
|
||||
COPY docker/rootfs/ /
|
||||
|
||||
|
||||
# Frigate deps (ffmpeg, python, nginx, go2rtc, s6-overlay, etc)
|
||||
FROM slim-base AS deps
|
||||
ARG TARGETARCH
|
||||
|
||||
ARG DEBIAN_FRONTEND
|
||||
# http://stackoverflow.com/questions/48162574/ddg#49462622
|
||||
ARG APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
|
||||
|
||||
# https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(Native-GPU-Support)
|
||||
ENV NVIDIA_VISIBLE_DEVICES=all
|
||||
ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility"
|
||||
|
||||
ENV PATH="/usr/lib/btbn-ffmpeg/bin:/usr/local/go2rtc/bin:/usr/local/nginx/sbin:${PATH}"
|
||||
|
||||
# Install dependencies
|
||||
RUN --mount=type=bind,source=docker/install_deps.sh,target=/deps/install_deps.sh \
|
||||
/deps/install_deps.sh
|
||||
|
||||
RUN --mount=type=bind,from=wheels,source=/wheels,target=/deps/wheels \
|
||||
pip3 install -U /deps/wheels/*.whl
|
||||
|
||||
COPY --from=deps-rootfs / /
|
||||
|
||||
RUN ldconfig
|
||||
|
||||
EXPOSE 5000
|
||||
EXPOSE 1935
|
||||
EXPOSE 8554
|
||||
EXPOSE 8555
|
||||
|
||||
# Fails if cont-init.d fails
|
||||
ENV S6_BEHAVIOUR_IF_STAGE2_FAILS=2
|
||||
# Wait indefinitely for cont-init.d to finish before starting services
|
||||
ENV S6_CMD_WAIT_FOR_SERVICES=1
|
||||
ENV S6_CMD_WAIT_FOR_SERVICES_MAXTIME=0
|
||||
# Give services (including Frigate) 30 seconds to stop before killing them
|
||||
# But this is not working currently because of:
|
||||
# https://github.com/just-containers/s6-overlay/issues/503
|
||||
ENV S6_SERVICES_GRACETIME=30000
|
||||
# Configure logging to prepend timestamps, log to stdout, keep 0 archives and rotate on 10MB
|
||||
ENV S6_LOGGING_SCRIPT="T 1 n0 s10000000 T"
|
||||
# TODO: remove after a new version of s6-overlay is released. See:
|
||||
# https://github.com/just-containers/s6-overlay/issues/460#issuecomment-1327127006
|
||||
ENV S6_SERVICES_READYTIME=50
|
||||
|
||||
ENTRYPOINT ["/init"]
|
||||
CMD []
|
||||
|
||||
# Frigate deps with Node.js and NPM for devcontainer
|
||||
FROM deps AS devcontainer
|
||||
|
||||
# Do not start the actual Frigate service on devcontainer as it will be started by VSCode
|
||||
# But start a fake service for simulating the logs
|
||||
COPY docker/fake_frigate_run /etc/services.d/frigate/run
|
||||
|
||||
# Install Node 16
|
||||
RUN apt-get update \
|
||||
&& apt-get install wget -y \
|
||||
&& wget -qO- https://deb.nodesource.com/setup_16.x | bash - \
|
||||
&& apt-get install -y nodejs \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& npm install -g npm@9
|
||||
|
||||
WORKDIR /workspace/frigate
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install make -y \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN --mount=type=bind,source=./requirements-dev.txt,target=/workspace/frigate/requirements-dev.txt \
|
||||
pip3 install -r requirements-dev.txt
|
||||
|
||||
CMD ["sleep", "infinity"]
|
||||
|
||||
|
||||
# Frigate web build
|
||||
# force this to run on amd64 because QEMU is painfully slow
|
||||
FROM --platform=linux/amd64 node:16 AS web-build
|
||||
|
||||
WORKDIR /work
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm install
|
||||
|
||||
COPY web/ ./
|
||||
RUN npm run build \
|
||||
&& mv dist/BASE_PATH/monacoeditorwork/* dist/assets/ \
|
||||
&& rm -rf dist/BASE_PATH
|
||||
|
||||
# Collect final files in a single layer
|
||||
FROM scratch AS rootfs
|
||||
|
||||
WORKDIR /opt/frigate/
|
||||
COPY frigate frigate/
|
||||
COPY migrations migrations/
|
||||
COPY --from=web-build /work/dist/ web/
|
||||
|
||||
# Frigate final container
|
||||
FROM deps AS frigate
|
||||
|
||||
WORKDIR /opt/frigate/
|
||||
COPY --from=rootfs / /
|
||||
|
||||
# Frigate w/ TensorRT Support as separate image
|
||||
FROM frigate AS frigate-tensorrt
|
||||
RUN --mount=type=bind,from=trt-wheels,source=/trt-wheels,target=/deps/trt-wheels \
|
||||
pip3 install -U /deps/trt-wheels/*.whl
|
||||
|
||||
# Dev Container w/ TRT
|
||||
FROM devcontainer AS devcontainer-trt
|
||||
|
||||
RUN --mount=type=bind,from=trt-wheels,source=/trt-wheels,target=/deps/trt-wheels \
|
||||
pip3 install -U /deps/trt-wheels/*.whl
|
||||
37
Makefile
@@ -1,39 +1,42 @@
|
||||
default_target: local
|
||||
|
||||
COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1)
|
||||
VERSION = 0.11.0
|
||||
VERSION = 0.12.0
|
||||
IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate
|
||||
CURRENT_UID := $(shell id -u)
|
||||
CURRENT_GID := $(shell id -g)
|
||||
|
||||
version:
|
||||
echo "VERSION=\"$(VERSION)-$(COMMIT_HASH)\"" > frigate/version.py
|
||||
echo 'VERSION = "$(VERSION)-$(COMMIT_HASH)"' > frigate/version.py
|
||||
|
||||
build_web:
|
||||
docker run --volume ${PWD}/web:/web -w /web --volume /etc/passwd:/etc/passwd:ro --volume /etc/group:/etc/group:ro -u $(CURRENT_UID):$(CURRENT_GID) node:16 /bin/bash -c "npm install && npm run build"
|
||||
local: version
|
||||
docker buildx build --target=frigate --tag frigate:latest --load .
|
||||
|
||||
nginx_frigate:
|
||||
docker buildx build --push --platform linux/arm/v7,linux/arm64/v8,linux/amd64 --tag blakeblackshear/frigate-nginx:1.0.2 --file docker/Dockerfile.nginx .
|
||||
|
||||
local:
|
||||
DOCKER_BUILDKIT=1 docker build -t frigate -f docker/Dockerfile .
|
||||
local-trt: version
|
||||
docker buildx build --target=frigate-tensorrt --tag frigate:latest-tensorrt --load .
|
||||
|
||||
amd64:
|
||||
docker buildx build --platform linux/amd64 --tag blakeblackshear/frigate:$(VERSION)-$(COMMIT_HASH) --file docker/Dockerfile .
|
||||
docker buildx build --platform linux/amd64 --target=frigate --tag $(IMAGE_REPO):$(VERSION)-$(COMMIT_HASH) .
|
||||
docker buildx build --platform linux/amd64 --target=frigate-tensorrt --tag $(IMAGE_REPO):$(VERSION)-$(COMMIT_HASH)-tensorrt .
|
||||
|
||||
arm64:
|
||||
docker buildx build --platform linux/arm64 --tag blakeblackshear/frigate:$(VERSION)-$(COMMIT_HASH) --file docker/Dockerfile .
|
||||
docker buildx build --platform linux/arm64 --target=frigate --tag $(IMAGE_REPO):$(VERSION)-$(COMMIT_HASH) .
|
||||
|
||||
armv7:
|
||||
docker buildx build --platform linux/arm/v7 --tag blakeblackshear/frigate:$(VERSION)-$(COMMIT_HASH) --file docker/Dockerfile .
|
||||
docker buildx build --platform linux/arm/v7 --target=frigate --tag $(IMAGE_REPO):$(VERSION)-$(COMMIT_HASH) .
|
||||
|
||||
build: version amd64 arm64 armv7
|
||||
docker buildx build --platform linux/arm/v7,linux/arm64/v8,linux/amd64 --tag blakeblackshear/frigate:$(VERSION)-$(COMMIT_HASH) --file docker/Dockerfile .
|
||||
docker buildx build --platform linux/arm/v7,linux/arm64/v8,linux/amd64 --target=frigate --tag $(IMAGE_REPO):$(VERSION)-$(COMMIT_HASH) .
|
||||
|
||||
push: build
|
||||
docker buildx build --push --platform linux/arm/v7,linux/arm64/v8,linux/amd64 --tag blakeblackshear/frigate:$(VERSION)-$(COMMIT_HASH) --file docker/Dockerfile .
|
||||
docker buildx build --push --platform linux/arm/v7,linux/arm64/v8,linux/amd64 --target=frigate --tag $(IMAGE_REPO):${GITHUB_REF_NAME}-$(COMMIT_HASH) .
|
||||
docker buildx build --push --platform linux/amd64 --target=frigate-tensorrt --tag $(IMAGE_REPO):${GITHUB_REF_NAME}-$(COMMIT_HASH)-tensorrt .
|
||||
|
||||
run_tests: frigate
|
||||
docker run --rm --entrypoint=python3 frigate:latest -u -m unittest
|
||||
docker run --rm --entrypoint=python3 frigate:latest -u -m mypy --config-file frigate/mypy.ini frigate
|
||||
run: local
|
||||
docker run --rm --publish=5000:5000 --volume=${PWD}/config/config.yml:/config/config.yml frigate:latest
|
||||
|
||||
run_tests: local
|
||||
docker run --rm --workdir=/opt/frigate --entrypoint= frigate:latest python3 -u -m unittest
|
||||
docker run --rm --workdir=/opt/frigate --entrypoint= frigate:latest python3 -u -m mypy --config-file frigate/mypy.ini frigate
|
||||
|
||||
.PHONY: run_tests
|
||||
|
||||
65
benchmark.py
@@ -3,10 +3,16 @@ from statistics import mean
|
||||
import multiprocessing as mp
|
||||
import numpy as np
|
||||
import datetime
|
||||
from frigate.edgetpu import LocalObjectDetector, EdgeTPUProcess, RemoteObjectDetector, load_labels
|
||||
from frigate.config import DetectorTypeEnum
|
||||
from frigate.object_detection import (
|
||||
LocalObjectDetector,
|
||||
ObjectDetectProcess,
|
||||
RemoteObjectDetector,
|
||||
load_labels,
|
||||
)
|
||||
|
||||
my_frame = np.expand_dims(np.full((300,300,3), 1, np.uint8), axis=0)
|
||||
labels = load_labels('/labelmap.txt')
|
||||
my_frame = np.expand_dims(np.full((300, 300, 3), 1, np.uint8), axis=0)
|
||||
labels = load_labels("/labelmap.txt")
|
||||
|
||||
######
|
||||
# Minimal same process runner
|
||||
@@ -39,20 +45,23 @@ labels = load_labels('/labelmap.txt')
|
||||
|
||||
|
||||
def start(id, num_detections, detection_queue, event):
|
||||
object_detector = RemoteObjectDetector(str(id), '/labelmap.txt', detection_queue, event)
|
||||
start = datetime.datetime.now().timestamp()
|
||||
object_detector = RemoteObjectDetector(
|
||||
str(id), "/labelmap.txt", detection_queue, event
|
||||
)
|
||||
start = datetime.datetime.now().timestamp()
|
||||
|
||||
frame_times = []
|
||||
for x in range(0, num_detections):
|
||||
start_frame = datetime.datetime.now().timestamp()
|
||||
detections = object_detector.detect(my_frame)
|
||||
frame_times.append(datetime.datetime.now().timestamp()-start_frame)
|
||||
frame_times = []
|
||||
for x in range(0, num_detections):
|
||||
start_frame = datetime.datetime.now().timestamp()
|
||||
detections = object_detector.detect(my_frame)
|
||||
frame_times.append(datetime.datetime.now().timestamp() - start_frame)
|
||||
|
||||
duration = datetime.datetime.now().timestamp() - start
|
||||
object_detector.cleanup()
|
||||
print(f"{id} - Processed for {duration:.2f} seconds.")
|
||||
print(f"{id} - FPS: {object_detector.fps.eps():.2f}")
|
||||
print(f"{id} - Average frame processing time: {mean(frame_times)*1000:.2f}ms")
|
||||
|
||||
duration = datetime.datetime.now().timestamp()-start
|
||||
object_detector.cleanup()
|
||||
print(f"{id} - Processed for {duration:.2f} seconds.")
|
||||
print(f"{id} - FPS: {object_detector.fps.eps():.2f}")
|
||||
print(f"{id} - Average frame processing time: {mean(frame_times)*1000:.2f}ms")
|
||||
|
||||
######
|
||||
# Separate process runner
|
||||
@@ -71,23 +80,29 @@ camera_processes = []
|
||||
|
||||
events = {}
|
||||
for x in range(0, 10):
|
||||
events[str(x)] = mp.Event()
|
||||
events[str(x)] = mp.Event()
|
||||
detection_queue = mp.Queue()
|
||||
edgetpu_process_1 = EdgeTPUProcess(detection_queue, events, 'usb:0')
|
||||
edgetpu_process_2 = EdgeTPUProcess(detection_queue, events, 'usb:1')
|
||||
edgetpu_process_1 = ObjectDetectProcess(
|
||||
detection_queue, events, DetectorTypeEnum.edgetpu, "usb:0"
|
||||
)
|
||||
edgetpu_process_2 = ObjectDetectProcess(
|
||||
detection_queue, events, DetectorTypeEnum.edgetpu, "usb:1"
|
||||
)
|
||||
|
||||
for x in range(0, 10):
|
||||
camera_process = mp.Process(target=start, args=(x, 300, detection_queue, events[str(x)]))
|
||||
camera_process.daemon = True
|
||||
camera_processes.append(camera_process)
|
||||
camera_process = mp.Process(
|
||||
target=start, args=(x, 300, detection_queue, events[str(x)])
|
||||
)
|
||||
camera_process.daemon = True
|
||||
camera_processes.append(camera_process)
|
||||
|
||||
start_time = datetime.datetime.now().timestamp()
|
||||
|
||||
for p in camera_processes:
|
||||
p.start()
|
||||
p.start()
|
||||
|
||||
for p in camera_processes:
|
||||
p.join()
|
||||
p.join()
|
||||
|
||||
duration = datetime.datetime.now().timestamp()-start_time
|
||||
print(f"Total - Processed for {duration:.2f} seconds.")
|
||||
duration = datetime.datetime.now().timestamp() - start_time
|
||||
print(f"Total - Processed for {duration:.2f} seconds.")
|
||||
|
||||
16
config/config.yml.example
Normal file
@@ -0,0 +1,16 @@
|
||||
mqtt:
|
||||
host: mqtt
|
||||
|
||||
cameras:
|
||||
test:
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: /media/frigate/car-stopping.mp4
|
||||
input_args: -re -stream_loop -1 -fflags +genpts
|
||||
roles:
|
||||
- detect
|
||||
- rtmp
|
||||
detect:
|
||||
height: 1080
|
||||
width: 1920
|
||||
fps: 5
|
||||
@@ -1,8 +1,7 @@
|
||||
version: "3"
|
||||
services:
|
||||
dev:
|
||||
container_name: frigate-dev
|
||||
user: vscode
|
||||
devcontainer:
|
||||
container_name: frigate-devcontainer
|
||||
# add groups from host for render, plugdev, video
|
||||
group_add:
|
||||
- "109" # render
|
||||
@@ -12,24 +11,27 @@ services:
|
||||
shm_size: "256mb"
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
# Use target devcontainer-trt for TensorRT dev
|
||||
target: devcontainer
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities: [gpu]
|
||||
devices:
|
||||
- /dev/bus/usb:/dev/bus/usb
|
||||
- /dev/dri:/dev/dri # for intel hwaccel, needs to be updated for your hardware
|
||||
# - /dev/dri:/dev/dri # for intel hwaccel, needs to be updated for your hardware
|
||||
volumes:
|
||||
- .:/workspace/frigate:cached
|
||||
- ./web/dist:/opt/frigate/web:cached
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- .:/lab/frigate:cached
|
||||
- ./config/config.yml:/config/config.yml:ro
|
||||
- ./debug:/media/frigate
|
||||
# Create the trt-models folder using the documented method of generating TRT models
|
||||
# - ./debug/trt-models:/trt-models
|
||||
- /dev/bus/usb:/dev/bus/usb
|
||||
ports:
|
||||
- "1935:1935"
|
||||
- "3000:3000"
|
||||
- "5000:5000"
|
||||
- "5001:5001"
|
||||
- "8080:8080"
|
||||
entrypoint: ["sudo", "/init"]
|
||||
command: /bin/sh -c "while sleep 1000; do :; done"
|
||||
mqtt:
|
||||
container_name: mqtt
|
||||
image: eclipse-mosquitto:1.6
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
FROM blakeblackshear/frigate-nginx:1.0.2 as nginx
|
||||
|
||||
FROM debian:11 as wheels
|
||||
ARG TARGETARCH
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Use a separate container to build wheels to prevent build dependencies in final image
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install -y \
|
||||
apt-transport-https \
|
||||
gnupg \
|
||||
wget \
|
||||
&& apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 9165938D90FDDD2E \
|
||||
&& echo "deb http://raspbian.raspberrypi.org/raspbian/ bullseye main contrib non-free rpi" | tee /etc/apt/sources.list.d/raspi.list \
|
||||
&& apt-get -qq update \
|
||||
&& apt-get -qq install -y \
|
||||
python3 \
|
||||
python3-dev \
|
||||
wget \
|
||||
# opencv dependencies
|
||||
build-essential cmake git pkg-config libgtk-3-dev \
|
||||
libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
|
||||
libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
|
||||
gfortran openexr libatlas-base-dev libssl-dev\
|
||||
libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
|
||||
libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev \
|
||||
# scipy dependencies
|
||||
gcc gfortran libopenblas-dev liblapack-dev
|
||||
|
||||
RUN wget -q https://bootstrap.pypa.io/get-pip.py -O get-pip.py \
|
||||
&& python3 get-pip.py "pip"
|
||||
|
||||
RUN if [ "${TARGETARCH}" = "arm" ]; \
|
||||
then echo "[global]" > /etc/pip.conf \
|
||||
&& echo "extra-index-url=https://www.piwheels.org/simple" >> /etc/pip.conf; \
|
||||
fi
|
||||
|
||||
COPY requirements.txt /requirements.txt
|
||||
RUN pip3 install -r requirements.txt
|
||||
|
||||
COPY requirements-wheels.txt /requirements-wheels.txt
|
||||
RUN pip3 wheel --wheel-dir=/wheels -r requirements-wheels.txt
|
||||
|
||||
# Frigate Container
|
||||
FROM debian:11-slim
|
||||
ARG TARGETARCH
|
||||
|
||||
ARG JELLYFIN_FFMPEG_VERSION=5.0.1-7
|
||||
# https://askubuntu.com/questions/972516/debian-frontend-environment-variable
|
||||
ARG DEBIAN_FRONTEND="noninteractive"
|
||||
# http://stackoverflow.com/questions/48162574/ddg#49462622
|
||||
ARG APT_KEY_DONT_WARN_ON_DANGEROUS_USAGE=DontWarn
|
||||
# https://github.com/NVIDIA/nvidia-docker/wiki/Installation-(Native-GPU-Support)
|
||||
ENV NVIDIA_DRIVER_CAPABILITIES="compute,video,utility"
|
||||
|
||||
ENV FLASK_ENV=development
|
||||
|
||||
COPY --from=wheels /wheels /wheels
|
||||
|
||||
# Install ffmpeg
|
||||
RUN apt-get -qq update \
|
||||
&& apt-get -qq install --no-install-recommends -y \
|
||||
apt-transport-https \
|
||||
gnupg \
|
||||
wget \
|
||||
unzip tzdata libxml2 xz-utils \
|
||||
python3-pip \
|
||||
# add raspberry pi repo
|
||||
&& apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 9165938D90FDDD2E \
|
||||
&& echo "deb http://raspbian.raspberrypi.org/raspbian/ bullseye main contrib non-free rpi" | tee /etc/apt/sources.list.d/raspi.list \
|
||||
# add coral repo
|
||||
&& apt-key adv --fetch-keys https://packages.cloud.google.com/apt/doc/apt-key.gpg \
|
||||
&& echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" > /etc/apt/sources.list.d/coral-edgetpu.list \
|
||||
&& echo "libedgetpu1-max libedgetpu/accepted-eula select true" | debconf-set-selections \
|
||||
# enable non-free repo
|
||||
&& sed -i -e's/ main/ main contrib non-free/g' /etc/apt/sources.list \
|
||||
&& apt-get -qq update \
|
||||
&& apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
# coral drivers
|
||||
libedgetpu1-max python3-tflite-runtime python3-pycoral \
|
||||
&& pip3 install -U /wheels/*.whl \
|
||||
# jellyfin-ffmpeg
|
||||
&& wget -O jellyfin.deb "https://repo.jellyfin.org/releases/server/debian/versions/jellyfin-ffmpeg/${JELLYFIN_FFMPEG_VERSION}/jellyfin-ffmpeg5_${JELLYFIN_FFMPEG_VERSION}-$( awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release )_$( dpkg --print-architecture ).deb" \
|
||||
&& apt-get -qq install --no-install-recommends --no-install-suggests -y ./jellyfin.deb \
|
||||
&& rm jellyfin.deb \
|
||||
# arch specific packages
|
||||
&& if [ "${TARGETARCH}" = "amd64" ]; then \
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
mesa-va-drivers intel-media-va-driver-non-free; \
|
||||
fi \
|
||||
# not sure why 32bit arm requires all these
|
||||
&& if [ "${TARGETARCH}" = "arm" ]; then \
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
libgtk-3-dev \
|
||||
libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
|
||||
libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
|
||||
gfortran openexr libatlas-base-dev libssl-dev\
|
||||
libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
|
||||
libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev; \
|
||||
fi \
|
||||
&& rm -rf /wheels \
|
||||
&& apt-get remove gnupg apt-transport-https -y \
|
||||
&& apt-get clean autoclean -y \
|
||||
&& apt-get autoremove -y \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ENV PATH=$PATH:/usr/lib/jellyfin-ffmpeg
|
||||
|
||||
COPY --from=nginx /usr/local/nginx/ /usr/local/nginx/
|
||||
|
||||
# get model and labels
|
||||
COPY labelmap.txt /labelmap.txt
|
||||
RUN wget -q https://github.com/google-coral/test_data/raw/release-frogfish/ssdlite_mobiledet_coco_qat_postprocess_edgetpu.tflite -O /edgetpu_model.tflite
|
||||
RUN wget -q https://github.com/google-coral/test_data/raw/release-frogfish/ssdlite_mobiledet_coco_qat_postprocess.tflite -O /cpu_model.tflite
|
||||
|
||||
WORKDIR /opt/frigate/
|
||||
ADD frigate frigate/
|
||||
ADD migrations migrations/
|
||||
|
||||
COPY web/dist web/
|
||||
|
||||
COPY docker/rootfs/ /
|
||||
|
||||
# s6-overlay
|
||||
RUN S6_ARCH="${TARGETARCH}" \
|
||||
&& if [ "${TARGETARCH}" = "amd64" ]; then S6_ARCH="amd64"; fi \
|
||||
&& if [ "${TARGETARCH}" = "arm" ]; then S6_ARCH="armhf"; fi \
|
||||
&& if [ "${TARGETARCH}" = "arm64" ]; then S6_ARCH="aarch64"; fi \
|
||||
&& wget -O /tmp/s6-overlay-installer "https://github.com/just-containers/s6-overlay/releases/download/v2.2.0.3/s6-overlay-${S6_ARCH}-installer" \
|
||||
&& chmod +x /tmp/s6-overlay-installer && /tmp/s6-overlay-installer /
|
||||
|
||||
EXPOSE 5000
|
||||
EXPOSE 1935
|
||||
|
||||
ENTRYPOINT ["/init"]
|
||||
|
||||
CMD ["python3", "-u", "-m", "frigate"]
|
||||
@@ -1,27 +0,0 @@
|
||||
FROM frigate:latest
|
||||
|
||||
ARG USERNAME=vscode
|
||||
ARG USER_UID=1000
|
||||
ARG USER_GID=$USER_UID
|
||||
|
||||
# Create the user
|
||||
RUN groupadd --gid $USER_GID $USERNAME \
|
||||
&& useradd --uid $USER_UID --gid $USER_GID -m $USERNAME -s /bin/bash \
|
||||
#
|
||||
# [Optional] Add sudo support. Omit if you don't need to install software after connecting.
|
||||
&& apt-get update \
|
||||
&& apt-get install -y sudo \
|
||||
&& echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
|
||||
&& chmod 0440 /etc/sudoers.d/$USERNAME
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y git curl vim htop
|
||||
|
||||
COPY requirements-dev.txt /opt/frigate/requirements-dev.txt
|
||||
RUN pip3 install -r requirements-dev.txt
|
||||
|
||||
# Install Node 16
|
||||
RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - \
|
||||
&& apt-get install -y nodejs
|
||||
|
||||
RUN npm install -g npm@latest
|
||||
50
docker/build_nginx.sh
Executable file
@@ -0,0 +1,50 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
NGINX_VERSION="1.22.1"
|
||||
VOD_MODULE_VERSION="1.30"
|
||||
SECURE_TOKEN_MODULE_VERSION="1.4"
|
||||
RTMP_MODULE_VERSION="1.2.1"
|
||||
|
||||
cp /etc/apt/sources.list /etc/apt/sources.list.d/sources-src.list
|
||||
sed -i 's|deb http|deb-src http|g' /etc/apt/sources.list.d/sources-src.list
|
||||
apt-get update
|
||||
|
||||
apt-get -yqq build-dep nginx
|
||||
|
||||
apt-get -yqq install --no-install-recommends ca-certificates wget
|
||||
update-ca-certificates -f
|
||||
mkdir /tmp/nginx
|
||||
wget -nv https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz
|
||||
tar -zxf nginx-${NGINX_VERSION}.tar.gz -C /tmp/nginx --strip-components=1
|
||||
rm nginx-${NGINX_VERSION}.tar.gz
|
||||
mkdir /tmp/nginx-vod-module
|
||||
wget -nv https://github.com/kaltura/nginx-vod-module/archive/refs/tags/${VOD_MODULE_VERSION}.tar.gz
|
||||
tar -zxf ${VOD_MODULE_VERSION}.tar.gz -C /tmp/nginx-vod-module --strip-components=1
|
||||
rm ${VOD_MODULE_VERSION}.tar.gz
|
||||
# Patch MAX_CLIPS to allow more clips to be added than the default 128
|
||||
sed -i 's/MAX_CLIPS (128)/MAX_CLIPS (1080)/g' /tmp/nginx-vod-module/vod/media_set.h
|
||||
mkdir /tmp/nginx-secure-token-module
|
||||
wget https://github.com/kaltura/nginx-secure-token-module/archive/refs/tags/${SECURE_TOKEN_MODULE_VERSION}.tar.gz
|
||||
tar -zxf ${SECURE_TOKEN_MODULE_VERSION}.tar.gz -C /tmp/nginx-secure-token-module --strip-components=1
|
||||
rm ${SECURE_TOKEN_MODULE_VERSION}.tar.gz
|
||||
mkdir /tmp/nginx-rtmp-module
|
||||
wget -nv https://github.com/arut/nginx-rtmp-module/archive/refs/tags/v${RTMP_MODULE_VERSION}.tar.gz
|
||||
tar -zxf v${RTMP_MODULE_VERSION}.tar.gz -C /tmp/nginx-rtmp-module --strip-components=1
|
||||
rm v${RTMP_MODULE_VERSION}.tar.gz
|
||||
|
||||
cd /tmp/nginx
|
||||
|
||||
./configure --prefix=/usr/local/nginx \
|
||||
--with-file-aio \
|
||||
--with-http_sub_module \
|
||||
--with-http_ssl_module \
|
||||
--with-threads \
|
||||
--add-module=../nginx-vod-module \
|
||||
--add-module=../nginx-secure-token-module \
|
||||
--add-module=../nginx-rtmp-module \
|
||||
--with-cc-opt="-O3 -Wno-error=implicit-fallthrough"
|
||||
|
||||
make -j$(nproc) && make install
|
||||
rm -rf /usr/local/nginx/html /usr/local/nginx/conf/*.default
|
||||
8
docker/fake_frigate_run
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Start the fake Frigate service
|
||||
|
||||
while true; do
|
||||
echo "The fake Frigate service is running..."
|
||||
sleep 5s
|
||||
done
|
||||
86
docker/install_deps.sh
Executable file
@@ -0,0 +1,86 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
apt-get -qq update
|
||||
|
||||
apt-get -qq install --no-install-recommends -y \
|
||||
apt-transport-https \
|
||||
gnupg \
|
||||
wget \
|
||||
procps vainfo \
|
||||
unzip locales tzdata libxml2 xz-utils \
|
||||
python3-pip
|
||||
|
||||
mkdir -p -m 600 /root/.gnupg
|
||||
|
||||
# add coral repo
|
||||
wget --quiet -O /usr/share/keyrings/google-edgetpu.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg
|
||||
echo "deb [signed-by=/usr/share/keyrings/google-edgetpu.gpg] https://packages.cloud.google.com/apt coral-edgetpu-stable main" | tee /etc/apt/sources.list.d/coral-edgetpu.list
|
||||
echo "libedgetpu1-max libedgetpu/accepted-eula select true" | debconf-set-selections
|
||||
|
||||
# enable non-free repo
|
||||
sed -i -e's/ main/ main contrib non-free/g' /etc/apt/sources.list
|
||||
|
||||
# coral drivers
|
||||
apt-get -qq update
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
libedgetpu1-max python3-tflite-runtime python3-pycoral
|
||||
|
||||
# btbn-ffmpeg -> amd64
|
||||
if [[ "${TARGETARCH}" == "amd64" ]]; then
|
||||
mkdir -p /usr/lib/btbn-ffmpeg
|
||||
wget -qO btbn-ffmpeg.tar.xz "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2022-07-31-12-37/ffmpeg-n5.1-2-g915ef932a3-linux64-gpl-5.1.tar.xz"
|
||||
tar -xf btbn-ffmpeg.tar.xz -C /usr/lib/btbn-ffmpeg --strip-components 1
|
||||
rm -rf btbn-ffmpeg.tar.xz /usr/lib/btbn-ffmpeg/doc /usr/lib/btbn-ffmpeg/bin/ffplay
|
||||
fi
|
||||
|
||||
# ffmpeg -> arm32
|
||||
if [[ "${TARGETARCH}" == "arm" ]]; then
|
||||
# add raspberry pi repo
|
||||
gpg --no-default-keyring --keyring /usr/share/keyrings/raspbian.gpg --keyserver keyserver.ubuntu.com --recv-keys 9165938D90FDDD2E
|
||||
echo "deb [signed-by=/usr/share/keyrings/raspbian.gpg] http://raspbian.raspberrypi.org/raspbian/ bullseye main contrib non-free rpi" | tee /etc/apt/sources.list.d/raspi.list
|
||||
apt-get -qq update
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y ffmpeg
|
||||
fi
|
||||
|
||||
# ffmpeg -> arm64
|
||||
if [[ "${TARGETARCH}" == "arm64" ]]; then
|
||||
# add raspberry pi repo
|
||||
gpg --no-default-keyring --keyring /usr/share/keyrings/raspbian.gpg --keyserver keyserver.ubuntu.com --recv-keys 82B129927FA3303E
|
||||
echo "deb [signed-by=/usr/share/keyrings/raspbian.gpg] https://archive.raspberrypi.org/debian/ bullseye main" | tee /etc/apt/sources.list.d/raspi.list
|
||||
apt-get -qq update
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y ffmpeg
|
||||
fi
|
||||
|
||||
# arch specific packages
|
||||
if [[ "${TARGETARCH}" == "amd64" ]]; then
|
||||
# Use debian testing repo only for hwaccel packages
|
||||
echo 'deb http://deb.debian.org/debian testing main non-free' >/etc/apt/sources.list.d/debian-testing.list
|
||||
apt-get -qq update
|
||||
# intel-opencl-icd specifically for GPU support in OpenVino
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
intel-opencl-icd \
|
||||
mesa-va-drivers libva-drm2 intel-media-va-driver-non-free i965-va-driver libmfx1 radeontop intel-gpu-tools
|
||||
rm -f /etc/apt/sources.list.d/debian-testing.list
|
||||
fi
|
||||
|
||||
if [[ "${TARGETARCH}" == "arm64" ]]; then
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
libva-drm2 mesa-va-drivers
|
||||
fi
|
||||
|
||||
# not sure why 32bit arm requires all these
|
||||
if [[ "${TARGETARCH}" == "arm" ]]; then
|
||||
apt-get -qq install --no-install-recommends --no-install-suggests -y \
|
||||
libgtk-3-dev \
|
||||
libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
|
||||
libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
|
||||
gfortran openexr libatlas-base-dev libtbb-dev libdc1394-22-dev libopenexr-dev \
|
||||
libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev
|
||||
fi
|
||||
|
||||
apt-get purge gnupg apt-transport-https wget xz-utils -y
|
||||
apt-get clean autoclean -y
|
||||
apt-get autoremove --purge -y
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
21
docker/install_s6_overlay.sh
Executable file
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
s6_version="3.1.2.1"
|
||||
|
||||
if [[ "${TARGETARCH}" == "amd64" ]]; then
|
||||
s6_arch="x86_64"
|
||||
elif [[ "${TARGETARCH}" == "arm" ]]; then
|
||||
s6_arch="armhf"
|
||||
elif [[ "${TARGETARCH}" == "arm64" ]]; then
|
||||
s6_arch="aarch64"
|
||||
fi
|
||||
|
||||
mkdir -p /rootfs/
|
||||
|
||||
wget -qO- "https://github.com/just-containers/s6-overlay/releases/download/v${s6_version}/s6-overlay-noarch.tar.xz" |
|
||||
tar -C /rootfs/ -Jxpf -
|
||||
|
||||
wget -qO- "https://github.com/just-containers/s6-overlay/releases/download/v${s6_version}/s6-overlay-${s6_arch}.tar.xz" |
|
||||
tar -C /rootfs/ -Jxpf -
|
||||
11
docker/rootfs/etc/cont-init.d/prepare-logs.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Prepare the logs folder for s6-log
|
||||
|
||||
set -o errexit -o nounset -o pipefail
|
||||
|
||||
dirs=(/dev/shm/logs/frigate /dev/shm/logs/go2rtc /dev/shm/logs/nginx)
|
||||
|
||||
mkdir -p "${dirs[@]}"
|
||||
chown nobody:nogroup "${dirs[@]}"
|
||||
chmod 02755 "${dirs[@]}"
|
||||
16
docker/rootfs/etc/services.d/frigate/finish
Executable file
@@ -0,0 +1,16 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Take down the S6 supervision tree when the service exits
|
||||
|
||||
set -o errexit -o nounset -o pipefail
|
||||
|
||||
# Prepare exit code
|
||||
if [[ "${1}" -eq 256 ]]; then
|
||||
exit_code="$((128 + ${2}))"
|
||||
else
|
||||
exit_code="${1}"
|
||||
fi
|
||||
|
||||
# Make the container exit with the same exit code as the service
|
||||
echo "${exit_code}" > /run/s6-linux-init-container-results/exitcode
|
||||
exec /run/s6/basedir/bin/halt
|
||||
4
docker/rootfs/etc/services.d/frigate/log/run
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
|
||||
exec logutil-service /dev/shm/logs/frigate
|
||||
11
docker/rootfs/etc/services.d/frigate/run
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Start the Frigate service
|
||||
|
||||
set -o errexit -o nounset -o pipefail
|
||||
|
||||
cd /opt/frigate
|
||||
|
||||
# Replace the bash process with the Frigate process, redirecting stderr to stdout
|
||||
exec 2>&1
|
||||
exec python3 -u -m frigate
|
||||
8
docker/rootfs/etc/services.d/go2rtc/finish
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Take down the S6 supervision tree when the service fails, or restart it
|
||||
# otherwise
|
||||
|
||||
if [[ "${1}" -ne 0 && "${1}" -ne 256 ]]; then
|
||||
exec /run/s6/basedir/bin/halt
|
||||
fi
|
||||
4
docker/rootfs/etc/services.d/go2rtc/log/run
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
|
||||
exec logutil-service /dev/shm/logs/go2rtc
|
||||
15
docker/rootfs/etc/services.d/go2rtc/run
Executable file
@@ -0,0 +1,15 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Start the go2rtc service
|
||||
|
||||
set -o errexit -o nounset -o pipefail
|
||||
|
||||
if [[ -f "/config/frigate-go2rtc.yaml" ]]; then
|
||||
config_path="/config/frigate-go2rtc.yaml"
|
||||
else
|
||||
config_path="/usr/local/go2rtc/go2rtc.yaml"
|
||||
fi
|
||||
|
||||
# Replace the bash process with the go2rtc process, redirecting stderr to stdout
|
||||
exec 2>&1
|
||||
exec go2rtc -config="${config_path}"
|
||||
11
docker/rootfs/etc/services.d/nginx/finish
Normal file → Executable file
@@ -1,5 +1,8 @@
|
||||
#!/usr/bin/execlineb -S1
|
||||
if { s6-test ${1} -ne 0 }
|
||||
if { s6-test ${1} -ne 256 }
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Take down the S6 supervision tree when the service fails, or restart it
|
||||
# otherwise
|
||||
|
||||
s6-svscanctl -t /var/run/s6/services
|
||||
if [[ "${1}" -ne 0 && "${1}" -ne 256 ]]; then
|
||||
exec /run/s6/basedir/bin/halt
|
||||
fi
|
||||
|
||||
4
docker/rootfs/etc/services.d/nginx/log/run
Executable file
@@ -0,0 +1,4 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
|
||||
exec logutil-service /dev/shm/logs/nginx
|
||||
9
docker/rootfs/etc/services.d/nginx/run
Normal file → Executable file
@@ -1,2 +1,7 @@
|
||||
#!/usr/bin/execlineb -P
|
||||
/usr/local/nginx/sbin/nginx
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
# Start the NGINX service
|
||||
|
||||
# Replace the bash process with the NGINX process, redirecting stderr to stdout
|
||||
exec 2>&1
|
||||
exec nginx
|
||||
|
||||
5
docker/rootfs/usr/local/bin/frigate
Normal file
@@ -0,0 +1,5 @@
|
||||
#!/command/with-contenv bash
|
||||
# shellcheck shell=bash
|
||||
|
||||
exec 2>&1
|
||||
exec python3 -u -m frigate "${@}"
|
||||
7
docker/rootfs/usr/local/go2rtc/go2rtc.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
log:
|
||||
format: text
|
||||
|
||||
webrtc:
|
||||
listen: ":8555"
|
||||
candidates:
|
||||
- stun:8555
|
||||
@@ -1,27 +1,30 @@
|
||||
daemon off;
|
||||
user root;
|
||||
worker_processes 1;
|
||||
worker_processes auto;
|
||||
|
||||
error_log /usr/local/nginx/logs/error.log warn;
|
||||
pid /var/run/nginx.pid;
|
||||
error_log /dev/stdout warn;
|
||||
pid /var/run/nginx.pid;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
include mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||
'$status $body_bytes_sent "$http_referer" '
|
||||
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||
|
||||
access_log /usr/local/nginx/logs/access.log main;
|
||||
access_log /dev/stdout main;
|
||||
|
||||
sendfile on;
|
||||
# send headers in one piece, it is better than sending them one by one
|
||||
tcp_nopush on;
|
||||
|
||||
keepalive_timeout 65;
|
||||
sendfile on;
|
||||
|
||||
keepalive_timeout 65;
|
||||
|
||||
gzip on;
|
||||
gzip_comp_level 6;
|
||||
@@ -30,18 +33,23 @@ http {
|
||||
gzip_vary on;
|
||||
|
||||
upstream frigate_api {
|
||||
server 127.0.0.1:5001;
|
||||
keepalive 1024;
|
||||
server 127.0.0.1:5001;
|
||||
keepalive 1024;
|
||||
}
|
||||
|
||||
upstream mqtt_ws {
|
||||
server 127.0.0.1:5002;
|
||||
keepalive 1024;
|
||||
server 127.0.0.1:5002;
|
||||
keepalive 1024;
|
||||
}
|
||||
|
||||
upstream jsmpeg {
|
||||
server 127.0.0.1:8082;
|
||||
keepalive 1024;
|
||||
server 127.0.0.1:8082;
|
||||
keepalive 1024;
|
||||
}
|
||||
|
||||
upstream go2rtc {
|
||||
server 127.0.0.1:1984;
|
||||
keepalive 1024;
|
||||
}
|
||||
|
||||
server {
|
||||
@@ -55,6 +63,20 @@ http {
|
||||
vod_upstream_location /api;
|
||||
vod_align_segments_to_key_frames on;
|
||||
vod_manifest_segment_durations_mode accurate;
|
||||
vod_ignore_edit_list on;
|
||||
vod_segment_duration 10000;
|
||||
vod_hls_mpegts_align_frames off;
|
||||
vod_hls_mpegts_interleave_frames on;
|
||||
|
||||
# file handle caching / aio
|
||||
open_file_cache max=1000 inactive=5m;
|
||||
open_file_cache_valid 2m;
|
||||
open_file_cache_min_uses 1;
|
||||
open_file_cache_errors on;
|
||||
aio on;
|
||||
|
||||
# https://github.com/kaltura/nginx-vod-module#vod_open_file_thread_pool
|
||||
vod_open_file_thread_pool default;
|
||||
|
||||
# vod caches
|
||||
vod_metadata_cache metadata_cache 512m;
|
||||
@@ -64,18 +86,12 @@ http {
|
||||
gzip on;
|
||||
gzip_types application/vnd.apple.mpegurl;
|
||||
|
||||
# file handle caching / aio
|
||||
open_file_cache max=1000 inactive=5m;
|
||||
open_file_cache_valid 2m;
|
||||
open_file_cache_min_uses 1;
|
||||
open_file_cache_errors on;
|
||||
aio on;
|
||||
|
||||
location /vod/ {
|
||||
aio threads;
|
||||
vod hls;
|
||||
|
||||
secure_token $args;
|
||||
secure_token_types application/vnd.apple.mpegurl;
|
||||
secure_token_types application/vnd.apple.mpegurl;
|
||||
|
||||
add_header Access-Control-Allow-Headers '*';
|
||||
add_header Access-Control-Expose-Headers 'Server,range,Content-Length,Content-Range';
|
||||
@@ -131,8 +147,8 @@ http {
|
||||
}
|
||||
|
||||
location /cache/ {
|
||||
internal; # This tells nginx it's not accessible from the outside
|
||||
alias /tmp/cache/;
|
||||
internal; # This tells nginx it's not accessible from the outside
|
||||
alias /tmp/cache/;
|
||||
}
|
||||
|
||||
location /recordings/ {
|
||||
@@ -164,7 +180,7 @@ http {
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location /live/ {
|
||||
location /live/jsmpeg/ {
|
||||
proxy_pass http://jsmpeg/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
@@ -172,10 +188,27 @@ http {
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location ~* /api/(.*\.(jpg|jpeg|png)$) {
|
||||
location /live/mse/ {
|
||||
proxy_pass http://go2rtc/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location /live/webrtc/ {
|
||||
proxy_pass http://go2rtc/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "Upgrade";
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location ~* /api/.*\.(jpg|jpeg|png)$ {
|
||||
add_header 'Access-Control-Allow-Origin' '*';
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
|
||||
proxy_pass http://frigate_api/$1$is_args$args;
|
||||
rewrite ^/api/(.*)$ $1 break;
|
||||
proxy_pass http://frigate_api;
|
||||
proxy_pass_request_headers on;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
@@ -210,7 +243,8 @@ http {
|
||||
sub_filter '"/BASE_PATH/dist/' '"$http_x_ingress_path/dist/';
|
||||
sub_filter '"/BASE_PATH/js/' '"$http_x_ingress_path/js/';
|
||||
sub_filter '"/BASE_PATH/assets/' '"$http_x_ingress_path/assets/';
|
||||
sub_filter '="/BASE_PATH/"' '=window.baseUrl';
|
||||
sub_filter '"/BASE_PATH/monacoeditorwork/' '"$http_x_ingress_path/assets/';
|
||||
sub_filter 'return"/BASE_PATH/"' 'return window.baseUrl';
|
||||
sub_filter '<body>' '<body><script>window.baseUrl="$http_x_ingress_path/";</script>';
|
||||
sub_filter_types text/css application/javascript;
|
||||
sub_filter_once off;
|
||||
@@ -234,4 +268,4 @@ rtmp {
|
||||
meta copy;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
34
docker/tensorrt_models.sh
Executable file
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -euxo pipefail
|
||||
|
||||
CUDA_HOME=/usr/local/cuda
|
||||
LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64
|
||||
OUTPUT_FOLDER=/tensorrt_models
|
||||
echo "Generating the following TRT Models: ${YOLO_MODELS:="yolov4-tiny-288,yolov4-tiny-416,yolov7-tiny-416"}"
|
||||
|
||||
# Create output folder
|
||||
mkdir -p ${OUTPUT_FOLDER}
|
||||
|
||||
# Install packages
|
||||
pip install --upgrade pip && pip install onnx==1.9.0 protobuf==3.20.3
|
||||
|
||||
# Clone tensorrt_demos repo
|
||||
git clone --depth 1 https://github.com/yeahme49/tensorrt_demos.git /tensorrt_demos
|
||||
|
||||
# Build libyolo
|
||||
cd /tensorrt_demos/plugins && make all
|
||||
cp libyolo_layer.so ${OUTPUT_FOLDER}/libyolo_layer.so
|
||||
|
||||
# Download yolo weights
|
||||
cd /tensorrt_demos/yolo && ./download_yolo.sh
|
||||
|
||||
# Build trt engine
|
||||
cd /tensorrt_demos/yolo
|
||||
|
||||
for model in ${YOLO_MODELS//,/ }
|
||||
do
|
||||
python3 yolo_to_onnx.py -m ${model}
|
||||
python3 onnx_to_tensorrt.py -m ${model}
|
||||
cp /tensorrt_demos/yolo/${model}.trt ${OUTPUT_FOLDER}/${model}.trt;
|
||||
done
|
||||
@@ -4,8 +4,6 @@ title: Advanced Options
|
||||
sidebar_label: Advanced Options
|
||||
---
|
||||
|
||||
## Advanced configuration
|
||||
|
||||
### `logger`
|
||||
|
||||
Change the default log level for troubleshooting purposes.
|
||||
@@ -25,7 +23,7 @@ Examples of available modules are:
|
||||
|
||||
- `frigate.app`
|
||||
- `frigate.mqtt`
|
||||
- `frigate.edgetpu`
|
||||
- `frigate.object_detection`
|
||||
- `frigate.zeroconf`
|
||||
- `detector.<detector_name>`
|
||||
- `watchdog.<camera_name>`
|
||||
@@ -35,6 +33,13 @@ Examples of available modules are:
|
||||
|
||||
This section can be used to set environment variables for those unable to modify the environment of the container (ie. within HassOS)
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
environment_vars:
|
||||
VARIABLE_NAME: variable_value
|
||||
```
|
||||
|
||||
### `database`
|
||||
|
||||
Event and recording information is managed in a sqlite database at `/media/frigate/frigate.db`. If that database is deleted, recordings will be orphaned and will need to be cleaned up manually. They also won't show up in the Media Browser within Home Assistant.
|
||||
@@ -52,6 +57,30 @@ database:
|
||||
|
||||
If using a custom model, the width and height will need to be specified.
|
||||
|
||||
Custom models may also require different input tensor formats. The colorspace conversion supports RGB, BGR, or YUV frames to be sent to the object detector. The input tensor shape parameter is an enumeration to match what specified by the model.
|
||||
|
||||
| Tensor Dimension | Description |
|
||||
| :--------------: | -------------- |
|
||||
| N | Batch Size |
|
||||
| H | Model Height |
|
||||
| W | Model Width |
|
||||
| C | Color Channels |
|
||||
|
||||
| Available Input Tensor Shapes |
|
||||
| :---------------------------: |
|
||||
| "nhwc" |
|
||||
| "nchw" |
|
||||
|
||||
```yaml
|
||||
# Optional: model config
|
||||
model:
|
||||
path: /path/to/model
|
||||
width: 320
|
||||
height: 320
|
||||
input_tensor: "nhwc"
|
||||
input_pixel_format: "bgr"
|
||||
```
|
||||
|
||||
The labelmap can be customized to your needs. A common reason to do this is to combine multiple object types that are easily confused when you don't need to be as granular such as car/truck. By default, truck is renamed to car because they are often confused. You cannot add new object types, but you can change the names of existing objects in the model.
|
||||
|
||||
```yaml
|
||||
@@ -67,3 +96,15 @@ model:
|
||||
```
|
||||
|
||||
Note that if you rename objects in the labelmap, you will also need to update your `objects -> track` list as well.
|
||||
|
||||
## Custom ffmpeg build
|
||||
|
||||
Included with Frigate is a build of ffmpeg that works for the vast majority of users. However, there exists some hardware setups which have incompatibilities with the included build. In this case, a docker volume mapping can be used to overwrite the included ffmpeg build with an ffmpeg build that works for your specific hardware setup.
|
||||
|
||||
To do this:
|
||||
|
||||
1. Download your ffmpeg build and uncompress to a folder on the host (let's use `/home/appdata/frigate/custom-ffmpeg` for this example).
|
||||
2. Update your docker-compose or docker CLI to include `'/home/appdata/frigate/custom-ffmpeg':'/usr/lib/btbn-ffmpeg':'ro'` in the volume mappings.
|
||||
3. Restart frigate and the custom version will be used if the mapping was done correctly.
|
||||
|
||||
NOTE: The folder that is mapped from the host needs to be the folder that contains `/bin`. So if the full structure is `/home/appdata/frigate/custom-ffmpeg/bin/ffmpeg` then `/home/appdata/frigate/custom-ffmpeg` needs to be mapped to `/usr/lib/btbn-ffmpeg`.
|
||||
|
||||
@@ -11,4 +11,25 @@ Birdseye offers different modes to customize which cameras show under which circ
|
||||
|
||||
### Custom Birdseye Icon
|
||||
|
||||
A custom icon can be added to the birdseye background by provided a file `custom.png` inside of the Frigate `media` folder. The file must be a png with the icon as transparent, any non-transparent pixels will be white when displayed in the birdseye view.
|
||||
A custom icon can be added to the birdseye background by providing a 180x180 image named `custom.png` inside of the Frigate `media` folder. The file must be a png with the icon as transparent, any non-transparent pixels will be white when displayed in the birdseye view.
|
||||
|
||||
### Birdseye view override at camera level
|
||||
|
||||
If you want to include a camera in Birdseye view only for specific circumstances, or just don't include it at all, the Birdseye setting can be set at the camera level.
|
||||
|
||||
```yaml
|
||||
# Include all cameras by default in Birdseye view
|
||||
birdseye:
|
||||
enabled: True
|
||||
mode: continuous
|
||||
|
||||
cameras:
|
||||
front:
|
||||
# Only include the "front" camera in Birdseye view when objects are detected
|
||||
birdseye:
|
||||
mode: objects
|
||||
back:
|
||||
# Exclude the "back" camera from Birdseye view
|
||||
birdseye:
|
||||
enabled: False
|
||||
```
|
||||
|
||||
@@ -3,83 +3,113 @@ id: camera_specific
|
||||
title: Camera Specific Configurations
|
||||
---
|
||||
|
||||
### MJPEG Cameras
|
||||
:::note
|
||||
|
||||
The input and output parameters need to be adjusted for MJPEG cameras
|
||||
This page makes use of presets of FFmpeg args. For more information on presets, see the [FFmpeg Presets](/configuration/ffmpeg_presets) page.
|
||||
|
||||
:::
|
||||
|
||||
## MJPEG Cameras
|
||||
|
||||
Note that mjpeg cameras require encoding the video into h264 for recording, and restream roles. This will use significantly more CPU than if the cameras supported h264 feeds directly. It is recommended to use the restream role to create an h264 restream and then use that as the source for ffmpeg.
|
||||
|
||||
```yaml
|
||||
input_args: -avoid_negative_ts make_zero -fflags nobuffer -flags low_delay -strict experimental -fflags +genpts+discardcorrupt -use_wallclock_as_timestamps 1
|
||||
mjpeg_cam:
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: rtsp://localhost:8554/mjpeg_cam
|
||||
roles:
|
||||
- detect
|
||||
- record
|
||||
- path: {your_mjpeg_stream_url}
|
||||
roles:
|
||||
- restream
|
||||
restream:
|
||||
enabled: true
|
||||
video_encoding: h264
|
||||
```
|
||||
|
||||
Note that mjpeg cameras require encoding the video into h264 for recording, and rtmp roles. This will use significantly more CPU than if the cameras supported h264 feeds directly.
|
||||
|
||||
```yaml
|
||||
output_args:
|
||||
record: -f segment -segment_time 10 -segment_format mp4 -reset_timestamps 1 -strftime 1 -c:v libx264 -an
|
||||
rtmp: -c:v libx264 -an -f flv
|
||||
```
|
||||
|
||||
### JPEG Stream Cameras
|
||||
## JPEG Stream Cameras
|
||||
|
||||
Cameras using a live changing jpeg image will need input parameters as below
|
||||
|
||||
```yaml
|
||||
input_args:
|
||||
- -r
|
||||
- 5 # << enter FPS here
|
||||
- -stream_loop
|
||||
- -1
|
||||
- -f
|
||||
- image2
|
||||
- -avoid_negative_ts
|
||||
- make_zero
|
||||
- -fflags
|
||||
- nobuffer
|
||||
- -flags
|
||||
- low_delay
|
||||
- -strict
|
||||
- experimental
|
||||
- -fflags
|
||||
- +genpts+discardcorrupt
|
||||
- -use_wallclock_as_timestamps
|
||||
- 1
|
||||
input_args: preset-http-jpeg-generic
|
||||
```
|
||||
|
||||
Outputting the stream will have the same args and caveats as per [MJPEG Cameras](#mjpeg-cameras)
|
||||
|
||||
### RTMP Cameras
|
||||
## RTMP Cameras
|
||||
|
||||
The input parameters need to be adjusted for RTMP cameras
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
input_args: -avoid_negative_ts make_zero -fflags nobuffer -flags low_delay -strict experimental -fflags +genpts+discardcorrupt -rw_timeout 5000000 -use_wallclock_as_timestamps 1 -f live_flv
|
||||
input_args: preset-rtmp-generic
|
||||
```
|
||||
|
||||
### Reolink 410/520 (possibly others)
|
||||
## UDP Only Cameras
|
||||
|
||||
According to [this discussion](https://github.com/blakeblackshear/frigate/issues/1713#issuecomment-932976305), the http video streams seem to be the most reliable for Reolink.
|
||||
If your cameras do not support TCP connections for RTSP, you can use UDP.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
input_args: preset-rtsp-udp
|
||||
```
|
||||
|
||||
## Model/vendor specific setup
|
||||
|
||||
### Annke C800
|
||||
|
||||
This camera is H.265 only. To be able to play clips on some devices (like MacOs or iPhone) the H.265 stream has to be repackaged and the audio stream has to be converted to aac. Unfortunately direct playback of in the browser is not working (yet), but the downloaded clip can be played locally.
|
||||
|
||||
```yaml
|
||||
cameras:
|
||||
annkec800: # <------ Name the camera
|
||||
ffmpeg:
|
||||
output_args:
|
||||
record: -f segment -segment_time 10 -segment_format mp4 -reset_timestamps 1 -strftime 1 -c:v copy -tag:v hvc1 -bsf:v hevc_mp4toannexb -c:a aac
|
||||
rtmp: -c:v copy -c:a aac -f flv
|
||||
|
||||
inputs:
|
||||
- path: rtsp://user:password@camera-ip:554/H264/ch1/main/av_stream # <----- Update for your camera
|
||||
roles:
|
||||
- detect
|
||||
- record
|
||||
- rtmp
|
||||
rtmp:
|
||||
enabled: False # <-- RTMP should be disabled if your stream is not H264
|
||||
detect:
|
||||
width: # <---- update for your camera's resolution
|
||||
height: # <---- update for your camera's resolution
|
||||
```
|
||||
|
||||
### Blue Iris RTSP Cameras
|
||||
|
||||
You will need to remove `nobuffer` flag for Blue Iris RTSP cameras
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
input_args: preset-rtsp-blue-iris
|
||||
```
|
||||
|
||||
### Reolink Cameras
|
||||
|
||||
Reolink has older cameras (ex: 410 & 520) as well as newer camera (ex: 520a & 511wa) which support different subsets of options. In both cases using the http stream is recommended.
|
||||
Frigate works much better with newer reolink cameras that are setup with the below options:
|
||||
|
||||
If available, recommended settings are:
|
||||
|
||||
- `On, fluency first` this sets the camera to CBR (constant bit rate)
|
||||
- `Interframe Space 1x` this sets the iframe interval to the same as the frame rate
|
||||
|
||||
According to [this discussion](https://github.com/blakeblackshear/frigate/issues/3235#issuecomment-1135876973), the http video streams seem to be the most reliable for Reolink.
|
||||
|
||||
```yaml
|
||||
cameras:
|
||||
reolink:
|
||||
ffmpeg:
|
||||
hwaccel_args:
|
||||
input_args:
|
||||
- -avoid_negative_ts
|
||||
- make_zero
|
||||
- -fflags
|
||||
- nobuffer+genpts+discardcorrupt
|
||||
- -flags
|
||||
- low_delay
|
||||
- -strict
|
||||
- experimental
|
||||
- -analyzeduration
|
||||
- 1000M
|
||||
- -probesize
|
||||
- 1000M
|
||||
- -rw_timeout
|
||||
- "5000000"
|
||||
input_args: preset-http-reolink
|
||||
inputs:
|
||||
- path: http://reolink_ip/flv?port=1935&app=bcs&stream=channel0_main.bcs&user=username&password=password
|
||||
roles:
|
||||
@@ -94,22 +124,13 @@ cameras:
|
||||
fps: 7
|
||||
```
|
||||
|
||||

|
||||
### Unifi Protect Cameras
|
||||
|
||||
### Blue Iris RTSP Cameras
|
||||
|
||||
You will need to remove `nobuffer` flag for Blue Iris RTSP cameras
|
||||
In the Unifi 2.0 update Unifi Protect Cameras had a change in audio sample rate which causes issues for ffmpeg. The input rate needs to be set for record and rtmp.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
input_args: -avoid_negative_ts make_zero -flags low_delay -strict experimental -fflags +genpts+discardcorrupt -rtsp_transport tcp -timeout 5000000 -use_wallclock_as_timestamps 1
|
||||
```
|
||||
|
||||
### UDP Only Cameras
|
||||
|
||||
If your cameras do not support TCP connections for RTSP, you can use UDP.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
input_args: -avoid_negative_ts make_zero -fflags +genpts+discardcorrupt -rtsp_transport udp -timeout 5000000 -use_wallclock_as_timestamps 1
|
||||
output_args:
|
||||
record: preset-record-ubiquiti
|
||||
rtmp: preset-rtmp-ubiquiti
|
||||
```
|
||||
|
||||
@@ -7,19 +7,23 @@ title: Cameras
|
||||
|
||||
Several inputs can be configured for each camera and the role of each input can be mixed and matched based on your needs. This allows you to use a lower resolution stream for object detection, but create recordings from a higher resolution stream, or vice versa.
|
||||
|
||||
A camera is enabled by default but can be temporarily disabled by using `enabled: False`. Existing events and recordings can still be accessed. Live streams, recording and detecting are not working. Camera specific configurations will be used.
|
||||
|
||||
Each role can only be assigned to one input per camera. The options for roles are as follows:
|
||||
|
||||
| Role | Description |
|
||||
| -------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `detect` | Main feed for object detection |
|
||||
| `record` | Saves segments of the video feed based on configuration settings. [docs](/configuration/record) |
|
||||
| `rtmp` | Broadcast as an RTMP feed for other services to consume. [docs](/configuration/rtmp) |
|
||||
| Role | Description |
|
||||
| ---------- | ---------------------------------------------------------------------------------------- |
|
||||
| `detect` | Main feed for object detection |
|
||||
| `record` | Saves segments of the video feed based on configuration settings. [docs](record.md) |
|
||||
| `restream` | Broadcast as RTSP feed and use the full res stream for live view. [docs](restream.md) |
|
||||
| `rtmp` | Deprecated: Broadcast as an RTMP feed for other services to consume. [docs](restream.md) |
|
||||
|
||||
```yaml
|
||||
mqtt:
|
||||
host: mqtt.server.com
|
||||
cameras:
|
||||
back:
|
||||
enabled: True
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: rtsp://viewer:{FRIGATE_RTSP_PASSWORD}@10.0.10.10:554/cam/realmonitor?channel=1&subtype=2
|
||||
@@ -43,3 +47,5 @@ cameras:
|
||||
front: ...
|
||||
side: ...
|
||||
```
|
||||
|
||||
For camera model specific settings check the [camera specific](camera_specific.md) infos.
|
||||
|
||||
@@ -3,11 +3,37 @@ id: detectors
|
||||
title: Detectors
|
||||
---
|
||||
|
||||
By default, Frigate will use a single CPU detector. If you have a Coral, you will need to configure your detector devices in the config file. When using multiple detectors, they run in dedicated processes, but pull from a common queue of requested detections across all cameras.
|
||||
Frigate provides the following builtin detector types: `cpu`, `edgetpu`, `openvino`, and `tensorrt`. By default, Frigate will use a single CPU detector. Other detectors may require additional configuration as described below. When using multiple detectors they will run in dedicated processes, but pull from a common queue of detection requests from across all cameras.
|
||||
|
||||
Frigate supports `edgetpu` and `cpu` as detector types. The device value should be specified according to the [Documentation for the TensorFlow Lite Python API](https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api).
|
||||
## CPU Detector (not recommended)
|
||||
|
||||
**Note**: There is no support for Nvidia GPUs to perform object detection with tensorflow. It can be used for ffmpeg decoding, but not object detection.
|
||||
The CPU detector type runs a TensorFlow Lite model utilizing the CPU without hardware acceleration. It is recommended to use a hardware accelerated detector type instead for better performance. To configure a CPU based detector, set the `"type"` attribute to `"cpu"`.
|
||||
|
||||
The number of threads used by the interpreter can be specified using the `"num_threads"` attribute, and defaults to `3.`
|
||||
|
||||
A TensorFlow Lite model is provided in the container at `/cpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with `model.path`.
|
||||
|
||||
```yaml
|
||||
detectors:
|
||||
cpu1:
|
||||
type: cpu
|
||||
num_threads: 3
|
||||
model:
|
||||
path: "/custom_model.tflite"
|
||||
cpu2:
|
||||
type: cpu
|
||||
num_threads: 3
|
||||
```
|
||||
|
||||
When using CPU detectors, you can add one CPU detector per camera. Adding more detectors than the number of cameras should not improve performance.
|
||||
|
||||
## Edge-TPU Detector
|
||||
|
||||
The EdgeTPU detector type runs a TensorFlow Lite model utilizing the Google Coral delegate for hardware acceleration. To configure an EdgeTPU detector, set the `"type"` attribute to `"edgetpu"`.
|
||||
|
||||
The EdgeTPU device can be specified using the `"device"` attribute according to the [Documentation for the TensorFlow Lite Python API](https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api). If not set, the delegate will use the first device it finds.
|
||||
|
||||
A TensorFlow Lite model is provided in the container at `/edgetpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with `model.path`.
|
||||
|
||||
### Single USB Coral
|
||||
|
||||
@@ -16,6 +42,8 @@ detectors:
|
||||
coral:
|
||||
type: edgetpu
|
||||
device: usb
|
||||
model:
|
||||
path: "/custom_model.tflite"
|
||||
```
|
||||
|
||||
### Multiple USB Corals
|
||||
@@ -31,6 +59,7 @@ detectors:
|
||||
```
|
||||
|
||||
### Native Coral (Dev Board)
|
||||
|
||||
_warning: may have [compatibility issues](https://github.com/blakeblackshear/frigate/issues/1706) after `v0.9.x`_
|
||||
|
||||
```yaml
|
||||
@@ -64,16 +93,143 @@ detectors:
|
||||
device: pci
|
||||
```
|
||||
|
||||
### CPU Detectors (not recommended)
|
||||
## OpenVINO Detector
|
||||
|
||||
The OpenVINO detector type runs an OpenVINO IR model on Intel CPU, GPU and VPU hardware. To configure an OpenVINO detector, set the `"type"` attribute to `"openvino"`.
|
||||
|
||||
The OpenVINO device to be used is specified using the `"device"` attribute according to the naming conventions in the [Device Documentation](https://docs.openvino.ai/latest/openvino_docs_OV_UG_Working_with_devices.html). Other supported devices could be `AUTO`, `CPU`, `GPU`, `MYRIAD`, etc. If not specified, the default OpenVINO device will be selected by the `AUTO` plugin.
|
||||
|
||||
OpenVINO is supported on 6th Gen Intel platforms (Skylake) and newer. A supported Intel platform is required to use the `GPU` device with OpenVINO. The `MYRIAD` device may be run on any platform, including Arm devices. For detailed system requirements, see [OpenVINO System Requirements](https://www.intel.com/content/www/us/en/developer/tools/openvino-toolkit/system-requirements.html)
|
||||
|
||||
An OpenVINO model is provided in the container at `/openvino-model/ssdlite_mobilenet_v2.xml` and is used by this detector type by default. The model comes from Intel's Open Model Zoo [SSDLite MobileNet V2](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/public/ssdlite_mobilenet_v2) and is converted to an FP16 precision IR model. Use the model configuration shown below when using the OpenVINO detector.
|
||||
|
||||
```yaml
|
||||
detectors:
|
||||
cpu1:
|
||||
type: cpu
|
||||
num_threads: 3
|
||||
cpu2:
|
||||
type: cpu
|
||||
num_threads: 3
|
||||
ov:
|
||||
type: openvino
|
||||
device: AUTO
|
||||
model:
|
||||
path: /openvino-model/ssdlite_mobilenet_v2.xml
|
||||
|
||||
model:
|
||||
width: 300
|
||||
height: 300
|
||||
input_tensor: nhwc
|
||||
input_pixel_format: bgr
|
||||
labelmap_path: /openvino-model/coco_91cl_bkgr.txt
|
||||
```
|
||||
|
||||
When using CPU detectors, you can add a CPU detector per camera. Adding more detectors than the number of cameras should not improve performance.
|
||||
### Intel NCS2 VPU and Myriad X Setup
|
||||
|
||||
Intel produces a neural net inference accelleration chip called Myriad X. This chip was sold in their Neural Compute Stick 2 (NCS2) which has been discontinued. If intending to use the MYRIAD device for accelleration, additional setup is required to pass through the USB device. The host needs a udev rule installed to handle the NCS2 device.
|
||||
|
||||
```bash
|
||||
sudo usermod -a -G users "$(whoami)"
|
||||
cat <<EOF > 97-myriad-usbboot.rules
|
||||
SUBSYSTEM=="usb", ATTRS{idProduct}=="2485", ATTRS{idVendor}=="03e7", GROUP="users", MODE="0666", ENV{ID_MM_DEVICE_IGNORE}="1"
|
||||
SUBSYSTEM=="usb", ATTRS{idProduct}=="f63b", ATTRS{idVendor}=="03e7", GROUP="users", MODE="0666", ENV{ID_MM_DEVICE_IGNORE}="1"
|
||||
EOF
|
||||
sudo cp 97-myriad-usbboot.rules /etc/udev/rules.d/
|
||||
sudo udevadm control --reload-rules
|
||||
sudo udevadm trigger
|
||||
```
|
||||
|
||||
Additionally, the Frigate docker container needs to run with the following configuration:
|
||||
|
||||
```bash
|
||||
--device-cgroup-rule='c 189:\* rmw' -v /dev/bus/usb:/dev/bus/usb
|
||||
```
|
||||
|
||||
or in your compose file:
|
||||
|
||||
```yml
|
||||
device_cgroup_rules:
|
||||
- "c 189:* rmw"
|
||||
volumes:
|
||||
- /dev/bus/usb:/dev/bus/usb
|
||||
```
|
||||
|
||||
## NVidia TensorRT Detector
|
||||
|
||||
NVidia GPUs may be used for object detection using the TensorRT libraries. Due to the size of the additional libraries, this detector is only provided in images with the `-tensorrt` tag suffix. This detector is designed to work with Yolo models for object detection.
|
||||
|
||||
### Minimum Hardware Support
|
||||
|
||||
The TensorRT detector uses the 11.x series of CUDA libraries which have minor version compatibility. The minimum driver version on the host system must be `>=450.80.02`. Also the GPU must support a Compute Capability of `5.0` or greater. This generally correlates to a Maxwell-era GPU or newer, check the NVIDIA GPU Compute Capability table linked below.
|
||||
|
||||
> **TODO:** NVidia claims support on compute 3.5 and 3.7, but marks it as deprecated. This would have some, but not all, Kepler GPUs as possibly working. This needs testing before making any claims of support.
|
||||
|
||||
To use the TensorRT detector, make sure your host system has the [nvidia-container-runtime](https://docs.docker.com/config/containers/resource_constraints/#access-an-nvidia-gpu) installed to pass through the GPU to the container and the host system has a compatible driver installed for your GPU.
|
||||
|
||||
There are improved capabilities in newer GPU architectures that TensorRT can benefit from, such as INT8 operations and Tensor cores. The features compatible with your hardware will be optimized when the model is converted to a trt file. Currently the script provided for generating the model provides a switch to enable/disable FP16 operations. If you wish to use newer features such as INT8 optimization, more work is required.
|
||||
|
||||
#### Compatibility References:
|
||||
|
||||
[NVIDIA TensorRT Support Matrix](https://docs.nvidia.com/deeplearning/tensorrt/archives/tensorrt-841/support-matrix/index.html)
|
||||
|
||||
[NVIDIA CUDA Compatibility](https://docs.nvidia.com/deploy/cuda-compatibility/index.html)
|
||||
|
||||
[NVIDIA GPU Compute Capability](https://developer.nvidia.com/cuda-gpus)
|
||||
|
||||
### Generate Models
|
||||
|
||||
The model used for TensorRT must be preprocessed on the same hardware platform that they will run on. This means that each user must run additional setup to generate a model file for the TensorRT library. A script is provided that will build several common models.
|
||||
|
||||
To generate model files, create a new folder to save the models, download the script, and launch a docker container that will run the script.
|
||||
|
||||
```bash
|
||||
mkdir trt-models
|
||||
wget https://raw.githubusercontent.com/blakeblackshear/frigate/docker/tensorrt_models.sh
|
||||
chmod +x tensorrt_models.sh
|
||||
docker run --gpus=all --rm -it -v `pwd`/trt-models:/tensorrt_models -v `pwd`/tensorrt_models.sh:/tensorrt_models.sh nvcr.io/nvidia/tensorrt:22.07-py3 /tensorrt_models.sh
|
||||
```
|
||||
|
||||
The `trt-models` folder can then be mapped into your frigate container as `trt-models` and the models referenced from the config.
|
||||
|
||||
If your GPU does not support FP16 operations, you can pass the environment variable `-e USE_FP16=False` to the `docker run` command to disable it.
|
||||
|
||||
Specific models can be selected by passing an environment variable to the `docker run` command. Use the form `-e YOLO_MODELS=yolov4-416,yolov4-tiny-416` to select one or more model names. The models available are shown below.
|
||||
|
||||
```
|
||||
yolov3-288
|
||||
yolov3-416
|
||||
yolov3-608
|
||||
yolov3-spp-288
|
||||
yolov3-spp-416
|
||||
yolov3-spp-608
|
||||
yolov3-tiny-288
|
||||
yolov3-tiny-416
|
||||
yolov4-288
|
||||
yolov4-416
|
||||
yolov4-608
|
||||
yolov4-csp-256
|
||||
yolov4-csp-512
|
||||
yolov4-p5-448
|
||||
yolov4-p5-896
|
||||
yolov4-tiny-288
|
||||
yolov4-tiny-416
|
||||
yolov4x-mish-320
|
||||
yolov4x-mish-640
|
||||
yolov7-tiny-288
|
||||
yolov7-tiny-416
|
||||
```
|
||||
|
||||
### Configuration Parameters
|
||||
|
||||
The TensorRT detector can be selected by specifying `tensorrt` as the model type. The GPU will need to be passed through to the docker container using the same methods described in the [Hardware Acceleration](hardware_acceleration.md#nvidia-gpu) section. If you pass through multiple GPUs, you can select which GPU is used for a detector with the `device` configuration parameter. The `device` parameter is an integer value of the GPU index, as shown by `nvidia-smi` within the container.
|
||||
|
||||
The TensorRT detector uses `.trt` model files that are located in `/trt-models/` by default. These model file path and dimensions used will depend on which model you have generated.
|
||||
|
||||
```yaml
|
||||
detectors:
|
||||
tensorrt:
|
||||
type: tensorrt
|
||||
device: 0 #This is the default, select the first GPU
|
||||
|
||||
model:
|
||||
path: /trt-models/yolov7-tiny-416.trt
|
||||
input_tensor: nchw
|
||||
input_pixel_format: rgb
|
||||
width: 416
|
||||
height: 416
|
||||
```
|
||||
|
||||
75
docs/docs/configuration/ffmpeg_presets.md
Normal file
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: ffmpeg_presets
|
||||
title: FFmpeg presets
|
||||
---
|
||||
|
||||
Some presets of FFmpeg args are provided by default to make the configuration easier. All presets can be seen in [this file](https://github.com/blakeblackshear/frigate/blob/master/frigate/ffmpeg_presets.py).
|
||||
|
||||
### Hwaccel Presets
|
||||
|
||||
It is highly recommended to use hwaccel presets in the config. These presets not only replace the longer args, but they also give frigate hints of what hardware is available and allows frigate to make other optimizations using the GPU such as when encoding the birdseye restream or when scaling a stream that has a size different than the native stream size.
|
||||
|
||||
See [the hwaccel docs](/configuration/hardware_acceleration.md) for more info on how to setup hwaccel for your GPU / iGPU.
|
||||
|
||||
| Preset | Usage | Other Notes |
|
||||
| --------------------- | ---------------------------- | ----------------------------------------------------- |
|
||||
| preset-rpi-32-h264 | 32 bit Rpi with h264 stream | |
|
||||
| preset-rpi-64-h264 | 64 bit Rpi with h264 stream | |
|
||||
| preset-vaapi | Intel & AMD VAAPI | Check hwaccel docs to ensure correct driver is chosen |
|
||||
| preset-intel-qsv-h264 | Intel QSV with h264 stream | If issues occur recommend using vaapi preset instead |
|
||||
| preset-intel-qsv-h265 | Intel QSV with h265 stream | If issues occur recommend using vaapi preset instead |
|
||||
| preset-nvidia-h264 | Nvidia GPU with h264 stream | |
|
||||
| preset-nvidia-h265 | Nvidia GPU with h265 stream | |
|
||||
| preset-nvidia-mjpeg | Nvidia GPU with mjpeg stream | Recommend restreaming mjpeg and using nvidia-h264 |
|
||||
|
||||
### Input Args Presets
|
||||
|
||||
Input args presets help make the config more readable and handle use cases for different types of streams to ensure maximum compatibility.
|
||||
|
||||
See [the camera specific docs](/configuration/camera_specific.md) for more info on non-standard cameras and recommendations for using them in frigate.
|
||||
|
||||
| Preset | Usage | Other Notes |
|
||||
| ------------------------- | ----------------------- | --------------------------------------------------- |
|
||||
| preset-http-jpeg-generic | HTTP Live Jpeg | Recommend restreaming live jpeg instead |
|
||||
| preset-http-mjpeg-generic | HTTP Mjpeg Stream | Recommend restreaming mjpeg stream instead |
|
||||
| preset-http-reolink | Reolink HTTP-FLV Stream | Only for reolink http, not when restreaming as rtsp |
|
||||
| preset-rtmp-generic | RTMP Stream | |
|
||||
| preset-rtsp-generic | RTSP Stream | This is the default when nothing is specified |
|
||||
| preset-rtsp-udp | RTSP Stream via UDP | Use when camera is UDP only |
|
||||
| preset-rtsp-blue-iris | Blue Iris RTSP Stream | Use when consuming a stream from Blue Iris |
|
||||
|
||||
:::caution
|
||||
|
||||
It is important to be mindful of input args when using restream because you can have a mix of protocols. `http` and `rtmp` presets cannot be used with `rtsp` streams. For example, when using a reolink cam with the rtsp restream as a source for record the preset-http-reolink will cause a crash. In this case presets will need to be set at the stream level. See the example below.
|
||||
|
||||
:::
|
||||
|
||||
```yaml
|
||||
cameras:
|
||||
reolink_cam:
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: http://192.168.0.139/flv?port=1935&app=bcs&stream=channel0_ext.bcs&user=admin&password={FRIGATE_CAM_PASSWORD}
|
||||
input_args: preset-http-reolink
|
||||
roles:
|
||||
- detect
|
||||
- path: rtsp://192.168.0.10:8554/garage
|
||||
input_args: preset-rtsp-generic
|
||||
roles:
|
||||
- record
|
||||
- path: http://192.168.0.139/flv?port=1935&app=bcs&stream=channel0_main.bcs&user=admin&password={FRIGATE_CAM_PASSWORD}
|
||||
roles:
|
||||
- restream
|
||||
```
|
||||
|
||||
### Output Args Presets
|
||||
|
||||
Output args presets help make the config more readable and handle use cases for different types of streams to ensure consistent recordings.
|
||||
|
||||
| Preset | Usage | Other Notes |
|
||||
| --------------------------- | --------------------------------- | --------------------------------------------- |
|
||||
| preset-record-generic | Record WITHOUT audio | This is the default when nothing is specified |
|
||||
| preset-record-generic-audio | Record WITH audio | Use this to enable audio in recordings |
|
||||
| preset-record-mjpeg | Record an mjpeg stream | Recommend restreaming mjpeg stream instead |
|
||||
| preset-record-jpeg | Record live jpeg | Recommend restreaming live jpeg instead |
|
||||
| preset-record-ubiquiti | Record ubiquiti stream with audio | Recordings with ubiquiti non-standard audio |
|
||||
@@ -7,27 +7,33 @@ It is recommended to update your configuration to enable hardware accelerated de
|
||||
|
||||
### Raspberry Pi 3/4
|
||||
|
||||
:::caution
|
||||
|
||||
There is currently a bug in ffmpeg that causes hwaccel to not work for the RPi kernel 5.15.61 and above. For more information see https://github.com/blakeblackshear/frigate/issues/3780
|
||||
|
||||
:::
|
||||
|
||||
Ensure you increase the allocated RAM for your GPU to at least 128 (raspi-config > Performance Options > GPU Memory).
|
||||
**NOTICE**: If you are using the addon, you may need to turn off `Protection mode` for hardware acceleration.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: -c:v h264_v4l2m2m
|
||||
hwaccel_args: preset-rpi-64-h264
|
||||
```
|
||||
|
||||
### Intel-based CPUs (<10th Generation) via Quicksync
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: -hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format yuv420p
|
||||
hwaccel_args: preset-vaapi
|
||||
```
|
||||
**NOTICE**: With some of the processors, like the J4125, the default driver `iHD` doesn't seem to work correctly for hardware acceleration. You may need to change the driver to `i965` by adding the following environment variable `LIBVA_DRIVER_NAME_JELLYFIN=i965` to your docker-compose file.
|
||||
**NOTICE**: With some of the processors, like the J4125, the default driver `iHD` doesn't seem to work correctly for hardware acceleration. You may need to change the driver to `i965` by adding the following environment variable `LIBVA_DRIVER_NAME=i965` to your docker-compose file or [in the frigate.yml for HA OS users](advanced.md#environment_vars).
|
||||
|
||||
### Intel-based CPUs (>=10th Generation) via Quicksync
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: -c:v h264_qsv
|
||||
hwaccel_args: preset-intel-qsv-h264
|
||||
```
|
||||
|
||||
### AMD/ATI GPUs (Radeon HD 2000 and newer GPUs) via libva-mesa-driver
|
||||
@@ -36,27 +42,30 @@ ffmpeg:
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: -hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -hwaccel_output_format yuv420p
|
||||
hwaccel_args: preset-vaapi
|
||||
```
|
||||
|
||||
### NVIDIA GPU
|
||||
|
||||
[Supported Nvidia GPUs for Decoding](https://developer.nvidia.com/video-encode-and-decode-gpu-support-matrix-new)
|
||||
|
||||
These instructions are based on the [jellyfin documentation](https://jellyfin.org/docs/general/administration/hardware-acceleration.html#nvidia-hardware-acceleration-on-docker-linux)
|
||||
|
||||
Add `--gpus all` to your docker run command or update your compose file.
|
||||
|
||||
If you have multiple Nvidia graphic card, you can add them with their ids obtained via `nvidia-smi` command
|
||||
```yaml
|
||||
services:
|
||||
frigate:
|
||||
...
|
||||
image: blakeblackshear/frigate:stable
|
||||
deploy: # <------------- Add this section
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities: [gpu]
|
||||
deploy: # <------------- Add this section
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
device_ids: ['0'] # this is only needed when using multiple GPUs
|
||||
count: 1 # number of GPUs
|
||||
capabilities: [gpu]
|
||||
```
|
||||
|
||||
The decoder you need to pass in the `hwaccel_args` will depend on the input video.
|
||||
@@ -76,17 +85,23 @@ A list of supported codecs (you can use `ffmpeg -decoders | grep cuvid` in the c
|
||||
V..... vp9_cuvid Nvidia CUVID VP9 decoder (codec vp9)
|
||||
```
|
||||
|
||||
For example, for H264 video, you'll select `h264_cuvid`.
|
||||
For example, for H264 video, you'll select `preset-nvidia-h264`.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: -c:v h264_cuvid
|
||||
hwaccel_args: preset-nvidia-h264
|
||||
```
|
||||
|
||||
If everything is working correctly, you should see a significant improvement in performance.
|
||||
Verify that hardware decoding is working by running `nvidia-smi`, which should show the ffmpeg
|
||||
processes:
|
||||
|
||||
:::note
|
||||
|
||||
nvidia-smi may not show ffmpeg processes when run inside the container [due to docker limitations](https://github.com/NVIDIA/nvidia-docker/issues/179#issuecomment-645579458)
|
||||
|
||||
:::
|
||||
|
||||
```
|
||||
+-----------------------------------------------------------------------------+
|
||||
| NVIDIA-SMI 455.38 Driver Version: 455.38 CUDA Version: 11.1 |
|
||||
|
||||
@@ -7,7 +7,7 @@ For Home Assistant Addon installations, the config file needs to be in the root
|
||||
|
||||
For all other installation types, the config file should be mapped to `/config/config.yml` inside the container.
|
||||
|
||||
It is recommended to start with a minimal configuration and add to it as described in [this guide](/guides/getting_started):
|
||||
It is recommended to start with a minimal configuration and add to it as described in [this guide](../guides/getting_started.md):
|
||||
|
||||
```yaml
|
||||
mqtt:
|
||||
@@ -19,12 +19,16 @@ cameras:
|
||||
- path: rtsp://viewer:{FRIGATE_RTSP_PASSWORD}@10.0.10.10:554/cam/realmonitor?channel=1&subtype=2
|
||||
roles:
|
||||
- detect
|
||||
- rtmp
|
||||
- restream
|
||||
detect:
|
||||
width: 1280
|
||||
height: 720
|
||||
```
|
||||
|
||||
### VSCode Configuration Schema
|
||||
|
||||
VSCode (and VSCode addon) supports the JSON schemas which will automatically validate the config. This can be added by adding `# yaml-language-server: $schema=http://frigate_host:5000/api/config/schema.json` to the top of the config file. `frigate_host` being the IP address of frigate or `ccab4aaf-frigate` if running in the addon.
|
||||
|
||||
### Full configuration reference:
|
||||
|
||||
:::caution
|
||||
@@ -35,6 +39,8 @@ It is not recommended to copy this full configuration file. Only specify values
|
||||
|
||||
```yaml
|
||||
mqtt:
|
||||
# Optional: Enable mqtt server (default: shown below)
|
||||
enabled: True
|
||||
# Required: host name
|
||||
host: mqtt.server.com
|
||||
# Optional: port (default: shown below)
|
||||
@@ -46,6 +52,8 @@ mqtt:
|
||||
# NOTE: must be unique if you are running multiple instances
|
||||
client_id: frigate
|
||||
# Optional: user
|
||||
# NOTE: MQTT user can be specified with an environment variables that must begin with 'FRIGATE_'.
|
||||
# e.g. user: '{FRIGATE_MQTT_USER}'
|
||||
user: mqtt_user
|
||||
# Optional: password
|
||||
# NOTE: MQTT password can be specified with an environment variables that must begin with 'FRIGATE_'.
|
||||
@@ -68,15 +76,13 @@ mqtt:
|
||||
# Optional: Detectors configuration. Defaults to a single CPU detector
|
||||
detectors:
|
||||
# Required: name of the detector
|
||||
coral:
|
||||
detector_name:
|
||||
# Required: type of the detector
|
||||
# Valid values are 'edgetpu' (requires device property below) and 'cpu'.
|
||||
type: edgetpu
|
||||
# Optional: device name as defined here: https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api
|
||||
device: usb
|
||||
# Optional: num_threads value passed to the tflite.Interpreter (default: shown below)
|
||||
# This value is only used for CPU types
|
||||
num_threads: 3
|
||||
# Frigate provided types include 'cpu', 'edgetpu', and 'openvino' (default: shown below)
|
||||
# Additional detector types can also be plugged in.
|
||||
# Detectors may require additional configuration.
|
||||
# Refer to the Detectors configuration page for more information.
|
||||
type: cpu
|
||||
|
||||
# Optional: Database configuration
|
||||
database:
|
||||
@@ -93,6 +99,12 @@ model:
|
||||
width: 320
|
||||
# Required: Object detection model input height (default: shown below)
|
||||
height: 320
|
||||
# Optional: Object detection model input colorspace
|
||||
# Valid values are rgb, bgr, or yuv. (default: shown below)
|
||||
input_pixel_format: rgb
|
||||
# Optional: Object detection model input tensor format
|
||||
# Valid values are nhwc or nchw (default: shown below)
|
||||
input_tensor: nhwc
|
||||
# Optional: Label name modifications. These are merged into the standard labelmap.
|
||||
labelmap:
|
||||
2: vehicle
|
||||
@@ -128,6 +140,7 @@ birdseye:
|
||||
mode: objects
|
||||
|
||||
# Optional: ffmpeg configuration
|
||||
# More information about presets at https://docs.frigate.video/configuration/ffmpeg_presets
|
||||
ffmpeg:
|
||||
# Optional: global ffmpeg args (default: shown below)
|
||||
global_args: -hide_banner -loglevel warning
|
||||
@@ -135,15 +148,15 @@ ffmpeg:
|
||||
# NOTE: See hardware acceleration docs for your specific device
|
||||
hwaccel_args: []
|
||||
# Optional: global input args (default: shown below)
|
||||
input_args: -avoid_negative_ts make_zero -fflags +genpts+discardcorrupt -rtsp_transport tcp -timeout 5000000 -use_wallclock_as_timestamps 1
|
||||
input_args: preset-rtsp-generic
|
||||
# Optional: global output args
|
||||
output_args:
|
||||
# Optional: output args for detect streams (default: shown below)
|
||||
detect: -f rawvideo -pix_fmt yuv420p
|
||||
# Optional: output args for record streams (default: shown below)
|
||||
record: -f segment -segment_time 10 -segment_format mp4 -reset_timestamps 1 -strftime 1 -c copy -an
|
||||
record: preset-record-generic
|
||||
# Optional: output args for rtmp streams (default: shown below)
|
||||
rtmp: -c copy -f flv
|
||||
rtmp: preset-rtmp-generic
|
||||
|
||||
# Optional: Detect configuration
|
||||
# NOTE: Can be overridden at the camera level
|
||||
@@ -311,6 +324,8 @@ snapshots:
|
||||
# Optional: Enable writing jpg snapshot to /media/frigate/clips (default: shown below)
|
||||
# This value can be set via MQTT and will be updated in startup based on retained value
|
||||
enabled: False
|
||||
# Optional: save a clean PNG copy of the snapshot image (default: shown below)
|
||||
clean_copy: True
|
||||
# Optional: print a timestamp on the snapshots (default: shown below)
|
||||
timestamp: False
|
||||
# Optional: draw bounding box on the snapshots (default: shown below)
|
||||
@@ -330,21 +345,35 @@ snapshots:
|
||||
person: 15
|
||||
|
||||
# Optional: RTMP configuration
|
||||
# NOTE: RTMP is deprecated in favor of restream
|
||||
# NOTE: Can be overridden at the camera level
|
||||
rtmp:
|
||||
# Optional: Enable the RTMP stream (default: True)
|
||||
enabled: True
|
||||
# Optional: Enable the RTMP stream (default: False)
|
||||
enabled: False
|
||||
|
||||
# Optional: Live stream configuration for WebUI
|
||||
# Optional: Restream configuration
|
||||
# NOTE: Can be overridden at the camera level
|
||||
live:
|
||||
# Optional: Set the height of the live stream. (default: 720)
|
||||
# This must be less than or equal to the height of the detect stream. Lower resolutions
|
||||
# reduce bandwidth required for viewing the live stream. Width is computed to match known aspect ratio.
|
||||
height: 720
|
||||
# Optional: Set the encode quality of the live stream (default: shown below)
|
||||
# 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources.
|
||||
quality: 8
|
||||
restream:
|
||||
# Optional: Enable the restream (default: True)
|
||||
enabled: True
|
||||
# Optional: Force audio compatibility with browsers (default: shown below)
|
||||
force_audio: True
|
||||
# Optional: Video encoding to be used. By default the codec will be copied but
|
||||
# it can be switched to another or an MJPEG stream can be encoded and restreamed
|
||||
# as h264 (default: shown below)
|
||||
video_encoding: "copy"
|
||||
# Optional: Restream birdseye via RTSP (default: shown below)
|
||||
# NOTE: Enabling this will set birdseye to run 24/7 which may increase CPU usage somewhat.
|
||||
birdseye: False
|
||||
# Optional: jsmpeg stream configuration for WebUI
|
||||
jsmpeg:
|
||||
# Optional: Set the height of the jsmpeg stream. (default: 720)
|
||||
# This must be less than or equal to the height of the detect stream. Lower resolutions
|
||||
# reduce bandwidth required for viewing the jsmpeg stream. Width is computed to match known aspect ratio.
|
||||
height: 720
|
||||
# Optional: Set the encode quality of the jsmpeg stream (default: shown below)
|
||||
# 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources.
|
||||
quality: 8
|
||||
|
||||
# Optional: in-feed timestamp style configuration
|
||||
# NOTE: Can be overridden at the camera level
|
||||
@@ -374,6 +403,10 @@ timestamp_style:
|
||||
cameras:
|
||||
# Required: name of the camera
|
||||
back:
|
||||
# Optional: Enable/Disable the camera (default: shown below).
|
||||
# If disabled: config is used but no live stream and no capture etc.
|
||||
# Events/Recordings are still viewable.
|
||||
enabled: True
|
||||
# Required: ffmpeg settings for the camera
|
||||
ffmpeg:
|
||||
# Required: A list of input streams for the camera. See documentation for more information.
|
||||
@@ -381,11 +414,12 @@ cameras:
|
||||
# Required: the path to the stream
|
||||
# NOTE: path may include environment variables, which must begin with 'FRIGATE_' and be referenced in {}
|
||||
- path: rtsp://viewer:{FRIGATE_RTSP_PASSWORD}@10.0.10.10:554/cam/realmonitor?channel=1&subtype=2
|
||||
# Required: list of roles for this stream. valid values are: detect,record,rtmp
|
||||
# NOTICE: In addition to assigning the record, and rtmp roles,
|
||||
# Required: list of roles for this stream. valid values are: detect,record,restream,rtmp
|
||||
# NOTICE: In addition to assigning the record, restream, and rtmp roles,
|
||||
# they must also be enabled in the camera config.
|
||||
roles:
|
||||
- detect
|
||||
- restream
|
||||
- rtmp
|
||||
# Optional: stream specific global args (default: inherit)
|
||||
# global_args:
|
||||
|
||||
44
docs/docs/configuration/live.md
Normal file
@@ -0,0 +1,44 @@
|
||||
---
|
||||
id: live
|
||||
title: Live View
|
||||
---
|
||||
|
||||
Frigate has different live view options, some of which require [restream](restream.md) to be enabled.
|
||||
|
||||
## Live View Options
|
||||
|
||||
Live view options can be selected while viewing the live stream. The options are:
|
||||
|
||||
| Source | Latency | Frame Rate | Resolution | Audio | Requires Restream | Other Limitations |
|
||||
| ------ | ------- | -------------------------------------- | -------------- | ---------------------------- | ----------------- | -------------------------------- |
|
||||
| jsmpeg | low | same as `detect -> fps`, capped at 10 | same as detect | no | no | none |
|
||||
| mse | low | native | native | yes (depends on audio codec) | yes | not supported on iOS or Firefox |
|
||||
| webrtc | lowest | native | native | yes (depends on audio codec) | yes | requires extra config |
|
||||
|
||||
### WebRTC extra configuration:
|
||||
|
||||
webRTC works by creating a websocket connection on extra ports. One of the following is required for webRTC to work:
|
||||
* Frigate is run with `network_mode: host` to support automatic UDP port pass through locally and remotely. See https://github.com/AlexxIT/go2rtc#module-webrtc for more details
|
||||
* Frigate is run with `network_mode: bridge` and has:
|
||||
* Router setup to forward port `8555` to port `8555` on the frigate device.
|
||||
* For local webRTC, you will need to create your own go2rtc config:
|
||||
|
||||
```yaml
|
||||
log:
|
||||
format: text
|
||||
|
||||
webrtc:
|
||||
listen: ":8555"
|
||||
candidates:
|
||||
- <frigate host ip address>:8555 # <--- enter frigate host IP here
|
||||
- stun:8555
|
||||
```
|
||||
|
||||
and pass that config to frigate via docker or `frigate-go2rtc.yaml` for addon users:
|
||||
|
||||
See https://github.com/AlexxIT/go2rtc#module-webrtc for more details
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- /path/to/your/go2rtc.yaml:/config/frigate-go2rtc.yaml:ro
|
||||
```
|
||||
@@ -9,7 +9,7 @@ Frigate includes the object models listed below from the Google Coral test data.
|
||||
|
||||
Please note:
|
||||
- `car` is listed twice because `truck` has been renamed to `car` by default. These object types are frequently confused.
|
||||
- `person` is the only tracked object by default. See the [full configuration reference](https://docs.frigate.video/configuration/index#full-configuration-reference) for an example of expanding the list of tracked objects.
|
||||
- `person` is the only tracked object by default. See the [full configuration reference](index.md#full-configuration-reference) for an example of expanding the list of tracked objects.
|
||||
|
||||
<ul>
|
||||
{labels.split("\n").map((label) => (
|
||||
@@ -25,4 +25,4 @@ Models for both CPU and EdgeTPU (Coral) are bundled in the image. You can use yo
|
||||
- EdgeTPU Model: `/edgetpu_model.tflite`
|
||||
- Labels: `/labelmap.txt`
|
||||
|
||||
You also need to update the [model config](/configuration/advanced#model) if they differ from the defaults.
|
||||
You also need to update the [model config](advanced.md#model) if they differ from the defaults.
|
||||
|
||||
@@ -3,9 +3,15 @@ id: record
|
||||
title: Recording
|
||||
---
|
||||
|
||||
Recordings can be enabled and are stored at `/media/frigate/recordings`. The folder structure for the recordings is `YYYY-MM/DD/HH/<camera_name>/MM.SS.mp4`. These recordings are written directly from your camera stream without re-encoding. Each camera supports a configurable retention policy in the config. Frigate chooses the largest matching retention value between the recording retention and the event retention when determining if a recording should be removed.
|
||||
Recordings can be enabled and are stored at `/media/frigate/recordings`. The folder structure for the recordings is `YYYY-MM-DD/HH/<camera_name>/MM.SS.mp4`. These recordings are written directly from your camera stream without re-encoding. Each camera supports a configurable retention policy in the config. Frigate chooses the largest matching retention value between the recording retention and the event retention when determining if a recording should be removed.
|
||||
|
||||
H265 recordings can be viewed in Edge and Safari only. All other browsers require recordings to be encoded with H264.
|
||||
New recording segments are written from the camera stream to cache, they are only moved to disk if they match the setup recording retention policy.
|
||||
|
||||
H265 recordings can be viewed in Chrome 108+, Edge and Safari only. All other browsers require recordings to be encoded with H264.
|
||||
|
||||
## Will Frigate delete old recordings if my storage runs out?
|
||||
|
||||
As of Frigate 0.12 if there is less than an hour left of storage, the oldest 2 hours of recordings will be deleted.
|
||||
|
||||
## What if I don't want 24/7 recordings?
|
||||
|
||||
@@ -25,20 +31,52 @@ When `retain -> days` is set to `0`, segments will be deleted from the cache if
|
||||
|
||||
## Can I have "24/7" recordings, but only at certain times?
|
||||
|
||||
Using Frigate UI, HomeAssistant, or MQTT, cameras can be automated to only record in certain situations or at certain times.
|
||||
Using Frigate UI, HomeAssistant, or MQTT, cameras can be automated to only record in certain situations or at certain times.
|
||||
|
||||
**WARNING**: Recordings still must be enabled in the config. If a camera has recordings disabled in the config, enabling via the methods listed above will have no effect.
|
||||
|
||||
## What do the different retain modes mean?
|
||||
|
||||
Frigate saves from the stream with the `record` role in 10 second segments. These options determine which recording segments are kept for 24/7 recording (but can also affect events).
|
||||
Frigate saves from the stream with the `record` role in 10 second segments. These options determine which recording segments are kept for 24/7 recording (but can also affect events).
|
||||
|
||||
Let's say you have frigate configured so that your doorbell camera would retain the last **2** days of 24/7 recording.
|
||||
- With the `all` option all 48 hours of those two days would be kept and viewable.
|
||||
Let's say you have frigate configured so that your doorbell camera would retain the last **2** days of 24/7 recording.
|
||||
- With the `all` option all 48 hours of those two days would be kept and viewable.
|
||||
- With the `motion` option the only parts of those 48 hours would be segments that frigate detected motion. This is the middle ground option that won't keep all 48 hours, but will likely keep all segments of interest along with the potential for some extra segments.
|
||||
- With the `active_objects` option the only segments that would be kept are those where there was a true positive object that was not considered stationary.
|
||||
|
||||
The same options are available with events. Let's consider a scenario where you drive up and park in your driveway, go inside, then come back out 4 hours later.
|
||||
- With the `all` option all segments for the duration of the event would be saved for the event. This event would have 4 hours of footage.
|
||||
- With the `motion` option all segments for the duration of the event with motion would be saved. This means any segment where a car drove by in the street, person walked by, lighting changed, etc. would be saved.
|
||||
- With the `active_objects` it would only keep segments where the object was active. In this case the only segments that would be saved would be the ones where the car was driving up, you going inside, you coming outside, and the car driving away. Essentially reducing the 4 hours to a minute or two of event footage.
|
||||
- With the `motion` option all segments for the duration of the event with motion would be saved. This means any segment where a car drove by in the street, person walked by, lighting changed, etc. would be saved.
|
||||
- With the `active_objects` it would only keep segments where the object was active. In this case the only segments that would be saved would be the ones where the car was driving up, you going inside, you coming outside, and the car driving away. Essentially reducing the 4 hours to a minute or two of event footage.
|
||||
|
||||
A configuration example of the above retain modes where all `motion` segments are stored for 7 days and `active objects` are stored for 14 days would be as follows:
|
||||
```yaml
|
||||
record:
|
||||
enabled: True
|
||||
retain:
|
||||
days: 7
|
||||
mode: motion
|
||||
events:
|
||||
retain:
|
||||
default: 14
|
||||
mode: active_objects
|
||||
```
|
||||
The above configuration example can be added globally or on a per camera basis.
|
||||
|
||||
### Object Specific Retention
|
||||
|
||||
You can also set specific retention length for an object type. The below configuration example builds on from above but also specifies that recordings of dogs only need to be kept for 2 days and recordings of cars should be kept for 7 days.
|
||||
```yaml
|
||||
record:
|
||||
enabled: True
|
||||
retain:
|
||||
days: 7
|
||||
mode: motion
|
||||
events:
|
||||
retain:
|
||||
default: 14
|
||||
mode: active_objects
|
||||
objects:
|
||||
dog: 2
|
||||
car: 7
|
||||
```
|
||||
|
||||
78
docs/docs/configuration/restream.md
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: restream
|
||||
title: Restream
|
||||
---
|
||||
|
||||
### RTSP
|
||||
|
||||
Frigate can restream your video feed as an RTSP feed for other applications such as Home Assistant to utilize it at `rtsp://<frigate_host>:8554/<camera_name>`. Port 8554 must be open. [This allows you to use a video feed for detection in frigate and Home Assistant live view at the same time without having to make two separate connections to the camera](#reduce-connections-to-camera). The video feed is copied from the original video feed directly to avoid re-encoding. This feed does not include any annotation by Frigate.
|
||||
|
||||
#### Force Audio
|
||||
|
||||
Different live view technologies (ex: MSE, WebRTC) support different audio codecs. The `restream -> force_audio` flag tells the restream to make multiple streams available so that all live view technologies are supported. Some camera streams don't work well with this, in which case `restream -> force_audio` should be disabled.
|
||||
|
||||
#### Birdseye Restream
|
||||
|
||||
Birdseye RTSP restream can be enabled at `restream -> birdseye` and accessed at `rtsp://<frigate_host>:8554/birdseye`. Enabling the restream will cause birdseye to run 24/7 which may increase CPU usage somewhat.
|
||||
|
||||
#### Changing Restream Codec
|
||||
|
||||
Generally it is recommended to let the codec from the camera be copied. But there may be some cases where h265 needs to be transcoded as h264 or an MJPEG stream can be encoded and restreamed as h264. In this case the encoding will need to be set, if any hardware acceleration presets are set then that will be used to encode the stream.
|
||||
|
||||
```yaml
|
||||
ffmpeg:
|
||||
hwaccel_args: your-hwaccel-preset # <- highly recommended so the GPU is used
|
||||
|
||||
cameras:
|
||||
mjpeg_cam:
|
||||
ffmpeg:
|
||||
...
|
||||
restream:
|
||||
video_encoding: h264
|
||||
```
|
||||
|
||||
### RTMP (Deprecated)
|
||||
|
||||
In previous Frigate versions RTMP was used for re-streaming. RTMP has disadvantages however including being incompatible with H.265, high bitrates, and certain audio codecs. RTMP is deprecated and it is recommended to move to the new restream role.
|
||||
|
||||
## Reduce Connections To Camera
|
||||
|
||||
Some cameras only support one active connection or you may just want to have a single connection open to the camera. The RTSP restream allows this to be possible.
|
||||
|
||||
### With Single Stream
|
||||
|
||||
One connection is made to the camera. One for the restream, `detect` and `record` connect to the restream.
|
||||
|
||||
```yaml
|
||||
cameras:
|
||||
test_cam:
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: rtsp://localhost:8554/test_cam # <--- the name here must match the name of the camera
|
||||
roles:
|
||||
- record
|
||||
- detect
|
||||
- path: rtsp://192.168.1.5:554/live0 # <--- 1 connection to camera stream
|
||||
roles:
|
||||
- restream
|
||||
```
|
||||
|
||||
### With Sub Stream
|
||||
|
||||
Two connections are made to the camera. One for the sub stream, one for the restream, `record` connects to the restream.
|
||||
|
||||
```yaml
|
||||
cameras:
|
||||
test_cam:
|
||||
ffmpeg:
|
||||
inputs:
|
||||
- path: rtsp://localhost:8554/test_cam # <--- the name here must match the name of the camera
|
||||
roles:
|
||||
- record
|
||||
- path: rtsp://192.168.1.5:554/stream # <--- camera high res stream
|
||||
roles:
|
||||
- restream
|
||||
- path: rtsp://192.168.1.5:554/substream # <--- camera sub stream
|
||||
roles:
|
||||
- detect
|
||||
```
|
||||
@@ -1,8 +0,0 @@
|
||||
---
|
||||
id: rtmp
|
||||
title: RTMP
|
||||
---
|
||||
|
||||
Frigate can re-stream your video feed as a RTMP feed for other applications such as Home Assistant to utilize it at `rtmp://<frigate_host>/live/<camera_name>`. Port 1935 must be open. This allows you to use a video feed for detection in frigate and Home Assistant live view at the same time without having to make two separate connections to the camera. The video feed is copied from the original video feed directly to avoid re-encoding. This feed does not include any annotation by Frigate.
|
||||
|
||||
Some video feeds are not compatible with RTMP. If you are experiencing issues, check to make sure your camera feed is h264 with AAC audio. If your camera doesn't support a compatible format for RTMP, you can use the ffmpeg args to re-encode it on the fly at the expense of increased CPU utilization. Some more information about it can be found [here](../faqs#audio-in-recordings).
|
||||
@@ -9,7 +9,7 @@ Zones cannot have the same name as a camera. If desired, a single zone can inclu
|
||||
|
||||
During testing, enable the Zones option for the debug feed so you can adjust as needed. The zone line will increase in thickness when any object enters the zone.
|
||||
|
||||
To create a zone, follow [the steps for a "Motion mask"](/configuration/masks), but use the section of the web UI for creating a zone instead.
|
||||
To create a zone, follow [the steps for a "Motion mask"](masks.md), but use the section of the web UI for creating a zone instead.
|
||||
|
||||
### Restricting zones to specific objects
|
||||
|
||||
|
||||
@@ -40,9 +40,11 @@ Fork [blakeblackshear/frigate-hass-integration](https://github.com/blakeblackshe
|
||||
|
||||
### Setup
|
||||
|
||||
#### 1. Build the version information and docker container locally by running `make`
|
||||
#### 1. Open the repo with Visual Studio Code
|
||||
|
||||
#### 2. Create a local config file for testing
|
||||
Upon opening, you should be prompted to open the project in a remote container. This will build a container on top of the base frigate container with all the development dependencies installed. This ensures everyone uses a consistent development environment without the need to install any dependencies on your host machine.
|
||||
|
||||
#### 2. Modify your local config file for testing
|
||||
|
||||
Place the file at `config/config.yml` in the root of the repo.
|
||||
|
||||
@@ -73,18 +75,14 @@ These input args tell ffmpeg to read the mp4 file in an infinite loop. You can u
|
||||
|
||||
Create and place these files in a `debug` folder in the root of the repo. This is also where recordings will be created if you enable them in your test config. Update your config from step 2 above to point at the right file. You can check the `docker-compose.yml` file in the repo to see how the volumes are mapped.
|
||||
|
||||
#### 4. Open the repo with Visual Studio Code
|
||||
|
||||
Upon opening, you should be prompted to open the project in a remote container. This will build a container on top of the base frigate container with all the development dependencies installed. This ensures everyone uses a consistent development environment without the need to install any dependencies on your host machine.
|
||||
|
||||
#### 5. Run frigate from the command line
|
||||
#### 4. Run frigate from the command line
|
||||
|
||||
VSCode will start the docker compose file for you and open a terminal window connected to `frigate-dev`.
|
||||
|
||||
- Run `python3 -m frigate` to start the backend.
|
||||
- In a separate terminal window inside VS Code, change into the `web` directory and run `npm install && npm start` to start the frontend.
|
||||
|
||||
#### 6. Teardown
|
||||
#### 5. Teardown
|
||||
|
||||
After closing VSCode, you may still have containers running. To close everything down, just run `docker-compose down -v` to cleanup all containers.
|
||||
|
||||
@@ -126,7 +124,7 @@ ffmpeg -c:v h264_qsv -re -stream_loop -1 -i https://streams.videolan.org/ffmpeg/
|
||||
|
||||
- [Frigate source code](#frigate-core-web-and-docs)
|
||||
- All [core](#core) prerequisites _or_ another running Frigate instance locally available
|
||||
- Node.js 14
|
||||
- Node.js 16
|
||||
|
||||
### Making changes
|
||||
|
||||
@@ -169,6 +167,7 @@ npm run lint
|
||||
```
|
||||
|
||||
- Add to unit tests and ensure they pass. As much as possible, you should strive to _increase_ test coverage whenever making changes. This will help ensure features do not accidentally become broken in the future.
|
||||
- If you run into error messages like "TypeError: Cannot read properties of undefined (reading 'context')" when running tests, this may be due to these issues (https://github.com/vitest-dev/vitest/issues/1910, https://github.com/vitest-dev/vitest/issues/1652) in vitest, but I haven't been able to resolve them.
|
||||
|
||||
```console
|
||||
npm run test
|
||||
@@ -181,7 +180,7 @@ npm run test
|
||||
### Prerequisites
|
||||
|
||||
- [Frigate source code](#frigate-core-web-and-docs)
|
||||
- Node.js 14
|
||||
- Node.js 16
|
||||
|
||||
### Making changes
|
||||
|
||||
@@ -218,6 +217,5 @@ docker buildx stop builder && docker buildx rm builder # <---- if existing
|
||||
docker run --privileged --rm tonistiigi/binfmt --install all
|
||||
docker buildx create --name builder --driver docker-container --driver-opt network=host --use
|
||||
docker buildx inspect builder --bootstrap
|
||||
make build_web
|
||||
make push
|
||||
```
|
||||
99
docs/docs/frigate/hardware.md
Normal file
@@ -0,0 +1,99 @@
|
||||
---
|
||||
id: hardware
|
||||
title: Recommended hardware
|
||||
---
|
||||
|
||||
## Cameras
|
||||
|
||||
Cameras that output H.264 video and AAC audio will offer the most compatibility with all features of Frigate and Home Assistant. It is also helpful if your camera supports multiple substreams to allow different resolutions to be used for detection, streaming, and recordings without re-encoding.
|
||||
|
||||
I recommend Dahua, Hikvision, and Amcrest in that order. Dahua edges out Hikvision because they are easier to find and order, not because they are better cameras. I personally use Dahua cameras because they are easier to purchase directly. In my experience Dahua and Hikvision both have multiple streams with configurable resolutions and frame rates and rock solid streams. They also both have models with large sensors well known for excellent image quality at night. Not all the models are equal. Larger sensors are better than higher resolutions; especially at night. Amcrest is the fallback recommendation because they are rebranded Dahuas. They are rebranding the lower end models with smaller sensors or less configuration options.
|
||||
|
||||
Many users have reported various issues with Reolink cameras, so I do not recommend them. If you are using Reolink, I suggest the [Reolink specific configuration](../configuration/camera_specific.md#reolink-410520-possibly-others). Wifi cameras are also not recommended. Their streams are less reliable and cause connection loss and/or lost video data.
|
||||
|
||||
Here are some of the camera's I recommend:
|
||||
|
||||
- <a href="https://amzn.to/3uFLtxB" target="_blank" rel="nofollow noopener sponsored">Loryta(Dahua) T5442TM-AS-LED</a> (affiliate link)
|
||||
- <a href="https://amzn.to/3isJ3gU" target="_blank" rel="nofollow noopener sponsored">Loryta(Dahua) IPC-T5442TM-AS</a> (affiliate link)
|
||||
- <a href="https://amzn.to/2ZWNWIA" target="_blank" rel="nofollow noopener sponsored">Amcrest IP5M-T1179EW-28MM</a> (affiliate link)
|
||||
|
||||
I may earn a small commission for my endorsement, recommendation, testimonial, or link to any products or services from this website.
|
||||
|
||||
## Server
|
||||
|
||||
My current favorite is the Minisforum GK41 because of the dual NICs that allow you to setup a dedicated private network for your cameras where they can be blocked from accessing the internet. There are many used workstation options on eBay that work very well. Anything with an Intel CPU and capable of running Debian should work fine. As a bonus, you may want to look for devices with a M.2 or PCIe express slot that is compatible with the Google Coral. I may earn a small commission for my endorsement, recommendation, testimonial, or link to any products or services from this website.
|
||||
|
||||
| Name | Coral Inference Speed | Coral Compatibility | Notes |
|
||||
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Odyssey X86 Blue J4125 (<a href="https://amzn.to/3oH4BKi" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) (<a href="https://www.seeedstudio.com/Frigate-NVR-with-Odyssey-Blue-and-Coral-USB-Accelerator.html?utm_source=Frigate" target="_blank" rel="nofollow noopener sponsored">SeeedStudio</a>) | 9-10ms | M.2 B+M, USB | Dual gigabit NICs for easy isolated camera network. Easily handles several 1080p cameras. |
|
||||
| Minisforum GK41 (<a href="https://amzn.to/3ptnb8D" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) | 9-10ms | USB | Dual gigabit NICs for easy isolated camera network. Easily handles several 1080p cameras. |
|
||||
| Beelink GK55 (<a href="https://amzn.to/35E79BC" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) | 9-10ms | USB | Dual gigabit NICs for easy isolated camera network. Easily handles several 1080p cameras. |
|
||||
| Intel NUC (<a href="https://amzn.to/3psFlHi" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) | 8-10ms | USB | Overkill for most, but great performance. Can handle many cameras at 5fps depending on typical amounts of motion. Requires extra parts. |
|
||||
| BMAX B2 Plus (<a href="https://amzn.to/3a6TBh8" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) | 10-12ms | USB | Good balance of performance and cost. Also capable of running many other services at the same time as frigate. |
|
||||
| Atomic Pi (<a href="https://amzn.to/2YjpY9m" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) | 16ms | USB | Good option for a dedicated low power board with a small number of cameras. Can leverage Intel QuickSync for stream decoding. |
|
||||
| Raspberry Pi 4 (64bit) (<a href="https://amzn.to/2YhSGHH" target="_blank" rel="nofollow noopener sponsored">Amazon</a>) | 10-15ms | USB | Can handle a small number of cameras. |
|
||||
|
||||
## Detectors
|
||||
|
||||
A detector is a device which is optimized for running inferences efficiently to detect objects. Using a recommended detector means there will be less latency between detections and more detections can be run per second. Frigate is designed around the epectation that a detector is used to achieve very low inference speeds. Offloading TensorFlow to a detector is an order of magnitude faster and will reduce your CPU load dramatically. As of 0.12, Frigate supports a handful of different detector types with varying inference speeds and performance.
|
||||
|
||||
### Google Coral TPU
|
||||
|
||||
It is strongly recommended to use a Google Coral. A $60 device will outperform $2000 CPU. Frigate should work with any supported Coral device from https://coral.ai
|
||||
|
||||
The USB version is compatible with the widest variety of hardware and does not require a driver on the host machine. However, it does lack the automatic throttling features of the other versions.
|
||||
|
||||
The PCIe and M.2 versions require installation of a driver on the host. Follow the instructions for your version from https://coral.ai
|
||||
|
||||
A single Coral can handle many cameras and will be sufficient for the majority of users. You can calculate the maximum performance of your Coral based on the inference speed reported by Frigate. With an inference speed of 10, your Coral will top out at `1000/10=100`, or 100 frames per second. If your detection fps is regularly getting close to that, you should first consider tuning motion masks. If those are already properly configured, a second Coral may be needed.
|
||||
|
||||
### OpenVino
|
||||
|
||||
The OpenVINO detector type is able to run on:
|
||||
- 6th Gen Intel Platforms and newer that have an iGPU
|
||||
- x86 & Arm32/64 hosts with VPU Hardware (ex: Intel NCS2)
|
||||
|
||||
More information is available [in the detector docs](/configuration/detectors#openvino-detector)
|
||||
|
||||
Inference speeds vary greatly depending on the CPU, GPU, or VPU used, some known examples are below:
|
||||
|
||||
| Name | Inference Speed | Notes |
|
||||
| ------------------- | --------------- | --------------------------------------------------------------------- |
|
||||
| Intel Celeron J4105 | ~ 25 ms | Inference speeds on CPU were ~ 150 ms |
|
||||
| Intel Celeron N4020 | 50 - 200 ms | Inference speeds on CPU were ~ 800 ms, greatly depends on other loads |
|
||||
| Intel NCS2 VPU | 60 - 65 ms | May vary based on host device |
|
||||
| Intel i5 1135G7 | 10 - 15 ms | |
|
||||
|
||||
### TensorRT
|
||||
|
||||
The TensortRT detector is able to run on x86 hosts that have an Nvidia GPU which supports the 11.x series of CUDA libraries. The minimum driver version on the host system must be `>=450.80.02`. Also the GPU must support a Compute Capability of `5.0` or greater. This generally correlates to a Maxwell-era GPU or newer, check the [TensorRT docs for more info](/configuration/detectors#nvidia-tensorrt-detector).
|
||||
|
||||
Inference speeds will vary greatly depending on the GPU and the model used.
|
||||
`tiny` variants are faster than the equivalent non-tiny model, some known examples are below:
|
||||
|
||||
| Name | Model | Inference Speed |
|
||||
| -------- | --------------- | --------------- |
|
||||
| RTX 3050 | yolov4-tiny-416 | ~ 5 ms |
|
||||
| RTX 3050 | yolov7-tiny-416 | ~ 6 ms |
|
||||
|
||||
## What does Frigate use the CPU for and what does it use a detector for? (ELI5 Version)
|
||||
|
||||
This is taken from a [user question on reddit](https://www.reddit.com/r/homeassistant/comments/q8mgau/comment/hgqbxh5/?utm_source=share&utm_medium=web2x&context=3). Modified slightly for clarity.
|
||||
|
||||
CPU Usage: I am a CPU, Mendel is a Google Coral
|
||||
|
||||
My buddy Mendel and I have been tasked with keeping the neighbor's red footed booby off my parent's yard. Now I'm really bad at identifying birds. It takes me forever, but my buddy Mendel is incredible at it.
|
||||
|
||||
Mendel however, struggles at pretty much anything else. So we make an agreement. I wait till I see something that moves, and snap a picture of it for Mendel. I then show him the picture and he tells me what it is. Most of the time it isn't anything. But eventually I see some movement and Mendel tells me it is the Booby. Score!
|
||||
|
||||
_What happens when I increase the resolution of my camera?_
|
||||
|
||||
However we realize that there is a problem. There is still booby poop all over the yard. How could we miss that! I've been watching all day! My parents check the window and realize its dirty and a bit small to see the entire yard so they clean it and put a bigger one in there. Now there is so much more to see! However I now have a much bigger area to scan for movement and have to work a lot harder! Even my buddy Mendel has to work harder, as now the pictures have a lot more detail in them that he has to look at to see if it is our sneaky booby.
|
||||
|
||||
Basically - When you increase the resolution and/or the frame rate of the stream there is now significantly more data for the CPU to parse. That takes additional computing power. The Google Coral is really good at doing object detection, but it doesn't have time to look everywhere all the time (especially when there are many windows to check). To balance it, Frigate uses the CPU to look for movement, then sends those frames to the Coral to do object detection. This allows the Coral to be available to a large number of cameras and not overload it.
|
||||
|
||||
## Do hwaccel args help if I am using a Coral?
|
||||
|
||||
YES! The Coral does not help with decoding video streams.
|
||||
|
||||
Decompressing video streams takes a significant amount of CPU power. Video compression uses key frames (also known as I-frames) to send a full frame in the video stream. The following frames only include the difference from the key frame, and the CPU has to compile each frame by merging the differences with the key frame. [More detailed explanation](https://blog.video.ibm.com/streaming-video-tips/keyframes-interframe-video-compression/). Higher resolutions and frame rates mean more processing power is needed to decode the video stream, so try and set them on the camera to avoid unnecessary decoding work.
|
||||
@@ -15,7 +15,7 @@ Use of a [Google Coral Accelerator](https://coral.ai/products/) is optional, but
|
||||
- Object detection with TensorFlow runs in separate processes for maximum FPS
|
||||
- Communicates over MQTT for easy integration into other systems
|
||||
- Recording with retention based on detected objects
|
||||
- Re-streaming via RTMP to reduce the number of connections to your camera
|
||||
- Re-streaming via RTSP to reduce the number of connections to your camera
|
||||
- A dynamic combined camera view of all tracked cameras.
|
||||
|
||||
## Screenshots
|
||||
@@ -3,11 +3,11 @@ id: installation
|
||||
title: Installation
|
||||
---
|
||||
|
||||
Frigate is a Docker container that can be run on any Docker host including as a [HassOS Addon](https://www.home-assistant.io/addons/). Note that a Home Assistant Addon is **not** the same thing as the integration. The [integration](integrations/home-assistant) is required to integrate Frigate into Home Assistant.
|
||||
Frigate is a Docker container that can be run on any Docker host including as a [HassOS Addon](https://www.home-assistant.io/addons/). Note that a Home Assistant Addon is **not** the same thing as the integration. The [integration](/integrations/home-assistant) is required to integrate Frigate into Home Assistant.
|
||||
|
||||
## Dependencies
|
||||
|
||||
**MQTT broker** - Frigate requires an MQTT broker. If using Home Assistant, Frigate and Home Assistant must be connected to the same MQTT broker.
|
||||
**MQTT broker (optional)** - An MQTT broker is optional with Frigate, but is required for the Home Assistant integration. If using Home Assistant, Frigate and Home Assistant must be connected to the same MQTT broker.
|
||||
|
||||
## Preparing your hardware
|
||||
|
||||
@@ -21,12 +21,6 @@ Windows is not officially supported, but some users have had success getting it
|
||||
|
||||
Frigate uses the following locations for read/write operations in the container. Docker volume mappings can be used to map these to any location on your host machine.
|
||||
|
||||
:::caution
|
||||
|
||||
Note that Frigate does not currently support limiting recordings based on available disk space automatically. If using recordings, you must specify retention settings for a number of days that will fit within the available disk space of your drive or Frigate will crash.
|
||||
|
||||
:::
|
||||
|
||||
- `/media/frigate/clips`: Used for snapshot storage. In the future, it will likely be renamed from `clips` to `snapshots`. The file structure here cannot be modified and isn't intended to be browsed or managed manually.
|
||||
- `/media/frigate/recordings`: Internal system storage for recording segments. The file structure here cannot be modified and isn't intended to be browsed or managed manually.
|
||||
- `/media/frigate/frigate.db`: Default location for the sqlite database. You will also see several files alongside this file while frigate is running. If moving the database location (often needed when using a network drive at `/media/frigate`), it is recommended to mount a volume with docker at `/db` and change the storage location of the database to `/db/frigate.db` in the config file.
|
||||
@@ -44,7 +38,7 @@ services:
|
||||
frigate:
|
||||
...
|
||||
volumes:
|
||||
- /path/to/your/config.yml:/config/config.yml:ro
|
||||
- /path/to/your/config.yml:/config/config.yml
|
||||
- /path/to/your/storage:/media/frigate
|
||||
- type: tmpfs # Optional: 1GB of memory, reduces SSD/SD Card wear
|
||||
target: /tmp/cache
|
||||
@@ -61,7 +55,7 @@ services:
|
||||
frigate:
|
||||
...
|
||||
volumes:
|
||||
- /path/to/your/config.yml:/config/config.yml:ro
|
||||
- /path/to/your/config.yml:/config/config.yml
|
||||
- /path/to/network/storage:/media/frigate
|
||||
- /path/to/local/disk:/db
|
||||
- type: tmpfs # Optional: 1GB of memory, reduces SSD/SD Card wear
|
||||
@@ -100,18 +94,7 @@ Additionally, the USB Coral draws a considerable amount of power. If using any o
|
||||
|
||||
## Docker
|
||||
|
||||
Running in Docker directly is the recommended install method.
|
||||
|
||||
Make sure you choose the right image for your architecture:
|
||||
|
||||
| Arch | Image Name |
|
||||
| ----------- | ------------------------------------------ |
|
||||
| amd64 | blakeblackshear/frigate:stable-amd64 |
|
||||
| amd64nvidia | blakeblackshear/frigate:stable-amd64nvidia |
|
||||
| armv7 | blakeblackshear/frigate:stable-armv7 |
|
||||
| aarch64 | blakeblackshear/frigate:stable-aarch64 |
|
||||
|
||||
It is recommended to run with docker-compose:
|
||||
Running in Docker with compose is the recommended install method:
|
||||
|
||||
```yaml
|
||||
version: "3.9"
|
||||
@@ -120,7 +103,7 @@ services:
|
||||
container_name: frigate
|
||||
privileged: true # this may not be necessary for all setups
|
||||
restart: unless-stopped
|
||||
image: blakeblackshear/frigate:<specify_version_tag>
|
||||
image: blakeblackshear/frigate:stable
|
||||
shm_size: "64mb" # update for your cameras based on calculation above
|
||||
devices:
|
||||
- /dev/bus/usb:/dev/bus/usb # passes the USB Coral, needs to be modified for other versions
|
||||
@@ -128,7 +111,7 @@ services:
|
||||
- /dev/dri/renderD128 # for intel hwaccel, needs to be updated for your hardware
|
||||
volumes:
|
||||
- /etc/localtime:/etc/localtime:ro
|
||||
- /path/to/your/config.yml:/config/config.yml:ro
|
||||
- /path/to/your/config.yml:/config/config.yml
|
||||
- /path/to/your/storage:/media/frigate
|
||||
- type: tmpfs # Optional: 1GB of memory, reduces SSD/SD Card wear
|
||||
target: /tmp/cache
|
||||
@@ -152,12 +135,12 @@ docker run -d \
|
||||
--device /dev/dri/renderD128 \
|
||||
--shm-size=64m \
|
||||
-v /path/to/your/storage:/media/frigate \
|
||||
-v /path/to/your/config.yml:/config/config.yml:ro \
|
||||
-v /path/to/your/config.yml:/config/config.yml \
|
||||
-v /etc/localtime:/etc/localtime:ro \
|
||||
-e FRIGATE_RTSP_PASSWORD='password' \
|
||||
-p 5000:5000 \
|
||||
-p 1935:1935 \
|
||||
blakeblackshear/frigate:<specify_version_tag>
|
||||
blakeblackshear/frigate:stable
|
||||
```
|
||||
|
||||
## Home Assistant Operating System (HassOS)
|
||||
10
docs/docs/guides/events_setup.md
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
id: events_setup
|
||||
title: Setting Up Events
|
||||
---
|
||||
|
||||
[Snapshots](../configuration/snapshots.md) and/or [Recordings](../configuration/record.md) must be enabled for events to be created for detected objects.
|
||||
|
||||
## Limiting Events to Areas of Interest
|
||||
|
||||
The best way to limit events to areas of interest is to use [zones](../configuration/zones.md) along with `required_zones` for events and snapshots to only have events created in areas of interest.
|
||||
@@ -3,17 +3,24 @@ id: getting_started
|
||||
title: Creating a config file
|
||||
---
|
||||
|
||||
This guide walks through the steps to build a configuration file for Frigate. It assumes that you already have an environment setup as described in [Installation](/installation). You should also configure your cameras according to the [camera setup guide](/guides/camera_setup)
|
||||
This guide walks through the steps to build a configuration file for Frigate. It 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](/guides/camera_setup)
|
||||
|
||||
### Step 1: Configure the MQTT server
|
||||
### Step 1: Configure the MQTT server (Optional)
|
||||
|
||||
Frigate requires a functioning MQTT server. Start by adding the mqtt section at the top level in your config:
|
||||
Use of a functioning MQTT server is optional for frigate, but required for the home assistant integration. Start by adding the mqtt section at the top level in your config:
|
||||
|
||||
If using mqtt:
|
||||
```yaml
|
||||
mqtt:
|
||||
host: <ip of your mqtt server>
|
||||
```
|
||||
|
||||
If not using mqtt:
|
||||
```yaml
|
||||
mqtt:
|
||||
enabled: False
|
||||
```
|
||||
|
||||
If using the Mosquitto Addon in Home Assistant, a username and password is required. For example:
|
||||
|
||||
```yaml
|
||||
@@ -23,7 +30,7 @@ mqtt:
|
||||
password: <password>
|
||||
```
|
||||
|
||||
Frigate supports many configuration options for mqtt. See the [configuration reference](/configuration/index#full-configuration-reference) for more info.
|
||||
Frigate supports many configuration options for mqtt. See the [configuration reference](../configuration/index.md#full-configuration-reference) for more info.
|
||||
|
||||
### Step 2: Configure detectors
|
||||
|
||||
@@ -39,7 +46,7 @@ detectors:
|
||||
device: usb
|
||||
```
|
||||
|
||||
More details on available detectors can be found [here](/configuration/detectors).
|
||||
More details on available detectors can be found [here](../configuration/detectors.md).
|
||||
|
||||
### Step 3: Add a minimal camera configuration
|
||||
|
||||
@@ -75,11 +82,11 @@ At this point you should be able to start Frigate and see the the video feed in
|
||||
|
||||
If you get a green image from the camera, this means ffmpeg was not able to get the video feed from your camera. Check the logs for error messages from ffmpeg. The default ffmpeg arguments are designed to work with H264 RTSP cameras that support TCP connections. If you do not have H264 cameras, make sure you have disabled RTMP. It is possible to enable it, but you must tell ffmpeg to re-encode the video with customized output args.
|
||||
|
||||
FFmpeg arguments for other types of cameras can be found [here](/configuration/camera_specific).
|
||||
FFmpeg arguments for other types of cameras can be found [here](../configuration/camera_specific.md).
|
||||
|
||||
### Step 5: Configure hardware acceleration (optional)
|
||||
|
||||
Now that you have a working camera configuration, you want to setup hardware acceleration to minimize the CPU required to decode your video streams. See the [hardware acceleration](/configuration/hardware_acceleration) config reference for examples applicable to your hardware.
|
||||
Now that you have a working camera configuration, you want to setup hardware acceleration to minimize the CPU required to decode your video streams. See the [hardware acceleration](../configuration/hardware_acceleration.md) config reference for examples applicable to your hardware.
|
||||
|
||||
In order to best evaluate the performance impact of hardware acceleration, it is recommended to temporarily disable detection.
|
||||
|
||||
@@ -115,7 +122,7 @@ cameras:
|
||||
|
||||
Now that you have optimized your configuration for decoding the video stream, you will want to check to see where to implement motion masks. To do this, navigate to the camera in the UI, select "Debug" at the top, and enable "Motion boxes" in the options below the video feed. 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.
|
||||
|
||||
Now that you know where you need to mask, use the "Mask & Zone creator" in the options pane to generate the coordinates needed for your config file. More information about masks can be found [here](/configuration/masks).
|
||||
Now that you know where you need to mask, use the "Mask & Zone creator" in the options pane to generate the coordinates needed for your config file. More information about masks can be found [here](../configuration/masks.md).
|
||||
|
||||
:::caution
|
||||
|
||||
@@ -178,7 +185,7 @@ cameras:
|
||||
|
||||
If you don't have separate streams for detect and record, you would just add the record role to the list on the first input.
|
||||
|
||||
By default, Frigate will retain video of all events for 10 days. The full set of options for recording can be found [here](/configuration/index#full-configuration-reference).
|
||||
By default, Frigate will retain video of all events for 10 days. The full set of options for recording can be found [here](../configuration/index.md#full-configuration-reference).
|
||||
|
||||
### Step 8: Enable snapshots (optional)
|
||||
|
||||
@@ -198,4 +205,4 @@ cameras:
|
||||
motion: ...
|
||||
```
|
||||
|
||||
By default, Frigate will retain snapshots of all events for 10 days. The full set of options for snapshots can be found [here](/configuration/index#full-configuration-reference).
|
||||
By default, Frigate will retain snapshots of all events for 10 days. The full set of options for snapshots can be found [here](../configuration/index.md#full-configuration-reference).
|
||||
|
||||
@@ -5,7 +5,7 @@ title: Home Assistant notifications
|
||||
|
||||
The best way to get started with notifications for Frigate is to use the [Blueprint](https://community.home-assistant.io/t/frigate-mobile-app-notifications/311091). You can use the yaml generated from the Blueprint as a starting point and customize from there.
|
||||
|
||||
It is generally recommended to trigger notifications based on the `frigate/events` mqtt topic. This provides the event_id needed to fetch [thumbnails/snapshots/clips](/integrations/home-assistant#notification-api) and other useful information to customize when and where you want to receive alerts. The data is published in the form of a change feed, which means you can reference the "previous state" of the object in the `before` section and the "current state" of the object in the `after` section. You can see an example [here](/integrations/mqtt#frigateevents).
|
||||
It is generally recommended to trigger notifications based on the `frigate/events` mqtt topic. This provides the event_id needed to fetch [thumbnails/snapshots/clips](../integrations/home-assistant.md#notification-api) and other useful information to customize when and where you want to receive alerts. The data is published in the form of a change feed, which means you can reference the "previous state" of the object in the `before` section and the "current state" of the object in the `after` section. You can see an example [here](../integrations/mqtt.md#frigateevents).
|
||||
|
||||
Here is a simple example of a notification automation of events which will update the existing notification for each change. This means the image you see in the notification will update as frigate finds a "better" image.
|
||||
|
||||
|
||||
84
docs/docs/guides/reverse_proxy.md
Normal file
@@ -0,0 +1,84 @@
|
||||
---
|
||||
id: reverse_proxy
|
||||
title: Setting up a Reverse Proxy
|
||||
---
|
||||
|
||||
This guide outlines the basic configuration steps needed to expose your Frigate UI to the internet.
|
||||
A common way of accomplishing this is to use a reverse proxy webserver between your router and your Frigate instance.
|
||||
A reverse proxy accepts HTTP requests from the public internet and redirects them transparently to internal webserver(s) on your network.
|
||||
|
||||
The suggested steps are:
|
||||
- **Configure** a 'proxy' HTTP webserver (such as [Apache2](https://httpd.apache.org/docs/current/) or [NPM](https://github.com/NginxProxyManager/nginx-proxy-manager)) and only expose ports 80/443 from this webserver to the internet
|
||||
- **Encrypt** content from the proxy webserver by installing SSL (such as with [Let's Encrypt](https://letsencrypt.org/)). Note that SSL is then not required on your Frigate webserver as the proxy encrypts all requests for you
|
||||
- **Restrict** access to your Frigate instance at the proxy using, for example, password authentication
|
||||
|
||||
:::caution
|
||||
A reverse proxy can be used to secure access to an internal webserver but the user will be entirely reliant
|
||||
on the steps they have taken. You must ensure you are following security best practices.
|
||||
This page does not attempt to outline the specific steps needed to secure your internal website.
|
||||
Please use your own knowledge to assess and vet the reverse proxy software before you install anything on your system.
|
||||
:::
|
||||
|
||||
There are several technologies available to implement reverse proxies. This document currently suggests one, using Apache2,
|
||||
and the community is invited to document others through a contribution to this page.
|
||||
|
||||
## Apache2 Reverse Proxy
|
||||
|
||||
In the configuration examples below, only the directives relevant to the reverse proxy approach above are included.
|
||||
On Debian Apache2 the configuration file will be named along the lines of `/etc/apache2/sites-available/cctv.conf`
|
||||
|
||||
### Step 1: Configure the Apache2 Reverse Proxy
|
||||
|
||||
Make life easier for yourself by presenting your Frigate interface as a DNS sub-domain rather than as a sub-folder of your main domain.
|
||||
Here we access Frigate via https://cctv.mydomain.co.uk
|
||||
```xml
|
||||
<VirtualHost *:443>
|
||||
ServerName cctv.mydomain.co.uk
|
||||
|
||||
ProxyPreserveHost On
|
||||
ProxyPass "/" "http://frigatepi.local:5000/"
|
||||
ProxyPassReverse "/" "http://frigatepi.local:5000/"
|
||||
|
||||
ProxyPass /ws ws://frigatepi.local:5000/ws
|
||||
ProxyPassReverse /ws ws://frigatepi.local:5000/ws
|
||||
|
||||
ProxyPass /live/ ws://frigatepi.local:5000/live/
|
||||
ProxyPassReverse /live/ ws://frigatepi.local:5000/live/
|
||||
|
||||
RewriteEngine on
|
||||
RewriteCond %{HTTP:Upgrade} =websocket [NC]
|
||||
RewriteRule /(.*) ws://frigatepi.local:5000/$1 [P,L]
|
||||
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
|
||||
RewriteRule /(.*) http://frigatepi.local:5000/$1 [P,L]
|
||||
</VirtualHost>
|
||||
```
|
||||
|
||||
### Step 2: Use SSL to encrypt access to your Frigate instance
|
||||
|
||||
Whilst this won't, on its own, prevent access to your Frigate webserver it will encrypt all content (such as login credentials).
|
||||
Installing SSL is beyond the scope of this document but [Let's Encrypt](https://letsencrypt.org/) is a widely used approach.
|
||||
This Apache2 configuration snippet then results in unencrypted requests being redirected to the webserver SSL port
|
||||
|
||||
```xml
|
||||
<VirtualHost *:80>
|
||||
ServerName cctv.mydomain.co.uk
|
||||
RewriteEngine on
|
||||
RewriteCond %{SERVER_NAME} =cctv.mydomain.co.uk
|
||||
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
|
||||
</VirtualHost>
|
||||
```
|
||||
|
||||
### Step 3: Authenticate users at the proxy
|
||||
|
||||
There are many ways to authenticate a website but a straightforward approach is to use [Apache2 password files](https://httpd.apache.org/docs/2.4/howto/auth.html).
|
||||
|
||||
```xml
|
||||
<VirtualHost *:443>
|
||||
<Location />
|
||||
AuthType Basic
|
||||
AuthName "Restricted Files"
|
||||
AuthUserFile "/var/www/passwords"
|
||||
Require user paul
|
||||
</Location>
|
||||
</VirtualHost>
|
||||
```
|
||||
@@ -3,7 +3,7 @@ id: stationary_objects
|
||||
title: Avoiding stationary objects
|
||||
---
|
||||
|
||||
Many people use Frigate to detect cars entering their driveway, and they often run into an issue with repeated events of a parked car being repeatedly detected. This is because object tracking stops when motion ends and the event ends. Motion detection works by determining if a sufficient number of pixels have changed between frames. Shadows or other lighting changes will be detected as motion. This will often cause a new event for a parked car.
|
||||
Many people use Frigate to detect cars entering their driveway, and they often run into an issue with repeated events of a parked car being repeatedly detected over the course of multiple days (for example if the car is lost at night and detected again the following morning.
|
||||
|
||||
You can use zones to restrict events and notifications to objects that have entered specific areas.
|
||||
|
||||
@@ -17,7 +17,7 @@ Frigate is designed to track objects as they move and over-masking can prevent i
|
||||
|
||||
To only be notified of cars that enter your driveway from the street, you could create multiple zones that cover your driveway. For cars, you would only notify if `entered_zones` from the events MQTT topic has more than 1 zone.
|
||||
|
||||
See [this example](/configuration/zones#restricting-zones-to-specific-objects) from the Zones documentation to see how to restrict zones to certain object types.
|
||||
See [this example](../configuration/zones.md#restricting-zones-to-specific-objects) from the Zones documentation to see how to restrict zones to certain object types.
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
---
|
||||
id: hardware
|
||||
title: Recommended hardware
|
||||
---
|
||||
|
||||
## Cameras
|
||||
|
||||
Cameras that output H.264 video and AAC audio will offer the most compatibility with all features of Frigate and Home Assistant. It is also helpful if your camera supports multiple substreams to allow different resolutions to be used for detection, streaming, and recordings without re-encoding.
|
||||
|
||||
I recommend Dahua, Hikvision, and Amcrest in that order. Dahua edges out Hikvision because they are easier to find and order, not because they are better cameras. I personally use Dahua cameras because they are easier to purchase directly. In my experience Dahua and Hikvision both have multiple streams with configurable resolutions and frame rates and rock solid streams. They also both have models with large sensors well known for excellent image quality at night. Not all the models are equal. Larger sensors are better than higher resolutions; especially at night. Amcrest is the fallback recommendation because they are rebranded Dahuas. They are rebranding the lower end models with smaller sensors or less configuration options.
|
||||
|
||||
Many users have reported various issues with Reolink cameras, so I do not recommend them. If you are using Reolink, I suggest the [Reolink specific configuration](configuration/camera_specific#reolink-410520-possibly-others). Wifi cameras are also not recommended. Their streams are less reliable and cause connection loss and/or lost video data.
|
||||
|
||||
Here are some of the camera's I recommend:
|
||||
|
||||
- <a href="https://amzn.to/3uFLtxB" target="_blank" rel="nofollow noopener sponsored">Loryta(Dahua) T5442TM-AS-LED</a> (affiliate link)
|
||||
- <a href="https://amzn.to/3isJ3gU" target="_blank" rel="nofollow noopener sponsored">Loryta(Dahua) IPC-T5442TM-AS</a> (affiliate link)
|
||||
- <a href="https://amzn.to/2ZWNWIA" target="_blank" rel="nofollow noopener sponsored">Amcrest IP5M-T1179EW-28MM</a> (affiliate link)
|
||||
|
||||
I may earn a small commission for my endorsement, recommendation, testimonial, or link to any products or services from this website.
|
||||
|
||||
## Server
|
||||
|
||||
My current favorite is the Minisforum GK41 because of the dual NICs that allow you to setup a dedicated private network for your cameras where they can be blocked from accessing the internet. There are many used workstation options on eBay that work very well. Anything with an Intel CPU and capable of running Debian should work fine. As a bonus, you may want to look for devices with a M.2 or PCIe express slot that is compatible with the Google Coral. I may earn a small commission for my endorsement, recommendation, testimonial, or link to any products or services from this website.
|
||||
|
||||
| Name | Inference Speed | Coral Compatibility | Notes |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| <a href="https://amzn.to/3oH4BKi" target="_blank" rel="nofollow noopener sponsored">Odyssey X86 Blue J4125</a> (affiliate link) | 9-10ms | M.2 B+M | Dual gigabit NICs for easy isolated camera network. Easily handles several 1080p cameras. |
|
||||
| <a href="https://amzn.to/3ptnb8D" target="_blank" rel="nofollow noopener sponsored">Minisforum GK41</a> (affiliate link) | 9-10ms | USB | Dual gigabit NICs for easy isolated camera network. Easily handles several 1080p cameras. |
|
||||
| <a href="https://amzn.to/35E79BC" target="_blank" rel="nofollow noopener sponsored">Beelink GK55</a> (affiliate link) | 9-10ms | USB | Dual gigabit NICs for easy isolated camera network. Easily handles several 1080p cameras. |
|
||||
| <a href="https://amzn.to/3psFlHi" target="_blank" rel="nofollow noopener sponsored">Intel NUC</a> (affiliate link) | 8-10ms | USB | Overkill for most, but great performance. Can handle many cameras at 5fps depending on typical amounts of motion. Requires extra parts. |
|
||||
| <a href="https://amzn.to/3a6TBh8" target="_blank" rel="nofollow noopener sponsored">BMAX B2 Plus</a> (affiliate link) | 10-12ms | USB | Good balance of performance and cost. Also capable of running many other services at the same time as frigate. |
|
||||
| <a href="https://amzn.to/2YjpY9m" target="_blank" rel="nofollow noopener sponsored">Atomic Pi</a> (affiliate link) | 16ms | USB | Good option for a dedicated low power board with a small number of cameras. Can leverage Intel QuickSync for stream decoding. |
|
||||
| <a href="https://amzn.to/2YhSGHH" target="_blank" rel="nofollow noopener sponsored">Raspberry Pi 4 (64bit)</a> (affiliate link) | 10-15ms | USB | Can handle a small number of cameras. |
|
||||
|
||||
## Google Coral TPU
|
||||
|
||||
It is strongly recommended to use a Google Coral. Frigate is designed around the expectation that a Coral is used to achieve very low inference speeds. Offloading TensorFlow to the Google Coral is an order of magnitude faster and will reduce your CPU load dramatically. A $60 device will outperform $2000 CPU. Frigate should work with any supported Coral device from https://coral.ai
|
||||
|
||||
The USB version is compatible with the widest variety of hardware and does not require a driver on the host machine. However, it does lack the automatic throttling features of the other versions.
|
||||
|
||||
The PCIe and M.2 versions require installation of a driver on the host. Follow the instructions for your version from https://coral.ai
|
||||
|
||||
A single Coral can handle many cameras and will be sufficient for the majority of users. You can calculate the maximum performance of your Coral based on the inference speed reported by Frigate. With an inference speed of 10, your Coral will top out at `1000/10=100`, or 100 frames per second. If your detection fps is regularly getting close to that, you should first consider tuning motion masks. If those are already properly configured, a second Coral may be needed.
|
||||
|
||||
### What does Frigate use the CPU for and what does it use the Coral for? (ELI5 Version)
|
||||
|
||||
This is taken from a [user question on reddit](https://www.reddit.com/r/homeassistant/comments/q8mgau/comment/hgqbxh5/?utm_source=share&utm_medium=web2x&context=3). Modified slightly for clarity.
|
||||
|
||||
CPU Usage: I am a CPU, Mendel is a Google Coral
|
||||
|
||||
My buddy Mendel and I have been tasked with keeping the neighbor's red footed booby off my parent's yard. Now I'm really bad at identifying birds. It takes me forever, but my buddy Mendel is incredible at it.
|
||||
|
||||
Mendel however, struggles at pretty much anything else. So we make an agreement. I wait till I see something that moves, and snap a picture of it for Mendel. I then show him the picture and he tells me what it is. Most of the time it isn't anything. But eventually I see some movement and Mendel tells me it is the Booby. Score!
|
||||
|
||||
_What happens when I increase the resolution of my camera?_
|
||||
|
||||
However we realize that there is a problem. There is still booby poop all over the yard. How could we miss that! I've been watching all day! My parents check the window and realize its dirty and a bit small to see the entire yard so they clean it and put a bigger one in there. Now there is so much more to see! However I now have a much bigger area to scan for movement and have to work a lot harder! Even my buddy Mendel has to work harder, as now the pictures have a lot more detail in them that he has to look at to see if it is our sneaky booby.
|
||||
|
||||
Basically - When you increase the resolution and/or the frame rate of the stream there is now significantly more data for the CPU to parse. That takes additional computing power. The Google Coral is really good at doing object detection, but it doesn't have time to look everywhere all the time (especially when there are many windows to check). To balance it, Frigate uses the CPU to look for movement, then sends those frames to the Coral to do object detection. This allows the Coral to be available to a large number of cameras and not overload it.
|
||||
|
||||
### Do hwaccel args help if I am using a Coral?
|
||||
|
||||
YES! The Coral does not help with decoding video streams.
|
||||
|
||||
Decompressing video streams takes a significant amount of CPU power. Video compression uses key frames (also known as I-frames) to send a full frame in the video stream. The following frames only include the difference from the key frame, and the CPU has to compile each frame by merging the differences with the key frame. [More detailed explanation](https://blog.video.ibm.com/streaming-video-tips/keyframes-interframe-video-compression/). Higher resolutions and frame rates mean more processing power is needed to decode the video stream, so try and set them on the camera to avoid unnecessary decoding work.
|
||||
@@ -159,13 +159,14 @@ Events from the database. Accepts the following query string parameters:
|
||||
| -------------------- | ---- | --------------------------------------------- |
|
||||
| `before` | int | Epoch time |
|
||||
| `after` | int | Epoch time |
|
||||
| `camera` | str | Camera name |
|
||||
| `label` | str | Label name |
|
||||
| `zone` | str | Zone name |
|
||||
| `cameras` | str | , separated list of cameras |
|
||||
| `labels` | str | , separated list of labels |
|
||||
| `zones` | str | , separated list of zones |
|
||||
| `limit` | int | Limit the number of events returned |
|
||||
| `has_snapshot` | int | Filter to events that have snapshots (0 or 1) |
|
||||
| `has_clip` | int | Filter to events that have clips (0 or 1) |
|
||||
| `include_thumbnails` | int | Include thumbnails in the response (0 or 1) |
|
||||
| `in_progress` | int | Limit to events in progress (0 or 1) |
|
||||
|
||||
### `GET /api/events/summary`
|
||||
|
||||
@@ -244,10 +245,6 @@ HTTP Live Streaming Video on Demand URL for the specified hour and camera. Can b
|
||||
|
||||
HTTP Live Streaming Video on Demand URL for the specified event. Can be viewed in an application like VLC.
|
||||
|
||||
### `GET /vod/event/<event-id>/index.m3u8`
|
||||
|
||||
HTTP Live Streaming Video on Demand URL for the specified event. Can be viewed in an application like VLC.
|
||||
|
||||
### `GET /vod/<camera>/start/<start-timestamp>/end/<end-timestamp>/index.m3u8`
|
||||
|
||||
HTTP Live Streaming Video on Demand URL for the camera with the specified time range. Can be viewed in an application like VLC.
|
||||
@@ -264,3 +261,11 @@ Get recording segment details for the given timestamp range.
|
||||
| -------- | ---- | ------------------------------------- |
|
||||
| `after` | int | Unix timestamp for beginning of range |
|
||||
| `before` | int | Unix timestamp for end of range |
|
||||
|
||||
### `GET /api/ffprobe`
|
||||
|
||||
Get ffprobe output for camera feed paths.
|
||||
|
||||
| param | Type | Description |
|
||||
| ------- | ------ | ---------------------------------- |
|
||||
| `paths` | string | `,` separated list of camera paths |
|
||||
|
||||
@@ -85,6 +85,17 @@ The integration provides:
|
||||
|
||||
This is accessible via "Media Browser" on the left menu panel in Home Assistant.
|
||||
|
||||
## Casting Clips To Media Devices
|
||||
|
||||
The integration supports casting clips and camera streams to supported media devices.
|
||||
|
||||
:::tip
|
||||
For clips to be castable to media devices, audio is required and may need to be [enabled for recordings](../troubleshooting/faqs.md#audio-in-recordings).
|
||||
|
||||
**NOTE: Even if you camera does not support audio, audio will need to be enabled for Casting to be accepted.**
|
||||
|
||||
:::
|
||||
|
||||
<a name="api"></a>
|
||||
|
||||
## Notification API
|
||||
@@ -123,7 +134,7 @@ For advanced usecases, this behavior can be changed with the [RTMP URL
|
||||
template](#options) option. When set, this string will override the default stream
|
||||
address that is derived from the default behavior described above. This option supports
|
||||
[jinja2 templates](https://jinja.palletsprojects.com/) and has the `camera` dict
|
||||
variables from [Frigate API](https://blakeblackshear.github.io/frigate/usage/api#apiconfig)
|
||||
variables from [Frigate API](api.md)
|
||||
available for the template. Note that no Home Assistant state is available to the
|
||||
template, only the camera dict from Frigate.
|
||||
|
||||
@@ -160,14 +171,14 @@ The Frigate integration seamlessly supports the use of multiple Frigate servers.
|
||||
In order for multiple Frigate instances to function correctly, the
|
||||
`topic_prefix` and `client_id` parameters must be set differently per server.
|
||||
See [MQTT
|
||||
configuration](https://blakeblackshear.github.io/frigate/configuration/index#mqtt)
|
||||
configuration](mqtt.md)
|
||||
for how to set these.
|
||||
|
||||
#### API URLs
|
||||
|
||||
When multiple Frigate instances are configured, [API](#api) URLs should include an
|
||||
identifier to tell Home Assistant which Frigate instance to refer to. The
|
||||
identifier used is the MQTT `client_id` paremeter included in the configuration,
|
||||
identifier used is the MQTT `client_id` parameter included in the configuration,
|
||||
and is used like so:
|
||||
|
||||
```
|
||||
|
||||
@@ -45,6 +45,7 @@ Message published for each changed event. The first message is published when th
|
||||
"frame_time": 1607123961.837752,
|
||||
"snapshot_time": 1607123961.837752,
|
||||
"label": "person",
|
||||
"sub_label": null,
|
||||
"top_score": 0.958984375,
|
||||
"false_positive": false,
|
||||
"start_time": 1607123955.475377,
|
||||
@@ -69,6 +70,7 @@ Message published for each changed event. The first message is published when th
|
||||
"frame_time": 1607123962.082975,
|
||||
"snapshot_time": 1607123961.837752,
|
||||
"label": "person",
|
||||
"sub_label": null,
|
||||
"top_score": 0.958984375,
|
||||
"false_positive": false,
|
||||
"start_time": 1607123955.475377,
|
||||
|
||||
48
docs/docs/integrations/plus.md
Normal file
@@ -0,0 +1,48 @@
|
||||
---
|
||||
id: plus
|
||||
title: Frigate+
|
||||
---
|
||||
|
||||
:::info
|
||||
|
||||
Frigate+ is under active development and currently only offers the ability to submit your examples with annotations. Models will be available after enough examples are submitted to train a robust model. It is free to create an account and upload your examples.
|
||||
|
||||
:::
|
||||
|
||||
Frigate+ offers models trained from scratch and specifically designed for the way Frigate NVR analyzes video footage. They offer higher accuracy with less resources. By uploading your own labeled examples, your model can be uniquely tuned for accuracy in your specific conditions. After tuning, performance is evaluated against a broad dataset and real world examples submitted by other Frigate+ users to prevent overfitting.
|
||||
|
||||
Custom models also include a more relevant set of objects for security cameras such as person, face, car, license plate, delivery truck, package, dog, cat, deer, and more. Interested in detecting an object unique to you? Upload examples to incorporate your own objects without worrying that you are reducing the accuracy of other object types in the model.
|
||||
|
||||
## Setup
|
||||
|
||||
### Create an account
|
||||
|
||||
Free accounts can be created at [https://plus.frigate.video](https://plus.frigate.video).
|
||||
|
||||
### Generate an API key
|
||||
|
||||
Once logged in, you can generate an API key for Frigate in Settings.
|
||||
|
||||

|
||||
|
||||
### Set your API key
|
||||
|
||||
In Frigate, you can set the `PLUS_API_KEY` environment variable to enable the `SEND TO FRIGATE+` buttons on the events page. You can set it in your Docker Compose file or in your Docker run command. Home Assistant Addon users can set it under Settings > Addons > Frigate NVR > Configuration > Options (be sure to toggle the "Show unused optional configuration options" switch).
|
||||
|
||||
:::caution
|
||||
|
||||
You cannot use the `environment_vars` section of your configuration file to set this environment variable.
|
||||
|
||||
:::
|
||||
|
||||
### Submit examples
|
||||
|
||||
Once your API key is configured, you can submit examples directly from the events page in Frigate using the `SEND TO FRIGATE+` button.
|
||||
|
||||

|
||||
|
||||
### Annotate and verify
|
||||
|
||||
You can view all of your submitted images at [https://plus.frigate.video](https://plus.frigate.video). Annotations can be added by clicking an image.
|
||||
|
||||

|
||||
@@ -5,7 +5,7 @@ title: Frequently Asked Questions
|
||||
|
||||
### Fatal Python error: Bus error
|
||||
|
||||
This error message is due to a shm-size that is too small. Try updating your shm-size according to [this guide](/installation#calculating-required-shm-size).
|
||||
This error message is due to a shm-size that is too small. Try updating your shm-size according to [this guide](../frigate/installation.md#calculating-required-shm-size).
|
||||
|
||||
### I am seeing a solid green image for my camera.
|
||||
|
||||
@@ -13,7 +13,7 @@ A solid green image means that frigate has not received any frames from ffmpeg.
|
||||
|
||||
### How can I get sound or audio in my recordings? {#audio-in-recordings}
|
||||
|
||||
By default, Frigate removes audio from recordings to reduce the likelihood of failing for invalid data. If you would like to include audio, you need to override the output args to remove `-an` for where you want to include audio. The recommended audio codec is `aac`. Not all audio codecs are supported by RTMP, so you may need to re-encode your audio with `-c:a aac`. The default ffmpeg args are shown [here](/configuration/index/#full-configuration-reference).
|
||||
By default, Frigate removes audio from recordings to reduce the likelihood of failing for invalid data. If you would like to include audio, you need to override the output args to remove `-an` for where you want to include audio. The recommended audio codec is `aac`. Not all audio codecs are supported by RTMP, so you may need to re-encode your audio with `-c:a aac`. The default ffmpeg args are shown [here](../configuration/index.md/#full-configuration-reference).
|
||||
|
||||
:::tip
|
||||
|
||||
@@ -47,3 +47,7 @@ These messages in the logs are expected in certain situations. Frigate checks th
|
||||
### "On connect called"
|
||||
|
||||
If you see repeated "On connect called" messages in your config, check for another instance of frigate. This happens when multiple frigate containers are trying to connect to mqtt with the same client_id.
|
||||
|
||||
### Error: Database Is Locked
|
||||
|
||||
sqlite does not work well on a network share, if the `/media` folder is mapped to a network share then [this guide](../configuration/advanced.md#database) should be used to move the database to a location on the internal drive.
|
||||
@@ -12,9 +12,15 @@ module.exports = {
|
||||
projectName: 'frigate',
|
||||
themeConfig: {
|
||||
algolia: {
|
||||
appId: 'WIURGBNBPY',
|
||||
apiKey: '81ec882db78f7fed05c51daf973f0362',
|
||||
indexName: 'frigate',
|
||||
},
|
||||
docs: {
|
||||
sidebar: {
|
||||
hideable: true,
|
||||
}
|
||||
},
|
||||
navbar: {
|
||||
title: 'Frigate',
|
||||
logo: {
|
||||
@@ -35,7 +41,7 @@ module.exports = {
|
||||
position: 'right',
|
||||
},
|
||||
{
|
||||
href: 'https://demo.frigate.video',
|
||||
href: 'http://demo.frigate.video',
|
||||
label: 'Demo',
|
||||
position: 'right',
|
||||
},
|
||||
@@ -46,8 +52,6 @@ module.exports = {
|
||||
},
|
||||
],
|
||||
},
|
||||
sidebarCollapsible: false,
|
||||
hideableSidebar: true,
|
||||
footer: {
|
||||
style: 'dark',
|
||||
links: [
|
||||
@@ -78,6 +82,7 @@ module.exports = {
|
||||
sidebarPath: require.resolve('./sidebars.js'),
|
||||
// Please change this to your repo.
|
||||
editUrl: 'https://github.com/blakeblackshear/frigate/edit/master/docs/',
|
||||
sidebarCollapsible: false
|
||||
},
|
||||
|
||||
theme: {
|
||||
|
||||
19494
docs/package-lock.json
generated
@@ -8,17 +8,20 @@
|
||||
"build": "docusaurus build",
|
||||
"swizzle": "docusaurus swizzle",
|
||||
"deploy": "docusaurus deploy",
|
||||
"clear": "docusaurus clear",
|
||||
"serve": "docusaurus serve",
|
||||
"clear": "docusaurus clear"
|
||||
"write-translations": "docusaurus write-translations",
|
||||
"write-heading-ids": "docusaurus write-heading-ids"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "^2.0.0-beta.20",
|
||||
"@docusaurus/preset-classic": "^2.0.0-beta.20",
|
||||
"@docusaurus/core": "^2.2.0",
|
||||
"@docusaurus/preset-classic": "^2.2.0",
|
||||
"@mdx-js/react": "^1.6.22",
|
||||
"clsx": "^1.1.1",
|
||||
"clsx": "^1.2.1",
|
||||
"raw-loader": "^4.0.2",
|
||||
"react": "^16.14.0",
|
||||
"react-dom": "^16.14.0"
|
||||
"prism-react-renderer": "^1.3.5",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
@@ -33,6 +36,10 @@
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^16.14.0"
|
||||
"@types/react": "^17.0.0",
|
||||
"@docusaurus/module-type-aliases": "2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.14"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
module.exports = {
|
||||
docs: {
|
||||
Frigate: ["index", "hardware", "installation"],
|
||||
Frigate: [
|
||||
"frigate/index",
|
||||
"frigate/hardware",
|
||||
"frigate/installation",
|
||||
],
|
||||
Guides: [
|
||||
"guides/camera_setup",
|
||||
"guides/getting_started",
|
||||
"guides/events_setup",
|
||||
"guides/false_positives",
|
||||
"guides/ha_notifications",
|
||||
"guides/stationary_objects",
|
||||
"guides/reverse_proxy",
|
||||
],
|
||||
Configuration: [
|
||||
"configuration/index",
|
||||
@@ -16,20 +22,27 @@ module.exports = {
|
||||
"configuration/record",
|
||||
"configuration/snapshots",
|
||||
"configuration/objects",
|
||||
"configuration/rtmp",
|
||||
"configuration/restream",
|
||||
"configuration/live",
|
||||
"configuration/zones",
|
||||
"configuration/birdseye",
|
||||
"configuration/stationary_objects",
|
||||
"configuration/advanced",
|
||||
"configuration/hardware_acceleration",
|
||||
"configuration/camera_specific",
|
||||
"configuration/ffmpeg_presets",
|
||||
],
|
||||
Integrations: [
|
||||
"integrations/plus",
|
||||
"integrations/home-assistant",
|
||||
"integrations/api",
|
||||
"integrations/mqtt",
|
||||
],
|
||||
Troubleshooting: ["faqs"],
|
||||
Development: ["contributing"],
|
||||
Troubleshooting: [
|
||||
"troubleshooting/faqs",
|
||||
],
|
||||
Development: [
|
||||
"development/contributing",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
BIN
docs/static/img/annotate.png
vendored
Normal file
|
After Width: | Height: | Size: 50 KiB |
BIN
docs/static/img/plus-api-key-min.png
vendored
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
docs/static/img/reolink-settings.png
vendored
|
Before Width: | Height: | Size: 13 KiB |
BIN
docs/static/img/send-to-plus.png
vendored
Normal file
|
After Width: | Height: | Size: 39 KiB |
110
frigate/app.py
@@ -1,37 +1,35 @@
|
||||
import json
|
||||
import logging
|
||||
import multiprocessing as mp
|
||||
from multiprocessing.queues import Queue
|
||||
from multiprocessing.synchronize import Event
|
||||
from multiprocessing.context import Process
|
||||
from multiprocessing.synchronize import Event as MpEvent
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import threading
|
||||
from logging.handlers import QueueHandler
|
||||
from typing import Optional
|
||||
from types import FrameType
|
||||
|
||||
import traceback
|
||||
import yaml
|
||||
from peewee_migrate import Router
|
||||
from playhouse.sqlite_ext import SqliteExtDatabase
|
||||
from playhouse.sqliteq import SqliteQueueDatabase
|
||||
from pydantic import ValidationError
|
||||
|
||||
from frigate.config import DetectorTypeEnum, FrigateConfig
|
||||
from frigate.comms.dispatcher import Communicator, Dispatcher
|
||||
from frigate.comms.mqtt import MqttClient
|
||||
from frigate.comms.ws import WebSocketClient
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.const import CACHE_DIR, CLIPS_DIR, RECORD_DIR
|
||||
from frigate.edgetpu import EdgeTPUProcess
|
||||
from frigate.object_detection import ObjectDetectProcess
|
||||
from frigate.events import EventCleanup, EventProcessor
|
||||
from frigate.http import create_app
|
||||
from frigate.log import log_process, root_configurer
|
||||
from frigate.models import Event, Recordings
|
||||
from frigate.mqtt import MqttSocketRelay, create_mqtt_client
|
||||
from frigate.object_processing import TrackedObjectProcessor
|
||||
from frigate.output import output_frames
|
||||
from frigate.plus import PlusApi
|
||||
from frigate.record import RecordingCleanup, RecordingMaintainer
|
||||
from frigate.restream import RestreamApi
|
||||
from frigate.stats import StatsEmitter, stats_init
|
||||
from frigate.storage import StorageMaintainer
|
||||
from frigate.version import VERSION
|
||||
from frigate.video import capture_camera, track_camera
|
||||
from frigate.watchdog import FrigateWatchdog
|
||||
@@ -42,10 +40,10 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
class FrigateApp:
|
||||
def __init__(self) -> None:
|
||||
self.stop_event: Event = mp.Event()
|
||||
self.stop_event: MpEvent = mp.Event()
|
||||
self.detection_queue: Queue = mp.Queue()
|
||||
self.detectors: dict[str, EdgeTPUProcess] = {}
|
||||
self.detection_out_events: dict[str, Event] = {}
|
||||
self.detectors: dict[str, ObjectDetectProcess] = {}
|
||||
self.detection_out_events: dict[str, MpEvent] = {}
|
||||
self.detection_shms: list[mp.shared_memory.SharedMemory] = []
|
||||
self.log_queue: Queue = mp.Queue()
|
||||
self.plus_api = PlusApi()
|
||||
@@ -165,29 +163,39 @@ class FrigateApp:
|
||||
self.db,
|
||||
self.stats_tracking,
|
||||
self.detected_frames_processor,
|
||||
self.storage_maintainer,
|
||||
self.plus_api,
|
||||
)
|
||||
|
||||
def init_mqtt(self) -> None:
|
||||
self.mqtt_client = create_mqtt_client(self.config, self.camera_metrics)
|
||||
def init_restream(self) -> None:
|
||||
self.restream = RestreamApi(self.config)
|
||||
self.restream.add_cameras()
|
||||
|
||||
def start_mqtt_relay(self) -> None:
|
||||
self.mqtt_relay = MqttSocketRelay(
|
||||
self.mqtt_client, self.config.mqtt.topic_prefix
|
||||
)
|
||||
self.mqtt_relay.start()
|
||||
def init_dispatcher(self) -> None:
|
||||
comms: list[Communicator] = []
|
||||
|
||||
if self.config.mqtt.enabled:
|
||||
comms.append(MqttClient(self.config))
|
||||
|
||||
self.ws_client = WebSocketClient(self.config)
|
||||
comms.append(self.ws_client)
|
||||
self.dispatcher = Dispatcher(self.config, self.camera_metrics, comms)
|
||||
|
||||
def start_detectors(self) -> None:
|
||||
model_path = self.config.model.path
|
||||
model_shape = (self.config.model.height, self.config.model.width)
|
||||
for name in self.config.cameras.keys():
|
||||
self.detection_out_events[name] = mp.Event()
|
||||
|
||||
try:
|
||||
largest_frame = max(
|
||||
[
|
||||
det.model.height * det.model.width * 3
|
||||
for (name, det) in self.config.detectors.items()
|
||||
]
|
||||
)
|
||||
shm_in = mp.shared_memory.SharedMemory(
|
||||
name=name,
|
||||
create=True,
|
||||
size=self.config.model.height * self.config.model.width * 3,
|
||||
size=largest_frame,
|
||||
)
|
||||
except FileExistsError:
|
||||
shm_in = mp.shared_memory.SharedMemory(name=name)
|
||||
@@ -202,33 +210,18 @@ class FrigateApp:
|
||||
self.detection_shms.append(shm_in)
|
||||
self.detection_shms.append(shm_out)
|
||||
|
||||
for name, detector in self.config.detectors.items():
|
||||
if detector.type == DetectorTypeEnum.cpu:
|
||||
self.detectors[name] = EdgeTPUProcess(
|
||||
name,
|
||||
self.detection_queue,
|
||||
self.detection_out_events,
|
||||
model_path,
|
||||
model_shape,
|
||||
"cpu",
|
||||
detector.num_threads,
|
||||
)
|
||||
if detector.type == DetectorTypeEnum.edgetpu:
|
||||
self.detectors[name] = EdgeTPUProcess(
|
||||
name,
|
||||
self.detection_queue,
|
||||
self.detection_out_events,
|
||||
model_path,
|
||||
model_shape,
|
||||
detector.device,
|
||||
detector.num_threads,
|
||||
)
|
||||
for name, detector_config in self.config.detectors.items():
|
||||
self.detectors[name] = ObjectDetectProcess(
|
||||
name,
|
||||
self.detection_queue,
|
||||
self.detection_out_events,
|
||||
detector_config,
|
||||
)
|
||||
|
||||
def start_detected_frames_processor(self) -> None:
|
||||
self.detected_frames_processor = TrackedObjectProcessor(
|
||||
self.config,
|
||||
self.mqtt_client,
|
||||
self.config.mqtt.topic_prefix,
|
||||
self.dispatcher,
|
||||
self.detected_frames_queue,
|
||||
self.event_queue,
|
||||
self.event_processed_queue,
|
||||
@@ -253,15 +246,18 @@ class FrigateApp:
|
||||
logger.info(f"Output process started: {output_processor.pid}")
|
||||
|
||||
def start_camera_processors(self) -> None:
|
||||
model_shape = (self.config.model.height, self.config.model.width)
|
||||
for name, config in self.config.cameras.items():
|
||||
if not self.config.cameras[name].enabled:
|
||||
logger.info(f"Camera processor not started for disabled camera {name}")
|
||||
continue
|
||||
|
||||
camera_process = mp.Process(
|
||||
target=track_camera,
|
||||
name=f"camera_processor:{name}",
|
||||
args=(
|
||||
name,
|
||||
config,
|
||||
model_shape,
|
||||
self.config.model,
|
||||
self.config.model.merged_labelmap,
|
||||
self.detection_queue,
|
||||
self.detection_out_events[name],
|
||||
@@ -276,6 +272,10 @@ class FrigateApp:
|
||||
|
||||
def start_camera_capture_processes(self) -> None:
|
||||
for name, config in self.config.cameras.items():
|
||||
if not self.config.cameras[name].enabled:
|
||||
logger.info(f"Capture process not started for disabled camera {name}")
|
||||
continue
|
||||
|
||||
capture_process = mp.Process(
|
||||
target=capture_camera,
|
||||
name=f"camera_capture:{name}",
|
||||
@@ -310,12 +310,15 @@ class FrigateApp:
|
||||
self.recording_cleanup = RecordingCleanup(self.config, self.stop_event)
|
||||
self.recording_cleanup.start()
|
||||
|
||||
def start_storage_maintainer(self) -> None:
|
||||
self.storage_maintainer = StorageMaintainer(self.config, self.stop_event)
|
||||
self.storage_maintainer.start()
|
||||
|
||||
def start_stats_emitter(self) -> None:
|
||||
self.stats_emitter = StatsEmitter(
|
||||
self.config,
|
||||
self.stats_tracking,
|
||||
self.mqtt_client,
|
||||
self.config.mqtt.topic_prefix,
|
||||
self.dispatcher,
|
||||
self.stop_event,
|
||||
)
|
||||
self.stats_emitter.start()
|
||||
@@ -352,19 +355,20 @@ class FrigateApp:
|
||||
self.set_log_levels()
|
||||
self.init_queues()
|
||||
self.init_database()
|
||||
self.init_mqtt()
|
||||
self.init_dispatcher()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.log_process.terminate()
|
||||
sys.exit(1)
|
||||
self.init_restream()
|
||||
self.start_detectors()
|
||||
self.start_video_output_processor()
|
||||
self.start_detected_frames_processor()
|
||||
self.start_camera_processors()
|
||||
self.start_camera_capture_processes()
|
||||
self.start_storage_maintainer()
|
||||
self.init_stats()
|
||||
self.init_web_server()
|
||||
self.start_mqtt_relay()
|
||||
self.start_event_processor()
|
||||
self.start_event_cleanup()
|
||||
self.start_recording_maintainer()
|
||||
@@ -390,7 +394,7 @@ class FrigateApp:
|
||||
logger.info(f"Stopping...")
|
||||
self.stop_event.set()
|
||||
|
||||
self.mqtt_relay.stop()
|
||||
self.ws_client.stop()
|
||||
self.detected_frames_processor.join()
|
||||
self.event_processor.join()
|
||||
self.event_cleanup.join()
|
||||
|
||||
197
frigate/comms/dispatcher.py
Normal file
@@ -0,0 +1,197 @@
|
||||
"""Handle communication between frigate and other applications."""
|
||||
|
||||
import logging
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.types import CameraMetricsTypes
|
||||
from frigate.util import restart_frigate
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Communicator(ABC):
|
||||
"""pub/sub model via specific protocol."""
|
||||
|
||||
@abstractmethod
|
||||
def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
|
||||
"""Send data via specific protocol."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def subscribe(self, receiver: Callable) -> None:
|
||||
"""Pass receiver so communicators can pass commands."""
|
||||
pass
|
||||
|
||||
|
||||
class Dispatcher:
|
||||
"""Handle communication between frigate and communicators."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: FrigateConfig,
|
||||
camera_metrics: dict[str, CameraMetricsTypes],
|
||||
communicators: list[Communicator],
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.camera_metrics = camera_metrics
|
||||
self.comms = communicators
|
||||
|
||||
for comm in self.comms:
|
||||
comm.subscribe(self._receive)
|
||||
|
||||
self._camera_settings_handlers: dict[str, Callable] = {
|
||||
"detect": self._on_detect_command,
|
||||
"improve_contrast": self._on_motion_improve_contrast_command,
|
||||
"motion": self._on_motion_command,
|
||||
"motion_contour_area": self._on_motion_contour_area_command,
|
||||
"motion_threshold": self._on_motion_threshold_command,
|
||||
"recordings": self._on_recordings_command,
|
||||
"snapshots": self._on_snapshots_command,
|
||||
}
|
||||
|
||||
def _receive(self, topic: str, payload: str) -> None:
|
||||
"""Handle receiving of payload from communicators."""
|
||||
if topic.endswith("set"):
|
||||
try:
|
||||
camera_name = topic.split("/")[-3]
|
||||
command = topic.split("/")[-2]
|
||||
self._camera_settings_handlers[command](camera_name, payload)
|
||||
except Exception as e:
|
||||
logger.error(f"Received invalid set command: {topic}")
|
||||
return
|
||||
elif topic == "restart":
|
||||
restart_frigate()
|
||||
|
||||
def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
|
||||
"""Handle publishing to communicators."""
|
||||
for comm in self.comms:
|
||||
comm.publish(topic, payload, retain)
|
||||
|
||||
def _on_detect_command(self, camera_name: str, payload: str) -> None:
|
||||
"""Callback for detect topic."""
|
||||
detect_settings = self.config.cameras[camera_name].detect
|
||||
|
||||
if payload == "ON":
|
||||
if not self.camera_metrics[camera_name]["detection_enabled"].value:
|
||||
logger.info(f"Turning on detection for {camera_name}")
|
||||
self.camera_metrics[camera_name]["detection_enabled"].value = True
|
||||
detect_settings.enabled = True
|
||||
|
||||
if not self.camera_metrics[camera_name]["motion_enabled"].value:
|
||||
logger.info(
|
||||
f"Turning on motion for {camera_name} due to detection being enabled."
|
||||
)
|
||||
self.camera_metrics[camera_name]["motion_enabled"].value = True
|
||||
self.publish(f"{camera_name}/motion/state", payload, retain=True)
|
||||
elif payload == "OFF":
|
||||
if self.camera_metrics[camera_name]["detection_enabled"].value:
|
||||
logger.info(f"Turning off detection for {camera_name}")
|
||||
self.camera_metrics[camera_name]["detection_enabled"].value = False
|
||||
detect_settings.enabled = False
|
||||
|
||||
self.publish(f"{camera_name}/detect/state", payload, retain=True)
|
||||
|
||||
def _on_motion_command(self, camera_name: str, payload: str) -> None:
|
||||
"""Callback for motion topic."""
|
||||
if payload == "ON":
|
||||
if not self.camera_metrics[camera_name]["motion_enabled"].value:
|
||||
logger.info(f"Turning on motion for {camera_name}")
|
||||
self.camera_metrics[camera_name]["motion_enabled"].value = True
|
||||
elif payload == "OFF":
|
||||
if self.camera_metrics[camera_name]["detection_enabled"].value:
|
||||
logger.error(
|
||||
f"Turning off motion is not allowed when detection is enabled."
|
||||
)
|
||||
return
|
||||
|
||||
if self.camera_metrics[camera_name]["motion_enabled"].value:
|
||||
logger.info(f"Turning off motion for {camera_name}")
|
||||
self.camera_metrics[camera_name]["motion_enabled"].value = False
|
||||
|
||||
self.publish(f"{camera_name}/motion/state", payload, retain=True)
|
||||
|
||||
def _on_motion_improve_contrast_command(
|
||||
self, camera_name: str, payload: str
|
||||
) -> None:
|
||||
"""Callback for improve_contrast topic."""
|
||||
motion_settings = self.config.cameras[camera_name].motion
|
||||
|
||||
if payload == "ON":
|
||||
if not self.camera_metrics[camera_name]["improve_contrast_enabled"].value:
|
||||
logger.info(f"Turning on improve contrast for {camera_name}")
|
||||
self.camera_metrics[camera_name][
|
||||
"improve_contrast_enabled"
|
||||
].value = True
|
||||
motion_settings.improve_contrast = True # type: ignore[union-attr]
|
||||
elif payload == "OFF":
|
||||
if self.camera_metrics[camera_name]["improve_contrast_enabled"].value:
|
||||
logger.info(f"Turning off improve contrast for {camera_name}")
|
||||
self.camera_metrics[camera_name][
|
||||
"improve_contrast_enabled"
|
||||
].value = False
|
||||
motion_settings.improve_contrast = False # type: ignore[union-attr]
|
||||
|
||||
self.publish(f"{camera_name}/improve_contrast/state", payload, retain=True)
|
||||
|
||||
def _on_motion_contour_area_command(self, camera_name: str, payload: int) -> None:
|
||||
"""Callback for motion contour topic."""
|
||||
try:
|
||||
payload = int(payload)
|
||||
except ValueError:
|
||||
f"Received unsupported value for motion contour area: {payload}"
|
||||
return
|
||||
|
||||
motion_settings = self.config.cameras[camera_name].motion
|
||||
logger.info(f"Setting motion contour area for {camera_name}: {payload}")
|
||||
self.camera_metrics[camera_name]["motion_contour_area"].value = payload
|
||||
motion_settings.contour_area = payload # type: ignore[union-attr]
|
||||
self.publish(f"{camera_name}/motion_contour_area/state", payload, retain=True)
|
||||
|
||||
def _on_motion_threshold_command(self, camera_name: str, payload: int) -> None:
|
||||
"""Callback for motion threshold topic."""
|
||||
try:
|
||||
payload = int(payload)
|
||||
except ValueError:
|
||||
f"Received unsupported value for motion threshold: {payload}"
|
||||
return
|
||||
|
||||
motion_settings = self.config.cameras[camera_name].motion
|
||||
logger.info(f"Setting motion threshold for {camera_name}: {payload}")
|
||||
self.camera_metrics[camera_name]["motion_threshold"].value = payload
|
||||
motion_settings.threshold = payload # type: ignore[union-attr]
|
||||
self.publish(f"{camera_name}/motion_threshold/state", payload, retain=True)
|
||||
|
||||
def _on_recordings_command(self, camera_name: str, payload: str) -> None:
|
||||
"""Callback for recordings topic."""
|
||||
record_settings = self.config.cameras[camera_name].record
|
||||
|
||||
if payload == "ON":
|
||||
if not record_settings.enabled:
|
||||
logger.info(f"Turning on recordings for {camera_name}")
|
||||
record_settings.enabled = True
|
||||
elif payload == "OFF":
|
||||
if record_settings.enabled:
|
||||
logger.info(f"Turning off recordings for {camera_name}")
|
||||
record_settings.enabled = False
|
||||
|
||||
self.publish(f"{camera_name}/recordings/state", payload, retain=True)
|
||||
|
||||
def _on_snapshots_command(self, camera_name: str, payload: str) -> None:
|
||||
"""Callback for snapshots topic."""
|
||||
snapshots_settings = self.config.cameras[camera_name].snapshots
|
||||
|
||||
if payload == "ON":
|
||||
if not snapshots_settings.enabled:
|
||||
logger.info(f"Turning on snapshots for {camera_name}")
|
||||
snapshots_settings.enabled = True
|
||||
elif payload == "OFF":
|
||||
if snapshots_settings.enabled:
|
||||
logger.info(f"Turning off snapshots for {camera_name}")
|
||||
snapshots_settings.enabled = False
|
||||
|
||||
self.publish(f"{camera_name}/snapshots/state", payload, retain=True)
|
||||
201
frigate/comms/mqtt.py
Normal file
@@ -0,0 +1,201 @@
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from frigate.comms.dispatcher import Communicator
|
||||
from frigate.config import FrigateConfig
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MqttClient(Communicator): # type: ignore[misc]
|
||||
"""Frigate wrapper for mqtt client."""
|
||||
|
||||
def __init__(self, config: FrigateConfig) -> None:
|
||||
self.config = config
|
||||
self.mqtt_config = config.mqtt
|
||||
self.connected: bool = False
|
||||
|
||||
def subscribe(self, receiver: Callable) -> None:
|
||||
"""Wrapper for allowing dispatcher to subscribe."""
|
||||
self._dispatcher = receiver
|
||||
self._start()
|
||||
|
||||
def publish(self, topic: str, payload: Any, retain: bool = False) -> None:
|
||||
"""Wrapper for publishing when client is in valid state."""
|
||||
if not self.connected:
|
||||
logger.error(f"Unable to publish to {topic}: client is not connected")
|
||||
return
|
||||
|
||||
self.client.publish(
|
||||
f"{self.mqtt_config.topic_prefix}/{topic}", payload, retain=retain
|
||||
)
|
||||
|
||||
def _set_initial_topics(self) -> None:
|
||||
"""Set initial state topics."""
|
||||
for camera_name, camera in self.config.cameras.items():
|
||||
self.publish(
|
||||
f"{camera_name}/recordings/state",
|
||||
"ON" if camera.record.enabled else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/snapshots/state",
|
||||
"ON" if camera.snapshots.enabled else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/detect/state",
|
||||
"ON" if camera.detect.enabled else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/motion/state",
|
||||
"ON",
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/improve_contrast/state",
|
||||
"ON" if camera.motion.improve_contrast else "OFF", # type: ignore[union-attr]
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/motion_threshold/state",
|
||||
camera.motion.threshold, # type: ignore[union-attr]
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/motion_contour_area/state",
|
||||
camera.motion.contour_area, # type: ignore[union-attr]
|
||||
retain=True,
|
||||
)
|
||||
self.publish(
|
||||
f"{camera_name}/motion",
|
||||
"OFF",
|
||||
retain=False,
|
||||
)
|
||||
|
||||
self.publish("available", "online", retain=True)
|
||||
|
||||
def on_mqtt_command(
|
||||
self, client: mqtt.Client, userdata: Any, message: mqtt.MQTTMessage
|
||||
) -> None:
|
||||
self._dispatcher(
|
||||
message.topic.replace(f"{self.mqtt_config.topic_prefix}/", "", 1),
|
||||
message.payload.decode(),
|
||||
)
|
||||
|
||||
def _on_connect(
|
||||
self,
|
||||
client: mqtt.Client,
|
||||
userdata: Any,
|
||||
flags: Any,
|
||||
rc: mqtt.ReasonCodes,
|
||||
) -> None:
|
||||
"""Mqtt connection callback."""
|
||||
threading.current_thread().name = "mqtt"
|
||||
if rc != 0:
|
||||
if rc == 3:
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: MQTT Server unavailable"
|
||||
)
|
||||
elif rc == 4:
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: MQTT Bad username or password"
|
||||
)
|
||||
elif rc == 5:
|
||||
logger.error("Unable to connect to MQTT server: MQTT Not authorized")
|
||||
else:
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: Connection refused. Error code: "
|
||||
+ str(rc)
|
||||
)
|
||||
|
||||
self.connected = True
|
||||
logger.debug("MQTT connected")
|
||||
client.subscribe(f"{self.mqtt_config.topic_prefix}/#")
|
||||
self._set_initial_topics()
|
||||
|
||||
def _on_disconnect(
|
||||
self, client: mqtt.Client, userdata: Any, flags: Any, rc: mqtt
|
||||
) -> None:
|
||||
"""Mqtt disconnection callback."""
|
||||
self.connected = False
|
||||
logger.error("MQTT disconnected")
|
||||
|
||||
def _start(self) -> None:
|
||||
"""Start mqtt client."""
|
||||
self.client = mqtt.Client(client_id=self.mqtt_config.client_id)
|
||||
self.client.on_connect = self._on_connect
|
||||
self.client.will_set(
|
||||
self.mqtt_config.topic_prefix + "/available",
|
||||
payload="offline",
|
||||
qos=1,
|
||||
retain=True,
|
||||
)
|
||||
|
||||
# register callbacks
|
||||
for name in self.config.cameras.keys():
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/recordings/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/snapshots/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/detect/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/motion/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/improve_contrast/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/motion_threshold/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/{name}/motion_contour_area/set",
|
||||
self.on_mqtt_command,
|
||||
)
|
||||
|
||||
self.client.message_callback_add(
|
||||
f"{self.mqtt_config.topic_prefix}/restart", self.on_mqtt_command
|
||||
)
|
||||
|
||||
if not self.mqtt_config.tls_ca_certs is None:
|
||||
if (
|
||||
not self.mqtt_config.tls_client_cert is None
|
||||
and not self.mqtt_config.tls_client_key is None
|
||||
):
|
||||
self.client.tls_set(
|
||||
self.mqtt_config.tls_ca_certs,
|
||||
self.mqtt_config.tls_client_cert,
|
||||
self.mqtt_config.tls_client_key,
|
||||
)
|
||||
else:
|
||||
self.client.tls_set(self.mqtt_config.tls_ca_certs)
|
||||
if not self.mqtt_config.tls_insecure is None:
|
||||
self.client.tls_insecure_set(self.mqtt_config.tls_insecure)
|
||||
if not self.mqtt_config.user is None:
|
||||
self.client.username_pw_set(
|
||||
self.mqtt_config.user, password=self.mqtt_config.password
|
||||
)
|
||||
try:
|
||||
# https://stackoverflow.com/a/55390477
|
||||
# with connect_async, retries are handled automatically
|
||||
self.client.connect_async(self.mqtt_config.host, self.mqtt_config.port, 60)
|
||||
self.client.loop_start()
|
||||
except Exception as e:
|
||||
logger.error(f"Unable to connect to MQTT server: {e}")
|
||||
return
|
||||
97
frigate/comms/ws.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""Websocket communicator."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from typing import Callable
|
||||
|
||||
from wsgiref.simple_server import make_server
|
||||
from ws4py.server.wsgirefserver import (
|
||||
WebSocketWSGIHandler,
|
||||
WebSocketWSGIRequestHandler,
|
||||
WSGIServer,
|
||||
)
|
||||
from ws4py.server.wsgiutils import WebSocketWSGIApplication
|
||||
from ws4py.websocket import WebSocket
|
||||
|
||||
from frigate.comms.dispatcher import Communicator
|
||||
from frigate.config import FrigateConfig
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class WebSocketClient(Communicator): # type: ignore[misc]
|
||||
"""Frigate wrapper for ws client."""
|
||||
|
||||
def __init__(self, config: FrigateConfig) -> None:
|
||||
self.config = config
|
||||
|
||||
def subscribe(self, receiver: Callable) -> None:
|
||||
self._dispatcher = receiver
|
||||
self.start()
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the websocket client."""
|
||||
|
||||
class _WebSocketHandler(WebSocket): # type: ignore[misc]
|
||||
receiver = self._dispatcher
|
||||
|
||||
def received_message(self, message: WebSocket.received_message) -> None:
|
||||
try:
|
||||
json_message = json.loads(message.data.decode("utf-8"))
|
||||
json_message = {
|
||||
"topic": json_message.get("topic"),
|
||||
"payload": json_message.get("payload"),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"Unable to parse websocket message as valid json: {message.data.decode('utf-8')}"
|
||||
)
|
||||
return
|
||||
|
||||
logger.debug(
|
||||
f"Publishing mqtt message from websockets at {json_message['topic']}."
|
||||
)
|
||||
self.receiver(
|
||||
json_message["topic"],
|
||||
json_message["payload"],
|
||||
)
|
||||
|
||||
# start a websocket server on 5002
|
||||
WebSocketWSGIHandler.http_version = "1.1"
|
||||
self.websocket_server = make_server(
|
||||
"127.0.0.1",
|
||||
5002,
|
||||
server_class=WSGIServer,
|
||||
handler_class=WebSocketWSGIRequestHandler,
|
||||
app=WebSocketWSGIApplication(handler_cls=_WebSocketHandler),
|
||||
)
|
||||
self.websocket_server.initialize_websockets_manager()
|
||||
self.websocket_thread = threading.Thread(
|
||||
target=self.websocket_server.serve_forever
|
||||
)
|
||||
self.websocket_thread.start()
|
||||
|
||||
def publish(self, topic: str, payload: str, _: bool) -> None:
|
||||
try:
|
||||
ws_message = json.dumps(
|
||||
{
|
||||
"topic": topic,
|
||||
"payload": payload,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
# if the payload can't be decoded don't relay to clients
|
||||
logger.debug(f"payload for {topic} wasn't text. Skipping...")
|
||||
return
|
||||
|
||||
self.websocket_server.manager.broadcast(ws_message)
|
||||
|
||||
def stop(self) -> None:
|
||||
self.websocket_server.manager.close_all()
|
||||
self.websocket_server.manager.stop()
|
||||
self.websocket_server.manager.join()
|
||||
self.websocket_server.shutdown()
|
||||
self.websocket_thread.join()
|
||||
@@ -9,11 +9,38 @@ from typing import Dict, List, Optional, Tuple, Union
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import yaml
|
||||
from pydantic import BaseModel, Extra, Field, validator
|
||||
from pydantic import BaseModel, Extra, Field, validator, parse_obj_as
|
||||
from pydantic.fields import PrivateAttr
|
||||
|
||||
from frigate.const import BASE_DIR, CACHE_DIR, YAML_EXT
|
||||
from frigate.util import create_mask, deep_merge, load_labels
|
||||
from frigate.const import (
|
||||
BASE_DIR,
|
||||
CACHE_DIR,
|
||||
REGEX_CAMERA_NAME,
|
||||
YAML_EXT,
|
||||
)
|
||||
from frigate.util import (
|
||||
create_mask,
|
||||
deep_merge,
|
||||
get_ffmpeg_arg_list,
|
||||
escape_special_characters,
|
||||
load_config_with_no_duplicates,
|
||||
load_labels,
|
||||
)
|
||||
from frigate.ffmpeg_presets import (
|
||||
parse_preset_hardware_acceleration_decode,
|
||||
parse_preset_hardware_acceleration_scale,
|
||||
parse_preset_input,
|
||||
parse_preset_output_record,
|
||||
parse_preset_output_rtmp,
|
||||
)
|
||||
from frigate.detectors import (
|
||||
PixelFormatEnum,
|
||||
InputTensorEnum,
|
||||
ModelConfig,
|
||||
DetectorConfig,
|
||||
)
|
||||
from frigate.version import VERSION
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -33,23 +60,13 @@ class FrigateBaseModel(BaseModel):
|
||||
extra = Extra.forbid
|
||||
|
||||
|
||||
class DetectorTypeEnum(str, Enum):
|
||||
edgetpu = "edgetpu"
|
||||
cpu = "cpu"
|
||||
|
||||
|
||||
class DetectorConfig(FrigateBaseModel):
|
||||
type: DetectorTypeEnum = Field(default=DetectorTypeEnum.cpu, title="Detector Type")
|
||||
device: str = Field(default="usb", title="Device Type")
|
||||
num_threads: int = Field(default=3, title="Number of detection threads")
|
||||
|
||||
|
||||
class UIConfig(FrigateBaseModel):
|
||||
use_experimental: bool = Field(default=False, title="Experimental UI")
|
||||
|
||||
|
||||
class MqttConfig(FrigateBaseModel):
|
||||
host: str = Field(title="MQTT Host")
|
||||
enabled: bool = Field(title="Enable MQTT Communication.", default=True)
|
||||
host: str = Field(default="", title="MQTT Host")
|
||||
port: int = Field(default=1883, title="MQTT Port")
|
||||
topic_prefix: str = Field(default="frigate", title="MQTT Topic Prefix")
|
||||
client_id: str = Field(default="frigate", title="MQTT Client ID")
|
||||
@@ -339,35 +356,10 @@ class BirdseyeCameraConfig(BaseModel):
|
||||
|
||||
|
||||
FFMPEG_GLOBAL_ARGS_DEFAULT = ["-hide_banner", "-loglevel", "warning"]
|
||||
FFMPEG_INPUT_ARGS_DEFAULT = [
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-rtsp_transport",
|
||||
"tcp",
|
||||
"-timeout",
|
||||
"5000000",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
]
|
||||
FFMPEG_INPUT_ARGS_DEFAULT = "preset-rtsp-generic"
|
||||
DETECT_FFMPEG_OUTPUT_ARGS_DEFAULT = ["-f", "rawvideo", "-pix_fmt", "yuv420p"]
|
||||
RTMP_FFMPEG_OUTPUT_ARGS_DEFAULT = ["-c", "copy", "-f", "flv"]
|
||||
RECORD_FFMPEG_OUTPUT_ARGS_DEFAULT = [
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
"10",
|
||||
"-segment_format",
|
||||
"mp4",
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
"-strftime",
|
||||
"1",
|
||||
"-c",
|
||||
"copy",
|
||||
"-an",
|
||||
]
|
||||
RTMP_FFMPEG_OUTPUT_ARGS_DEFAULT = "preset-rtmp-generic"
|
||||
RECORD_FFMPEG_OUTPUT_ARGS_DEFAULT = "preset-record-generic"
|
||||
|
||||
|
||||
class FfmpegOutputArgsConfig(FrigateBaseModel):
|
||||
@@ -403,6 +395,7 @@ class FfmpegConfig(FrigateBaseModel):
|
||||
|
||||
class CameraRoleEnum(str, Enum):
|
||||
record = "record"
|
||||
restream = "restream"
|
||||
rtmp = "rtmp"
|
||||
detect = "detect"
|
||||
|
||||
@@ -513,12 +506,32 @@ class CameraMqttConfig(FrigateBaseModel):
|
||||
|
||||
|
||||
class RtmpConfig(FrigateBaseModel):
|
||||
enabled: bool = Field(default=True, title="RTMP restreaming enabled.")
|
||||
enabled: bool = Field(default=False, title="RTMP restreaming enabled.")
|
||||
|
||||
|
||||
class CameraLiveConfig(FrigateBaseModel):
|
||||
height: int = Field(default=720, title="Live camera view height")
|
||||
quality: int = Field(default=8, ge=1, le=31, title="Live camera view quality")
|
||||
class JsmpegStreamConfig(FrigateBaseModel):
|
||||
height: int = Field(default=720, title="Live camera view height.")
|
||||
quality: int = Field(default=8, ge=1, le=31, title="Live camera view quality.")
|
||||
|
||||
|
||||
class RestreamCodecEnum(str, Enum):
|
||||
copy = "copy"
|
||||
h264 = "h264"
|
||||
h265 = "h265"
|
||||
|
||||
|
||||
class RestreamConfig(FrigateBaseModel):
|
||||
enabled: bool = Field(default=True, title="Restreaming enabled.")
|
||||
video_encoding: RestreamCodecEnum = Field(
|
||||
default=RestreamCodecEnum.copy, title="Method for encoding the restream."
|
||||
)
|
||||
force_audio: bool = Field(
|
||||
default=True, title="Force audio compatibility with the browser."
|
||||
)
|
||||
birdseye: bool = Field(default=False, title="Restream the birdseye feed via RTSP.")
|
||||
jsmpeg: JsmpegStreamConfig = Field(
|
||||
default_factory=JsmpegStreamConfig, title="Jsmpeg Stream Configuration."
|
||||
)
|
||||
|
||||
|
||||
class CameraUiConfig(FrigateBaseModel):
|
||||
@@ -529,7 +542,8 @@ class CameraUiConfig(FrigateBaseModel):
|
||||
|
||||
|
||||
class CameraConfig(FrigateBaseModel):
|
||||
name: Optional[str] = Field(title="Camera name.", regex="^[a-zA-Z0-9_-]+$")
|
||||
name: Optional[str] = Field(title="Camera name.", regex=REGEX_CAMERA_NAME)
|
||||
enabled: bool = Field(default=True, title="Enable camera.")
|
||||
ffmpeg: CameraFfmpegConfig = Field(title="FFmpeg configuration for the camera.")
|
||||
best_image_timeout: int = Field(
|
||||
default=60,
|
||||
@@ -544,8 +558,8 @@ class CameraConfig(FrigateBaseModel):
|
||||
rtmp: RtmpConfig = Field(
|
||||
default_factory=RtmpConfig, title="RTMP restreaming configuration."
|
||||
)
|
||||
live: CameraLiveConfig = Field(
|
||||
default_factory=CameraLiveConfig, title="Live playback settings."
|
||||
restream: RestreamConfig = Field(
|
||||
default_factory=RestreamConfig, title="Restreaming configuration."
|
||||
)
|
||||
snapshots: SnapshotsConfig = Field(
|
||||
default_factory=SnapshotsConfig, title="Snapshot configuration."
|
||||
@@ -582,7 +596,16 @@ class CameraConfig(FrigateBaseModel):
|
||||
|
||||
# add roles to the input if there is only one
|
||||
if len(config["ffmpeg"]["inputs"]) == 1:
|
||||
config["ffmpeg"]["inputs"][0]["roles"] = ["record", "rtmp", "detect"]
|
||||
has_rtmp = "rtmp" in config["ffmpeg"]["inputs"][0].get("roles", [])
|
||||
|
||||
config["ffmpeg"]["inputs"][0]["roles"] = [
|
||||
"record",
|
||||
"detect",
|
||||
"restream",
|
||||
]
|
||||
|
||||
if has_rtmp:
|
||||
config["ffmpeg"]["inputs"][0]["roles"].append("rtmp")
|
||||
|
||||
super().__init__(**config)
|
||||
|
||||
@@ -613,36 +636,29 @@ class CameraConfig(FrigateBaseModel):
|
||||
def _get_ffmpeg_cmd(self, ffmpeg_input: CameraInput):
|
||||
ffmpeg_output_args = []
|
||||
if "detect" in ffmpeg_input.roles:
|
||||
detect_args = (
|
||||
self.ffmpeg.output_args.detect
|
||||
if isinstance(self.ffmpeg.output_args.detect, list)
|
||||
else self.ffmpeg.output_args.detect.split(" ")
|
||||
)
|
||||
ffmpeg_output_args = (
|
||||
[
|
||||
"-r",
|
||||
str(self.detect.fps),
|
||||
"-s",
|
||||
f"{self.detect.width}x{self.detect.height}",
|
||||
]
|
||||
+ detect_args
|
||||
+ ffmpeg_output_args
|
||||
+ ["pipe:"]
|
||||
detect_args = get_ffmpeg_arg_list(self.ffmpeg.output_args.detect)
|
||||
scale_detect_args = parse_preset_hardware_acceleration_scale(
|
||||
ffmpeg_input.hwaccel_args or self.ffmpeg.hwaccel_args,
|
||||
detect_args,
|
||||
self.detect.fps,
|
||||
self.detect.width,
|
||||
self.detect.height,
|
||||
)
|
||||
|
||||
ffmpeg_output_args = scale_detect_args + ffmpeg_output_args + ["pipe:"]
|
||||
if "rtmp" in ffmpeg_input.roles and self.rtmp.enabled:
|
||||
rtmp_args = (
|
||||
self.ffmpeg.output_args.rtmp
|
||||
if isinstance(self.ffmpeg.output_args.rtmp, list)
|
||||
else self.ffmpeg.output_args.rtmp.split(" ")
|
||||
rtmp_args = get_ffmpeg_arg_list(
|
||||
parse_preset_output_rtmp(self.ffmpeg.output_args.rtmp)
|
||||
or self.ffmpeg.output_args.rtmp
|
||||
)
|
||||
|
||||
ffmpeg_output_args = (
|
||||
rtmp_args + [f"rtmp://127.0.0.1/live/{self.name}"] + ffmpeg_output_args
|
||||
)
|
||||
if "record" in ffmpeg_input.roles and self.record.enabled:
|
||||
record_args = (
|
||||
self.ffmpeg.output_args.record
|
||||
if isinstance(self.ffmpeg.output_args.record, list)
|
||||
else self.ffmpeg.output_args.record.split(" ")
|
||||
record_args = get_ffmpeg_arg_list(
|
||||
parse_preset_output_record(self.ffmpeg.output_args.record)
|
||||
or self.ffmpeg.output_args.record
|
||||
)
|
||||
|
||||
ffmpeg_output_args = (
|
||||
@@ -655,18 +671,20 @@ class CameraConfig(FrigateBaseModel):
|
||||
if len(ffmpeg_output_args) == 0:
|
||||
return None
|
||||
|
||||
global_args = ffmpeg_input.global_args or self.ffmpeg.global_args
|
||||
hwaccel_args = ffmpeg_input.hwaccel_args or self.ffmpeg.hwaccel_args
|
||||
input_args = ffmpeg_input.input_args or self.ffmpeg.input_args
|
||||
|
||||
global_args = (
|
||||
global_args if isinstance(global_args, list) else global_args.split(" ")
|
||||
global_args = get_ffmpeg_arg_list(
|
||||
ffmpeg_input.global_args or self.ffmpeg.global_args
|
||||
)
|
||||
hwaccel_args = (
|
||||
hwaccel_args if isinstance(hwaccel_args, list) else hwaccel_args.split(" ")
|
||||
hwaccel_args = get_ffmpeg_arg_list(
|
||||
parse_preset_hardware_acceleration_decode(ffmpeg_input.hwaccel_args)
|
||||
or ffmpeg_input.hwaccel_args
|
||||
or parse_preset_hardware_acceleration_decode(self.ffmpeg.hwaccel_args)
|
||||
or self.ffmpeg.hwaccel_args
|
||||
)
|
||||
input_args = (
|
||||
input_args if isinstance(input_args, list) else input_args.split(" ")
|
||||
input_args = get_ffmpeg_arg_list(
|
||||
parse_preset_input(ffmpeg_input.input_args, self.detect.fps)
|
||||
or ffmpeg_input.input_args
|
||||
or parse_preset_input(self.ffmpeg.input_args, self.detect.fps)
|
||||
or self.ffmpeg.input_args
|
||||
)
|
||||
|
||||
cmd = (
|
||||
@@ -674,7 +692,7 @@ class CameraConfig(FrigateBaseModel):
|
||||
+ global_args
|
||||
+ hwaccel_args
|
||||
+ input_args
|
||||
+ ["-i", ffmpeg_input.path]
|
||||
+ ["-i", escape_special_characters(ffmpeg_input.path)]
|
||||
+ ffmpeg_output_args
|
||||
)
|
||||
|
||||
@@ -687,40 +705,6 @@ class DatabaseConfig(FrigateBaseModel):
|
||||
)
|
||||
|
||||
|
||||
class ModelConfig(FrigateBaseModel):
|
||||
path: Optional[str] = Field(title="Custom Object detection model path.")
|
||||
labelmap_path: Optional[str] = Field(title="Label map for custom object detector.")
|
||||
width: int = Field(default=320, title="Object detection model input width.")
|
||||
height: int = Field(default=320, title="Object detection model input height.")
|
||||
labelmap: Dict[int, str] = Field(
|
||||
default_factory=dict, title="Labelmap customization."
|
||||
)
|
||||
_merged_labelmap: Optional[Dict[int, str]] = PrivateAttr()
|
||||
_colormap: Dict[int, Tuple[int, int, int]] = PrivateAttr()
|
||||
|
||||
@property
|
||||
def merged_labelmap(self) -> Dict[int, str]:
|
||||
return self._merged_labelmap
|
||||
|
||||
@property
|
||||
def colormap(self) -> Dict[int, Tuple[int, int, int]]:
|
||||
return self._colormap
|
||||
|
||||
def __init__(self, **config):
|
||||
super().__init__(**config)
|
||||
|
||||
self._merged_labelmap = {
|
||||
**load_labels(config.get("labelmap_path", "/labelmap.txt")),
|
||||
**config.get("labelmap", {}),
|
||||
}
|
||||
|
||||
cmap = plt.cm.get_cmap("tab10", len(self._merged_labelmap.keys()))
|
||||
|
||||
self._colormap = {}
|
||||
for key, val in self._merged_labelmap.items():
|
||||
self._colormap[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
|
||||
|
||||
|
||||
class LogLevelEnum(str, Enum):
|
||||
debug = "debug"
|
||||
info = "info"
|
||||
@@ -738,6 +722,90 @@ class LoggerConfig(FrigateBaseModel):
|
||||
)
|
||||
|
||||
|
||||
def verify_config_roles(camera_config: CameraConfig) -> None:
|
||||
"""Verify that roles are setup in the config correctly."""
|
||||
assigned_roles = list(
|
||||
set([r for i in camera_config.ffmpeg.inputs for r in i.roles])
|
||||
)
|
||||
|
||||
if camera_config.record.enabled and not "record" in assigned_roles:
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has record enabled, but record is not assigned to an input."
|
||||
)
|
||||
|
||||
if camera_config.rtmp.enabled and not "rtmp" in assigned_roles:
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has rtmp enabled, but rtmp is not assigned to an input."
|
||||
)
|
||||
|
||||
if camera_config.restream.enabled and not "restream" in assigned_roles:
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has restream enabled, but restream is not assigned to an input."
|
||||
)
|
||||
|
||||
|
||||
def verify_old_retain_config(camera_config: CameraConfig) -> None:
|
||||
"""Leave log if old retain_days is used."""
|
||||
if not camera_config.record.retain_days is None:
|
||||
logger.warning(
|
||||
"The 'retain_days' config option has been DEPRECATED and will be removed in a future version. Please use the 'days' setting under 'retain'"
|
||||
)
|
||||
if camera_config.record.retain.days == 0:
|
||||
camera_config.record.retain.days = camera_config.record.retain_days
|
||||
|
||||
|
||||
def verify_recording_retention(camera_config: CameraConfig) -> None:
|
||||
"""Verify that recording retention modes are ranked correctly."""
|
||||
rank_map = {
|
||||
RetainModeEnum.all: 0,
|
||||
RetainModeEnum.motion: 1,
|
||||
RetainModeEnum.active_objects: 2,
|
||||
}
|
||||
|
||||
if (
|
||||
camera_config.record.retain.days != 0
|
||||
and rank_map[camera_config.record.retain.mode]
|
||||
> rank_map[camera_config.record.events.retain.mode]
|
||||
):
|
||||
logger.warning(
|
||||
f"{camera_config.name}: Recording retention is configured for {camera_config.record.retain.mode} and event retention is configured for {camera_config.record.events.retain.mode}. The more restrictive retention policy will be applied."
|
||||
)
|
||||
|
||||
|
||||
def verify_recording_segments_setup_with_reasonable_time(
|
||||
camera_config: CameraConfig,
|
||||
) -> None:
|
||||
"""Verify that recording segments are setup and segment time is not greater than 60."""
|
||||
record_args: list[str] = get_ffmpeg_arg_list(
|
||||
camera_config.ffmpeg.output_args.record
|
||||
)
|
||||
|
||||
if record_args[0].startswith("preset"):
|
||||
return
|
||||
|
||||
seg_arg_index = record_args.index("-segment_time")
|
||||
|
||||
if seg_arg_index < 0:
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has no segment_time in recording output args, segment args are required for record."
|
||||
)
|
||||
|
||||
if int(record_args[seg_arg_index + 1]) > 60:
|
||||
raise ValueError(
|
||||
f"Camera {camera_config.name} has invalid segment_time output arg, segment_time must be 60 or less."
|
||||
)
|
||||
|
||||
|
||||
def verify_zone_objects_are_tracked(camera_config: CameraConfig) -> None:
|
||||
"""Verify that user has not entered zone objects that are not in the tracking config."""
|
||||
for zone_name, zone in camera_config.zones.items():
|
||||
for obj in zone.objects:
|
||||
if obj not in camera_config.objects.track:
|
||||
raise ValueError(
|
||||
f"Zone {zone_name} is configured to track {obj} but that object type is not added to objects -> track."
|
||||
)
|
||||
|
||||
|
||||
class FrigateConfig(FrigateBaseModel):
|
||||
mqtt: MqttConfig = Field(title="MQTT Configuration.")
|
||||
database: DatabaseConfig = Field(
|
||||
@@ -751,7 +819,7 @@ class FrigateConfig(FrigateBaseModel):
|
||||
default_factory=ModelConfig, title="Detection model configuration."
|
||||
)
|
||||
detectors: Dict[str, DetectorConfig] = Field(
|
||||
default={name: DetectorConfig(**d) for name, d in DEFAULT_DETECTORS.items()},
|
||||
default=DEFAULT_DETECTORS,
|
||||
title="Detector hardware configuration.",
|
||||
)
|
||||
logger: LoggerConfig = Field(
|
||||
@@ -763,12 +831,12 @@ class FrigateConfig(FrigateBaseModel):
|
||||
snapshots: SnapshotsConfig = Field(
|
||||
default_factory=SnapshotsConfig, title="Global snapshots configuration."
|
||||
)
|
||||
live: CameraLiveConfig = Field(
|
||||
default_factory=CameraLiveConfig, title="Global live configuration."
|
||||
)
|
||||
rtmp: RtmpConfig = Field(
|
||||
default_factory=RtmpConfig, title="Global RTMP restreaming configuration."
|
||||
)
|
||||
restream: RestreamConfig = Field(
|
||||
default_factory=RestreamConfig, title="Global restream configuration."
|
||||
)
|
||||
birdseye: BirdseyeConfig = Field(
|
||||
default_factory=BirdseyeConfig, title="Birdseye configuration."
|
||||
)
|
||||
@@ -795,18 +863,19 @@ class FrigateConfig(FrigateBaseModel):
|
||||
"""Merge camera config with globals."""
|
||||
config = self.copy(deep=True)
|
||||
|
||||
# MQTT password substitution
|
||||
if config.mqtt.password:
|
||||
# MQTT user/password substitutions
|
||||
if config.mqtt.user or config.mqtt.password:
|
||||
config.mqtt.user = config.mqtt.user.format(**FRIGATE_ENV_VARS)
|
||||
config.mqtt.password = config.mqtt.password.format(**FRIGATE_ENV_VARS)
|
||||
|
||||
# Global config to propegate down to camera level
|
||||
# Global config to propagate down to camera level
|
||||
global_config = config.dict(
|
||||
include={
|
||||
"birdseye": ...,
|
||||
"record": ...,
|
||||
"snapshots": ...,
|
||||
"live": ...,
|
||||
"rtmp": ...,
|
||||
"restream": ...,
|
||||
"objects": ...,
|
||||
"motion": ...,
|
||||
"detect": ...,
|
||||
@@ -879,46 +948,55 @@ class FrigateConfig(FrigateBaseModel):
|
||||
**camera_config.motion.dict(exclude_unset=True),
|
||||
)
|
||||
|
||||
# check runtime config
|
||||
assigned_roles = list(
|
||||
set([r for i in camera_config.ffmpeg.inputs for r in i.roles])
|
||||
)
|
||||
if camera_config.record.enabled and not "record" in assigned_roles:
|
||||
raise ValueError(
|
||||
f"Camera {name} has record enabled, but record is not assigned to an input."
|
||||
)
|
||||
verify_config_roles(camera_config)
|
||||
verify_old_retain_config(camera_config)
|
||||
verify_recording_retention(camera_config)
|
||||
verify_recording_segments_setup_with_reasonable_time(camera_config)
|
||||
verify_zone_objects_are_tracked(camera_config)
|
||||
|
||||
if camera_config.rtmp.enabled and not "rtmp" in assigned_roles:
|
||||
raise ValueError(
|
||||
f"Camera {name} has rtmp enabled, but rtmp is not assigned to an input."
|
||||
)
|
||||
|
||||
# backwards compatibility for retain_days
|
||||
if not camera_config.record.retain_days is None:
|
||||
if camera_config.rtmp.enabled:
|
||||
logger.warning(
|
||||
"The 'retain_days' config option has been DEPRECATED and will be removed in a future version. Please use the 'days' setting under 'retain'"
|
||||
"RTMP restream is deprecated in favor of the restream role, recommend disabling RTMP."
|
||||
)
|
||||
if camera_config.record.retain.days == 0:
|
||||
camera_config.record.retain.days = camera_config.record.retain_days
|
||||
|
||||
# warning if the higher level record mode is potentially more restrictive than the events
|
||||
rank_map = {
|
||||
RetainModeEnum.all: 0,
|
||||
RetainModeEnum.motion: 1,
|
||||
RetainModeEnum.active_objects: 2,
|
||||
}
|
||||
if (
|
||||
camera_config.record.retain.days != 0
|
||||
and rank_map[camera_config.record.retain.mode]
|
||||
> rank_map[camera_config.record.events.retain.mode]
|
||||
):
|
||||
logger.warning(
|
||||
f"{name}: Recording retention is configured for {camera_config.record.retain.mode} and event retention is configured for {camera_config.record.events.retain.mode}. The more restrictive retention policy will be applied."
|
||||
)
|
||||
# generage the ffmpeg commands
|
||||
# generate the ffmpeg commands
|
||||
camera_config.create_ffmpeg_cmds()
|
||||
config.cameras[name] = camera_config
|
||||
|
||||
# get list of unique enabled labels for tracking
|
||||
enabled_labels = set(config.objects.track)
|
||||
|
||||
for _, camera in config.cameras.items():
|
||||
enabled_labels.update(camera.objects.track)
|
||||
|
||||
config.model.create_colormap(sorted(enabled_labels))
|
||||
|
||||
for key, detector in config.detectors.items():
|
||||
detector_config: DetectorConfig = parse_obj_as(DetectorConfig, detector)
|
||||
if detector_config.model is None:
|
||||
detector_config.model = config.model
|
||||
else:
|
||||
model = detector_config.model
|
||||
schema = ModelConfig.schema()["properties"]
|
||||
if (
|
||||
model.width != schema["width"]["default"]
|
||||
or model.height != schema["height"]["default"]
|
||||
or model.labelmap_path is not None
|
||||
or model.labelmap is not {}
|
||||
or model.input_tensor != schema["input_tensor"]["default"]
|
||||
or model.input_pixel_format
|
||||
!= schema["input_pixel_format"]["default"]
|
||||
):
|
||||
logger.warning(
|
||||
"Customizing more than a detector model path is unsupported."
|
||||
)
|
||||
merged_model = deep_merge(
|
||||
detector_config.model.dict(exclude_unset=True),
|
||||
config.model.dict(exclude_unset=True),
|
||||
)
|
||||
detector_config.model = ModelConfig.parse_obj(merged_model)
|
||||
config.detectors[key] = detector_config
|
||||
|
||||
return config
|
||||
|
||||
@validator("cameras")
|
||||
@@ -935,8 +1013,13 @@ class FrigateConfig(FrigateBaseModel):
|
||||
raw_config = f.read()
|
||||
|
||||
if config_file.endswith(YAML_EXT):
|
||||
config = yaml.safe_load(raw_config)
|
||||
config = load_config_with_no_duplicates(raw_config)
|
||||
elif config_file.endswith(".json"):
|
||||
config = json.loads(raw_config)
|
||||
|
||||
return cls.parse_obj(config)
|
||||
|
||||
@classmethod
|
||||
def parse_raw(cls, raw_config):
|
||||
config = load_config_with_no_duplicates(raw_config)
|
||||
return cls.parse_obj(config)
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
BASE_DIR = "/media/frigate"
|
||||
CLIPS_DIR = f"{BASE_DIR}/clips"
|
||||
RECORD_DIR = f"{BASE_DIR}/recordings"
|
||||
BIRDSEYE_PIPE = "/tmp/cache/birdseye"
|
||||
CACHE_DIR = "/tmp/cache"
|
||||
YAML_EXT = (".yaml", ".yml")
|
||||
PLUS_ENV_VAR = "PLUS_API_KEY"
|
||||
PLUS_API_HOST = "https://api.frigate.video"
|
||||
MAX_SEGMENT_DURATION = 600
|
||||
BTBN_PATH = "/usr/lib/btbn-ffmpeg"
|
||||
|
||||
# Regex Consts
|
||||
|
||||
REGEX_CAMERA_NAME = "^[a-zA-Z0-9_-]+$"
|
||||
REGEX_RTSP_CAMERA_USER_PASS = ":\/\/[a-zA-Z0-9_-]+:[\S]+@"
|
||||
REGEX_HTTP_CAMERA_USER_PASS = "user=[a-zA-Z0-9_-]+&password=[\S]+"
|
||||
|
||||
# Known Driver Names
|
||||
|
||||
DRIVER_ENV_VAR = "LIBVA_DRIVER_NAME"
|
||||
DRIVER_AMD = "radeonsi"
|
||||
DRIVER_INTEL_i965 = "i965"
|
||||
DRIVER_INTEL_iHD = "iHD"
|
||||
|
||||
24
frigate/detectors/__init__.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import logging
|
||||
|
||||
from .detection_api import DetectionApi
|
||||
from .detector_config import (
|
||||
PixelFormatEnum,
|
||||
InputTensorEnum,
|
||||
ModelConfig,
|
||||
)
|
||||
from .detector_types import DetectorTypeEnum, api_types, DetectorConfig
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_detector(detector_config):
|
||||
if detector_config.type == DetectorTypeEnum.cpu:
|
||||
logger.warning(
|
||||
"CPU detectors are not recommended and should only be used for testing or for trial purposes."
|
||||
)
|
||||
|
||||
api = api_types.get(detector_config.type)
|
||||
if not api:
|
||||
raise ValueError(detector_config.type)
|
||||
return api(detector_config)
|
||||
17
frigate/detectors/detection_api.py
Normal file
@@ -0,0 +1,17 @@
|
||||
import logging
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DetectionApi(ABC):
|
||||
type_key: str
|
||||
|
||||
@abstractmethod
|
||||
def __init__(self, detector_config):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def detect_raw(self, tensor_input):
|
||||
pass
|
||||
80
frigate/detectors/detector_config.py
Normal file
@@ -0,0 +1,80 @@
|
||||
import logging
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional, Tuple, Union, Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from pydantic import BaseModel, Extra, Field, validator
|
||||
from pydantic.fields import PrivateAttr
|
||||
|
||||
from frigate.util import load_labels
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PixelFormatEnum(str, Enum):
|
||||
rgb = "rgb"
|
||||
bgr = "bgr"
|
||||
yuv = "yuv"
|
||||
|
||||
|
||||
class InputTensorEnum(str, Enum):
|
||||
nchw = "nchw"
|
||||
nhwc = "nhwc"
|
||||
|
||||
|
||||
class ModelConfig(BaseModel):
|
||||
path: Optional[str] = Field(title="Custom Object detection model path.")
|
||||
labelmap_path: Optional[str] = Field(title="Label map for custom object detector.")
|
||||
width: int = Field(default=320, title="Object detection model input width.")
|
||||
height: int = Field(default=320, title="Object detection model input height.")
|
||||
labelmap: Dict[int, str] = Field(
|
||||
default_factory=dict, title="Labelmap customization."
|
||||
)
|
||||
input_tensor: InputTensorEnum = Field(
|
||||
default=InputTensorEnum.nhwc, title="Model Input Tensor Shape"
|
||||
)
|
||||
input_pixel_format: PixelFormatEnum = Field(
|
||||
default=PixelFormatEnum.rgb, title="Model Input Pixel Color Format"
|
||||
)
|
||||
_merged_labelmap: Optional[Dict[int, str]] = PrivateAttr()
|
||||
_colormap: Dict[int, Tuple[int, int, int]] = PrivateAttr()
|
||||
|
||||
@property
|
||||
def merged_labelmap(self) -> Dict[int, str]:
|
||||
return self._merged_labelmap
|
||||
|
||||
@property
|
||||
def colormap(self) -> Dict[int, Tuple[int, int, int]]:
|
||||
return self._colormap
|
||||
|
||||
def __init__(self, **config):
|
||||
super().__init__(**config)
|
||||
|
||||
self._merged_labelmap = {
|
||||
**load_labels(config.get("labelmap_path", "/labelmap.txt")),
|
||||
**config.get("labelmap", {}),
|
||||
}
|
||||
self._colormap = {}
|
||||
|
||||
def create_colormap(self, enabled_labels: set[str]) -> None:
|
||||
"""Get a list of colors for enabled labels."""
|
||||
cmap = plt.cm.get_cmap("tab10", len(enabled_labels))
|
||||
|
||||
for key, val in enumerate(enabled_labels):
|
||||
self._colormap[val] = tuple(int(round(255 * c)) for c in cmap(key)[:3])
|
||||
|
||||
class Config:
|
||||
extra = Extra.forbid
|
||||
|
||||
|
||||
class BaseDetectorConfig(BaseModel):
|
||||
# the type field must be defined in all subclasses
|
||||
type: str = Field(default="cpu", title="Detector Type")
|
||||
model: ModelConfig = Field(
|
||||
default=None, title="Detector specific model configuration."
|
||||
)
|
||||
|
||||
class Config:
|
||||
extra = Extra.allow
|
||||
arbitrary_types_allowed = True
|
||||
35
frigate/detectors/detector_types.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import logging
|
||||
import importlib
|
||||
import pkgutil
|
||||
from typing import Union
|
||||
from typing_extensions import Annotated
|
||||
from enum import Enum
|
||||
from pydantic import Field
|
||||
|
||||
from . import plugins
|
||||
from .detection_api import DetectionApi
|
||||
from .detector_config import BaseDetectorConfig
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
plugin_modules = [
|
||||
importlib.import_module(name)
|
||||
for finder, name, ispkg in pkgutil.iter_modules(
|
||||
plugins.__path__, plugins.__name__ + "."
|
||||
)
|
||||
]
|
||||
|
||||
api_types = {det.type_key: det for det in DetectionApi.__subclasses__()}
|
||||
|
||||
|
||||
class StrEnum(str, Enum):
|
||||
pass
|
||||
|
||||
|
||||
DetectorTypeEnum = StrEnum("DetectorTypeEnum", {k: k for k in api_types})
|
||||
|
||||
DetectorConfig = Annotated[
|
||||
Union[tuple(BaseDetectorConfig.__subclasses__())],
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
0
frigate/detectors/plugins/__init__.py
Normal file
60
frigate/detectors/plugins/cpu_tfl.py
Normal file
@@ -0,0 +1,60 @@
|
||||
import logging
|
||||
import numpy as np
|
||||
|
||||
from frigate.detectors.detection_api import DetectionApi
|
||||
from frigate.detectors.detector_config import BaseDetectorConfig
|
||||
from typing import Literal
|
||||
from pydantic import Extra, Field
|
||||
import tflite_runtime.interpreter as tflite
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DETECTOR_KEY = "cpu"
|
||||
|
||||
|
||||
class CpuDetectorConfig(BaseDetectorConfig):
|
||||
type: Literal[DETECTOR_KEY]
|
||||
num_threads: int = Field(default=3, title="Number of detection threads")
|
||||
|
||||
|
||||
class CpuTfl(DetectionApi):
|
||||
type_key = DETECTOR_KEY
|
||||
|
||||
def __init__(self, detector_config: CpuDetectorConfig):
|
||||
self.interpreter = tflite.Interpreter(
|
||||
model_path=detector_config.model.path or "/cpu_model.tflite",
|
||||
num_threads=detector_config.num_threads or 3,
|
||||
)
|
||||
|
||||
self.interpreter.allocate_tensors()
|
||||
|
||||
self.tensor_input_details = self.interpreter.get_input_details()
|
||||
self.tensor_output_details = self.interpreter.get_output_details()
|
||||
|
||||
def detect_raw(self, tensor_input):
|
||||
self.interpreter.set_tensor(self.tensor_input_details[0]["index"], tensor_input)
|
||||
self.interpreter.invoke()
|
||||
|
||||
boxes = self.interpreter.tensor(self.tensor_output_details[0]["index"])()[0]
|
||||
class_ids = self.interpreter.tensor(self.tensor_output_details[1]["index"])()[0]
|
||||
scores = self.interpreter.tensor(self.tensor_output_details[2]["index"])()[0]
|
||||
count = int(
|
||||
self.interpreter.tensor(self.tensor_output_details[3]["index"])()[0]
|
||||
)
|
||||
|
||||
detections = np.zeros((20, 6), np.float32)
|
||||
|
||||
for i in range(count):
|
||||
if scores[i] < 0.4 or i == 20:
|
||||
break
|
||||
detections[i] = [
|
||||
class_ids[i],
|
||||
float(scores[i]),
|
||||
boxes[i][0],
|
||||
boxes[i][1],
|
||||
boxes[i][2],
|
||||
boxes[i][3],
|
||||
]
|
||||
|
||||
return detections
|
||||
76
frigate/detectors/plugins/edgetpu_tfl.py
Normal file
@@ -0,0 +1,76 @@
|
||||
import logging
|
||||
import numpy as np
|
||||
|
||||
from frigate.detectors.detection_api import DetectionApi
|
||||
from frigate.detectors.detector_config import BaseDetectorConfig
|
||||
from typing import Literal
|
||||
from pydantic import Extra, Field
|
||||
import tflite_runtime.interpreter as tflite
|
||||
from tflite_runtime.interpreter import load_delegate
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DETECTOR_KEY = "edgetpu"
|
||||
|
||||
|
||||
class EdgeTpuDetectorConfig(BaseDetectorConfig):
|
||||
type: Literal[DETECTOR_KEY]
|
||||
device: str = Field(default=None, title="Device Type")
|
||||
|
||||
|
||||
class EdgeTpuTfl(DetectionApi):
|
||||
type_key = DETECTOR_KEY
|
||||
|
||||
def __init__(self, detector_config: EdgeTpuDetectorConfig):
|
||||
device_config = {"device": "usb"}
|
||||
if detector_config.device is not None:
|
||||
device_config = {"device": detector_config.device}
|
||||
|
||||
edge_tpu_delegate = None
|
||||
|
||||
try:
|
||||
logger.info(f"Attempting to load TPU as {device_config['device']}")
|
||||
edge_tpu_delegate = load_delegate("libedgetpu.so.1.0", device_config)
|
||||
logger.info("TPU found")
|
||||
self.interpreter = tflite.Interpreter(
|
||||
model_path=detector_config.model.path or "/edgetpu_model.tflite",
|
||||
experimental_delegates=[edge_tpu_delegate],
|
||||
)
|
||||
except ValueError:
|
||||
logger.error(
|
||||
"No EdgeTPU was detected. If you do not have a Coral device yet, you must configure CPU detectors."
|
||||
)
|
||||
raise
|
||||
|
||||
self.interpreter.allocate_tensors()
|
||||
|
||||
self.tensor_input_details = self.interpreter.get_input_details()
|
||||
self.tensor_output_details = self.interpreter.get_output_details()
|
||||
|
||||
def detect_raw(self, tensor_input):
|
||||
self.interpreter.set_tensor(self.tensor_input_details[0]["index"], tensor_input)
|
||||
self.interpreter.invoke()
|
||||
|
||||
boxes = self.interpreter.tensor(self.tensor_output_details[0]["index"])()[0]
|
||||
class_ids = self.interpreter.tensor(self.tensor_output_details[1]["index"])()[0]
|
||||
scores = self.interpreter.tensor(self.tensor_output_details[2]["index"])()[0]
|
||||
count = int(
|
||||
self.interpreter.tensor(self.tensor_output_details[3]["index"])()[0]
|
||||
)
|
||||
|
||||
detections = np.zeros((20, 6), np.float32)
|
||||
|
||||
for i in range(count):
|
||||
if scores[i] < 0.4 or i == 20:
|
||||
break
|
||||
detections[i] = [
|
||||
class_ids[i],
|
||||
float(scores[i]),
|
||||
boxes[i][0],
|
||||
boxes[i][1],
|
||||
boxes[i][2],
|
||||
boxes[i][3],
|
||||
]
|
||||
|
||||
return detections
|
||||
66
frigate/detectors/plugins/openvino.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import logging
|
||||
import numpy as np
|
||||
import openvino.runtime as ov
|
||||
|
||||
from frigate.detectors.detection_api import DetectionApi
|
||||
from frigate.detectors.detector_config import BaseDetectorConfig
|
||||
from typing import Literal
|
||||
from pydantic import Extra, Field
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DETECTOR_KEY = "openvino"
|
||||
|
||||
|
||||
class OvDetectorConfig(BaseDetectorConfig):
|
||||
type: Literal[DETECTOR_KEY]
|
||||
device: str = Field(default=None, title="Device Type")
|
||||
|
||||
|
||||
class OvDetector(DetectionApi):
|
||||
type_key = DETECTOR_KEY
|
||||
|
||||
def __init__(self, detector_config: OvDetectorConfig):
|
||||
self.ov_core = ov.Core()
|
||||
self.ov_model = self.ov_core.read_model(detector_config.model.path)
|
||||
|
||||
self.interpreter = self.ov_core.compile_model(
|
||||
model=self.ov_model, device_name=detector_config.device
|
||||
)
|
||||
logger.info(f"Model Input Shape: {self.interpreter.input(0).shape}")
|
||||
self.output_indexes = 0
|
||||
while True:
|
||||
try:
|
||||
tensor_shape = self.interpreter.output(self.output_indexes).shape
|
||||
logger.info(f"Model Output-{self.output_indexes} Shape: {tensor_shape}")
|
||||
self.output_indexes += 1
|
||||
except:
|
||||
logger.info(f"Model has {self.output_indexes} Output Tensors")
|
||||
break
|
||||
|
||||
def detect_raw(self, tensor_input):
|
||||
|
||||
infer_request = self.interpreter.create_infer_request()
|
||||
infer_request.infer([tensor_input])
|
||||
|
||||
results = infer_request.get_output_tensor()
|
||||
|
||||
detections = np.zeros((20, 6), np.float32)
|
||||
i = 0
|
||||
for object_detected in results.data[0, 0, :]:
|
||||
if object_detected[0] != -1:
|
||||
logger.debug(object_detected)
|
||||
if object_detected[2] < 0.1 or i == 20:
|
||||
break
|
||||
detections[i] = [
|
||||
object_detected[1], # Label ID
|
||||
float(object_detected[2]), # Confidence
|
||||
object_detected[4], # y_min
|
||||
object_detected[3], # x_min
|
||||
object_detected[6], # y_max
|
||||
object_detected[5], # x_max
|
||||
]
|
||||
i += 1
|
||||
|
||||
return detections
|
||||
318
frigate/detectors/plugins/tensorrt.py
Normal file
@@ -0,0 +1,318 @@
|
||||
import logging
|
||||
|
||||
import ctypes
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import tensorrt as trt
|
||||
from cuda import cuda
|
||||
|
||||
TRT_SUPPORT = True
|
||||
except ModuleNotFoundError as e:
|
||||
TRT_SUPPORT = False
|
||||
|
||||
from frigate.detectors.detection_api import DetectionApi
|
||||
from frigate.detectors.detector_config import BaseDetectorConfig
|
||||
from typing import Literal
|
||||
from pydantic import Field
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DETECTOR_KEY = "tensorrt"
|
||||
|
||||
if TRT_SUPPORT:
|
||||
|
||||
class TrtLogger(trt.ILogger):
|
||||
def __init__(self):
|
||||
trt.ILogger.__init__(self)
|
||||
|
||||
def log(self, severity, msg):
|
||||
logger.log(self.getSeverity(severity), msg)
|
||||
|
||||
def getSeverity(self, sev: trt.ILogger.Severity) -> int:
|
||||
if sev == trt.ILogger.VERBOSE:
|
||||
return logging.DEBUG
|
||||
elif sev == trt.ILogger.INFO:
|
||||
return logging.INFO
|
||||
elif sev == trt.ILogger.WARNING:
|
||||
return logging.WARNING
|
||||
elif sev == trt.ILogger.ERROR:
|
||||
return logging.ERROR
|
||||
elif sev == trt.ILogger.INTERNAL_ERROR:
|
||||
return logging.CRITICAL
|
||||
else:
|
||||
return logging.DEBUG
|
||||
|
||||
|
||||
class TensorRTDetectorConfig(BaseDetectorConfig):
|
||||
type: Literal[DETECTOR_KEY]
|
||||
device: int = Field(default=0, title="GPU Device Index")
|
||||
|
||||
|
||||
class HostDeviceMem(object):
|
||||
"""Simple helper data class that's a little nicer to use than a 2-tuple."""
|
||||
|
||||
def __init__(self, host_mem, device_mem, nbytes, size):
|
||||
self.host = host_mem
|
||||
err, self.host_dev = cuda.cuMemHostGetDevicePointer(self.host, 0)
|
||||
self.device = device_mem
|
||||
self.nbytes = nbytes
|
||||
self.size = size
|
||||
|
||||
def __str__(self):
|
||||
return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device)
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
def __del__(self):
|
||||
cuda.cuMemFreeHost(self.host)
|
||||
cuda.cuMemFree(self.device)
|
||||
|
||||
|
||||
class TensorRtDetector(DetectionApi):
|
||||
type_key = DETECTOR_KEY
|
||||
|
||||
def _load_engine(self, model_path):
|
||||
try:
|
||||
ctypes.cdll.LoadLibrary(
|
||||
"/usr/local/lib/python3.9/dist-packages/nvidia/cuda_runtime/lib/libcudart.so.11.0"
|
||||
)
|
||||
ctypes.cdll.LoadLibrary(
|
||||
"/usr/local/lib/python3.9/dist-packages/tensorrt/libnvinfer.so.8"
|
||||
)
|
||||
trt.init_libnvinfer_plugins(self.trt_logger, "")
|
||||
|
||||
ctypes.cdll.LoadLibrary("/trt-models/libyolo_layer.so")
|
||||
except OSError as e:
|
||||
logger.error(
|
||||
"ERROR: failed to load libraries. %s",
|
||||
e,
|
||||
)
|
||||
|
||||
with open(model_path, "rb") as f, trt.Runtime(self.trt_logger) as runtime:
|
||||
return runtime.deserialize_cuda_engine(f.read())
|
||||
|
||||
def _get_input_shape(self):
|
||||
"""Get input shape of the TensorRT YOLO engine."""
|
||||
binding = self.engine[0]
|
||||
assert self.engine.binding_is_input(binding)
|
||||
binding_dims = self.engine.get_binding_shape(binding)
|
||||
if len(binding_dims) == 4:
|
||||
return (
|
||||
tuple(binding_dims[2:]),
|
||||
trt.nptype(self.engine.get_binding_dtype(binding)),
|
||||
)
|
||||
elif len(binding_dims) == 3:
|
||||
return (
|
||||
tuple(binding_dims[1:]),
|
||||
trt.nptype(self.engine.get_binding_dtype(binding)),
|
||||
)
|
||||
else:
|
||||
raise ValueError(
|
||||
"bad dims of binding %s: %s" % (binding, str(binding_dims))
|
||||
)
|
||||
|
||||
def _allocate_buffers(self):
|
||||
"""Allocates all host/device in/out buffers required for an engine."""
|
||||
inputs = []
|
||||
outputs = []
|
||||
bindings = []
|
||||
output_idx = 0
|
||||
for binding in self.engine:
|
||||
binding_dims = self.engine.get_binding_shape(binding)
|
||||
if len(binding_dims) == 4:
|
||||
# explicit batch case (TensorRT 7+)
|
||||
size = trt.volume(binding_dims)
|
||||
elif len(binding_dims) == 3:
|
||||
# implicit batch case (TensorRT 6 or older)
|
||||
size = trt.volume(binding_dims) * self.engine.max_batch_size
|
||||
else:
|
||||
raise ValueError(
|
||||
"bad dims of binding %s: %s" % (binding, str(binding_dims))
|
||||
)
|
||||
nbytes = size * self.engine.get_binding_dtype(binding).itemsize
|
||||
# Allocate host and device buffers
|
||||
err, host_mem = cuda.cuMemHostAlloc(
|
||||
nbytes, Flags=cuda.CU_MEMHOSTALLOC_DEVICEMAP
|
||||
)
|
||||
assert err is cuda.CUresult.CUDA_SUCCESS, f"cuMemAllocHost returned {err}"
|
||||
logger.debug(
|
||||
f"Allocated Tensor Binding {binding} Memory {nbytes} Bytes ({size} * {self.engine.get_binding_dtype(binding)})"
|
||||
)
|
||||
err, device_mem = cuda.cuMemAlloc(nbytes)
|
||||
assert err is cuda.CUresult.CUDA_SUCCESS, f"cuMemAlloc returned {err}"
|
||||
# Append the device buffer to device bindings.
|
||||
bindings.append(int(device_mem))
|
||||
# Append to the appropriate list.
|
||||
if self.engine.binding_is_input(binding):
|
||||
logger.debug(f"Input has Shape {binding_dims}")
|
||||
inputs.append(HostDeviceMem(host_mem, device_mem, nbytes, size))
|
||||
else:
|
||||
# each grid has 3 anchors, each anchor generates a detection
|
||||
# output of 7 float32 values
|
||||
assert size % 7 == 0, f"output size was {size}"
|
||||
logger.debug(f"Output has Shape {binding_dims}")
|
||||
outputs.append(HostDeviceMem(host_mem, device_mem, nbytes, size))
|
||||
output_idx += 1
|
||||
assert len(inputs) == 1, f"inputs len was {len(inputs)}"
|
||||
assert len(outputs) == 1, f"output len was {len(outputs)}"
|
||||
return inputs, outputs, bindings
|
||||
|
||||
def _do_inference(self):
|
||||
"""do_inference (for TensorRT 7.0+)
|
||||
This function is generalized for multiple inputs/outputs for full
|
||||
dimension networks.
|
||||
Inputs and outputs are expected to be lists of HostDeviceMem objects.
|
||||
"""
|
||||
# Push CUDA Context
|
||||
cuda.cuCtxPushCurrent(self.cu_ctx)
|
||||
|
||||
# Transfer input data to the GPU.
|
||||
[
|
||||
cuda.cuMemcpyHtoDAsync(inp.device, inp.host, inp.nbytes, self.stream)
|
||||
for inp in self.inputs
|
||||
]
|
||||
|
||||
# Run inference.
|
||||
if not self.context.execute_async_v2(
|
||||
bindings=self.bindings, stream_handle=self.stream
|
||||
):
|
||||
logger.warn(f"Execute returned false")
|
||||
|
||||
# Transfer predictions back from the GPU.
|
||||
[
|
||||
cuda.cuMemcpyDtoHAsync(out.host, out.device, out.nbytes, self.stream)
|
||||
for out in self.outputs
|
||||
]
|
||||
|
||||
# Synchronize the stream
|
||||
cuda.cuStreamSynchronize(self.stream)
|
||||
|
||||
# Pop CUDA Context
|
||||
cuda.cuCtxPopCurrent()
|
||||
|
||||
# Return only the host outputs.
|
||||
return [
|
||||
np.array(
|
||||
(ctypes.c_float * out.size).from_address(out.host), dtype=np.float32
|
||||
)
|
||||
for out in self.outputs
|
||||
]
|
||||
|
||||
def __init__(self, detector_config: TensorRTDetectorConfig):
|
||||
assert (
|
||||
TRT_SUPPORT
|
||||
), f"TensorRT libraries not found, {DETECTOR_KEY} detector not present"
|
||||
|
||||
(cuda_err,) = cuda.cuInit(0)
|
||||
assert (
|
||||
cuda_err == cuda.CUresult.CUDA_SUCCESS
|
||||
), f"Failed to initialize cuda {cuda_err}"
|
||||
err, dev_count = cuda.cuDeviceGetCount()
|
||||
logger.debug(f"Num Available Devices: {dev_count}")
|
||||
assert (
|
||||
detector_config.device < dev_count
|
||||
), f"Invalid TensorRT Device Config. Device {detector_config.device} Invalid."
|
||||
err, self.cu_ctx = cuda.cuCtxCreate(
|
||||
cuda.CUctx_flags.CU_CTX_MAP_HOST, detector_config.device
|
||||
)
|
||||
|
||||
self.conf_th = 0.4 ##TODO: model config parameter
|
||||
self.nms_threshold = 0.4
|
||||
err, self.stream = cuda.cuStreamCreate(0)
|
||||
self.trt_logger = TrtLogger()
|
||||
self.engine = self._load_engine(detector_config.model.path)
|
||||
self.input_shape = self._get_input_shape()
|
||||
|
||||
try:
|
||||
self.context = self.engine.create_execution_context()
|
||||
(
|
||||
self.inputs,
|
||||
self.outputs,
|
||||
self.bindings,
|
||||
) = self._allocate_buffers()
|
||||
except Exception as e:
|
||||
logger.error(e)
|
||||
raise RuntimeError("fail to allocate CUDA resources") from e
|
||||
|
||||
logger.debug("TensorRT loaded. Input shape is %s", self.input_shape)
|
||||
logger.debug("TensorRT version is %s", trt.__version__[0])
|
||||
|
||||
def __del__(self):
|
||||
"""Free CUDA memories."""
|
||||
if self.outputs is not None:
|
||||
del self.outputs
|
||||
if self.inputs is not None:
|
||||
del self.inputs
|
||||
if self.stream is not None:
|
||||
cuda.cuStreamDestroy(self.stream)
|
||||
del self.stream
|
||||
del self.engine
|
||||
del self.context
|
||||
del self.trt_logger
|
||||
cuda.cuCtxDestroy(self.cu_ctx)
|
||||
|
||||
def _postprocess_yolo(self, trt_outputs, conf_th):
|
||||
"""Postprocess TensorRT outputs.
|
||||
# Args
|
||||
trt_outputs: a list of 2 or 3 tensors, where each tensor
|
||||
contains a multiple of 7 float32 numbers in
|
||||
the order of [x, y, w, h, box_confidence, class_id, class_prob]
|
||||
conf_th: confidence threshold
|
||||
# Returns
|
||||
boxes, scores, classes
|
||||
"""
|
||||
# filter low-conf detections and concatenate results of all yolo layers
|
||||
detections = []
|
||||
for o in trt_outputs:
|
||||
dets = o.reshape((-1, 7))
|
||||
dets = dets[dets[:, 4] * dets[:, 6] >= conf_th]
|
||||
detections.append(dets)
|
||||
detections = np.concatenate(detections, axis=0)
|
||||
|
||||
return detections
|
||||
|
||||
def detect_raw(self, tensor_input):
|
||||
# Input tensor has the shape of the [height, width, 3]
|
||||
# Output tensor of float32 of shape [20, 6] where:
|
||||
# O - class id
|
||||
# 1 - score
|
||||
# 2..5 - a value between 0 and 1 of the box: [top, left, bottom, right]
|
||||
|
||||
# normalize
|
||||
if self.input_shape[-1] != trt.int8:
|
||||
tensor_input = tensor_input.astype(self.input_shape[-1])
|
||||
tensor_input /= 255.0
|
||||
|
||||
self.inputs[0].host = np.ascontiguousarray(
|
||||
tensor_input.astype(self.input_shape[-1])
|
||||
)
|
||||
trt_outputs = self._do_inference()
|
||||
|
||||
raw_detections = self._postprocess_yolo(trt_outputs, self.conf_th)
|
||||
|
||||
if len(raw_detections) == 0:
|
||||
return np.zeros((20, 6), np.float32)
|
||||
|
||||
# raw_detections: Nx7 numpy arrays of
|
||||
# [[x, y, w, h, box_confidence, class_id, class_prob],
|
||||
|
||||
# Calculate score as box_confidence x class_prob
|
||||
raw_detections[:, 4] = raw_detections[:, 4] * raw_detections[:, 6]
|
||||
# Reorder elements by the score, best on top, remove class_prob
|
||||
ordered = raw_detections[raw_detections[:, 4].argsort()[::-1]][:, 0:6]
|
||||
# transform width to right with clamp to 0..1
|
||||
ordered[:, 2] = np.clip(ordered[:, 2] + ordered[:, 0], 0, 1)
|
||||
# transform height to bottom with clamp to 0..1
|
||||
ordered[:, 3] = np.clip(ordered[:, 3] + ordered[:, 1], 0, 1)
|
||||
# put result into the correct order and limit to top 20
|
||||
detections = ordered[:, [5, 4, 1, 0, 3, 2]][:20]
|
||||
# pad to 20x6 shape
|
||||
append_cnt = 20 - len(detections)
|
||||
if append_cnt > 0:
|
||||
detections = np.append(
|
||||
detections, np.zeros((append_cnt, 6), np.float32), axis=0
|
||||
)
|
||||
|
||||
return detections
|
||||
@@ -11,43 +11,55 @@ from peewee import fn
|
||||
from frigate.config import EventsConfig, FrigateConfig, RecordConfig
|
||||
from frigate.const import CLIPS_DIR
|
||||
from frigate.models import Event
|
||||
from frigate.types import CameraMetricsTypes
|
||||
|
||||
from multiprocessing.queues import Queue
|
||||
from multiprocessing.synchronize import Event as MpEvent
|
||||
from typing import Dict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def should_insert_db(prev_event, current_event):
|
||||
def should_insert_db(prev_event: Event, current_event: Event) -> bool:
|
||||
"""If current event has new clip or snapshot."""
|
||||
return (not prev_event["has_clip"] and not prev_event["has_snapshot"]) and (
|
||||
current_event["has_clip"] or current_event["has_snapshot"]
|
||||
)
|
||||
|
||||
|
||||
def should_update_db(prev_event, current_event):
|
||||
def should_update_db(prev_event: Event, current_event: Event) -> bool:
|
||||
"""If current_event has updated fields and (clip or snapshot)."""
|
||||
return (current_event["has_clip"] or current_event["has_snapshot"]) and (
|
||||
prev_event["top_score"] != current_event["top_score"]
|
||||
or prev_event["entered_zones"] != current_event["entered_zones"]
|
||||
or prev_event["thumbnail"] != current_event["thumbnail"]
|
||||
or prev_event["has_clip"] != current_event["has_clip"]
|
||||
or prev_event["has_snapshot"] != current_event["has_snapshot"]
|
||||
)
|
||||
if current_event["has_clip"] or current_event["has_snapshot"]:
|
||||
if (
|
||||
prev_event["top_score"] != current_event["top_score"]
|
||||
or prev_event["entered_zones"] != current_event["entered_zones"]
|
||||
or prev_event["thumbnail"] != current_event["thumbnail"]
|
||||
or prev_event["has_clip"] != current_event["has_clip"]
|
||||
or prev_event["has_snapshot"] != current_event["has_snapshot"]
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class EventProcessor(threading.Thread):
|
||||
def __init__(
|
||||
self, config, camera_processes, event_queue, event_processed_queue, stop_event
|
||||
self,
|
||||
config: FrigateConfig,
|
||||
camera_processes: dict[str, CameraMetricsTypes],
|
||||
event_queue: Queue,
|
||||
event_processed_queue: Queue,
|
||||
stop_event: MpEvent,
|
||||
):
|
||||
threading.Thread.__init__(self)
|
||||
self.name = "event_processor"
|
||||
self.config = config
|
||||
self.camera_processes = camera_processes
|
||||
self.cached_clips = {}
|
||||
self.event_queue = event_queue
|
||||
self.event_processed_queue = event_processed_queue
|
||||
self.events_in_process = {}
|
||||
self.events_in_process: Dict[str, Event] = {}
|
||||
self.stop_event = stop_event
|
||||
|
||||
def run(self):
|
||||
def run(self) -> None:
|
||||
# set an end_time on events without an end_time on startup
|
||||
Event.update(end_time=Event.start_time + 30).where(
|
||||
Event.end_time == None
|
||||
@@ -147,14 +159,15 @@ class EventProcessor(threading.Thread):
|
||||
|
||||
|
||||
class EventCleanup(threading.Thread):
|
||||
def __init__(self, config: FrigateConfig, stop_event):
|
||||
def __init__(self, config: FrigateConfig, stop_event: MpEvent):
|
||||
threading.Thread.__init__(self)
|
||||
self.name = "event_cleanup"
|
||||
self.config = config
|
||||
self.stop_event = stop_event
|
||||
self.camera_keys = list(self.config.cameras.keys())
|
||||
|
||||
def expire(self, media_type):
|
||||
def expire(self, media_type: str) -> None:
|
||||
# TODO: Refactor media_type to enum
|
||||
## Expire events from unlisted cameras based on the global config
|
||||
if media_type == "clips":
|
||||
retain_config = self.config.record.events.retain
|
||||
@@ -253,7 +266,7 @@ class EventCleanup(threading.Thread):
|
||||
)
|
||||
update_query.execute()
|
||||
|
||||
def purge_duplicates(self):
|
||||
def purge_duplicates(self) -> None:
|
||||
duplicate_query = """with grouped_events as (
|
||||
select id,
|
||||
label,
|
||||
@@ -287,7 +300,7 @@ class EventCleanup(threading.Thread):
|
||||
.execute()
|
||||
)
|
||||
|
||||
def run(self):
|
||||
def run(self) -> None:
|
||||
# only expire events every 5 minutes
|
||||
while not self.stop_event.wait(300):
|
||||
self.expire("clips")
|
||||
|
||||
438
frigate/ffmpeg_presets.py
Normal file
@@ -0,0 +1,438 @@
|
||||
"""Handles inserting and maintaining ffmpeg presets."""
|
||||
|
||||
import os
|
||||
|
||||
from typing import Any
|
||||
|
||||
from frigate.version import VERSION
|
||||
from frigate.const import BTBN_PATH
|
||||
|
||||
TIMEOUT_PARAM = "-timeout" if os.path.exists(BTBN_PATH) else "-stimeout"
|
||||
|
||||
_user_agent_args = [
|
||||
"-user_agent",
|
||||
f"FFmpeg Frigate/{VERSION}",
|
||||
]
|
||||
|
||||
PRESETS_HW_ACCEL_DECODE = {
|
||||
"preset-rpi-32-h264": ["-c:v", "h264_v4l2m2m"],
|
||||
"preset-rpi-64-h264": ["-c:v", "h264_v4l2m2m"],
|
||||
"preset-vaapi": [
|
||||
"-hwaccel_flags",
|
||||
"allow_profile_mismatch",
|
||||
"-hwaccel",
|
||||
"vaapi",
|
||||
"-hwaccel_device",
|
||||
"/dev/dri/renderD128",
|
||||
"-hwaccel_output_format",
|
||||
"vaapi",
|
||||
],
|
||||
"preset-intel-qsv-h264": [
|
||||
"-hwaccel",
|
||||
"qsv",
|
||||
"-qsv_device",
|
||||
"/dev/dri/renderD128",
|
||||
"-hwaccel_output_format",
|
||||
"qsv",
|
||||
"-c:v",
|
||||
"h264_qsv",
|
||||
],
|
||||
"preset-intel-qsv-h265": [
|
||||
"-hwaccel",
|
||||
"qsv",
|
||||
"-qsv_device",
|
||||
"/dev/dri/renderD128",
|
||||
"-hwaccel_output_format",
|
||||
"qsv",
|
||||
"-c:v",
|
||||
"hevc_qsv",
|
||||
],
|
||||
"preset-nvidia-h264": [
|
||||
"-hwaccel",
|
||||
"cuda",
|
||||
"-hwaccel_output_format",
|
||||
"cuda",
|
||||
"-extra_hw_frames",
|
||||
"2",
|
||||
"-c:v",
|
||||
"h264_cuvid",
|
||||
],
|
||||
"preset-nvidia-h265": [
|
||||
"-hwaccel",
|
||||
"cuda",
|
||||
"-hwaccel_output_format",
|
||||
"cuda",
|
||||
"-extra_hw_frames",
|
||||
"2",
|
||||
"-c:v",
|
||||
"hevc_cuvid",
|
||||
],
|
||||
"preset-nvidia-mjpeg": [
|
||||
"-hwaccel",
|
||||
"cuda",
|
||||
"-hwaccel_output_format",
|
||||
"cuda",
|
||||
"-extra_hw_frames",
|
||||
"2",
|
||||
"-c:v",
|
||||
"mjpeg_cuvid",
|
||||
],
|
||||
}
|
||||
|
||||
PRESETS_HW_ACCEL_SCALE = {
|
||||
"preset-rpi-32-h264": ["-f", "rawvideo", "-pix_fmt", "yuv420p"],
|
||||
"preset-rpi-64-h264": ["-f", "rawvideo", "-pix_fmt", "yuv420p"],
|
||||
"preset-vaapi": [
|
||||
"-vf",
|
||||
"fps={},scale_vaapi=w={}:h={},hwdownload,format=yuv420p",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
],
|
||||
"preset-intel-qsv-h264": [
|
||||
"-vf",
|
||||
"vpp_qsv=framerate={},scale_qsv=w={}:h={}:format=nv12,hwdownload,format=nv12,format=yuv420p",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
],
|
||||
"preset-intel-qsv-h265": [
|
||||
"-vf",
|
||||
"vpp_qsv=framerate={},scale_qsv=w={}:h={}:format=nv12,hwdownload,format=nv12,format=yuv420p",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
],
|
||||
"preset-nvidia-h264": [
|
||||
"-vf",
|
||||
"fps={},scale_cuda=w={}:h={}:format=nv12,hwdownload,format=nv12,format=yuv420p",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
],
|
||||
"preset-nvidia-h265": [
|
||||
"-vf",
|
||||
"fps={},scale_cuda=w={}:h={}:format=nv12,hwdownload,format=nv12,format=yuv420p",
|
||||
"-f",
|
||||
"rawvideo",
|
||||
],
|
||||
"default": [
|
||||
"-r",
|
||||
"{}",
|
||||
"-s",
|
||||
"{}",
|
||||
],
|
||||
}
|
||||
|
||||
PRESETS_HW_ACCEL_ENCODE = {
|
||||
"preset-rpi-32-h264": "ffmpeg -hide_banner {0} -c:v h264_v4l2m2m -g 50 -bf 0 {1}",
|
||||
"preset-rpi-64-h264": "ffmpeg -hide_banner {0} -c:v h264_v4l2m2m -g 50 -bf 0 {1}",
|
||||
"preset-intel-qsv-h264": "ffmpeg -hide_banner {0} -c:v h264_qsv -g 50 -bf 0 -profile:v high -level:v 4.1 -async_depth:v 1 {1}",
|
||||
"preset-intel-qsv-h265": "ffmpeg -hide_banner {0} -c:v h264_qsv -g 50 -bf 0 -profile:v high -level:v 4.1 -async_depth:v 1 {1}",
|
||||
"preset-nvidia-h264": "ffmpeg -hide_banner {0} -c:v h264_nvenc -g 50 -profile:v high -level:v auto -preset:v p2 -tune:v ll {1}",
|
||||
"preset-nvidia-h265": "ffmpeg -hide_banner {0} -c:v h264_nvenc -g 50 -profile:v high -level:v auto -preset:v p2 -tune:v ll {1}",
|
||||
"default": "ffmpeg -hide_banner {0} -c:v libx264 -g 50 -profile:v high -level:v 4.1 -preset:v superfast -tune:v zerolatency {1}",
|
||||
}
|
||||
|
||||
PRESETS_HW_ACCEL_GO2RTC_ENGINE = {
|
||||
"preset-rpi-32-h264": "v4l2m2m",
|
||||
"preset-rpi-64-h264": "v4l2m2m",
|
||||
"preset-intel-vaapi": "vaapi",
|
||||
"preset-intel-qsv-h264": "vaapi", # go2rtc doesn't support qsv
|
||||
"preset-intel-qsv-h265": "vaapi",
|
||||
"preset-amd-vaapi": "vaapi",
|
||||
"preset-nvidia-h264": "cuda",
|
||||
"preset-nvidia-h265": "cuda",
|
||||
}
|
||||
|
||||
|
||||
def parse_preset_hardware_acceleration_decode(arg: Any) -> list[str]:
|
||||
"""Return the correct preset if in preset format otherwise return None."""
|
||||
if not isinstance(arg, str):
|
||||
return None
|
||||
|
||||
return PRESETS_HW_ACCEL_DECODE.get(arg, None)
|
||||
|
||||
|
||||
def parse_preset_hardware_acceleration_scale(
|
||||
arg: Any,
|
||||
detect_args: list[str],
|
||||
fps: int,
|
||||
width: int,
|
||||
height: int,
|
||||
) -> list[str]:
|
||||
"""Return the correct scaling preset or default preset if none is set."""
|
||||
if not isinstance(arg, str) or " " in arg:
|
||||
scale = PRESETS_HW_ACCEL_SCALE["default"].copy()
|
||||
scale[1] = str(fps)
|
||||
scale[3] = f"{width}x{height}"
|
||||
scale.extend(detect_args)
|
||||
return scale
|
||||
|
||||
scale = PRESETS_HW_ACCEL_SCALE.get(arg, PRESETS_HW_ACCEL_SCALE["default"]).copy()
|
||||
scale[1] = scale[1].format(fps, width, height)
|
||||
return scale
|
||||
|
||||
|
||||
def parse_preset_hardware_acceleration_encode(arg: Any, input: str, output: str) -> str:
|
||||
"""Return the correct scaling preset or default preset if none is set."""
|
||||
if not isinstance(arg, str):
|
||||
return PRESETS_HW_ACCEL_ENCODE["default"].format(input, output)
|
||||
|
||||
return PRESETS_HW_ACCEL_ENCODE.get(arg, PRESETS_HW_ACCEL_ENCODE["default"]).format(
|
||||
input,
|
||||
output,
|
||||
)
|
||||
|
||||
|
||||
def parse_preset_hardware_acceleration_go2rtc_engine(arg: Any) -> list[str]:
|
||||
"""Return the correct engine for the preset otherwise returns None."""
|
||||
if not isinstance(arg, str):
|
||||
return None
|
||||
|
||||
return PRESETS_HW_ACCEL_GO2RTC_ENGINE.get(arg)
|
||||
|
||||
|
||||
PRESETS_INPUT = {
|
||||
"preset-http-jpeg-generic": _user_agent_args
|
||||
+ [
|
||||
"-r",
|
||||
"{}",
|
||||
"-stream_loop",
|
||||
"-1",
|
||||
"-f",
|
||||
"image2",
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"nobuffer",
|
||||
"-flags",
|
||||
"low_delay",
|
||||
"-strict",
|
||||
"experimental",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
],
|
||||
"preset-http-mjpeg-generic": _user_agent_args
|
||||
+ [
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"nobuffer",
|
||||
"-flags",
|
||||
"low_delay",
|
||||
"-strict",
|
||||
"experimental",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
],
|
||||
"preset-http-reolink": _user_agent_args
|
||||
+ [
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-flags",
|
||||
"low_delay",
|
||||
"-strict",
|
||||
"experimental",
|
||||
"-analyzeduration",
|
||||
"1000M",
|
||||
"-probesize",
|
||||
"1000M",
|
||||
"-rw_timeout",
|
||||
"5000000",
|
||||
],
|
||||
"preset-rtmp-generic": [
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"nobuffer",
|
||||
"-flags",
|
||||
"low_delay",
|
||||
"-strict",
|
||||
"experimental",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-rw_timeout",
|
||||
"5000000",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
"-f",
|
||||
"live_flv",
|
||||
],
|
||||
"preset-rtsp-generic": _user_agent_args
|
||||
+ [
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-rtsp_transport",
|
||||
"tcp",
|
||||
TIMEOUT_PARAM,
|
||||
"5000000",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
],
|
||||
"preset-rtsp-udp": _user_agent_args
|
||||
+ [
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-rtsp_transport",
|
||||
"udp",
|
||||
TIMEOUT_PARAM,
|
||||
"5000000",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
],
|
||||
"preset-rtsp-blue-iris": _user_agent_args
|
||||
+ [
|
||||
"-user_agent",
|
||||
f"FFmpeg Frigate/{VERSION}",
|
||||
"-avoid_negative_ts",
|
||||
"make_zero",
|
||||
"-flags",
|
||||
"low_delay",
|
||||
"-strict",
|
||||
"experimental",
|
||||
"-fflags",
|
||||
"+genpts+discardcorrupt",
|
||||
"-rtsp_transport",
|
||||
"tcp",
|
||||
TIMEOUT_PARAM,
|
||||
"5000000",
|
||||
"-use_wallclock_as_timestamps",
|
||||
"1",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def parse_preset_input(arg: Any, detect_fps: int) -> list[str]:
|
||||
"""Return the correct preset if in preset format otherwise return None."""
|
||||
if not isinstance(arg, str):
|
||||
return None
|
||||
|
||||
if arg == "preset-http-jpeg-generic":
|
||||
input = PRESETS_INPUT[arg].copy()
|
||||
input[1] = str(detect_fps)
|
||||
return input
|
||||
|
||||
return PRESETS_INPUT.get(arg, None)
|
||||
|
||||
|
||||
PRESETS_RECORD_OUTPUT = {
|
||||
"preset-record-generic": [
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
"10",
|
||||
"-segment_format",
|
||||
"mp4",
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
"-strftime",
|
||||
"1",
|
||||
"-c",
|
||||
"copy",
|
||||
"-an",
|
||||
],
|
||||
"preset-record-generic-audio": [
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
"10",
|
||||
"-segment_format",
|
||||
"mp4",
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
"-strftime",
|
||||
"1",
|
||||
"-c:v",
|
||||
"copy",
|
||||
"-c:a",
|
||||
"aac",
|
||||
],
|
||||
"preset-record-mjpeg": [
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
"10",
|
||||
"-segment_format",
|
||||
"mp4",
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
"-strftime",
|
||||
"1",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-an",
|
||||
],
|
||||
"preset-record-jpeg": [
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
"10",
|
||||
"-segment_format",
|
||||
"mp4",
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
"-strftime",
|
||||
"1",
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-an",
|
||||
],
|
||||
"preset-record-ubiquiti": [
|
||||
"-f",
|
||||
"segment",
|
||||
"-segment_time",
|
||||
"10",
|
||||
"-segment_format",
|
||||
"mp4",
|
||||
"-reset_timestamps",
|
||||
"1",
|
||||
"-strftime",
|
||||
"1",
|
||||
"-c:v",
|
||||
"copy",
|
||||
"-ar",
|
||||
"44100",
|
||||
"-c:a",
|
||||
"aac",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def parse_preset_output_record(arg: Any) -> list[str]:
|
||||
"""Return the correct preset if in preset format otherwise return None."""
|
||||
if not isinstance(arg, str):
|
||||
return None
|
||||
|
||||
return PRESETS_RECORD_OUTPUT.get(arg, None)
|
||||
|
||||
|
||||
PRESETS_RTMP_OUTPUT = {
|
||||
"preset-rtmp-generic": ["-c", "copy", "-f", "flv"],
|
||||
"preset-rtmp-mjpeg": ["-c:v", "libx264", "-an", "-f", "flv"],
|
||||
"preset-rtmp-jpeg": ["-c:v", "libx264", "-an", "-f", "flv"],
|
||||
"preset-rtmp-ubiquiti": [
|
||||
"-c:v",
|
||||
"copy",
|
||||
"-f",
|
||||
"flv",
|
||||
"-ar",
|
||||
"44100",
|
||||
"-c:a",
|
||||
"aac",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def parse_preset_output_rtmp(arg: Any) -> list[str]:
|
||||
"""Return the correct preset if in preset format otherwise return None."""
|
||||
if not isinstance(arg, str):
|
||||
return None
|
||||
|
||||
return PRESETS_RTMP_OUTPUT.get(arg, None)
|
||||
504
frigate/http.py
@@ -1,13 +1,19 @@
|
||||
import base64
|
||||
from collections import OrderedDict
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import copy
|
||||
import glob
|
||||
import logging
|
||||
import json
|
||||
import os
|
||||
import subprocess as sp
|
||||
import pytz
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from functools import reduce
|
||||
from pathlib import Path
|
||||
from tzlocal import get_localzone_name
|
||||
from urllib.parse import unquote
|
||||
|
||||
import cv2
|
||||
|
||||
@@ -25,9 +31,18 @@ from flask import (
|
||||
from peewee import SqliteDatabase, operator, fn, DoesNotExist
|
||||
from playhouse.shortcuts import model_to_dict
|
||||
|
||||
from frigate.const import CLIPS_DIR, PLUS_ENV_VAR
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.const import CLIPS_DIR, MAX_SEGMENT_DURATION, RECORD_DIR
|
||||
from frigate.models import Event, Recordings
|
||||
from frigate.object_processing import TrackedObject
|
||||
from frigate.stats import stats_snapshot
|
||||
from frigate.util import (
|
||||
clean_camera_user_pass,
|
||||
ffprobe_stream,
|
||||
restart_frigate,
|
||||
vainfo_hwaccel,
|
||||
)
|
||||
from frigate.storage import StorageMaintainer
|
||||
from frigate.version import VERSION
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -40,6 +55,7 @@ def create_app(
|
||||
database: SqliteDatabase,
|
||||
stats_tracking,
|
||||
detected_frames_processor,
|
||||
storage_maintainer: StorageMaintainer,
|
||||
plus_api,
|
||||
):
|
||||
app = Flask(__name__)
|
||||
@@ -57,7 +73,10 @@ def create_app(
|
||||
app.frigate_config = frigate_config
|
||||
app.stats_tracking = stats_tracking
|
||||
app.detected_frames_processor = detected_frames_processor
|
||||
app.storage_maintainer = storage_maintainer
|
||||
app.plus_api = plus_api
|
||||
app.camera_error_image = None
|
||||
app.hwaccel_errors = []
|
||||
|
||||
app.register_blueprint(bp)
|
||||
|
||||
@@ -71,6 +90,8 @@ def is_healthy():
|
||||
|
||||
@bp.route("/events/summary")
|
||||
def events_summary():
|
||||
tz_name = request.args.get("timezone", default="utc", type=str)
|
||||
tz_offset = f"{int(datetime.now(pytz.timezone(tz_name)).utcoffset().total_seconds()/60/60)} hour"
|
||||
has_clip = request.args.get("has_clip", type=int)
|
||||
has_snapshot = request.args.get("has_snapshot", type=int)
|
||||
|
||||
@@ -90,7 +111,7 @@ def events_summary():
|
||||
Event.camera,
|
||||
Event.label,
|
||||
fn.strftime(
|
||||
"%Y-%m-%d", fn.datetime(Event.start_time, "unixepoch", "localtime")
|
||||
"%Y-%m-%d", fn.datetime(Event.start_time, "unixepoch", tz_offset)
|
||||
).alias("day"),
|
||||
Event.zones,
|
||||
fn.COUNT(Event.id).alias("count"),
|
||||
@@ -100,7 +121,7 @@ def events_summary():
|
||||
Event.camera,
|
||||
Event.label,
|
||||
fn.strftime(
|
||||
"%Y-%m-%d", fn.datetime(Event.start_time, "unixepoch", "localtime")
|
||||
"%Y-%m-%d", fn.datetime(Event.start_time, "unixepoch", tz_offset)
|
||||
),
|
||||
Event.zones,
|
||||
)
|
||||
@@ -210,7 +231,7 @@ def delete_retain(id):
|
||||
@bp.route("/events/<id>/sub_label", methods=("POST",))
|
||||
def set_sub_label(id):
|
||||
try:
|
||||
event = Event.get(Event.id == id)
|
||||
event: Event = Event.get(Event.id == id)
|
||||
except DoesNotExist:
|
||||
return make_response(
|
||||
jsonify({"success": False, "message": "Event " + id + " not found"}), 404
|
||||
@@ -233,6 +254,16 @@ def set_sub_label(id):
|
||||
400,
|
||||
)
|
||||
|
||||
if not event.end_time:
|
||||
tracked_obj: TrackedObject = (
|
||||
current_app.detected_frames_processor.camera_states[
|
||||
event.camera
|
||||
].tracked_objects.get(event.id)
|
||||
)
|
||||
|
||||
if tracked_obj:
|
||||
tracked_obj.obj_data["sub_label"] = new_sub_label
|
||||
|
||||
event.sub_label = new_sub_label
|
||||
event.save()
|
||||
return make_response(
|
||||
@@ -248,6 +279,8 @@ def set_sub_label(id):
|
||||
|
||||
@bp.route("/sub_labels")
|
||||
def get_sub_labels():
|
||||
split_joined = request.args.get("split_joined", type=int)
|
||||
|
||||
try:
|
||||
events = Event.select(Event.sub_label).distinct()
|
||||
except Exception as e:
|
||||
@@ -260,6 +293,16 @@ def get_sub_labels():
|
||||
if None in sub_labels:
|
||||
sub_labels.remove(None)
|
||||
|
||||
if split_joined:
|
||||
for label in sub_labels:
|
||||
if "," in label:
|
||||
sub_labels.remove(label)
|
||||
parts = label.split(",")
|
||||
|
||||
for part in parts:
|
||||
if not (part.strip()) in sub_labels:
|
||||
sub_labels.append(part.strip())
|
||||
|
||||
return jsonify(sub_labels)
|
||||
|
||||
|
||||
@@ -341,11 +384,11 @@ def event_thumbnail(id, max_cache_age=2592000):
|
||||
@bp.route("/<camera_name>/<label>/best.jpg")
|
||||
@bp.route("/<camera_name>/<label>/thumbnail.jpg")
|
||||
def label_thumbnail(camera_name, label):
|
||||
label = unquote(label)
|
||||
if label == "any":
|
||||
event_query = (
|
||||
Event.select()
|
||||
.where(Event.camera == camera_name)
|
||||
.where(Event.has_snapshot == True)
|
||||
.order_by(Event.start_time.desc())
|
||||
)
|
||||
else:
|
||||
@@ -353,7 +396,6 @@ def label_thumbnail(camera_name, label):
|
||||
Event.select()
|
||||
.where(Event.camera == camera_name)
|
||||
.where(Event.label == label)
|
||||
.where(Event.has_snapshot == True)
|
||||
.order_by(Event.start_time.desc())
|
||||
)
|
||||
|
||||
@@ -424,6 +466,7 @@ def event_snapshot(id):
|
||||
|
||||
@bp.route("/<camera_name>/<label>/snapshot.jpg")
|
||||
def label_snapshot(camera_name, label):
|
||||
label = unquote(label)
|
||||
if label == "any":
|
||||
event_query = (
|
||||
Event.select()
|
||||
@@ -489,16 +532,42 @@ def event_clip(id):
|
||||
|
||||
@bp.route("/events")
|
||||
def events():
|
||||
limit = request.args.get("limit", 100)
|
||||
camera = request.args.get("camera", "all")
|
||||
label = request.args.get("label", "all")
|
||||
cameras = request.args.get("cameras", "all")
|
||||
|
||||
# handle old camera arg
|
||||
if cameras == "all" and camera != "all":
|
||||
cameras = camera
|
||||
|
||||
label = unquote(request.args.get("label", "all"))
|
||||
labels = request.args.get("labels", "all")
|
||||
|
||||
# handle old label arg
|
||||
if labels == "all" and label != "all":
|
||||
labels = label
|
||||
|
||||
sub_label = request.args.get("sub_label", "all")
|
||||
sub_labels = request.args.get("sub_labels", "all")
|
||||
|
||||
# handle old sub_label arg
|
||||
if sub_labels == "all" and sub_label != "all":
|
||||
sub_labels = sub_label
|
||||
|
||||
zone = request.args.get("zone", "all")
|
||||
zones = request.args.get("zones", "all")
|
||||
|
||||
# handle old label arg
|
||||
if zones == "all" and zone != "all":
|
||||
zones = zone
|
||||
|
||||
limit = request.args.get("limit", 100)
|
||||
after = request.args.get("after", type=float)
|
||||
before = request.args.get("before", type=float)
|
||||
has_clip = request.args.get("has_clip", type=int)
|
||||
has_snapshot = request.args.get("has_snapshot", type=int)
|
||||
in_progress = request.args.get("in_progress", type=int)
|
||||
include_thumbnails = request.args.get("include_thumbnails", default=1, type=int)
|
||||
favorites = request.args.get("favorites", type=int)
|
||||
|
||||
clauses = []
|
||||
excluded_fields = []
|
||||
@@ -521,14 +590,46 @@ def events():
|
||||
if camera != "all":
|
||||
clauses.append((Event.camera == camera))
|
||||
|
||||
if label != "all":
|
||||
clauses.append((Event.label == label))
|
||||
if cameras != "all":
|
||||
camera_list = cameras.split(",")
|
||||
clauses.append((Event.camera << camera_list))
|
||||
|
||||
if sub_label != "all":
|
||||
clauses.append((Event.sub_label == sub_label))
|
||||
if labels != "all":
|
||||
label_list = labels.split(",")
|
||||
clauses.append((Event.label << label_list))
|
||||
|
||||
if zone != "all":
|
||||
clauses.append((Event.zones.cast("text") % f'*"{zone}"*'))
|
||||
if sub_labels != "all":
|
||||
# use matching so joined sub labels are included
|
||||
# for example a sub label 'bob' would get events
|
||||
# with sub labels 'bob' and 'bob, john'
|
||||
sub_label_clauses = []
|
||||
filtered_sub_labels = sub_labels.split(",")
|
||||
|
||||
if "None" in filtered_sub_labels:
|
||||
filtered_sub_labels.remove("None")
|
||||
sub_label_clauses.append((Event.sub_label.is_null()))
|
||||
|
||||
for label in filtered_sub_labels:
|
||||
sub_label_clauses.append((Event.sub_label.cast("text") % f"*{label}*"))
|
||||
|
||||
sub_label_clause = reduce(operator.or_, sub_label_clauses)
|
||||
clauses.append((sub_label_clause))
|
||||
|
||||
if zones != "all":
|
||||
# use matching so events with multiple zones
|
||||
# still match on a search where any zone matches
|
||||
zone_clauses = []
|
||||
filtered_zones = zones.split(",")
|
||||
|
||||
if "None" in filtered_zones:
|
||||
filtered_zones.remove("None")
|
||||
zone_clauses.append((Event.zones.length() == 0))
|
||||
|
||||
for zone in filtered_zones:
|
||||
zone_clauses.append((Event.zones.cast("text") % f'*"{zone}"*'))
|
||||
|
||||
zone_clause = reduce(operator.or_, zone_clauses)
|
||||
clauses.append((zone_clause))
|
||||
|
||||
if after:
|
||||
clauses.append((Event.start_time > after))
|
||||
@@ -542,11 +643,17 @@ def events():
|
||||
if not has_snapshot is None:
|
||||
clauses.append((Event.has_snapshot == has_snapshot))
|
||||
|
||||
if not in_progress is None:
|
||||
clauses.append((Event.end_time.is_null(in_progress)))
|
||||
|
||||
if not include_thumbnails:
|
||||
excluded_fields.append(Event.thumbnail)
|
||||
else:
|
||||
selected_columns.append(Event.thumbnail)
|
||||
|
||||
if favorites:
|
||||
clauses.append((Event.retain_indefinitely == favorites))
|
||||
|
||||
if len(clauses) == 0:
|
||||
clauses.append((True))
|
||||
|
||||
@@ -564,19 +671,98 @@ def events():
|
||||
def config():
|
||||
config = current_app.frigate_config.dict()
|
||||
|
||||
# add in the ffmpeg_cmds
|
||||
for camera_name, camera in current_app.frigate_config.cameras.items():
|
||||
camera_dict = config["cameras"][camera_name]
|
||||
|
||||
# clean paths
|
||||
for input in camera_dict.get("ffmpeg", {}).get("inputs", []):
|
||||
input["path"] = clean_camera_user_pass(input["path"])
|
||||
|
||||
# add clean ffmpeg_cmds
|
||||
camera_dict["ffmpeg_cmds"] = copy.deepcopy(camera.ffmpeg_cmds)
|
||||
for cmd in camera_dict["ffmpeg_cmds"]:
|
||||
cmd["cmd"] = " ".join(cmd["cmd"])
|
||||
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
|
||||
|
||||
config["plus"] = {"enabled": PLUS_ENV_VAR in os.environ}
|
||||
config["plus"] = {"enabled": current_app.plus_api.is_active()}
|
||||
|
||||
return jsonify(config)
|
||||
|
||||
|
||||
@bp.route("/config/schema")
|
||||
@bp.route("/config/raw")
|
||||
def config_raw():
|
||||
config_file = os.environ.get("CONFIG_FILE", "/config/config.yml")
|
||||
|
||||
# Check if we can use .yaml instead of .yml
|
||||
config_file_yaml = config_file.replace(".yml", ".yaml")
|
||||
|
||||
if os.path.isfile(config_file_yaml):
|
||||
config_file = config_file_yaml
|
||||
|
||||
if not os.path.isfile(config_file):
|
||||
return "Could not find file", 410
|
||||
|
||||
with open(config_file, "r") as f:
|
||||
raw_config = f.read()
|
||||
f.close()
|
||||
|
||||
return raw_config, 200
|
||||
|
||||
|
||||
@bp.route("/config/save", methods=["POST"])
|
||||
def config_save():
|
||||
new_config = request.get_data().decode()
|
||||
|
||||
if not new_config:
|
||||
return "Config with body param is required", 400
|
||||
|
||||
# Validate the config schema
|
||||
try:
|
||||
new_yaml = FrigateConfig.parse_raw(new_config)
|
||||
except Exception as e:
|
||||
return make_response(
|
||||
jsonify(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"\nConfig Error:\n\n{str(traceback.format_exc())}",
|
||||
}
|
||||
),
|
||||
400,
|
||||
)
|
||||
|
||||
# Save the config to file
|
||||
try:
|
||||
config_file = os.environ.get("CONFIG_FILE", "/config/config.yml")
|
||||
|
||||
# Check if we can use .yaml instead of .yml
|
||||
config_file_yaml = config_file.replace(".yml", ".yaml")
|
||||
|
||||
if os.path.isfile(config_file_yaml):
|
||||
config_file = config_file_yaml
|
||||
|
||||
with open(config_file, "w") as f:
|
||||
f.write(new_config)
|
||||
f.close()
|
||||
except Exception as e:
|
||||
return make_response(
|
||||
jsonify(
|
||||
{
|
||||
"success": False,
|
||||
"message": f"Could not write config file, be sure that frigate has write permission on the config file.",
|
||||
}
|
||||
),
|
||||
400,
|
||||
)
|
||||
|
||||
try:
|
||||
restart_frigate()
|
||||
except Exception as e:
|
||||
logging.error(f"Error restarting frigate: {e}")
|
||||
return "Config successfully saved, unable to restart frigate", 200
|
||||
|
||||
return "Config successfully saved, restarting...", 200
|
||||
|
||||
|
||||
@bp.route("/config/schema.json")
|
||||
def config_schema():
|
||||
return current_app.response_class(
|
||||
current_app.frigate_config.schema_json(), mimetype="application/json"
|
||||
@@ -590,7 +776,11 @@ def version():
|
||||
|
||||
@bp.route("/stats")
|
||||
def stats():
|
||||
stats = stats_snapshot(current_app.stats_tracking)
|
||||
stats = stats_snapshot(
|
||||
current_app.frigate_config,
|
||||
current_app.stats_tracking,
|
||||
current_app.hwaccel_errors,
|
||||
)
|
||||
return jsonify(stats)
|
||||
|
||||
|
||||
@@ -638,8 +828,38 @@ def latest_frame(camera_name):
|
||||
frame = current_app.detected_frames_processor.get_current_frame(
|
||||
camera_name, draw_options
|
||||
)
|
||||
if frame is None:
|
||||
frame = np.zeros((720, 1280, 3), np.uint8)
|
||||
|
||||
if frame is None or datetime.now().timestamp() > (
|
||||
current_app.detected_frames_processor.get_current_frame_time(camera_name)
|
||||
+ 10
|
||||
):
|
||||
if current_app.camera_error_image is None:
|
||||
error_image = glob.glob("/opt/frigate/frigate/images/camera-error.jpg")
|
||||
|
||||
if len(error_image) > 0:
|
||||
current_app.camera_error_image = cv2.imread(
|
||||
error_image[0], cv2.IMREAD_UNCHANGED
|
||||
)
|
||||
|
||||
frame = current_app.camera_error_image
|
||||
|
||||
height = int(request.args.get("h", str(frame.shape[0])))
|
||||
width = int(height * frame.shape[1] / frame.shape[0])
|
||||
|
||||
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
|
||||
|
||||
ret, jpg = cv2.imencode(
|
||||
".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), resize_quality]
|
||||
)
|
||||
response = make_response(jpg.tobytes())
|
||||
response.headers["Content-Type"] = "image/jpeg"
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return response
|
||||
elif camera_name == "birdseye" and current_app.frigate_config.restream.birdseye:
|
||||
frame = cv2.cvtColor(
|
||||
current_app.detected_frames_processor.get_current_frame(camera_name),
|
||||
cv2.COLOR_YUV2BGR_I420,
|
||||
)
|
||||
|
||||
height = int(request.args.get("h", str(frame.shape[0])))
|
||||
width = int(height * frame.shape[1] / frame.shape[0])
|
||||
@@ -657,14 +877,38 @@ def latest_frame(camera_name):
|
||||
return "Camera named {} not found".format(camera_name), 404
|
||||
|
||||
|
||||
@bp.route("/recordings/storage", methods=["GET"])
|
||||
def get_recordings_storage_usage():
|
||||
recording_stats = stats_snapshot(
|
||||
current_app.frigate_config,
|
||||
current_app.stats_tracking,
|
||||
current_app.hwaccel_errors,
|
||||
)["service"]["storage"][RECORD_DIR]
|
||||
total_mb = recording_stats["total"]
|
||||
|
||||
camera_usages: dict[
|
||||
str, dict
|
||||
] = current_app.storage_maintainer.calculate_camera_usages()
|
||||
|
||||
for camera_name in camera_usages.keys():
|
||||
if camera_usages.get(camera_name, {}).get("usage"):
|
||||
camera_usages[camera_name]["usage_percent"] = (
|
||||
camera_usages.get(camera_name, {}).get("usage", 0) / total_mb
|
||||
) * 100
|
||||
|
||||
return jsonify(camera_usages)
|
||||
|
||||
|
||||
# return hourly summary for recordings of camera
|
||||
@bp.route("/<camera_name>/recordings/summary")
|
||||
def recordings_summary(camera_name):
|
||||
tz_name = request.args.get("timezone", default="utc", type=str)
|
||||
tz_offset = f"{int(datetime.now(pytz.timezone(tz_name)).utcoffset().total_seconds()/60/60)} hour"
|
||||
recording_groups = (
|
||||
Recordings.select(
|
||||
fn.strftime(
|
||||
"%Y-%m-%d %H",
|
||||
fn.datetime(Recordings.start_time, "unixepoch", "localtime"),
|
||||
fn.datetime(Recordings.start_time, "unixepoch", tz_offset),
|
||||
).alias("hour"),
|
||||
fn.SUM(Recordings.duration).alias("duration"),
|
||||
fn.SUM(Recordings.motion).alias("motion"),
|
||||
@@ -674,13 +918,13 @@ def recordings_summary(camera_name):
|
||||
.group_by(
|
||||
fn.strftime(
|
||||
"%Y-%m-%d %H",
|
||||
fn.datetime(Recordings.start_time, "unixepoch", "localtime"),
|
||||
fn.datetime(Recordings.start_time, "unixepoch", tz_offset),
|
||||
)
|
||||
)
|
||||
.order_by(
|
||||
fn.strftime(
|
||||
"%Y-%m-%d H",
|
||||
fn.datetime(Recordings.start_time, "unixepoch", "localtime"),
|
||||
fn.datetime(Recordings.start_time, "unixepoch", tz_offset),
|
||||
).desc()
|
||||
)
|
||||
)
|
||||
@@ -688,14 +932,16 @@ def recordings_summary(camera_name):
|
||||
event_groups = (
|
||||
Event.select(
|
||||
fn.strftime(
|
||||
"%Y-%m-%d %H", fn.datetime(Event.start_time, "unixepoch", "localtime")
|
||||
"%Y-%m-%d %H",
|
||||
fn.datetime(Event.start_time, "unixepoch", tz_offset),
|
||||
).alias("hour"),
|
||||
fn.COUNT(Event.id).alias("count"),
|
||||
)
|
||||
.where(Event.camera == camera_name, Event.has_clip)
|
||||
.group_by(
|
||||
fn.strftime(
|
||||
"%Y-%m-%d %H", fn.datetime(Event.start_time, "unixepoch", "localtime")
|
||||
"%Y-%m-%d %H",
|
||||
fn.datetime(Event.start_time, "unixepoch", tz_offset),
|
||||
),
|
||||
)
|
||||
.objects()
|
||||
@@ -739,6 +985,7 @@ def recordings(camera_name):
|
||||
Recordings.id,
|
||||
Recordings.start_time,
|
||||
Recordings.end_time,
|
||||
Recordings.segment_size,
|
||||
Recordings.motion,
|
||||
Recordings.objects,
|
||||
)
|
||||
@@ -753,9 +1000,9 @@ def recordings(camera_name):
|
||||
return jsonify([e for e in recordings.dicts()])
|
||||
|
||||
|
||||
@bp.route("/<camera>/start/<int:start_ts>/end/<int:end_ts>/clip.mp4")
|
||||
@bp.route("/<camera>/start/<float:start_ts>/end/<float:end_ts>/clip.mp4")
|
||||
def recording_clip(camera, start_ts, end_ts):
|
||||
@bp.route("/<camera_name>/start/<int:start_ts>/end/<int:end_ts>/clip.mp4")
|
||||
@bp.route("/<camera_name>/start/<float:start_ts>/end/<float:end_ts>/clip.mp4")
|
||||
def recording_clip(camera_name, start_ts, end_ts):
|
||||
download = request.args.get("download", type=bool)
|
||||
|
||||
recordings = (
|
||||
@@ -765,7 +1012,7 @@ def recording_clip(camera, start_ts, end_ts):
|
||||
| (Recordings.end_time.between(start_ts, end_ts))
|
||||
| ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time))
|
||||
)
|
||||
.where(Recordings.camera == camera)
|
||||
.where(Recordings.camera == camera_name)
|
||||
.order_by(Recordings.start_time.asc())
|
||||
)
|
||||
|
||||
@@ -780,36 +1027,41 @@ def recording_clip(camera, start_ts, end_ts):
|
||||
if clip.end_time > end_ts:
|
||||
playlist_lines.append(f"outpoint {int(end_ts - clip.start_time)}")
|
||||
|
||||
file_name = f"clip_{camera}_{start_ts}-{end_ts}.mp4"
|
||||
file_name = f"clip_{camera_name}_{start_ts}-{end_ts}.mp4"
|
||||
path = f"/tmp/cache/{file_name}"
|
||||
|
||||
ffmpeg_cmd = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-protocol_whitelist",
|
||||
"pipe,file",
|
||||
"-f",
|
||||
"concat",
|
||||
"-safe",
|
||||
"0",
|
||||
"-i",
|
||||
"/dev/stdin",
|
||||
"-c",
|
||||
"copy",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
path,
|
||||
]
|
||||
if not os.path.exists(path):
|
||||
ffmpeg_cmd = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-protocol_whitelist",
|
||||
"pipe,file",
|
||||
"-f",
|
||||
"concat",
|
||||
"-safe",
|
||||
"0",
|
||||
"-i",
|
||||
"/dev/stdin",
|
||||
"-c",
|
||||
"copy",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
path,
|
||||
]
|
||||
p = sp.run(
|
||||
ffmpeg_cmd,
|
||||
input="\n".join(playlist_lines),
|
||||
encoding="ascii",
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
p = sp.run(
|
||||
ffmpeg_cmd,
|
||||
input="\n".join(playlist_lines),
|
||||
encoding="ascii",
|
||||
capture_output=True,
|
||||
)
|
||||
if p.returncode != 0:
|
||||
logger.error(p.stderr)
|
||||
return f"Could not create clip from recordings for {camera}.", 500
|
||||
if p.returncode != 0:
|
||||
logger.error(p.stderr)
|
||||
return f"Could not create clip from recordings for {camera_name}.", 500
|
||||
else:
|
||||
logger.debug(
|
||||
f"Ignoring subsequent request for {path} as it already exists in the cache."
|
||||
)
|
||||
|
||||
response = make_response()
|
||||
response.headers["Content-Description"] = "File Transfer"
|
||||
@@ -825,9 +1077,9 @@ def recording_clip(camera, start_ts, end_ts):
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/vod/<camera>/start/<int:start_ts>/end/<int:end_ts>")
|
||||
@bp.route("/vod/<camera>/start/<float:start_ts>/end/<float:end_ts>")
|
||||
def vod_ts(camera, start_ts, end_ts):
|
||||
@bp.route("/vod/<camera_name>/start/<int:start_ts>/end/<int:end_ts>")
|
||||
@bp.route("/vod/<camera_name>/start/<float:start_ts>/end/<float:end_ts>")
|
||||
def vod_ts(camera_name, start_ts, end_ts):
|
||||
recordings = (
|
||||
Recordings.select()
|
||||
.where(
|
||||
@@ -835,27 +1087,25 @@ def vod_ts(camera, start_ts, end_ts):
|
||||
| Recordings.end_time.between(start_ts, end_ts)
|
||||
| ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time))
|
||||
)
|
||||
.where(Recordings.camera == camera)
|
||||
.where(Recordings.camera == camera_name)
|
||||
.order_by(Recordings.start_time.asc())
|
||||
)
|
||||
|
||||
clips = []
|
||||
durations = []
|
||||
max_duration_ms = MAX_SEGMENT_DURATION * 1000
|
||||
|
||||
recording: Recordings
|
||||
for recording in recordings:
|
||||
clip = {"type": "source", "path": recording.path}
|
||||
duration = int(recording.duration * 1000)
|
||||
# Determine if offset is needed for first clip
|
||||
if recording.start_time < start_ts:
|
||||
offset = int((start_ts - recording.start_time) * 1000)
|
||||
clip["clipFrom"] = offset
|
||||
duration -= offset
|
||||
|
||||
# Determine if we need to end the last clip early
|
||||
if recording.end_time > end_ts:
|
||||
duration -= int((recording.end_time - end_ts) * 1000)
|
||||
|
||||
if duration > 0:
|
||||
if 0 < duration < max_duration_ms:
|
||||
clip["keyFrameDurations"] = [duration]
|
||||
clips.append(clip)
|
||||
durations.append(duration)
|
||||
else:
|
||||
@@ -870,20 +1120,40 @@ def vod_ts(camera, start_ts, end_ts):
|
||||
{
|
||||
"cache": hour_ago.timestamp() > start_ts,
|
||||
"discontinuity": False,
|
||||
"consistentSequenceMediaInfo": True,
|
||||
"durations": durations,
|
||||
"segment_duration": max(durations),
|
||||
"sequences": [{"clips": clips}],
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/vod/<year_month>/<day>/<hour>/<camera>")
|
||||
def vod_hour(year_month, day, hour, camera):
|
||||
start_date = datetime.strptime(f"{year_month}-{day} {hour}", "%Y-%m-%d %H")
|
||||
@bp.route("/vod/<year_month>/<day>/<hour>/<camera_name>")
|
||||
def vod_hour_no_timezone(year_month, day, hour, camera_name):
|
||||
return vod_hour(
|
||||
year_month, day, hour, camera_name, get_localzone_name().replace("/", ",")
|
||||
)
|
||||
|
||||
|
||||
# TODO make this nicer when vod module is removed
|
||||
@bp.route("/vod/<year_month>/<day>/<hour>/<camera_name>/<tz_name>")
|
||||
def vod_hour(year_month, day, hour, camera_name, tz_name):
|
||||
tz_offset = int(
|
||||
datetime.now(pytz.timezone(tz_name.replace(",", "/")))
|
||||
.utcoffset()
|
||||
.total_seconds()
|
||||
/ 60
|
||||
/ 60
|
||||
)
|
||||
parts = year_month.split("-")
|
||||
start_date = datetime(
|
||||
int(parts[0]), int(parts[1]), int(day), int(hour), tzinfo=timezone.utc
|
||||
) - timedelta(hours=tz_offset)
|
||||
end_date = start_date + timedelta(hours=1) - timedelta(milliseconds=1)
|
||||
start_ts = start_date.timestamp()
|
||||
end_ts = end_date.timestamp()
|
||||
|
||||
return vod_ts(camera, start_ts, end_ts)
|
||||
return vod_ts(camera_name, start_ts, end_ts)
|
||||
|
||||
|
||||
@bp.route("/vod/event/<id>")
|
||||
@@ -941,3 +1211,91 @@ def imagestream(detected_frames_processor, camera_name, fps, height, draw_option
|
||||
b"--frame\r\n"
|
||||
b"Content-Type: image/jpeg\r\n\r\n" + jpg.tobytes() + b"\r\n\r\n"
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/ffprobe", methods=["GET"])
|
||||
def ffprobe():
|
||||
path_param = request.args.get("paths", "")
|
||||
|
||||
if not path_param:
|
||||
return jsonify(
|
||||
{"success": False, "message": f"Path needs to be provided."}, "404"
|
||||
)
|
||||
|
||||
if path_param.startswith("camera"):
|
||||
camera = path_param[7:]
|
||||
|
||||
if camera not in current_app.frigate_config.cameras.keys():
|
||||
return jsonify(
|
||||
{"success": False, "message": f"{camera} is not a valid camera."}, "404"
|
||||
)
|
||||
|
||||
if not current_app.frigate_config.cameras[camera].enabled:
|
||||
return jsonify(
|
||||
{"success": False, "message": f"{camera} is not enabled."}, "404"
|
||||
)
|
||||
|
||||
paths = map(
|
||||
lambda input: input.path,
|
||||
current_app.frigate_config.cameras[camera].ffmpeg.inputs,
|
||||
)
|
||||
elif "," in clean_camera_user_pass(path_param):
|
||||
paths = path_param.split(",")
|
||||
else:
|
||||
paths = [path_param]
|
||||
|
||||
# user has multiple streams
|
||||
output = []
|
||||
|
||||
for path in paths:
|
||||
ffprobe = ffprobe_stream(path.strip())
|
||||
output.append(
|
||||
{
|
||||
"return_code": ffprobe.returncode,
|
||||
"stderr": json.loads(ffprobe.stderr.decode("unicode_escape").strip())
|
||||
if ffprobe.stderr.decode()
|
||||
else {},
|
||||
"stdout": json.loads(ffprobe.stdout.decode("unicode_escape").strip())
|
||||
if ffprobe.stdout.decode()
|
||||
else {},
|
||||
}
|
||||
)
|
||||
|
||||
return jsonify(output)
|
||||
|
||||
|
||||
@bp.route("/vainfo", methods=["GET"])
|
||||
def vainfo():
|
||||
vainfo = vainfo_hwaccel()
|
||||
return jsonify(
|
||||
{
|
||||
"return_code": vainfo.returncode,
|
||||
"stderr": vainfo.stderr.decode("unicode_escape").strip()
|
||||
if vainfo.returncode != 0
|
||||
else "",
|
||||
"stdout": vainfo.stdout.decode("unicode_escape").strip()
|
||||
if vainfo.returncode == 0
|
||||
else "",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/logs/<service>", methods=["GET"])
|
||||
def logs(service: str):
|
||||
log_locations = {
|
||||
"frigate": "/dev/shm/logs/frigate/current",
|
||||
"go2rtc": "/dev/shm/logs/go2rtc/current",
|
||||
"nginx": "/dev/shm/logs/nginx/current",
|
||||
}
|
||||
service_location = log_locations.get(service)
|
||||
|
||||
if not service:
|
||||
return f"{service} is not a valid service", 404
|
||||
|
||||
try:
|
||||
file = open(service_location, "r")
|
||||
contents = file.read()
|
||||
file.close()
|
||||
return contents, 200
|
||||
except FileNotFoundError as e:
|
||||
return f"Could not find log file: {e}", 500
|
||||
|
||||
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.3 KiB |
BIN
frigate/images/camera-error.jpg
Normal file
|
After Width: | Height: | Size: 143 KiB |
@@ -2,7 +2,6 @@
|
||||
import logging
|
||||
import threading
|
||||
import os
|
||||
import signal
|
||||
import queue
|
||||
from multiprocessing.queues import Queue
|
||||
from logging import handlers
|
||||
@@ -10,6 +9,8 @@ from setproctitle import setproctitle
|
||||
from typing import Deque
|
||||
from collections import deque
|
||||
|
||||
from frigate.util import clean_camera_user_pass
|
||||
|
||||
|
||||
def listener_configurer() -> None:
|
||||
root = logging.getLogger()
|
||||
@@ -55,6 +56,11 @@ class LogPipe(threading.Thread):
|
||||
self.pipeReader = os.fdopen(self.fdRead)
|
||||
self.start()
|
||||
|
||||
def cleanup_log(self, log: str) -> str:
|
||||
"""Cleanup the log line to remove sensitive info and string tokens."""
|
||||
log = clean_camera_user_pass(log).strip("\n")
|
||||
return log
|
||||
|
||||
def fileno(self) -> int:
|
||||
"""Return the write file descriptor of the pipe"""
|
||||
return self.fdWrite
|
||||
@@ -62,7 +68,7 @@ class LogPipe(threading.Thread):
|
||||
def run(self) -> None:
|
||||
"""Run the thread, logging everything."""
|
||||
for line in iter(self.pipeReader.readline, ""):
|
||||
self.deque.append(line.strip("\n"))
|
||||
self.deque.append(self.cleanup_log(line))
|
||||
|
||||
self.pipeReader.close()
|
||||
|
||||
|
||||
@@ -41,3 +41,4 @@ class Recordings(Model): # type: ignore[misc]
|
||||
duration = FloatField()
|
||||
motion = IntegerField(null=True)
|
||||
objects = IntegerField(null=True)
|
||||
segment_size = FloatField(default=0) # this should be stored as MB
|
||||
|
||||
399
frigate/mqtt.py
@@ -1,399 +0,0 @@
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from wsgiref.simple_server import make_server
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
from ws4py.server.wsgirefserver import (
|
||||
WebSocketWSGIHandler,
|
||||
WebSocketWSGIRequestHandler,
|
||||
WSGIServer,
|
||||
)
|
||||
from ws4py.server.wsgiutils import WebSocketWSGIApplication
|
||||
from ws4py.websocket import WebSocket
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.util import restart_frigate
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_mqtt_client(config: FrigateConfig, camera_metrics):
|
||||
mqtt_config = config.mqtt
|
||||
|
||||
def on_recordings_command(client, userdata, message):
|
||||
payload = message.payload.decode()
|
||||
logger.debug(f"on_recordings_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
record_settings = config.cameras[camera_name].record
|
||||
|
||||
if payload == "ON":
|
||||
if not record_settings.enabled:
|
||||
logger.info(f"Turning on recordings for {camera_name} via mqtt")
|
||||
record_settings.enabled = True
|
||||
elif payload == "OFF":
|
||||
if record_settings.enabled:
|
||||
logger.info(f"Turning off recordings for {camera_name} via mqtt")
|
||||
record_settings.enabled = False
|
||||
else:
|
||||
logger.warning(f"Received unsupported value at {message.topic}: {payload}")
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_snapshots_command(client, userdata, message):
|
||||
payload = message.payload.decode()
|
||||
logger.debug(f"on_snapshots_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
snapshots_settings = config.cameras[camera_name].snapshots
|
||||
|
||||
if payload == "ON":
|
||||
if not snapshots_settings.enabled:
|
||||
logger.info(f"Turning on snapshots for {camera_name} via mqtt")
|
||||
snapshots_settings.enabled = True
|
||||
elif payload == "OFF":
|
||||
if snapshots_settings.enabled:
|
||||
logger.info(f"Turning off snapshots for {camera_name} via mqtt")
|
||||
snapshots_settings.enabled = False
|
||||
else:
|
||||
logger.warning(f"Received unsupported value at {message.topic}: {payload}")
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_detect_command(client, userdata, message):
|
||||
payload = message.payload.decode()
|
||||
logger.debug(f"on_detect_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
detect_settings = config.cameras[camera_name].detect
|
||||
|
||||
if payload == "ON":
|
||||
if not camera_metrics[camera_name]["detection_enabled"].value:
|
||||
logger.info(f"Turning on detection for {camera_name} via mqtt")
|
||||
camera_metrics[camera_name]["detection_enabled"].value = True
|
||||
detect_settings.enabled = True
|
||||
|
||||
if not camera_metrics[camera_name]["motion_enabled"].value:
|
||||
logger.info(
|
||||
f"Turning on motion for {camera_name} due to detection being enabled."
|
||||
)
|
||||
camera_metrics[camera_name]["motion_enabled"].value = True
|
||||
elif payload == "OFF":
|
||||
if camera_metrics[camera_name]["detection_enabled"].value:
|
||||
logger.info(f"Turning off detection for {camera_name} via mqtt")
|
||||
camera_metrics[camera_name]["detection_enabled"].value = False
|
||||
detect_settings.enabled = False
|
||||
else:
|
||||
logger.warning(f"Received unsupported value at {message.topic}: {payload}")
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_motion_command(client, userdata, message):
|
||||
payload = message.payload.decode()
|
||||
logger.debug(f"on_motion_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
if payload == "ON":
|
||||
if not camera_metrics[camera_name]["motion_enabled"].value:
|
||||
logger.info(f"Turning on motion for {camera_name} via mqtt")
|
||||
camera_metrics[camera_name]["motion_enabled"].value = True
|
||||
elif payload == "OFF":
|
||||
if camera_metrics[camera_name]["detection_enabled"].value:
|
||||
logger.error(
|
||||
f"Turning off motion is not allowed when detection is enabled."
|
||||
)
|
||||
return
|
||||
|
||||
if camera_metrics[camera_name]["motion_enabled"].value:
|
||||
logger.info(f"Turning off motion for {camera_name} via mqtt")
|
||||
camera_metrics[camera_name]["motion_enabled"].value = False
|
||||
else:
|
||||
logger.warning(f"Received unsupported value at {message.topic}: {payload}")
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_improve_contrast_command(client, userdata, message):
|
||||
payload = message.payload.decode()
|
||||
logger.debug(f"on_improve_contrast_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
motion_settings = config.cameras[camera_name].motion
|
||||
|
||||
if payload == "ON":
|
||||
if not camera_metrics[camera_name]["improve_contrast_enabled"].value:
|
||||
logger.info(f"Turning on improve contrast for {camera_name} via mqtt")
|
||||
camera_metrics[camera_name]["improve_contrast_enabled"].value = True
|
||||
motion_settings.improve_contrast = True
|
||||
elif payload == "OFF":
|
||||
if camera_metrics[camera_name]["improve_contrast_enabled"].value:
|
||||
logger.info(f"Turning off improve contrast for {camera_name} via mqtt")
|
||||
camera_metrics[camera_name]["improve_contrast_enabled"].value = False
|
||||
motion_settings.improve_contrast = False
|
||||
else:
|
||||
logger.warning(f"Received unsupported value at {message.topic}: {payload}")
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_motion_threshold_command(client, userdata, message):
|
||||
try:
|
||||
payload = int(message.payload.decode())
|
||||
except ValueError:
|
||||
logger.warning(
|
||||
f"Received unsupported value at {message.topic}: {message.payload.decode()}"
|
||||
)
|
||||
return
|
||||
|
||||
logger.debug(f"on_motion_threshold_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
motion_settings = config.cameras[camera_name].motion
|
||||
|
||||
logger.info(f"Setting motion threshold for {camera_name} via mqtt: {payload}")
|
||||
camera_metrics[camera_name]["motion_threshold"].value = payload
|
||||
motion_settings.threshold = payload
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_motion_contour_area_command(client, userdata, message):
|
||||
try:
|
||||
payload = int(message.payload.decode())
|
||||
except ValueError:
|
||||
logger.warning(
|
||||
f"Received unsupported value at {message.topic}: {message.payload.decode()}"
|
||||
)
|
||||
return
|
||||
|
||||
logger.debug(f"on_motion_contour_area_toggle: {message.topic} {payload}")
|
||||
|
||||
camera_name = message.topic.split("/")[-3]
|
||||
|
||||
motion_settings = config.cameras[camera_name].motion
|
||||
|
||||
logger.info(
|
||||
f"Setting motion contour area for {camera_name} via mqtt: {payload}"
|
||||
)
|
||||
camera_metrics[camera_name]["motion_contour_area"].value = payload
|
||||
motion_settings.contour_area = payload
|
||||
|
||||
state_topic = f"{message.topic[:-4]}/state"
|
||||
client.publish(state_topic, payload, retain=True)
|
||||
|
||||
def on_restart_command(client, userdata, message):
|
||||
restart_frigate()
|
||||
|
||||
def on_connect(client, userdata, flags, rc):
|
||||
threading.current_thread().name = "mqtt"
|
||||
if rc != 0:
|
||||
if rc == 3:
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: MQTT Server unavailable"
|
||||
)
|
||||
elif rc == 4:
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: MQTT Bad username or password"
|
||||
)
|
||||
elif rc == 5:
|
||||
logger.error("Unable to connect to MQTT server: MQTT Not authorized")
|
||||
else:
|
||||
logger.error(
|
||||
"Unable to connect to MQTT server: Connection refused. Error code: "
|
||||
+ str(rc)
|
||||
)
|
||||
|
||||
logger.debug("MQTT connected")
|
||||
client.subscribe(f"{mqtt_config.topic_prefix}/#")
|
||||
client.publish(mqtt_config.topic_prefix + "/available", "online", retain=True)
|
||||
|
||||
client = mqtt.Client(client_id=mqtt_config.client_id)
|
||||
client.on_connect = on_connect
|
||||
client.will_set(
|
||||
mqtt_config.topic_prefix + "/available", payload="offline", qos=1, retain=True
|
||||
)
|
||||
|
||||
# register callbacks
|
||||
for name in config.cameras.keys():
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/recordings/set", on_recordings_command
|
||||
)
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/snapshots/set", on_snapshots_command
|
||||
)
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/detect/set", on_detect_command
|
||||
)
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion/set", on_motion_command
|
||||
)
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/improve_contrast/set",
|
||||
on_improve_contrast_command,
|
||||
)
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion_threshold/set",
|
||||
on_motion_threshold_command,
|
||||
)
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion_contour_area/set",
|
||||
on_motion_contour_area_command,
|
||||
)
|
||||
|
||||
client.message_callback_add(
|
||||
f"{mqtt_config.topic_prefix}/restart", on_restart_command
|
||||
)
|
||||
|
||||
if not mqtt_config.tls_ca_certs is None:
|
||||
if (
|
||||
not mqtt_config.tls_client_cert is None
|
||||
and not mqtt_config.tls_client_key is None
|
||||
):
|
||||
client.tls_set(
|
||||
mqtt_config.tls_ca_certs,
|
||||
mqtt_config.tls_client_cert,
|
||||
mqtt_config.tls_client_key,
|
||||
)
|
||||
else:
|
||||
client.tls_set(mqtt_config.tls_ca_certs)
|
||||
if not mqtt_config.tls_insecure is None:
|
||||
client.tls_insecure_set(mqtt_config.tls_insecure)
|
||||
if not mqtt_config.user is None:
|
||||
client.username_pw_set(mqtt_config.user, password=mqtt_config.password)
|
||||
try:
|
||||
client.connect(mqtt_config.host, mqtt_config.port, 60)
|
||||
except Exception as e:
|
||||
logger.error(f"Unable to connect to MQTT server: {e}")
|
||||
raise
|
||||
|
||||
client.loop_start()
|
||||
|
||||
for name in config.cameras.keys():
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/recordings/state",
|
||||
"ON" if config.cameras[name].record.enabled else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/snapshots/state",
|
||||
"ON" if config.cameras[name].snapshots.enabled else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/detect/state",
|
||||
"ON" if config.cameras[name].detect.enabled else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion/state",
|
||||
"ON",
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/improve_contrast/state",
|
||||
"ON" if config.cameras[name].motion.improve_contrast else "OFF",
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion_threshold/state",
|
||||
config.cameras[name].motion.threshold,
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion_contour_area/state",
|
||||
config.cameras[name].motion.contour_area,
|
||||
retain=True,
|
||||
)
|
||||
client.publish(
|
||||
f"{mqtt_config.topic_prefix}/{name}/motion",
|
||||
"OFF",
|
||||
retain=False,
|
||||
)
|
||||
|
||||
return client
|
||||
|
||||
|
||||
class MqttSocketRelay:
|
||||
def __init__(self, mqtt_client, topic_prefix):
|
||||
self.mqtt_client = mqtt_client
|
||||
self.topic_prefix = topic_prefix
|
||||
|
||||
def start(self):
|
||||
class MqttWebSocket(WebSocket):
|
||||
topic_prefix = self.topic_prefix
|
||||
mqtt_client = self.mqtt_client
|
||||
|
||||
def received_message(self, message):
|
||||
try:
|
||||
json_message = json.loads(message.data.decode("utf-8"))
|
||||
json_message = {
|
||||
"topic": f"{self.topic_prefix}/{json_message['topic']}",
|
||||
"payload": json_message.get("payload"),
|
||||
"retain": json_message.get("retain", False),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("Unable to parse websocket message as valid json.")
|
||||
return
|
||||
|
||||
logger.debug(
|
||||
f"Publishing mqtt message from websockets at {json_message['topic']}."
|
||||
)
|
||||
self.mqtt_client.publish(
|
||||
json_message["topic"],
|
||||
json_message["payload"],
|
||||
retain=json_message["retain"],
|
||||
)
|
||||
|
||||
# start a websocket server on 5002
|
||||
WebSocketWSGIHandler.http_version = "1.1"
|
||||
self.websocket_server = make_server(
|
||||
"127.0.0.1",
|
||||
5002,
|
||||
server_class=WSGIServer,
|
||||
handler_class=WebSocketWSGIRequestHandler,
|
||||
app=WebSocketWSGIApplication(handler_cls=MqttWebSocket),
|
||||
)
|
||||
self.websocket_server.initialize_websockets_manager()
|
||||
self.websocket_thread = threading.Thread(
|
||||
target=self.websocket_server.serve_forever
|
||||
)
|
||||
|
||||
def send(client, userdata, message):
|
||||
"""Sends mqtt messages to clients."""
|
||||
try:
|
||||
logger.debug(f"Received mqtt message on {message.topic}.")
|
||||
ws_message = json.dumps(
|
||||
{
|
||||
"topic": message.topic.replace(f"{self.topic_prefix}/", ""),
|
||||
"payload": message.payload.decode(),
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
# if the payload can't be decoded don't relay to clients
|
||||
logger.debug(
|
||||
f"MQTT payload for {message.topic} wasn't text. Skipping..."
|
||||
)
|
||||
return
|
||||
|
||||
self.websocket_server.manager.broadcast(ws_message)
|
||||
|
||||
self.mqtt_client.message_callback_add(f"{self.topic_prefix}/#", send)
|
||||
|
||||
self.websocket_thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.websocket_server.manager.close_all()
|
||||
self.websocket_server.manager.stop()
|
||||
self.websocket_server.manager.join()
|
||||
self.websocket_server.shutdown()
|
||||
self.websocket_thread.join()
|
||||
@@ -12,7 +12,8 @@ enable_error_code = ignore-without-code
|
||||
check_untyped_defs = true
|
||||
disallow_incomplete_defs = true
|
||||
disallow_subclassing_any = true
|
||||
disallow_untyped_calls = true
|
||||
# https://github.com/python/mypy/issues/10757
|
||||
disallow_untyped_calls = false
|
||||
disallow_untyped_decorators = true
|
||||
disallow_untyped_defs = true
|
||||
no_implicit_optional = true
|
||||
@@ -34,6 +35,9 @@ disallow_untyped_calls = false
|
||||
[mypy-frigate.const]
|
||||
ignore_errors = false
|
||||
|
||||
[mypy-frigate.events]
|
||||
ignore_errors = false
|
||||
|
||||
[mypy-frigate.log]
|
||||
ignore_errors = false
|
||||
|
||||
|
||||