Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42ff221b07 | ||
|
|
9a153cda80 | ||
|
|
1f37e699b2 | ||
|
|
45789d44d6 | ||
|
|
c1445ea1e1 | ||
|
|
74274ae30e | ||
|
|
233a73e1dc | ||
|
|
f8b48544f8 | ||
|
|
5e9783fed3 | ||
|
|
78186a2725 | ||
|
|
824206faaa | ||
|
|
f61fef9b32 | ||
|
|
37049f7ca4 | ||
|
|
8db2fd4a91 | ||
|
|
3a2db7aaa8 | ||
|
|
78375b220d | ||
|
|
1ea8f182fa | ||
|
|
8380227f8f | ||
|
|
a424fa55c0 | ||
|
|
cd582b90c8 | ||
|
|
2348c1e442 | ||
|
|
7ae5e14c2d | ||
|
|
7faddb3b50 | ||
|
|
50126a3833 | ||
|
|
0a9aa284ae | ||
|
|
7f8cf76a8c | ||
|
|
cdec5b0958 | ||
|
|
4235d9dc85 | ||
|
|
27e0ddc888 | ||
|
|
78f0a87528 | ||
|
|
31723e9469 | ||
|
|
2ae25a1e58 | ||
|
|
8a11f6e867 | ||
|
|
8c6f5be1bd | ||
|
|
b728ba14c7 | ||
|
|
ceff4c2495 | ||
|
|
8b825cc5fa | ||
|
|
b45aee252f | ||
|
|
0b9a7c17e9 | ||
|
|
2291f778da | ||
|
|
6fafb67c45 | ||
|
|
1d3336ece5 | ||
|
|
1892278633 | ||
|
|
afe6346e74 | ||
|
|
c8d08d22b2 | ||
|
|
ad26b55730 | ||
|
|
6c87d81a81 | ||
|
|
3771098c2f | ||
|
|
94805c881e | ||
|
|
5734321633 | ||
|
|
fb4f929109 | ||
|
|
16022c8b28 | ||
|
|
17f3695ca7 | ||
|
|
000f756420 | ||
|
|
6a1415913b | ||
|
|
3014be9008 | ||
|
|
618aafef2c | ||
|
|
ca5de6445d | ||
|
|
82a39a2fa1 | ||
|
|
77be9483b0 | ||
|
|
4fcaf4d538 | ||
|
|
70e62170a9 | ||
|
|
92447b63b8 | ||
|
|
1bcf1cfe85 | ||
|
|
aef898c471 | ||
|
|
0bbd334a78 | ||
|
|
80e705bd60 | ||
|
|
19c2031691 | ||
|
|
52c4515e62 | ||
|
|
8d3c0af7af | ||
|
|
f4d7bebbf1 | ||
|
|
e04c2a10f0 | ||
|
|
1dc25da8f2 | ||
|
|
df3b36954c | ||
|
|
d12d17c052 | ||
|
|
c0d0f396b0 | ||
|
|
7fccda4aa7 | ||
|
|
17846c7bfc | ||
|
|
8adae665fb | ||
|
|
a5a3cf9715 | ||
|
|
ac0703dbfd | ||
|
|
fa155df974 | ||
|
|
e7b9aee122 | ||
|
|
4f2a010e33 | ||
|
|
f1c35a1809 | ||
|
|
a2bec57251 | ||
|
|
8ead7ad2fc | ||
|
|
bd2a3b4ebc | ||
|
|
c37cedf183 | ||
|
|
1fe1ce5046 | ||
|
|
7ebe73b226 | ||
|
|
7dae880bb2 | ||
|
|
438d2a71e1 | ||
|
|
0f76622b17 | ||
|
|
9945b02fd9 | ||
|
|
f514733706 | ||
|
|
bd9da2620b | ||
|
|
6d0d290644 | ||
|
|
a3aa3c4556 | ||
|
|
f253100ea7 | ||
|
|
ad5d09045c | ||
|
|
8bd560b04e |
No files matched your search
@@ -7,6 +7,7 @@ jobs:
|
||||
name: native
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-22.04, windows-2022, macos-12]
|
||||
steps:
|
||||
@@ -138,7 +139,7 @@ jobs:
|
||||
|
||||
push_to_registry:
|
||||
name: Build Docker image
|
||||
if: startsWith(github.ref, 'refs/tags/') == false && github.event_name == 'push'
|
||||
if: github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- "cross"
|
||||
@@ -182,13 +183,20 @@ jobs:
|
||||
- name: Get tag name
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
branch="${GITHUB_REF#refs/heads/}"
|
||||
tags="${REPO_NAME}:${branch}"
|
||||
if [ "${branch}" == "master" ]; then
|
||||
tags="${tags},${REPO_NAME}:latest"
|
||||
tags=""
|
||||
if [[ "${GITHUB_REF}" =~ ^'refs/tags/'(.*) ]]; then
|
||||
gittag="$(echo "${BASH_REMATCH[1]}" | sed -E 's|[/]|-|g')"
|
||||
tags="${REPO_NAME}:${gittag}"
|
||||
elif [[ "${GITHUB_REF}" =~ ^'refs/heads/'(.*) ]]; then
|
||||
branch="$(echo "${BASH_REMATCH[1]}" | sed -E 's|[/]|-|g')"
|
||||
tags="${REPO_NAME}:${branch}"
|
||||
if [ "${branch}" == "master" ]; then
|
||||
tags="${tags},${REPO_NAME}:latest"
|
||||
fi
|
||||
fi
|
||||
echo "TAGS=${tags}" >> $GITHUB_OUTPUT
|
||||
echo "TAGS=${tags}" >> "${GITHUB_OUTPUT}"
|
||||
env:
|
||||
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
|
||||
- name: Install latest rust
|
||||
@@ -260,7 +268,7 @@ jobs:
|
||||
id: toml
|
||||
run: |
|
||||
NEOLINK_VERSION="$(toml get Cargo.toml package.version | sed 's|"||g')"
|
||||
echo "version=${NEOLINK_VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "version=${NEOLINK_VERSION}" >> $GITHUB_OUTPUT
|
||||
- name: Download Windows
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
name: DockerHub
|
||||
|
||||
on: [push, pull_request, workflow_dispatch]
|
||||
|
||||
jobs:
|
||||
native:
|
||||
name: native
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check token is set
|
||||
id: vars
|
||||
shell: bash
|
||||
run: |
|
||||
unset HAS_SECRET
|
||||
if [ -n $SECRET ]; then HAS_SECRET='true' ; fi
|
||||
echo "HAS_SECRET_TOKEN=${HAS_SECRET}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
SECRET: "${{ secrets.DOCKER_PRUNE_TOKEN }}"
|
||||
- name: Convert username to lower case for docker
|
||||
id: string_user
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: ASzc/change-string-case-action@v5
|
||||
with:
|
||||
string: ${{ github.repository_owner }}
|
||||
- name: Convert repo to lower case for docker
|
||||
id: string_repo
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: ASzc/change-string-case-action@v5
|
||||
with:
|
||||
string: ${{ github.event.repository.name }}
|
||||
- name: Run Clean Script
|
||||
shell: bash
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
run: |
|
||||
#!/bin/bash
|
||||
|
||||
#Script will delete all images in all repositories of your docker hub account which are older than x days
|
||||
|
||||
set -e
|
||||
|
||||
|
||||
# set username and password
|
||||
UNAME="${OWNER}"
|
||||
TOKEN="${TOKEN}"
|
||||
DAYS="${DAYS}"
|
||||
REPO_NAME="${REPO_NAME}"
|
||||
|
||||
# get list of namespaces accessible by user (not in use right now)
|
||||
#NAMESPACES=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/namespaces/ | jq -r '.namespaces|.[]')
|
||||
|
||||
#echo $TOKEN
|
||||
echo
|
||||
# get list of repos for that user account
|
||||
echo "List of Repositories in ${UNAME} Docker Hub account"
|
||||
REPO_LIST="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/?page_size=10000" | jq -r '.results|.[]|.name')"
|
||||
echo "$REPO_LIST"
|
||||
echo
|
||||
# build a list of all images & tags
|
||||
for i in ${REPO_LIST}
|
||||
do
|
||||
# get tags for repo
|
||||
IMAGE_TAGS="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/?page_size=10000" | jq -r '.results|.[]|.name')"
|
||||
|
||||
# build a list of images from tags
|
||||
for j in ${IMAGE_TAGS}
|
||||
do
|
||||
# add each tag to list
|
||||
FULL_IMAGE_LIST="${FULL_IMAGE_LIST} ${UNAME}/${i}:${j}"
|
||||
|
||||
done
|
||||
done
|
||||
|
||||
# output list of all docker images
|
||||
echo
|
||||
echo "List of all docker images in ${UNAME} Docker Hub account"
|
||||
for i in ${FULL_IMAGE_LIST}
|
||||
do
|
||||
echo "${i}"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "Identifying and deleting images which are older than ${DAYS} days in ${UNAME} docker hub account"
|
||||
# Note!!! Please un-comment below line if you wanna perform operation on all repositories of your Docker Hub account
|
||||
#for i in ${REPO_LIST}
|
||||
|
||||
repos=(
|
||||
"${REPO_NAME}"
|
||||
)
|
||||
|
||||
for i in "${repos[@]}"; do
|
||||
# get tags for repo
|
||||
echo
|
||||
echo "Looping Through $i repository in ${UNAME} account"
|
||||
IMAGE_TAGS="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/?page_size=10000" | jq -r '.results|.[]|.name')"
|
||||
|
||||
# build a list of images from tags
|
||||
for j in ${IMAGE_TAGS}
|
||||
do
|
||||
echo
|
||||
# add last_updated_time
|
||||
updated_time="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/${j}/?page_size=10000" | jq -r '.last_updated')"
|
||||
echo "$updated_time"
|
||||
datetime=$updated_time
|
||||
timeago="${DAYS} days ago"
|
||||
|
||||
dtSec=$(date --date "$datetime" +'%s')
|
||||
taSec=$(date --date "$timeago" +'%s')
|
||||
|
||||
echo "INFO: dtSec=$dtSec, taSec=$taSec"
|
||||
|
||||
if [ "$dtSec" -lt "$taSec" ]
|
||||
then
|
||||
echo "This image ${UNAME}/${i}:${j} is older than ${DAYS} days, deleting this image"
|
||||
## Please uncomment below line to delete docker hub images of docker hub repositories
|
||||
curl -s -X DELETE -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/${j}/"
|
||||
else
|
||||
echo "This image ${UNAME}/${i}:${j} is within ${DAYS} days time range, keep this image"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
echo "Script execution ends"
|
||||
env:
|
||||
DAYS: "100"
|
||||
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
|
||||
OWNER: ${{ steps.string_user.outputs.lowercase }}
|
||||
TOKEN: ${{ secrets.DOCKER_PRUNE_TOKEN }}
|
||||
@@ -14,3 +14,9 @@
|
||||
|
||||
# Committing IntelliJ project files is a violation of intergalactic law
|
||||
.idea/
|
||||
|
||||
# MacOS
|
||||
.DS_Store
|
||||
._.DS_Store
|
||||
**/.DS_Store
|
||||
**/._.DS_Store
|
||||
@@ -0,0 +1,19 @@
|
||||
repos:
|
||||
- repo: https://github.com/doublify/pre-commit-rust
|
||||
rev: eeee35a
|
||||
hooks:
|
||||
- id: fmt
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.4.0 # Use the ref you want to point at
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: check-case-conflict
|
||||
- id: check-merge-conflict
|
||||
- id: check-toml
|
||||
- id: mixed-line-ending
|
||||
- repo: https://github.com/igorshubovych/markdownlint-cli
|
||||
rev: v0.33.0
|
||||
hooks:
|
||||
- id: markdownlint-fix
|
||||
files: README.md
|
||||
|
||||
Generated
+926
-792
File diff suppressed because it is too large.
Load diff
+24
-34
@@ -1,9 +1,10 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.2"
|
||||
version = "0.5.8"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
@@ -11,37 +12,26 @@ members = [
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
neolink_core = { path = "crates/core", version = "0.5.2" }
|
||||
aes = "0.6"
|
||||
cfb-mode = "0.6"
|
||||
cookie-factory = "0.3"
|
||||
crossbeam = "0.8"
|
||||
crossbeam-channel = "0.5.1"
|
||||
err-derive = "0.2"
|
||||
anyhow = "1.0.70"
|
||||
byte-slice-cast = "1.2.2"
|
||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||
crossbeam-channel = "0.5.8"
|
||||
env_logger = "*"
|
||||
gstreamer = "0.19.0"
|
||||
gstreamer-app = "0.19.0"
|
||||
gstreamer-rtsp = "0.19.0"
|
||||
gstreamer-rtsp-server = { version = "0.19.0", features = ["v1_16"]}
|
||||
lazy_static = "1.4"
|
||||
log = { version = "0.4" }
|
||||
itertools = "0.9"
|
||||
md5 = "0.7"
|
||||
nom = "6.1.2"
|
||||
regex = "1"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
socket2 = "0.3"
|
||||
structopt = "0.3"
|
||||
time = "0.2"
|
||||
toml = "0.5"
|
||||
yaserde = "0.3.16"
|
||||
yaserde_derive = "0.3.16"
|
||||
xml-rs = "0.8"
|
||||
validator = "0.10"
|
||||
validator_derive = "0.10"
|
||||
byte-slice-cast = "1.0.0"
|
||||
rumqttc = "0.8.0"
|
||||
tokio = { version = "1.0", features = ["rt", "macros", "io-util"] }
|
||||
anyhow = "1.0.42"
|
||||
async-trait = "0.1.64"
|
||||
futures = "0.3.26"
|
||||
futures = "0.3.28"
|
||||
gstreamer = "0.20.3"
|
||||
gstreamer-app = "0.20.0"
|
||||
gstreamer-rtsp = "0.20.0"
|
||||
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.8" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.20.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
time = "0.3.20"
|
||||
tokio = { version = "1.27.0", features = ["rt", "macros", "io-util"] }
|
||||
tokio-stream = "0.1.12"
|
||||
toml = "0.7.3"
|
||||
validator = "0.16.0"
|
||||
validator_derive = "0.16.0"
|
||||
yaserde = "0.8.0"
|
||||
+5
-1
@@ -50,6 +50,9 @@ RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
libgstrtspserver-1.0-0 \
|
||||
libgstreamer1.0-0 \
|
||||
gstreamer1.0-tools \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad && \
|
||||
apt-get clean -y && rm -rf /var/lib/apt/lists/*
|
||||
@@ -59,7 +62,8 @@ COPY --from=build \
|
||||
/usr/local/bin/neolink
|
||||
COPY docker/entrypoint.sh /entrypoint.sh
|
||||
|
||||
RUN chmod +x "/usr/local/bin/neolink" && \
|
||||
RUN gst-inspect-1.0; \
|
||||
chmod +x "/usr/local/bin/neolink" && \
|
||||
"/usr/local/bin/neolink" --version
|
||||
|
||||
CMD ["/usr/local/bin/neolink", "rtsp", "--config", "/etc/neolink.toml"]
|
||||
|
||||
@@ -18,50 +18,62 @@ does has been reverse engineered.
|
||||
|
||||
## This Fork
|
||||
|
||||
This fork is an extension of [thirtythreeforty's](https://github.com/thirtythreeforty/neolink)
|
||||
with additional features not yet in upstream master.
|
||||
This fork is an extension of
|
||||
[thirtythreeforty's](https://github.com/thirtythreeforty/neolink) with additional
|
||||
features not yet in upstream master.
|
||||
|
||||
**Major Features**:
|
||||
|
||||
- MQTT
|
||||
- Motion Detection
|
||||
- Paused Streams (when no rtsp client or no motion detected)
|
||||
- Save a still image to disk
|
||||
|
||||
**Minor Features**:
|
||||
|
||||
- Improved error messages when your missing gstreamer plugins
|
||||
- Protocol more closely follows offical reolink format
|
||||
- Possibly can handle more simulatenous connections
|
||||
- More ways to connect to the camera. Including Relaying through reolink
|
||||
servers
|
||||
- Camera battery levels can be displayed in the log
|
||||
|
||||
## Installation
|
||||
|
||||
Download from the [release page](https://github.com/QuantumEntangledAndy/neolink/releases)
|
||||
Download from the
|
||||
[release page](https://github.com/QuantumEntangledAndy/neolink/releases)
|
||||
|
||||
Extract the zip
|
||||
|
||||
Install the latest [gstreamer](https://gstreamer.freedesktop.org/download/) (1.20.5 as of writing this).
|
||||
Install the latest [gstreamer](https://gstreamer.freedesktop.org/download/)
|
||||
(1.20.5 as of writing this).
|
||||
|
||||
- **Windows**: ensure you install `full` when prompted in the MSI options.
|
||||
- **Mac**: Install the dpkg version on the offical gstreamer website over the brew version
|
||||
- **Mac**: Install the dpkg version on the offical gstreamer website over
|
||||
the brew version
|
||||
- **Ubuntu/Debian**: These packages should work
|
||||
|
||||
```bash
|
||||
sudo apt install \
|
||||
libgstrtspserver-1.0-0 \
|
||||
libgstreamer1.0-0 \
|
||||
libgstreamer-plugins-bad1.0-0 \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad
|
||||
```
|
||||
|
||||
Make a config file see below.
|
||||
|
||||
|
||||
## Config/Usage
|
||||
|
||||
### RTSP
|
||||
|
||||
To use `neolink` you need a config file.
|
||||
|
||||
There's a more complete example [here](https://github.com/QuantumEntangledAndy/neolink/blob/master/sample_config.toml),
|
||||
There's a more complete example
|
||||
[here](https://github.com/QuantumEntangledAndy/neolink/blob/master/sample_config.toml),
|
||||
but the following should work as a minimal example.
|
||||
|
||||
```toml
|
||||
@@ -78,9 +90,11 @@ name = "Camera02"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "BCDEF0123456789A"
|
||||
address = "192.168.1.10"
|
||||
```
|
||||
|
||||
Create a text file with called `neolink.toml` in the same folder as the neolink binary. With your config options.
|
||||
Create a text file with called `neolink.toml` in the same folder as the
|
||||
neolink binary. With your config options.
|
||||
|
||||
When ready start `neolink` with the following command
|
||||
using the terminal in the same folder the neolink binary is in.
|
||||
@@ -89,6 +103,47 @@ using the terminal in the same folder the neolink binary is in.
|
||||
./neolink rtsp --config=neolink.toml
|
||||
```
|
||||
|
||||
### Discovery
|
||||
|
||||
To connect to a camera using a UID we need to find the IP address of the camera
|
||||
with that UID
|
||||
|
||||
The IP is discovered with four methods
|
||||
|
||||
1. Local discovery: Here we send a broadcast on all visible networks asking
|
||||
the local network if there is a camera with this UID. This only works if
|
||||
the network supports broadcasts
|
||||
|
||||
If you know the ip address you can put it into the `address` field of the
|
||||
config and attempt a direct connection without broadcasts. This requires a
|
||||
route from neolink to the camera.
|
||||
|
||||
2. Remote discovery: Here a ask the reolink servers what the IP address is.
|
||||
This requires that we contact reolink and provide some basic information
|
||||
like the UID. Once we have this information we connect directly to the
|
||||
local IP address. This requires a route from neolink to the camera and
|
||||
for the camera to be able to contact the reolink IPs.
|
||||
|
||||
3. Map discovery: In this case we register our IP address with reolink and ask
|
||||
the camera to connect to us. Once the camera either polls/recives a connect
|
||||
request from the reolink servers the camera will then initiate a connect
|
||||
to neolink. This requires that our IP and the reolink IPs are reacable from
|
||||
the camera.
|
||||
|
||||
4. Relay: In this case we request that reolink relay our connection. Neolink
|
||||
nor the camera need to be able to direcly contact each other. But both
|
||||
neolink and the camera need to be able to contact reolink.
|
||||
|
||||
This can be controlled with the config
|
||||
|
||||
```toml
|
||||
discovery = "local"
|
||||
```
|
||||
|
||||
In the `[[cameras]]` section of the toml.
|
||||
|
||||
Possible values are `local`, `remote`, `map`, `relay` later values implictly
|
||||
enable prior methods.
|
||||
|
||||
### MQTT
|
||||
|
||||
@@ -119,18 +174,29 @@ Neolink will publish these messages:
|
||||
Messages are prefixed with `neolink/{CAMERANAME}`
|
||||
|
||||
Control messages:
|
||||
|
||||
- `/control/led [on|off]` Turns status LED on/off
|
||||
- `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
|
||||
- `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light
|
||||
detection
|
||||
- `/control/reboot` Reboot the camera
|
||||
- `/control/ptz` [up|down|left|right|in|out] (amount) Control the PTZ movements, amount defaults to 32.0
|
||||
- `/control/ptz [up|down|left|right|in|out]` (amount) Control the PTZ
|
||||
movements, amount defaults to 32.0
|
||||
- `/control/pir [on|off]`
|
||||
|
||||
Status Messages:
|
||||
`/status offline` Sent when the neolink goes offline this is a LastWill message
|
||||
`/status disconnected` Sent when the camera goes offline
|
||||
`/status/battery` Sent in reply to a `/query/battery`
|
||||
|
||||
- `/status offline` Sent when the neolink goes offline this is a LastWill
|
||||
message
|
||||
- `/status disconnected` Sent when the camera goes offline
|
||||
- `/status/battery` Sent in reply to a `/query/battery` an XML encoded version
|
||||
of the battery status
|
||||
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||
pir status
|
||||
|
||||
Query Messages:
|
||||
`/query/battery` Request that the camera reports its battery level (Not Yet Implemented)
|
||||
|
||||
- `/query/battery` Request that the camera reports its battery level
|
||||
- `/query/pir` Request that the camera reports its pir status
|
||||
|
||||
### Pause
|
||||
|
||||
@@ -147,7 +213,6 @@ uid = "ABCDEF0123456789"
|
||||
[cameras.pause]
|
||||
on_motion = true # Should pause when no motion
|
||||
on_client = true # Should pause when no rtsp client
|
||||
mode = "none" # What to do when paused values are: none, black, still, test
|
||||
timeout = 2.1 # How long to wait after motion stops before pausing
|
||||
```
|
||||
|
||||
@@ -157,16 +222,46 @@ Then start the rtsp server as usual:
|
||||
./neolink rtsp --config=neolink.toml
|
||||
```
|
||||
|
||||
### Battery Levels
|
||||
|
||||
If you have a battery camera and would like to see the battery messages in th
|
||||
log add the following to your config
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
# Usual camera options like uid etc
|
||||
print_format = "Human"
|
||||
```
|
||||
|
||||
You can also print into xml format with `print_format = "Xml"` which can then b
|
||||
passed by a script for processing.
|
||||
|
||||
### Docker
|
||||
|
||||
[Docker](https://hub.docker.com/r/quantumentangledandy/neolink) builds are also provided
|
||||
in multiple architectures. The latest tag tracks master while each branch gets it's own tag.
|
||||
[Docker](https://hub.docker.com/r/quantumentangledandy/neolink) builds are also
|
||||
provided in multiple architectures. The latest tag tracks master while each
|
||||
|
||||
branch gets it's own tag.
|
||||
|
||||
```bash
|
||||
docker pull quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
### Image
|
||||
|
||||
You can write an image from the stream to disk using:
|
||||
|
||||
```bash
|
||||
neolink image --config=config.toml --file-path=filepath CameraName
|
||||
```
|
||||
|
||||
Where filepath is the path to save the image to and CameraName is the name o
|
||||
the camera from the config to save the image from.
|
||||
|
||||
File is always jpeg and the extension given in filepath will be added or changed
|
||||
|
||||
to reflect this.
|
||||
|
||||
## License
|
||||
|
||||
Neolink is free software, released under the GNU Affero General Public License
|
||||
|
||||
+25
-28
@@ -1,41 +1,38 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.2"
|
||||
version = "0.5.8"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[dependencies]
|
||||
aes = "0.6"
|
||||
async-trait = "0.1.63"
|
||||
bytes = "1.0.0"
|
||||
cfb-mode = "0.6"
|
||||
cookie-factory = "0.3"
|
||||
crc32fast = "1.2.1"
|
||||
crossbeam = "0.8"
|
||||
crossbeam-channel = "0.5.6"
|
||||
aes = "0.8.2"
|
||||
bytes = "1.4.0"
|
||||
cfb-mode = "0.8.2"
|
||||
cookie-factory = "0.3.2"
|
||||
crc32fast = "1.3.2"
|
||||
crossbeam-channel = "0.5.8"
|
||||
delegate = "0.9.0"
|
||||
err-derive = "0.2"
|
||||
futures = "0.3.25"
|
||||
err-derive = "0.3.1"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
lazy_static = "1.4"
|
||||
local-ip-address = "0.4.4"
|
||||
log = { version = "0.4" }
|
||||
md5 = "0.7"
|
||||
nom = { version = "6.1.2", features = ["alloc"] }
|
||||
rand = "0.8.4"
|
||||
regex = "1.5.4"
|
||||
socket2 = "0.3"
|
||||
time = "0.2"
|
||||
tokio = { version = "1.24.2", features = ["full"] }
|
||||
tokio-stream = { version = "0.1.11", features = ["sync", "time", "net"] }
|
||||
tokio-util = { version = "0.7.4", features = ["full"] }
|
||||
|
||||
xml-rs = "0.8"
|
||||
yaserde = "0.3.16"
|
||||
yaserde_derive = "0.3.16"
|
||||
lazy_static = "1.4.0"
|
||||
local-ip-address = "0.5.1"
|
||||
log = "0.4.17"
|
||||
md5 = "0.7.0"
|
||||
nom = { version = "7.1.3", features = ["alloc"] }
|
||||
rand = "0.8.5"
|
||||
regex = "1.7.3"
|
||||
serde = { version = "1.0.106", features = ["derive"] }
|
||||
time = { version = "0.3.20" , features = [ "macros", "parsing", "local-offset" ]}
|
||||
tokio = { version = "1.27.0", features = ["full"] }
|
||||
tokio-stream = { version = "0.1.12", features = ["sync", "time", "net"] }
|
||||
tokio-util = { version = "0.7.7", features = ["full"] }
|
||||
yaserde = "0.8.0"
|
||||
yaserde_derive = "0.8.0"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_matches = "1.5.0"
|
||||
env_logger = "*"
|
||||
indoc = "0.3"
|
||||
indoc = "2.0.1"
|
||||
@@ -7,6 +7,7 @@ use crate::bc::model::*;
|
||||
use crate::bc::xml::*;
|
||||
use crate::{Credentials, Error, Result};
|
||||
use bytes::BytesMut;
|
||||
use std::io;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
pub(crate) struct BcCodex {
|
||||
@@ -27,7 +28,15 @@ impl Encoder<Bc> for BcCodex {
|
||||
fn encode(&mut self, item: Bc, dst: &mut BytesMut) -> Result<()> {
|
||||
// let context = self.context.read().unwrap();
|
||||
let buf: Vec<u8> = Default::default();
|
||||
let buf = item.serialize(buf, self.context.get_encrypted())?;
|
||||
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
|
||||
EncryptionProtocol::Aes(_) if item.meta.msg_id == 1 => {
|
||||
// During login the encyption protocol cannot go higher than BCEncrypt
|
||||
// even if we support AES. (BUt it can go lower i.e. None)
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
n => *n,
|
||||
};
|
||||
let buf = item.serialize(buf, &enc_protocol)?;
|
||||
dst.reserve(buf.len());
|
||||
dst.extend_from_slice(buf.as_slice());
|
||||
Ok(())
|
||||
@@ -37,6 +46,24 @@ impl Encoder<Bc> for BcCodex {
|
||||
impl Decoder for BcCodex {
|
||||
type Item = Bc;
|
||||
type Error = Error;
|
||||
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match self.decode(buf)? {
|
||||
Some(frame) => Ok(Some(frame)),
|
||||
None => {
|
||||
if buf.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("bytes remaining on BC stream: {:X?}", buf),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
// trace!("Decoding: {:X?}", src);
|
||||
let bc = Bc::deserialize(&self.context, src);
|
||||
|
||||
@@ -160,7 +160,13 @@ fn bc_modern_msg<'a>(
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x02 => EncryptionProtocol::BCEncrypt, // This is AES but the first packet with the NONCE is BCEcrypt, since the NONCE in this packet is required to build the AES key
|
||||
_ => context.get_encrypted().clone(),
|
||||
BcHeader { msg_id: 1, .. }
|
||||
if matches!(context.get_encrypted(), EncryptionProtocol::Aes(_)) =>
|
||||
{
|
||||
// Maximum encryption level is BCEncrypt during login... Not sure why Reolink did it like that
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
_ => *context.get_encrypted(),
|
||||
};
|
||||
|
||||
let processed_payload_buf =
|
||||
|
||||
@@ -27,14 +27,12 @@ pub const MSG_ID_MOTION_REQUEST: u32 = 31;
|
||||
pub const MSG_ID_MOTION: u32 = 33;
|
||||
/// Version messages have this ID
|
||||
pub const MSG_ID_VERSION: u32 = 80;
|
||||
/// Getting PIR status messages have this ID
|
||||
pub const MSG_ID_GET_PIR_ALARM: u32 = 212;
|
||||
/// Setting PIR status messages have this ID
|
||||
pub const MSG_ID_START_PIR_ALARM: u32 = 213;
|
||||
/// Ping messages have this ID
|
||||
pub const MSG_ID_PING: u32 = 93;
|
||||
/// General system info messages have this ID
|
||||
pub const MSG_ID_GET_GENERAL: u32 = 104;
|
||||
/// Used to get the abilities of a user
|
||||
pub const MSG_ID_ABILITY_INFO: u32 = 151;
|
||||
/// Setting general system info (clock mostly) messages have this ID
|
||||
pub const MSG_ID_SET_GENERAL: u32 = 105;
|
||||
/// Will send the talk config for talk back data to follow this msg
|
||||
@@ -45,8 +43,16 @@ pub const MSG_ID_TALK: u32 = 202;
|
||||
pub const MSG_ID_GET_LED_STATUS: u32 = 208;
|
||||
/// Setting the LED status is done with this ID
|
||||
pub const MSG_ID_SET_LED_STATUS: u32 = 209;
|
||||
/// Getting PIR status messages have this ID
|
||||
pub const MSG_ID_GET_PIR_ALARM: u32 = 212;
|
||||
/// Setting PIR status messages have this ID
|
||||
pub const MSG_ID_START_PIR_ALARM: u32 = 213;
|
||||
/// UDP Keep alive
|
||||
pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234;
|
||||
/// Battery message initiaed by the camera
|
||||
pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252;
|
||||
/// Battery message initiaed by the client
|
||||
pub const MSG_ID_BATTERY_INFO: u32 = 253;
|
||||
|
||||
/// An empty password in legacy format
|
||||
pub const EMPTY_LEGACY_PASSWORD: &str =
|
||||
@@ -169,7 +175,7 @@ pub(super) struct BcSendInfo {
|
||||
/// These are the encyption modes supported by the camera
|
||||
///
|
||||
/// The mode is negotiated during login
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum EncryptionProtocol {
|
||||
/// Older camera use no encryption
|
||||
Unencrypted,
|
||||
|
||||
+153
-2
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::io::{Read, Write};
|
||||
// YaSerde is currently naming the traits and the derive macros identically
|
||||
use yaserde::{ser::Config, YaDeserialize, YaSerialize};
|
||||
use yaserde::ser::Config;
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -76,6 +76,15 @@ pub struct BcXml {
|
||||
/// Sent to move the camera
|
||||
#[yaserde(rename = "PtzControl")]
|
||||
pub ptz_control: Option<PtzControl>,
|
||||
/// Recieved on login/low battery events
|
||||
#[yaserde(rename = "BatteryList")]
|
||||
pub battery_list: Option<BatteryList>,
|
||||
/// Recieved on request for battery info
|
||||
#[yaserde(rename = "BatteryInfo")]
|
||||
pub battery_info: Option<BatteryInfo>,
|
||||
/// Recieved on request for a users persmissions/capabilitoes
|
||||
#[yaserde(rename = "AbilityInfo")]
|
||||
pub ability_info: Option<AbilityInfo>,
|
||||
}
|
||||
|
||||
impl BcXml {
|
||||
@@ -232,6 +241,9 @@ pub struct Extension {
|
||||
/// The channel ID. This is usually `0` unless using an NVR
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: Option<u8>,
|
||||
/// The rfID used in the PIR
|
||||
#[yaserde(rename = "rfId")]
|
||||
pub rf_id: Option<u8>,
|
||||
}
|
||||
|
||||
impl Default for Extension {
|
||||
@@ -242,6 +254,7 @@ impl Default for Extension {
|
||||
user_name: None,
|
||||
token: None,
|
||||
channel_id: None,
|
||||
rf_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -330,7 +343,54 @@ pub struct RfAlarmCfg {
|
||||
/// reduce False alarm boolean
|
||||
pub reduceFalseAlarm: u8,
|
||||
/// XML time block for all week days
|
||||
pub timeBlockList: String,
|
||||
#[yaserde(rename = "timeBlockList")]
|
||||
pub time_block_list: TimeBlockList,
|
||||
/// The alarm handle to attach to this Rf
|
||||
#[yaserde(rename = "alarmHandle")]
|
||||
pub alarm_handle: AlarmHandle,
|
||||
}
|
||||
|
||||
/// TimeBlockList XML
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "timeBlockList")]
|
||||
pub struct TimeBlockList {
|
||||
/// List of time block entries which disable/enable the PIR at a time
|
||||
#[yaserde(rename = "timeBlock")]
|
||||
pub time_block: Vec<TimeBlock>,
|
||||
}
|
||||
|
||||
/// TimeBlock XML Used to set the time to enable/disable PIR dectection
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "timeBlock")]
|
||||
pub struct TimeBlock {
|
||||
/// Whether to enable or disable for this time block
|
||||
pub enable: u8,
|
||||
/// The day of the week for this block
|
||||
pub weekDay: String,
|
||||
/// Time to start this block
|
||||
#[yaserde(rename = "beginHour")]
|
||||
pub begin_hour: u8,
|
||||
/// Time to end this block
|
||||
#[yaserde(rename = "endHour")]
|
||||
pub end_hour: u8,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
/// AlarmHandle Xml
|
||||
pub struct AlarmHandle {
|
||||
/// Items in the alarm handle
|
||||
pub item: Vec<AlarmHandleItem>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
/// An item in the alarm handle
|
||||
#[yaserde(rename = "item")]
|
||||
pub struct AlarmHandleItem {
|
||||
/// The channel ID
|
||||
pub channel: u8,
|
||||
/// The handle type: Known values, comma seperated list of snap,rec,push
|
||||
#[yaserde(rename = "handleType")]
|
||||
pub handle_type: String,
|
||||
}
|
||||
|
||||
/// TalkConfig xml
|
||||
@@ -463,6 +523,97 @@ pub struct PtzControl {
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
/// A list of battery infos. This message is sent from the camera as
|
||||
/// an event
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct BatteryList {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Battery info items
|
||||
#[yaserde(rename = "BatteryInfo")]
|
||||
pub battery_info: Vec<BatteryInfo>,
|
||||
}
|
||||
|
||||
/// The individual battery info
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct BatteryInfo {
|
||||
/// The channel the for the camera usually 0
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Charge status known values, "chargeComplete", "charging", "none",
|
||||
#[yaserde(rename = "chargeStatus")]
|
||||
pub charge_status: String,
|
||||
/// Status of charging port known values: "solarPanel"
|
||||
#[yaserde(rename = "adapterStatus")]
|
||||
pub adapter_status: String,
|
||||
/// Voltage
|
||||
pub voltage: i32,
|
||||
/// Current
|
||||
pub current: i32,
|
||||
/// Temperture
|
||||
pub temperature: i32,
|
||||
/// % charge from 0-100
|
||||
#[yaserde(rename = "batteryPercent")]
|
||||
pub battery_percent: u32,
|
||||
/// Low power flag. Known values 0, 1 (0=false)
|
||||
#[yaserde(rename = "lowPower")]
|
||||
pub low_power: u32,
|
||||
/// Battery version info: Known values 2
|
||||
#[yaserde(rename = "batteryVersion")]
|
||||
pub battery_version: u32,
|
||||
}
|
||||
|
||||
/// The ability battery info
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AbilityInfo {
|
||||
/// Username with this ability
|
||||
#[yaserde(rename = "userName")]
|
||||
pub username: String,
|
||||
/// System permissions
|
||||
pub system: Option<AbilityInfoToken>,
|
||||
/// Network permissions
|
||||
pub network: Option<AbilityInfoToken>,
|
||||
/// Alarm permissions
|
||||
pub alarm: Option<AbilityInfoToken>,
|
||||
/// Image permissions
|
||||
pub image: Option<AbilityInfoToken>,
|
||||
/// Video permissions
|
||||
pub video: Option<AbilityInfoToken>,
|
||||
/// Secutiry permissions
|
||||
pub security: Option<AbilityInfoToken>,
|
||||
/// Replay permissions
|
||||
pub replay: Option<AbilityInfoToken>,
|
||||
/// PTZ permissions
|
||||
#[yaserde(rename = "PTZ")]
|
||||
pub ptz: Option<AbilityInfoToken>,
|
||||
/// IO permissions
|
||||
#[yaserde(rename = "IO")]
|
||||
pub io: Option<AbilityInfoToken>,
|
||||
/// Streaming permissions
|
||||
pub streaming: Option<AbilityInfoToken>,
|
||||
}
|
||||
|
||||
/// Ability info for system token
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AbilityInfoToken {
|
||||
/// Submodule for this ability info token
|
||||
#[yaserde(rename = "subModule")]
|
||||
pub sub_module: Vec<AbilityInfoSubModule>,
|
||||
}
|
||||
|
||||
/// Token submodule infomation
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "subModule")]
|
||||
pub struct AbilityInfoSubModule {
|
||||
/// The channel the for the camera usually 0
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: Option<u8>,
|
||||
/// The comma seperated list of permissions like this: `general_rw, norm_rw, version_ro`
|
||||
#[yaserde(rename = "abilityValue")]
|
||||
pub ability_value: String,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
pub fn xml_ver() -> String {
|
||||
"1.1".to_string()
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
use super::model::EncryptionProtocol;
|
||||
use aes::Aes128;
|
||||
use cfb_mode::cipher::{NewStreamCipher, StreamCipher};
|
||||
use cfb_mode::Cfb;
|
||||
use aes::{
|
||||
cipher::{AsyncStreamCipher, KeyIvInit},
|
||||
Aes128,
|
||||
};
|
||||
use cfb_mode::{Decryptor, Encryptor};
|
||||
|
||||
type Aes128CfbEnc = Encryptor<Aes128>;
|
||||
type Aes128CfbDec = Decryptor<Aes128>;
|
||||
|
||||
const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF];
|
||||
const IV: &[u8] = b"0123456789abcdef";
|
||||
@@ -20,7 +25,7 @@ pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
|
||||
// AES decryption
|
||||
|
||||
let mut decrypted = buf.to_vec();
|
||||
Cfb::<Aes128>::new(aeskey.into(), IV.into()).decrypt(&mut decrypted);
|
||||
Aes128CfbDec::new(aeskey.into(), IV.into()).decrypt(&mut decrypted);
|
||||
decrypted
|
||||
}
|
||||
}
|
||||
@@ -39,7 +44,7 @@ pub fn encrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol
|
||||
EncryptionProtocol::Aes(aeskey) => {
|
||||
// AES encryption
|
||||
let mut encrypted = buf.to_vec();
|
||||
Cfb::<Aes128>::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
|
||||
Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
|
||||
encrypted
|
||||
}
|
||||
}
|
||||
|
||||
+308
-221
@@ -1,13 +1,22 @@
|
||||
use crate::{bc, Credentials};
|
||||
use crate::bc;
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
use std::net::ToSocketAddrs;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::atomic::{AtomicBool, AtomicU16, Ordering},
|
||||
};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use Md5Trunc::*;
|
||||
|
||||
mod abilityinfo;
|
||||
mod battery;
|
||||
mod connection;
|
||||
mod credentials;
|
||||
mod errors;
|
||||
mod keepalive;
|
||||
mod ledstate;
|
||||
mod login;
|
||||
mod logout;
|
||||
@@ -23,8 +32,10 @@ mod time;
|
||||
mod version;
|
||||
|
||||
pub(crate) use connection::*;
|
||||
pub use credentials::*;
|
||||
pub use errors::Error;
|
||||
pub use ledstate::LightState;
|
||||
pub use login::MaxEncryption;
|
||||
pub use motion::{MotionData, MotionStatus};
|
||||
pub use pirstate::PirState;
|
||||
pub use ptz::Direction;
|
||||
@@ -34,13 +45,11 @@ pub use stream::{StreamData, StreamKind};
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl From<crossbeam_channel::RecvTimeoutError> for Error {
|
||||
fn from(k: crossbeam_channel::RecvTimeoutError) -> Self {
|
||||
match k {
|
||||
crossbeam_channel::RecvTimeoutError::Timeout => Error::Timeout,
|
||||
crossbeam_channel::RecvTimeoutError::Disconnected => Error::TimeoutDisconnected,
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
enum ReadKind {
|
||||
ReadOnly,
|
||||
ReadWrite,
|
||||
None,
|
||||
}
|
||||
|
||||
///
|
||||
@@ -53,250 +62,285 @@ pub struct BcCamera {
|
||||
message_num: AtomicU16,
|
||||
// Certain commands such as logout require the username/pass in plain text.... why....???
|
||||
credentials: Credentials,
|
||||
abilities: RwLock<HashMap<String, ReadKind>>,
|
||||
}
|
||||
|
||||
/// Options used to construct a camera
|
||||
#[derive(Debug)]
|
||||
pub struct BcCameraOpt {
|
||||
/// Name, mostly used for message logs
|
||||
pub name: String,
|
||||
/// Channel the camera is on 0 unless using a NVR
|
||||
pub channel_id: u8,
|
||||
/// IPs of the camera
|
||||
pub addrs: Vec<IpAddr>,
|
||||
/// The UID of the camera
|
||||
pub uid: Option<String>,
|
||||
/// Port to try optional. When not given all known BC ports will be tried
|
||||
/// When given all known bc port AND the given port will be tried
|
||||
pub port: Option<u16>,
|
||||
/// Protocol decides if UDP/TCP are used for the camera
|
||||
pub protocol: ConnectionProtocol,
|
||||
/// Discovery method to allow
|
||||
pub discovery: DiscoveryMethods,
|
||||
/// Printing format for auxilaary data such as battery levels
|
||||
pub aux_printing: PrintFormat,
|
||||
/// Credentials for login
|
||||
pub credentials: Credentials,
|
||||
}
|
||||
|
||||
/// Used to choose the print format of various status messages like battery levels
|
||||
///
|
||||
/// Currently this is just the format of battery levels but if we ever got more status
|
||||
/// messages then they will also use this information
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub enum PrintFormat {
|
||||
/// None, don't print
|
||||
None,
|
||||
/// A human readable output
|
||||
Human,
|
||||
/// Xml formatted
|
||||
Xml,
|
||||
}
|
||||
|
||||
/// Type of connection to try
|
||||
#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub enum ConnectionProtocol {
|
||||
/// TCP and UDP
|
||||
#[default]
|
||||
TcpUdp,
|
||||
/// TCP only
|
||||
Tcp,
|
||||
/// Udp only
|
||||
Udp,
|
||||
}
|
||||
|
||||
enum CameraLocation {
|
||||
Tcp(SocketAddr),
|
||||
Udp(DiscoveryResult),
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
/// Create a new camera interface with this address and channel ID
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `host` - The address of the camera either ip address or hostname string
|
||||
///
|
||||
/// * `channel_id` - The channel ID this is usually zero unless using a NVR
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns either an error or the camera
|
||||
///
|
||||
pub async fn new_with_addr<U: ToSocketAddrs, V: Into<String>, W: Into<String>>(
|
||||
host: U,
|
||||
channel_id: u8,
|
||||
username: V,
|
||||
passwd: Option<W>,
|
||||
) -> Result<Self> {
|
||||
let username: String = username.into();
|
||||
let passwd: Option<String> = passwd.map(|t| t.into());
|
||||
let addr_iter = match host.to_socket_addrs() {
|
||||
Ok(iter) => iter,
|
||||
Err(_) => return Err(Error::AddrResolutionError),
|
||||
};
|
||||
for addr in addr_iter {
|
||||
if let Ok(cam) = Self::new(
|
||||
SocketAddrOrUid::SocketAddr(addr),
|
||||
channel_id,
|
||||
&username,
|
||||
passwd.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(cam);
|
||||
/// Try to connect to the camera via appropaite methods and return
|
||||
/// the location that should be used
|
||||
async fn find_camera(options: &BcCameraOpt) -> Result<CameraLocation> {
|
||||
let mut tcp_set = tokio::task::JoinSet::new();
|
||||
let mut local_set = tokio::task::JoinSet::new();
|
||||
let mut remote_set = tokio::task::JoinSet::new();
|
||||
let mut map_set = tokio::task::JoinSet::new();
|
||||
let mut relay_set = tokio::task::JoinSet::new();
|
||||
|
||||
if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol {
|
||||
let mut sockets = vec![];
|
||||
match options.port {
|
||||
Some(9000) | None => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, 9000));
|
||||
}
|
||||
}
|
||||
Some(n) => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, n));
|
||||
sockets.push(SocketAddr::new(*addr, 9000));
|
||||
}
|
||||
}
|
||||
}
|
||||
for socket in sockets.drain(..) {
|
||||
let channel_id: u8 = options.channel_id;
|
||||
let name: String = options.name.clone();
|
||||
tcp_set.spawn(async move {
|
||||
Discovery::check_tcp(socket, channel_id).await.map(|_| {
|
||||
info!("{}: TCP Discovery success at {:?}", name, &socket);
|
||||
socket
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Timeout)
|
||||
}
|
||||
if let (Some(uid), ConnectionProtocol::Udp | ConnectionProtocol::TcpUdp) =
|
||||
(options.uid.as_ref(), options.protocol)
|
||||
{
|
||||
let mut sockets = vec![];
|
||||
match options.port {
|
||||
None | Some(2015) | Some(2018) => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, 2018));
|
||||
sockets.push(SocketAddr::new(*addr, 2015));
|
||||
}
|
||||
}
|
||||
Some(n) => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, n));
|
||||
sockets.push(SocketAddr::new(*addr, 2015));
|
||||
sockets.push(SocketAddr::new(*addr, 2018));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (allow_local, allow_remote, allow_map, allow_relay) = match options.discovery {
|
||||
DiscoveryMethods::None => (false, false, false, false),
|
||||
DiscoveryMethods::Local => (true, false, false, false),
|
||||
DiscoveryMethods::Remote => (true, true, false, false),
|
||||
DiscoveryMethods::Map => (true, true, true, false),
|
||||
DiscoveryMethods::Relay => (true, true, true, true),
|
||||
DiscoveryMethods::Debug => (false, false, false, true),
|
||||
};
|
||||
|
||||
///
|
||||
/// Create a new camera interface with this uid and channel ID
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `uid` - The uid of the camera
|
||||
///
|
||||
/// * `channel_id` - The channel ID this is usually zero unless using a NVR
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns either an error or the camera
|
||||
///
|
||||
pub async fn new_with_uid<U: Into<String>, V: Into<String>>(
|
||||
uid: &str,
|
||||
channel_id: u8,
|
||||
username: U,
|
||||
passwd: Option<V>,
|
||||
discovery_method: DiscoveryMethods,
|
||||
) -> Result<Self> {
|
||||
Self::new(
|
||||
SocketAddrOrUid::Uid(uid.to_string(), discovery_method),
|
||||
channel_id,
|
||||
username,
|
||||
passwd,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
///
|
||||
/// Create a new camera interface with this address/uid and channel ID
|
||||
///
|
||||
/// This method will first perform hostname resolution on the address
|
||||
/// then fallback to uid if that resolution fails.
|
||||
///
|
||||
/// Be aware that it is possible (although unlikely) that there is
|
||||
/// a dns entry with the same address as the uid. If uncertain use
|
||||
/// one of the other methods.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `host` - The address of the camera either ip address, hostname string, or uid
|
||||
///
|
||||
/// * `channel_id` - The channel ID this is usually zero unless using a NVR
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns either an error or the camera
|
||||
///
|
||||
pub async fn new_with_addr_or_uid<U: ToSocketAddrsOrUid, V: Into<String>, W: Into<String>>(
|
||||
host: U,
|
||||
channel_id: u8,
|
||||
username: V,
|
||||
passwd: Option<W>,
|
||||
) -> Result<Self> {
|
||||
let addr_iter = match host.to_socket_addrs_or_uid() {
|
||||
Ok(iter) => iter,
|
||||
Err(_) => return Err(Error::AddrResolutionError),
|
||||
};
|
||||
let username: String = username.into();
|
||||
let passwd: Option<String> = passwd.map(|t| t.into());
|
||||
for addr_or_uid in addr_iter {
|
||||
if let Ok(cam) = Self::new(addr_or_uid, channel_id, &username, passwd.as_ref()).await {
|
||||
return Ok(cam);
|
||||
if allow_local {
|
||||
let uid_local = uid.clone();
|
||||
let name: String = options.name.clone();
|
||||
local_set.spawn(async move {
|
||||
trace!("{}: Starting Local discovery", name);
|
||||
let result = Discovery::local(&uid_local, Some(sockets)).await;
|
||||
if let Ok(disc) = &result {
|
||||
info!(
|
||||
"{}: Local discovery success {} at {}",
|
||||
name,
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
);
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_remote {
|
||||
let uid_remote = uid.clone();
|
||||
let name: String = options.name.clone();
|
||||
remote_set.spawn(async move {
|
||||
trace!("Starting Remote discovery");
|
||||
let result = Discovery::remote(&uid_remote).await;
|
||||
if let Ok(disc) = &result {
|
||||
info!(
|
||||
"{}: Remote discovery success {} at {}",
|
||||
name,
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
);
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_map {
|
||||
let uid_map = uid.clone();
|
||||
let name: String = options.name.clone();
|
||||
map_set.spawn(async move {
|
||||
trace!("Starting Map");
|
||||
let result = Discovery::map(&uid_map).await;
|
||||
if let Ok(disc) = &result {
|
||||
info!("{}: Map success {} at {}", name, uid_map, disc.get_addr());
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_relay {
|
||||
let uid_relay = uid.clone();
|
||||
let name: String = options.name.clone();
|
||||
relay_set.spawn(async move {
|
||||
trace!("Starting Relay");
|
||||
let result = Discovery::relay(&uid_relay).await;
|
||||
if let Ok(disc) = &result {
|
||||
info!(
|
||||
"{}: Relay success {} at {}",
|
||||
name,
|
||||
uid_relay,
|
||||
disc.get_addr()
|
||||
);
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Timeout)
|
||||
// Wait for all TCP to finish
|
||||
while let Some(result) = tcp_set.join_next().await {
|
||||
if let Ok(Ok(addr)) = result {
|
||||
return Ok(CameraLocation::Tcp(addr));
|
||||
}
|
||||
}
|
||||
debug!("TCP fail");
|
||||
// Tcp failed see if Local faired any better
|
||||
// Wait for all local to finish
|
||||
while let Some(result) = local_set.join_next().await {
|
||||
if let Ok(Ok(discovery)) = result {
|
||||
return Ok(CameraLocation::Udp(discovery));
|
||||
}
|
||||
}
|
||||
debug!("Local fail");
|
||||
// Local failed see if Remote faired any better
|
||||
// Wait for all remote to finish
|
||||
while let Some(result) = remote_set.join_next().await {
|
||||
if let Ok(Ok(discovery)) = result {
|
||||
return Ok(CameraLocation::Udp(discovery));
|
||||
}
|
||||
}
|
||||
debug!("Remote fail");
|
||||
// Remote failed see if Map faired any better
|
||||
// Wait for all Map to finish
|
||||
while let Some(result) = map_set.join_next().await {
|
||||
if let Ok(Ok(discovery)) = result {
|
||||
return Ok(CameraLocation::Udp(discovery));
|
||||
}
|
||||
}
|
||||
debug!("Map fail");
|
||||
// Map failed see if Relay faired any better
|
||||
// Wait for all Relay to finish
|
||||
while let Some(result) = relay_set.join_next().await {
|
||||
if let Ok(Ok(discovery)) = result {
|
||||
return Ok(CameraLocation::Udp(discovery));
|
||||
}
|
||||
}
|
||||
debug!("Relay (All) fail");
|
||||
// Nothing works
|
||||
Err(Error::CannotInitCamera)
|
||||
}
|
||||
|
||||
///
|
||||
/// Create a new camera interface with this address/uid and channel ID
|
||||
/// Create a new camera interface
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `addr` - An enum of [`SocketAddrOrUid`] that contains the address
|
||||
///
|
||||
/// * `channel_id` - The channel ID this is usually zero unless using a NVR
|
||||
///
|
||||
/// * `username` - The username to login with
|
||||
///
|
||||
/// * `passed` - The password to login with required for AES encrypted camera
|
||||
/// * `options` - Camera information see [`BcCameraOpt]
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns either an error or the camera
|
||||
///
|
||||
pub async fn new<U: Into<String>, V: Into<String>>(
|
||||
addr: SocketAddrOrUid,
|
||||
channel_id: u8,
|
||||
username: U,
|
||||
passwd: Option<V>,
|
||||
) -> Result<Self> {
|
||||
let username: String = username.into();
|
||||
let passwd: Option<String> = passwd.map(|t| t.into());
|
||||
pub async fn new(options: &BcCameraOpt) -> Result<Self> {
|
||||
let username: String = options.credentials.username.clone();
|
||||
let passwd: Option<String> = options.credentials.password.clone();
|
||||
|
||||
let (sink, source): (BcConnSink, BcConnSource) = match addr {
|
||||
SocketAddrOrUid::SocketAddr(addr) => {
|
||||
debug!("Trying address {}", addr);
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
SocketAddrOrUid::Uid(uid, method) => {
|
||||
debug!("Trying uid {}", uid);
|
||||
// TODO Make configurable
|
||||
let (allow_local, allow_remote, allow_relay) = match method {
|
||||
DiscoveryMethods::None => (false, false, false),
|
||||
DiscoveryMethods::Local => (true, false, false),
|
||||
DiscoveryMethods::Remote => (true, true, false),
|
||||
DiscoveryMethods::Relay => (true, true, true),
|
||||
};
|
||||
|
||||
let discovery = {
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
if allow_local {
|
||||
let uid_local = uid.clone();
|
||||
set.spawn(async move {
|
||||
debug!("Starting Local discovery");
|
||||
let result = Discovery::local(&uid_local).await;
|
||||
if let Ok(disc) = &result {
|
||||
debug!(
|
||||
"Local discovery success {} at {}",
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
);
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_remote {
|
||||
let uid_remote = uid.clone();
|
||||
set.spawn(async move {
|
||||
debug!("Starting Remote discovery");
|
||||
let result = Discovery::remote(&uid_remote).await;
|
||||
if let Ok(disc) = &result {
|
||||
debug!(
|
||||
"Remote discovery success {} at {}",
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
);
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
if allow_relay {
|
||||
let uid_relay = uid.clone();
|
||||
set.spawn(async move {
|
||||
debug!("Starting Relay");
|
||||
let result = Discovery::relay(&uid_relay).await;
|
||||
if let Ok(disc) = &result {
|
||||
debug!("Relay success {} at {}", uid_relay, disc.get_addr());
|
||||
}
|
||||
result
|
||||
});
|
||||
}
|
||||
|
||||
let last_result;
|
||||
loop {
|
||||
match set.join_next().await {
|
||||
Some(Ok(Ok(disc))) => {
|
||||
last_result = Ok(disc);
|
||||
break;
|
||||
}
|
||||
Some(Ok(Err(e))) => {
|
||||
debug!("Discovery Error: {:?}", e);
|
||||
}
|
||||
Some(Err(join_error)) => {
|
||||
last_result = Err(Error::OtherString(format!(
|
||||
"Panic while joining Discovery threads: {:?}",
|
||||
join_error
|
||||
)));
|
||||
break;
|
||||
}
|
||||
None => {
|
||||
last_result = Err(Error::DiscoveryTimeout);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
last_result
|
||||
}?;
|
||||
let (x, r) = UdpSource::new_from_discovery(discovery, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
let (sink, source): (BcConnSink, BcConnSource) = {
|
||||
match BcCamera::find_camera(options).await? {
|
||||
CameraLocation::Tcp(addr) => {
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
CameraLocation::Udp(discovery) => {
|
||||
let (x, r) =
|
||||
UdpSource::new_from_discovery(discovery, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let conn = BcConnection::new(sink, source).await?;
|
||||
|
||||
debug!("Success");
|
||||
trace!("Success");
|
||||
let me = Self {
|
||||
connection: Arc::new(conn),
|
||||
message_num: AtomicU16::new(0),
|
||||
channel_id,
|
||||
channel_id: options.channel_id,
|
||||
logged_in: AtomicBool::new(false),
|
||||
credentials: Credentials::new(username, passwd),
|
||||
abilities: Default::default(),
|
||||
};
|
||||
me.keepalive().await?;
|
||||
if let Err(e) = me.monitor_battery(options.aux_printing).await {
|
||||
warn!("Could not monitor battery: {:?}", e);
|
||||
}
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
@@ -315,6 +359,49 @@ impl BcCamera {
|
||||
fn get_credentials(&self) -> &Credentials {
|
||||
&self.credentials
|
||||
}
|
||||
|
||||
async fn has_ability<T: Into<String>>(&self, name: T) -> ReadKind {
|
||||
let abilities = self.abilities.read().await;
|
||||
if let Some(kind) = abilities.get(&name.into()).copied() {
|
||||
kind
|
||||
} else {
|
||||
ReadKind::None
|
||||
}
|
||||
}
|
||||
async fn has_ability_ro<T: Into<String>>(&self, name: T) -> Result<()> {
|
||||
let s: String = name.into();
|
||||
match self.has_ability(&s).await {
|
||||
ReadKind::ReadWrite | ReadKind::ReadOnly => Ok(()),
|
||||
ReadKind::None => Err(Error::MissingAbility {
|
||||
name: s.clone(),
|
||||
requested: "read".to_string(),
|
||||
actual: "none".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
async fn has_ability_rw<T: Into<String>>(&self, name: T) -> Result<()> {
|
||||
let s: String = name.into();
|
||||
match self.has_ability(&s).await {
|
||||
ReadKind::ReadWrite => Ok(()),
|
||||
ReadKind::ReadOnly => Err(Error::MissingAbility {
|
||||
name: s.clone(),
|
||||
requested: "write".to_string(),
|
||||
actual: "read".to_string(),
|
||||
}),
|
||||
ReadKind::None => Err(Error::MissingAbility {
|
||||
name: s.clone(),
|
||||
requested: "write".to_string(),
|
||||
actual: "none".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for all thread to finish
|
||||
///
|
||||
/// If an error is returned in any thread it will return the first error
|
||||
pub async fn join(&self) -> Result<()> {
|
||||
self.connection.join().await
|
||||
}
|
||||
}
|
||||
|
||||
/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use log::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the ability info xml for the current user
|
||||
pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_ABILITY_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
user_name: Some(self.get_credentials().username.clone()),
|
||||
token: Some("system, streaming, PTZ, IO, security, replay, disk, network, alarm, record, video, image".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
ability_info: Some(ability_info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(ability_info)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected AbilityInfo xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Populate ability list of the camera
|
||||
pub async fn polulate_abilities(&self) -> Result<()> {
|
||||
let info = self.get_abilityinfo().await?;
|
||||
let info_res = yaserde::ser::serialize_with_writer(&info, vec![], &Default::default());
|
||||
if let Ok(Ok(info_str)) = info_res.map(String::from_utf8) {
|
||||
debug!("Abilities: {}", info_str);
|
||||
}
|
||||
|
||||
let mut abilities: Vec<String> = vec![];
|
||||
|
||||
let mut tokens: Vec<Option<&AbilityInfoToken>> = vec![
|
||||
info.system.as_ref(),
|
||||
info.network.as_ref(),
|
||||
info.alarm.as_ref(),
|
||||
info.image.as_ref(),
|
||||
info.video.as_ref(),
|
||||
info.security.as_ref(),
|
||||
info.replay.as_ref(),
|
||||
info.ptz.as_ref(),
|
||||
info.io.as_ref(),
|
||||
info.streaming.as_ref(),
|
||||
];
|
||||
|
||||
for token in tokens.drain(..).flatten() {
|
||||
for sub_module in token.sub_module.iter() {
|
||||
abilities.extend(
|
||||
sub_module
|
||||
.ability_value
|
||||
.replace(' ', "")
|
||||
.split(',')
|
||||
.map(|s| s.to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut locked_abilities = self.abilities.write().await;
|
||||
for ability in abilities.iter() {
|
||||
let mut abilities_ro = ability.split('_').map(|s| s.to_string());
|
||||
if let (Some(ability_name), Some(ability_kind)) =
|
||||
(abilities_ro.next(), abilities_ro.next())
|
||||
{
|
||||
match ability_kind.as_str() {
|
||||
"rw" => {
|
||||
locked_abilities.insert(ability_name, super::ReadKind::ReadWrite);
|
||||
}
|
||||
"ro" => {
|
||||
locked_abilities.insert(ability_name, super::ReadKind::ReadOnly);
|
||||
}
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Handles battery related messages
|
||||
//!
|
||||
//! There are primarily two messages:
|
||||
//! - BatteryInfoList which the camera sends as part of its login info
|
||||
//! - BatteryInfo which the client can request on demand
|
||||
//!
|
||||
|
||||
use super::{BcCamera, PrintFormat, Result};
|
||||
use crate::{
|
||||
bc::{model::*, xml::BatteryInfo},
|
||||
Error,
|
||||
};
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handller to respond to battery messages
|
||||
/// These messages are sent by the camera on login and maybe
|
||||
/// also on low battery events
|
||||
pub async fn monitor_battery(&self, format: PrintFormat) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| {
|
||||
if let Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_list: Some(battery_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
..
|
||||
} = bc
|
||||
{
|
||||
for battery in battery_list.battery_info.iter() {
|
||||
match format {
|
||||
PrintFormat::None => {}
|
||||
PrintFormat::Human => {
|
||||
println!(
|
||||
"==Battery==\n\
|
||||
Charge: {}%,\n\
|
||||
Temperature: {}°C,\n\
|
||||
LowPower: {},\n\
|
||||
Adapter: {},\n\
|
||||
ChargeStatus: {},\n\
|
||||
",
|
||||
battery.battery_percent,
|
||||
battery.temperature,
|
||||
if battery.low_power == 1 {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
battery.adapter_status,
|
||||
battery.charge_status,
|
||||
);
|
||||
}
|
||||
PrintFormat::Xml => {
|
||||
let bat_ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(
|
||||
battery,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
)
|
||||
.expect("Should Ser the struct"),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", bat_ser);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Requests the current battery status of the camera
|
||||
pub async fn battery_info(&self) -> Result<BatteryInfo> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_BATTERY_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
|
||||
if let Bc {
|
||||
meta: BcMeta {
|
||||
response_code: 200, ..
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_info: Some(battery_info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
} = msg
|
||||
{
|
||||
Ok(battery_info)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the battery info (maybe no battery) command.",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -7,11 +7,20 @@ use std::collections::btree_map::Entry;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::{channel, Sender};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::yield_now;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
type Subscriber = Arc<RwLock<BTreeMap<u16, Sender<Bc>>>>;
|
||||
type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>;
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their Num
|
||||
num: RwLock<BTreeMap<u16, Sender<Result<Bc>>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: RwLock<BTreeMap<u32, MsgHandler>>,
|
||||
}
|
||||
|
||||
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
|
||||
pub(crate) type BcConnSource = Box<dyn Stream<Item = Result<Bc>> + Send + Sync + Unpin>;
|
||||
|
||||
@@ -21,95 +30,171 @@ pub(crate) type BcConnSource = Box<dyn Stream<Item = Result<Bc>> + Send + Sync +
|
||||
///
|
||||
/// There can be only one subscriber per kind of message at a time.
|
||||
pub struct BcConnection {
|
||||
sink: Arc<Mutex<BcConnSink>>,
|
||||
subscribers: Subscriber,
|
||||
sink: Sender<Result<Bc>>,
|
||||
subscribers: Arc<Subscriber>,
|
||||
#[allow(dead_code)] // Not dead we just need to hold a reference to keep it alive
|
||||
rx_thread: JoinSet<()>,
|
||||
rx_thread: RwLock<JoinSet<Result<()>>>,
|
||||
}
|
||||
|
||||
impl BcConnection {
|
||||
pub async fn new(sink: BcConnSink, mut source: BcConnSource) -> Result<BcConnection> {
|
||||
let subscribers: Subscriber = Default::default();
|
||||
|
||||
pub async fn new(mut sink: BcConnSink, mut source: BcConnSource) -> Result<BcConnection> {
|
||||
let subscribers: Arc<Subscriber> = Default::default();
|
||||
let subs = subscribers.clone();
|
||||
|
||||
let (sinker, sinker_rx) = channel::<Result<Bc>>(100);
|
||||
let mut rx_thread = JoinSet::new();
|
||||
|
||||
let sink_thread = sinker.clone();
|
||||
rx_thread.spawn(async move {
|
||||
loop {
|
||||
yield_now().await; // Give other tasks a chance to run before pulling next packet
|
||||
let packet = source.next().await;
|
||||
let bc = match packet {
|
||||
Some(Ok(bc)) => bc,
|
||||
Some(Err(e)) => {
|
||||
error!("Deserialization error: {:?}", e);
|
||||
break;
|
||||
}
|
||||
Some(res) => res,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if let Err(e) = Self::poll(bc, &subs).await {
|
||||
error!("Subscription error: {:?}", e);
|
||||
break;
|
||||
}
|
||||
Self::poll(bc, &subs, &sink_thread).await?
|
||||
}
|
||||
});
|
||||
|
||||
rx_thread.spawn(async move { sink.send_all(&mut ReceiverStream::new(sinker_rx)).await });
|
||||
|
||||
Ok(BcConnection {
|
||||
sink: Arc::new(Mutex::new(sink)),
|
||||
sink: sinker,
|
||||
subscribers,
|
||||
rx_thread,
|
||||
rx_thread: RwLock::new(rx_thread),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
|
||||
trace!("send Wait: {:?}", bc);
|
||||
self.sink.lock().await.send(bc).await?;
|
||||
trace!("send Complete");
|
||||
self.sink.send(Ok(bc)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
match self.subscribers.write().await.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => vac_entry.insert(tx),
|
||||
Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_num }),
|
||||
match self.subscribers.num.write().await.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(tx);
|
||||
}
|
||||
Entry::Occupied(mut occ_entry) => {
|
||||
if occ_entry.get().is_closed() {
|
||||
occ_entry.insert(tx);
|
||||
} else {
|
||||
return Err(Error::SimultaneousSubscription { msg_num });
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(BcSubscription::new(rx, msg_num, self))
|
||||
Ok(BcSubscription::new(rx, msg_num as u32, self))
|
||||
}
|
||||
|
||||
pub fn unsubscribe(&self, msg_num: u16) -> Result<()> {
|
||||
let subs = self.subscribers.clone();
|
||||
tokio::task::spawn(async move {
|
||||
subs.write().await.remove(&msg_num);
|
||||
});
|
||||
/// Some messages are initiated by the camera. This creates a handler for them
|
||||
/// It requires a closure that will be used to handle the message
|
||||
/// and return either None or Some(Bc) reply
|
||||
pub async fn handle_msg<T>(&self, msg_id: u32, handler: T) -> Result<()>
|
||||
where
|
||||
T: Fn(&Bc) -> Option<Bc> + Send + Sync + 'static,
|
||||
{
|
||||
match self.subscribers.id.write().await.entry(msg_id) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(Box::new(handler));
|
||||
}
|
||||
Entry::Occupied(_) => {
|
||||
return Err(Error::SimultaneousSubscriptionId { msg_id });
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop a message handler created using [`handle_msg`]
|
||||
#[allow(dead_code)] // Currently unused but added for future use
|
||||
pub async fn unhandle_msg(&self, msg_id: u32) -> Result<()> {
|
||||
self.subscribers.id.write().await.remove(&msg_id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn poll(
|
||||
response: Result<Bc>,
|
||||
subscribers: &Subscriber,
|
||||
sink: &Sender<Result<Bc>>,
|
||||
) -> Result<()> {
|
||||
match response {
|
||||
Ok(response) => {
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
|
||||
let mut remove_it_num = false;
|
||||
match (
|
||||
subscribers.id.read().await.get(&msg_id),
|
||||
subscribers.num.read().await.get(&msg_num),
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
if let Some(reply) = occ(&response) {
|
||||
assert!(reply.meta.msg_num == response.meta.msg_num);
|
||||
sink.send(Ok(reply)).await?;
|
||||
}
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
if occ.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
}
|
||||
if occ.send(Ok(response)).await.is_err() {
|
||||
remove_it_num = true;
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
if remove_it_num {
|
||||
subscribers.num.write().await.remove(&msg_num);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in subscribers.num.read().await.values() {
|
||||
let _ = sub.send(Err(e.clone())).await;
|
||||
}
|
||||
subscribers.num.write().await.clear();
|
||||
subscribers.id.write().await.clear();
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn poll(response: Bc, subscribers: &Subscriber) -> Result<()> {
|
||||
// Don't hold the lock during deserialization so we don't poison the subscribers mutex if
|
||||
// something goes wrong
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
|
||||
let mut remove_it = false;
|
||||
match subscribers.read().await.get(&msg_num) {
|
||||
Some(occ) => {
|
||||
if occ.send(response).await.is_err() {
|
||||
// Exceedingly unlikely, unless you mishandle the subscription object
|
||||
warn!("Subscriber to ID {} dropped their channel", msg_id);
|
||||
remove_it = true;
|
||||
pub(crate) async fn join(&self) -> Result<()> {
|
||||
let mut locked_threads = self.rx_thread.write().await;
|
||||
while let Some(res) = locked_threads.join_next().await {
|
||||
match res {
|
||||
Err(e) => {
|
||||
locked_threads.abort_all();
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
debug!("Ignoring uninteresting message num {}", msg_id);
|
||||
trace!("Contents: {:?}", response);
|
||||
Ok(Err(e)) => {
|
||||
locked_threads.abort_all();
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
}
|
||||
}
|
||||
if remove_it {
|
||||
subscribers.write().await.remove(&msg_num);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use super::BcConnection;
|
||||
use crate::bcmedia::codex::BcMediaCodex;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use futures::stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt};
|
||||
use std::io::Result as IoResult;
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
@@ -11,21 +11,21 @@ use tokio_util::codec::FramedRead;
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
|
||||
pub struct BcSubscription<'a> {
|
||||
rx: ReceiverStream<Bc>,
|
||||
msg_num: u16,
|
||||
rx: ReceiverStream<Result<Bc>>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
}
|
||||
|
||||
pub struct BcStream<'a> {
|
||||
rx: &'a mut ReceiverStream<Bc>,
|
||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
||||
}
|
||||
|
||||
impl<'a> Unpin for BcStream<'a> {}
|
||||
|
||||
impl<'a> Stream for BcStream<'a> {
|
||||
type Item = Bc;
|
||||
type Item = Result<Bc>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Bc>> {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
|
||||
let mut this = self.as_mut();
|
||||
match Pin::new(&mut this.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(bc)) => Poll::Ready(Some(bc)),
|
||||
@@ -36,7 +36,7 @@ impl<'a> Stream for BcStream<'a> {
|
||||
}
|
||||
|
||||
pub struct BcPayloadStream<'a> {
|
||||
rx: &'a mut ReceiverStream<Bc>,
|
||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
||||
}
|
||||
|
||||
impl<'a> Unpin for BcPayloadStream<'a> {}
|
||||
@@ -48,31 +48,50 @@ impl<'a> Stream for BcPayloadStream<'a> {
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<IoResult<Vec<u8>>>> {
|
||||
// log::debug!("PayloadStream: Poll");
|
||||
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(bc)) => {
|
||||
log::info!("Got Bc Packet");
|
||||
match bc {
|
||||
Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
..
|
||||
}),
|
||||
Poll::Ready(Some(Ok(Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
..
|
||||
} => Poll::Ready(Some(Ok(data))),
|
||||
_ => Poll::Pending,
|
||||
}
|
||||
}),
|
||||
..
|
||||
}))) => {
|
||||
// log::debug!("PayloadStream: Data");
|
||||
return Poll::Ready(Some(Ok(data)));
|
||||
}
|
||||
Poll::Ready(Some(Ok(_bc))) => {
|
||||
// trace!("Got other BC in payload stream");
|
||||
// log::debug!("PayloadStream: Other Data!");
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
// log::debug!("PayloadStream: Err");
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
// log::debug!("PayloadStream: None");
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
// log::debug!("PayloadStream: Pend");
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(None) => Poll::Ready(None),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
// log::debug!("PayloadStream: Default Pend and Wake");
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>>>, BcMediaCodex>;
|
||||
|
||||
impl<'a> BcSubscription<'a> {
|
||||
pub fn new(rx: Receiver<Bc>, msg_num: u16, conn: &'a BcConnection) -> BcSubscription<'a> {
|
||||
pub fn new(
|
||||
rx: Receiver<Result<Bc>>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
rx: ReceiverStream::new(rx),
|
||||
msg_num,
|
||||
@@ -81,15 +100,17 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
assert!(bc.meta.msg_num == self.msg_num);
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
self.conn.send(bc).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn recv(&mut self) -> Result<Bc> {
|
||||
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
|
||||
assert!(bc.meta.msg_num == self.msg_num);
|
||||
Ok(bc)
|
||||
if let Ok(bc) = &bc {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
@@ -103,18 +124,10 @@ impl<'a> BcSubscription<'a> {
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn bcmedia_stream(&'_ mut self) -> BcMediaStream<'_> {
|
||||
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> BcMediaStream<'_> {
|
||||
let async_read = BcPayloadStream { rx: &mut self.rx }
|
||||
.into_async_read()
|
||||
.compat();
|
||||
FramedRead::new(async_read, BcMediaCodex::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes it difficult to avoid unsubscribing when you're finished
|
||||
impl<'a> Drop for BcSubscription<'a> {
|
||||
fn drop(&mut self) {
|
||||
// It's fine if we can't unsubscribe as that means we already have
|
||||
let _ = self.conn.unsubscribe(self.msg_num);
|
||||
FramedRead::new(async_read, BcMediaCodex::new(strict))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,8 @@
|
||||
//! in the bc packets.
|
||||
//!
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::UdpSocket;
|
||||
use std::sync::Arc;
|
||||
use tokio::{net::UdpSocket, task::JoinSet};
|
||||
|
||||
mod bcconn;
|
||||
mod bcsub;
|
||||
@@ -19,13 +20,19 @@ pub(crate) use self::{
|
||||
};
|
||||
|
||||
pub(crate) struct DiscoveryResult {
|
||||
socket: UdpSocket,
|
||||
socket: Arc<UdpSocket>,
|
||||
addr: SocketAddr,
|
||||
keep_alive_tasks: JoinSet<()>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
}
|
||||
|
||||
impl DiscoveryResult {
|
||||
/// Stop all keep alive and any remaining tasks that the discover is managing
|
||||
pub(crate) async fn shutdown(&mut self) {
|
||||
self.keep_alive_tasks.shutdown().await;
|
||||
}
|
||||
/// Get the address discovered
|
||||
pub(crate) fn get_addr(&self) -> &SocketAddr {
|
||||
&self.addr
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::collections::VecDeque;
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::{
|
||||
net::UdpSocket,
|
||||
@@ -43,15 +44,18 @@ impl UdpSource {
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
) -> Result<Self> {
|
||||
let stream = connect().await?;
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await
|
||||
}
|
||||
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
||||
discovery: DiscoveryResult,
|
||||
mut discovery: DiscoveryResult,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
) -> Result<Self> {
|
||||
// Ensure that the discovery keep alive are all stopped here
|
||||
// We now handle all coms in UdpSource
|
||||
discovery.shutdown().await;
|
||||
Self::new_from_socket(
|
||||
discovery.socket,
|
||||
discovery.addr,
|
||||
@@ -64,7 +68,7 @@ impl UdpSource {
|
||||
}
|
||||
|
||||
pub(crate) async fn new_from_socket<T: Into<String>, U: Into<String>>(
|
||||
stream: UdpSocket,
|
||||
stream: Arc<UdpSocket>,
|
||||
addr: SocketAddr,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
@@ -124,14 +128,14 @@ impl Sink<Bc> for UdpSource {
|
||||
}
|
||||
|
||||
pub(crate) struct BcUdpSource {
|
||||
inner: UdpFramed<BcUdpCodex, UdpSocket>,
|
||||
inner: UdpFramed<BcUdpCodex, Arc<UdpSocket>>,
|
||||
addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl BcUdpSource {
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn new(addr: SocketAddr) -> Result<Self> {
|
||||
let stream = connect().await?;
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(stream, addr).await
|
||||
}
|
||||
@@ -141,7 +145,7 @@ impl BcUdpSource {
|
||||
Self::new_from_socket(discovery.socket, discovery.addr).await
|
||||
}
|
||||
|
||||
pub(crate) async fn new_from_socket(stream: UdpSocket, addr: SocketAddr) -> Result<Self> {
|
||||
pub(crate) async fn new_from_socket(stream: Arc<UdpSocket>, addr: SocketAddr) -> Result<Self> {
|
||||
Ok(Self {
|
||||
inner: UdpFramed::new(stream, BcUdpCodex::new()),
|
||||
addr,
|
||||
@@ -159,7 +163,8 @@ impl BcUdpSource {
|
||||
recieved: Default::default(),
|
||||
state: State::Normal,
|
||||
send_buffer: Default::default(),
|
||||
interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -194,9 +199,10 @@ impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
|
||||
}
|
||||
|
||||
enum State {
|
||||
Normal,
|
||||
Flushing,
|
||||
Closed,
|
||||
Normal, // Normal recieve
|
||||
Flushing, // Used to send ack packets and things in the buffer
|
||||
Closed, // Used to shutdown
|
||||
YieldNow, // Used to ensure we rest between polling packets so as to not starve the runtime
|
||||
}
|
||||
|
||||
pub(crate) struct UdpPayloadSource {
|
||||
@@ -211,49 +217,77 @@ pub(crate) struct UdpPayloadSource {
|
||||
send_buffer: VecDeque<BcUdp>,
|
||||
/// Offical Client does ack every 10ms if we don't also do this the camera
|
||||
/// seems to think we have a poor connection and will abort
|
||||
/// This `intveral` controls how ofen we do this
|
||||
interval: Interval,
|
||||
/// This `ack_interval` controls how ofen we do this
|
||||
ack_interval: Interval,
|
||||
/// Offical Client does resend every 500ms
|
||||
/// This `resend_interval` controls how ofen we do this
|
||||
resend_interval: Interval,
|
||||
}
|
||||
|
||||
impl UdpPayloadSource {
|
||||
fn build_send_ack(&self) -> UdpAck {
|
||||
assert!(self.packets_want > 0);
|
||||
let start: u32 = self.packets_want - 1;
|
||||
let missing_ids = if let Some(end) = self.recieved.keys().max() {
|
||||
let mut vec = vec![];
|
||||
// From last contiguous packet to last recieved packet
|
||||
// create a payload of `00` (unreceived) and `01` (received)
|
||||
// that can be used to form the `UdpAck` packet
|
||||
for i in (start + 1)..(end + 1) {
|
||||
if self.recieved.contains_key(&i) {
|
||||
vec.push(1)
|
||||
} else {
|
||||
vec.push(0)
|
||||
}
|
||||
if self.packets_want > 0 {
|
||||
let mut first_missing: u32 = self.packets_want;
|
||||
while self.recieved.contains_key(&first_missing) {
|
||||
// Happens if we have recieved but not consumed yet
|
||||
first_missing += 1;
|
||||
}
|
||||
vec
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let missing_ids = if let Some(end) = self.recieved.keys().max() {
|
||||
let mut vec = vec![];
|
||||
// From last contiguous packet to last recieved packet
|
||||
// create a payload of `00` (unreceived) and `01` (received)
|
||||
// that can be used to form the `UdpAck` packet
|
||||
for i in (first_missing)..(end + 1) {
|
||||
if self.recieved.contains_key(&i) {
|
||||
vec.push(1)
|
||||
} else {
|
||||
vec.push(0)
|
||||
}
|
||||
}
|
||||
vec
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
|
||||
UdpAck {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: start,
|
||||
payload: missing_ids,
|
||||
UdpAck {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: first_missing - 1, // Last we actually have is first_missing - 1
|
||||
group_id: 0,
|
||||
payload: missing_ids,
|
||||
}
|
||||
} else {
|
||||
UdpAck::empty(self.camera_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_ack(&mut self, ack: UdpAck) {
|
||||
let start = ack.packet_id;
|
||||
self.sent.retain(|&k, _| k > start);
|
||||
if start != 0xffffffff {
|
||||
// -1 means havent got anything yet
|
||||
self.sent.retain(|&k, _| k > start);
|
||||
|
||||
for (idx, &value) in ack.payload.iter().enumerate() {
|
||||
let packet_id = (start + 1) + idx as u32;
|
||||
if value > 0 {
|
||||
self.sent.remove(&packet_id);
|
||||
for (idx, &value) in ack.payload.iter().enumerate() {
|
||||
let packet_id = (start + 1) + idx as u32;
|
||||
if value > 0 {
|
||||
self.sent.remove(&packet_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn maintanence(&mut self, cx: &mut Context<'_>) {
|
||||
// Check for periodic resends
|
||||
if self.resend_interval.poll_tick(cx).is_ready() {
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
}
|
||||
}
|
||||
if self.ack_interval.poll_tick(cx).is_ready() {
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
self.send_buffer.push_back(ack);
|
||||
self.state = State::Flushing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for UdpPayloadSource {
|
||||
@@ -262,109 +296,102 @@ impl Stream for UdpPayloadSource {
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let camera_addr = self.inner.addr;
|
||||
let mut this = self.get_mut();
|
||||
loop {
|
||||
match this.state {
|
||||
State::Normal => {
|
||||
trace!("UDPSource.State: Normal");
|
||||
// Data ready to go
|
||||
if let Some(payload) = this.recieved.remove(&this.packets_want) {
|
||||
trace!("UDPSource.Data: PreReady: {}", this.packets_want);
|
||||
this.packets_want += 1;
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
}
|
||||
// Check for periodic resends
|
||||
if this.interval.poll_tick(cx).is_ready() {
|
||||
trace!("UDPSource.RecievedPacker: Resend");
|
||||
for (_, resend) in this.sent.iter() {
|
||||
this.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
}
|
||||
if this.packets_want == 0 {
|
||||
// When no packets have been recieved the
|
||||
// ACK is different specifically unknown_b
|
||||
// is set to -1 and packet_id is also set to
|
||||
// -1
|
||||
// TODO Add this style of ACK
|
||||
} else {
|
||||
match this.state {
|
||||
State::Normal => {
|
||||
this.state = State::YieldNow;
|
||||
// Data ready to go
|
||||
if let Some(payload) = this.recieved.remove(&this.packets_want) {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
}
|
||||
// Handle resend events
|
||||
this.maintanence(cx);
|
||||
// Normal behaviors
|
||||
match this.inner.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
payload,
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id >= this.packets_want =>
|
||||
{
|
||||
if packet_id == this.packets_want {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
}
|
||||
this.state = State::Flushing;
|
||||
continue;
|
||||
}
|
||||
// Normal behaviors
|
||||
match this.inner.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
payload,
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id >= this.packets_want =>
|
||||
{
|
||||
if packet_id == this.packets_want {
|
||||
trace!("UDPSource.RecievedPacker: NewData: {}", this.packets_want);
|
||||
this.packets_want += 1;
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
} else {
|
||||
trace!("UDPSource.RecievedPacker: OtherData");
|
||||
this.recieved.insert(packet_id, payload);
|
||||
}
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id && addr == camera_addr => {
|
||||
trace!("UDPSource.RecievedPacket: Ack");
|
||||
this.handle_ack(ack);
|
||||
// Rather then immediatly flush wait for the next call
|
||||
// this.state = State::Flushing;
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
trace!("UDPSource.RecievedPacker: Error");
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
trace!("UDPSource.RecievedPacker: Empty");
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(Some(Ok((bcudp, addr)))) => {
|
||||
trace!(
|
||||
"UDPSource.RecievedPacker: UnexpectedData {:?} from {}",
|
||||
bcudp,
|
||||
addr
|
||||
);
|
||||
} // _ => {
|
||||
// trace!("UDPSource.RecievedPacker: Other?");
|
||||
// // Repeat/unintersting packet
|
||||
// }
|
||||
}
|
||||
}
|
||||
State::Flushing => {
|
||||
trace!("UDPSource.State: Flushing");
|
||||
match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
Poll::Ready(Err(e)) => {
|
||||
return Poll::Ready(Some(Err(e)));
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
} else {
|
||||
this.recieved.insert(packet_id, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
State::Closed => {
|
||||
trace!("UDPSource.State: Closed");
|
||||
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
..
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id < this.packets_want =>
|
||||
{
|
||||
trace!("UdpPayloadSource.RecievedPacket: Old data: {}", packet_id);
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id && addr == camera_addr => {
|
||||
this.handle_ack(ack);
|
||||
// Rather then immediatly flush wait for the next call
|
||||
// this.state = State::Flushing;
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(Some(Ok((bcudp, addr)))) => {
|
||||
trace!(
|
||||
"UdpPayloadSource.RecievedPacker: UnexpectedData {:?} from {}",
|
||||
bcudp,
|
||||
addr
|
||||
);
|
||||
} // _ => {
|
||||
// trace!("UDPSource.RecievedPacker: Other?");
|
||||
// // Repeat/unintersting packet
|
||||
// }
|
||||
}
|
||||
}
|
||||
State::Flushing => match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
Poll::Ready(Err(e)) => {
|
||||
return Poll::Ready(Some(Err(e)));
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
},
|
||||
State::Closed => {
|
||||
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
|
||||
}
|
||||
State::YieldNow => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,7 +404,7 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal => this
|
||||
State::Normal | State::YieldNow => this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
@@ -416,44 +443,45 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
loop {
|
||||
match this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let Some(next) = this.send_buffer.pop_front() {
|
||||
match this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let BcUdp::Data(data) = &next {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
match this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let Some(next) = this.send_buffer.pop_front() {
|
||||
match this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let BcUdp::Data(data) = &next {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((next, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((next, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
} else {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
} else {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
@@ -495,9 +523,9 @@ impl futures::AsyncWrite for UdpPayloadSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to create a TcpStream with a connect timeout
|
||||
/// Helper to create a UdpStream
|
||||
async fn connect() -> Result<UdpSocket> {
|
||||
let mut ports: Vec<u16> = (53500..54000).into_iter().collect();
|
||||
let mut ports: Vec<u16> = (53500..54000).collect();
|
||||
let mut rng = thread_rng();
|
||||
ports.shuffle(&mut rng);
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Handles credentials for camera including default reolink password
|
||||
|
||||
use std::convert::TryInto;
|
||||
|
||||
/// Used for caching and supplying the credentials
|
||||
#[derive(Clone)]
|
||||
pub struct Credentials {
|
||||
/// The username to login to the camera with
|
||||
pub username: String,
|
||||
/// The password to use for login. Some camera allow this to be ommited
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Credentials {
|
||||
/// Default credentials for some reolink cameras
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
username: "admin".to_string(),
|
||||
password: Some("123456".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"username", &self.username)
|
||||
.entry(&"password", &"******")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
|
||||
Self {
|
||||
username: username.into(),
|
||||
password: password.map(|t| t.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to make an AES key from the login password and the NONCE
|
||||
/// negotiated during login
|
||||
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!(
|
||||
"{}-{}",
|
||||
nonce.as_ref(),
|
||||
self.password.clone().unwrap_or_default()
|
||||
);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,22 @@ pub enum Error {
|
||||
#[error(display = "IO Error: {:?}", _0)]
|
||||
Io(#[error(source)] std::sync::Arc<std::io::Error>),
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in time coversion: {:?}", _0)]
|
||||
TimeRange(#[error(source)] time::error::ComponentRange),
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in time parsing")]
|
||||
TimeParse,
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in try from NonZeroInt")]
|
||||
TryFromInt(#[error(source)] std::num::TryFromIntError),
|
||||
|
||||
/// /// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in time conversion")]
|
||||
TimeTryFrom(#[error(source)] time::error::TryFromParsed),
|
||||
|
||||
/// Raised when a Bc reply was not understood
|
||||
#[error(display = "Communication error")]
|
||||
UnintelligibleReply {
|
||||
@@ -23,6 +39,10 @@ pub enum Error {
|
||||
#[error(display = "Camera responded with Service Unavaliable")]
|
||||
CameraServiceUnavaliable,
|
||||
|
||||
/// Raised when the camera responds with a status code over than OK during login
|
||||
#[error(display = "Camera responded with Err during login")]
|
||||
CameraLoginFail,
|
||||
|
||||
/// Raised when a connection is dropped.
|
||||
#[error(display = "Dropped connection")]
|
||||
DroppedConnection,
|
||||
@@ -35,14 +55,26 @@ pub enum Error {
|
||||
#[error(display = "Dropped connection")]
|
||||
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
|
||||
|
||||
/// Raised when the RX_TIMEOUT is reach
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error(display = "Send Error")]
|
||||
TokioBcSendError,
|
||||
|
||||
/// Raised when the TIMEOUT is reach
|
||||
#[error(display = "Timeout")]
|
||||
Timeout,
|
||||
Timeout(#[error(source)] std::sync::Arc<tokio::time::error::Elapsed>),
|
||||
|
||||
/// Raised when a timeout fails in a non standard way such as timeout during shutdown
|
||||
#[error(display = "TimeoutError")]
|
||||
TimeoutError(#[error(source)] tokio::time::error::Error),
|
||||
|
||||
/// Raised when connection is dropped because the timeout is reach
|
||||
#[error(display = "Dropped connection")]
|
||||
TimeoutDisconnected,
|
||||
|
||||
/// Raised when a camera cannot be connected to ay any of the given addresses
|
||||
#[error(display = "Cannot contact camera at given address")]
|
||||
CannotInitCamera,
|
||||
|
||||
/// Raised when failed to login to the camera
|
||||
#[error(display = "Credential error")]
|
||||
AuthFailed,
|
||||
@@ -63,13 +95,20 @@ pub enum Error {
|
||||
#[error(display = "Cookie GenError")]
|
||||
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once
|
||||
/// Raised when a connection is subscrbed to more than once for msg_num
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscription {
|
||||
/// The message number that was subscribed to
|
||||
msg_num: u16,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscriptionId {
|
||||
/// The message number that was subscribed to
|
||||
msg_id: u32,
|
||||
},
|
||||
|
||||
/// Raised when a new encyrption byte is observed
|
||||
#[error(display = "Unknown encryption: {:x?}", _0)]
|
||||
UnknownEncryption(usize),
|
||||
@@ -128,6 +167,26 @@ pub enum Error {
|
||||
#[error(display = "Nom Parsing error: {}", _0)]
|
||||
NomError(String),
|
||||
|
||||
/// Raised when a camera/user lacks an ability
|
||||
#[error(
|
||||
display = "Missing ability: {} with {} permission has only {}",
|
||||
name,
|
||||
requested,
|
||||
actual
|
||||
)]
|
||||
MissingAbility {
|
||||
/// Name of the ability
|
||||
name: String,
|
||||
/// Requested permission (read/write)
|
||||
requested: String,
|
||||
/// Actual permission (read/write/none)
|
||||
actual: String,
|
||||
},
|
||||
|
||||
/// Raised when a thread panics
|
||||
#[error(display = "Thread panicked")]
|
||||
JoinError(#[error(source)] std::sync::Arc<tokio::task::JoinError>),
|
||||
|
||||
/// A generic catch all error
|
||||
#[error(display = "Other error: {}", _0)]
|
||||
Other(&'static str),
|
||||
@@ -143,6 +202,12 @@ impl From<std::io::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error {
|
||||
fn from(_: tokio::sync::mpsc::error::SendError<T>) -> Self {
|
||||
Error::TokioBcSendError
|
||||
}
|
||||
}
|
||||
|
||||
impl From<cookie_factory::GenError> for Error {
|
||||
fn from(k: cookie_factory::GenError) -> Self {
|
||||
Error::GenError(std::sync::Arc::new(k))
|
||||
@@ -155,6 +220,18 @@ impl From<local_ip_address::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tokio::task::JoinError> for Error {
|
||||
fn from(k: tokio::task::JoinError) -> Self {
|
||||
Error::JoinError(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tokio::time::error::Elapsed> for Error {
|
||||
fn from(k: tokio::time::error::Elapsed) -> Self {
|
||||
Error::Timeout(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<nom::Err<NomErrorType<'a>>> for Error {
|
||||
fn from(k: nom::Err<NomErrorType<'a>>) -> Self {
|
||||
match k {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
use super::{BcCamera, Result};
|
||||
use crate::bc::model::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handller to respond to keep alive messages
|
||||
/// These messages are sent by the camera so we listen to
|
||||
/// a message ID rather than setting a message number and
|
||||
/// responding to it
|
||||
pub async fn keepalive(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| {
|
||||
Some(Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UDP_KEEP_ALIVE,
|
||||
channel_id: bc.meta.channel_id,
|
||||
msg_num: bc.meta.msg_num,
|
||||
stream_type: bc.meta.stream_type,
|
||||
response_code: 200,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use crate::bc::{model::*, xml::*};
|
||||
impl BcCamera {
|
||||
/// Get the [LedState] xml which contains the LED status of the camera
|
||||
pub async fn get_ledstate(&self) -> Result<LedState> {
|
||||
self.has_ability_ro("ledState").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
@@ -51,6 +52,7 @@ impl BcCamera {
|
||||
|
||||
/// Set the led lights using the [LedState] xml
|
||||
pub async fn set_ledstate(&self, mut led_state: LedState) -> Result<()> {
|
||||
self.has_ability_rw("ledState").await?;
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
@@ -2,11 +2,35 @@ use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
/// The requested encryption level to request
|
||||
/// to the camera
|
||||
///
|
||||
/// The camera may use a lower one depending on support
|
||||
///
|
||||
/// Note the reolink camera only encrypt the control messages
|
||||
/// the camera feed is always accessible
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum MaxEncryption {
|
||||
/// No encryption
|
||||
None,
|
||||
/// BCEncrypt is a simple XOR algortirhm with a fixed key
|
||||
/// used in many older models
|
||||
BcEncrypt,
|
||||
/// AES is used in newer model
|
||||
Aes,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Login to the camera.
|
||||
///
|
||||
/// This should be called before most other commands
|
||||
pub async fn login(&self) -> Result<DeviceInfo> {
|
||||
self.login_with_maxenc(MaxEncryption::Aes).await
|
||||
}
|
||||
/// Login to the camera.
|
||||
///
|
||||
/// This should be called before most other commands
|
||||
pub async fn login_with_maxenc(&self, max_encryption: MaxEncryption) -> Result<DeviceInfo> {
|
||||
let device_info;
|
||||
// This { is here due to the connection and set_credentials both requiring a mutable borrow
|
||||
{
|
||||
@@ -31,13 +55,18 @@ impl BcCamera {
|
||||
.map(|p| md5_string(p, ZeroLast))
|
||||
.unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
||||
|
||||
let enc_byte = match max_encryption {
|
||||
MaxEncryption::None => 0xdc00,
|
||||
MaxEncryption::BcEncrypt => 0xdc01,
|
||||
MaxEncryption::Aes => 0xdc02,
|
||||
};
|
||||
let legacy_login = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_LOGIN,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0xdc02,
|
||||
response_code: enc_byte,
|
||||
class: 0x6514,
|
||||
},
|
||||
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
|
||||
@@ -107,7 +136,7 @@ impl BcCamera {
|
||||
sub_login.send(modern_login).await?;
|
||||
let modern_reply = sub_login.recv().await?;
|
||||
if modern_reply.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
return Err(Error::CameraLoginFail);
|
||||
}
|
||||
|
||||
match modern_reply.body {
|
||||
@@ -135,6 +164,10 @@ impl BcCamera {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Populate the list of abilities this user has with the camera
|
||||
log::debug!("Populating abilities");
|
||||
self.polulate_abilities().await?;
|
||||
Ok(device_info)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc::{channel, error::TryRecvError, Receiver};
|
||||
use tokio::task::{self, JoinHandle};
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
/// Motion Status that the callback can send
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -19,8 +19,8 @@ pub enum MotionStatus {
|
||||
///
|
||||
/// When this object is dropped the motion events are stopped
|
||||
pub struct MotionData {
|
||||
handle: Option<JoinHandle<Result<()>>>,
|
||||
rx: Receiver<MotionStatus>,
|
||||
handle: JoinSet<Result<()>>,
|
||||
rx: Receiver<Result<MotionStatus>>,
|
||||
last_update: MotionStatus,
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ impl MotionData {
|
||||
pub fn motion_detected_within(&mut self, duration: Duration) -> Result<Option<bool>> {
|
||||
self.consume_motion_events()?;
|
||||
Ok(match &self.last_update {
|
||||
MotionStatus::Start(time) => Some((Instant::now() - *time) < duration),
|
||||
MotionStatus::Start(_) => Some(true),
|
||||
MotionStatus::Stop(time) => Some((Instant::now() - *time) < duration),
|
||||
MotionStatus::NoChange(_) => None,
|
||||
})
|
||||
@@ -58,7 +58,7 @@ impl MotionData {
|
||||
let mut results: Vec<MotionStatus> = vec![];
|
||||
loop {
|
||||
match self.rx.try_recv() {
|
||||
Ok(motion) => results.push(motion),
|
||||
Ok(motion) => results.push(motion?),
|
||||
Err(TryRecvError::Empty) => break,
|
||||
Err(e) => return Err(Error::from(e)),
|
||||
}
|
||||
@@ -68,16 +68,93 @@ impl MotionData {
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MotionData {
|
||||
fn drop(&mut self) {
|
||||
if let Some(h) = self.handle.take() {
|
||||
let backoff = crossbeam::utils::Backoff::new();
|
||||
h.abort();
|
||||
while !h.is_finished() {
|
||||
backoff.snooze();
|
||||
/// Await a new motion event
|
||||
///
|
||||
///
|
||||
pub async fn next_motion(&mut self) -> Result<MotionStatus> {
|
||||
let motions = self.consume_motion_events()?;
|
||||
if let Some(last) = motions.last() {
|
||||
Ok(*last)
|
||||
} else if let Some(moition) = self.rx.recv().await {
|
||||
let moition = moition?;
|
||||
self.last_update = moition;
|
||||
Ok(moition)
|
||||
} else {
|
||||
Err(Error::Other("Motion dropped"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the motion to stop
|
||||
///
|
||||
/// It must be stopped for at least the given duration
|
||||
pub async fn await_stop(&mut self, duration: Duration) -> Result<()> {
|
||||
let motions = self.consume_motion_events()?;
|
||||
let mut last_motion = motions.last().copied();
|
||||
loop {
|
||||
if let Some(MotionStatus::Stop(time)) = last_motion {
|
||||
// In stop state
|
||||
if duration.is_zero() || (Instant::now() - time) > duration {
|
||||
return Ok(());
|
||||
} else {
|
||||
// Schedule a sleep or wait for motion to start
|
||||
let remaining_sleep = duration - (Instant::now() - time);
|
||||
let result = tokio::select! {
|
||||
_ = tokio::time::sleep(remaining_sleep) => {None},
|
||||
v = async {
|
||||
loop {
|
||||
match self.next_motion().await {
|
||||
n @ Ok(MotionStatus::Start(_)) => {return n;},
|
||||
n @ Err(_) => {return n;},
|
||||
_ => {continue;}
|
||||
}
|
||||
}
|
||||
} => {Some(v)}
|
||||
};
|
||||
if let Some(v) = result {
|
||||
v?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
last_motion = Some(self.next_motion().await?);
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the motion to start
|
||||
///
|
||||
/// The motion must have a minimum duration as given
|
||||
pub async fn await_start(&mut self, duration: Duration) -> Result<()> {
|
||||
let motions = self.consume_motion_events()?;
|
||||
let mut last_motion = motions.last().copied();
|
||||
loop {
|
||||
if let Some(MotionStatus::Start(time)) = last_motion {
|
||||
// In start state
|
||||
if duration.is_zero() || (Instant::now() - time) > duration {
|
||||
return Ok(());
|
||||
} else {
|
||||
// Schedule a sleep or wait for motion to stop
|
||||
let result = tokio::select! {
|
||||
_ = tokio::time::sleep(duration - (Instant::now() - time)) => {None},
|
||||
v = async {
|
||||
loop {
|
||||
match self.next_motion().await {
|
||||
n @ Ok(MotionStatus::Stop(_)) => {return n;},
|
||||
n @ Err(_) => {return n;},
|
||||
_ => {continue;}
|
||||
}
|
||||
}
|
||||
} => {Some(v)}
|
||||
};
|
||||
if let Some(v) = result {
|
||||
v?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
last_motion = Some(self.next_motion().await?);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +163,7 @@ impl BcCamera {
|
||||
/// This message tells the camera to send the motion events to us
|
||||
/// Which are the recieved on msgid 33
|
||||
async fn start_motion_query(&self) -> Result<u16> {
|
||||
self.has_ability_rw("motion").await?;
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
@@ -132,8 +210,9 @@ impl BcCamera {
|
||||
// when whenever motion is detected.
|
||||
let (tx, rx) = channel(20);
|
||||
|
||||
let mut set = JoinSet::new();
|
||||
let channel_id = self.channel_id;
|
||||
let handle = task::spawn(async move {
|
||||
set.spawn(async move {
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
loop {
|
||||
@@ -168,7 +247,7 @@ impl BcCamera {
|
||||
}
|
||||
// On connection drop we stop
|
||||
Err(e) => Err(e),
|
||||
}?;
|
||||
};
|
||||
|
||||
if tx.send(status).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
@@ -179,9 +258,15 @@ impl BcCamera {
|
||||
});
|
||||
|
||||
Ok(MotionData {
|
||||
handle: Some(handle),
|
||||
handle: set,
|
||||
rx,
|
||||
last_update: MotionStatus::NoChange(Instant::now()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MotionData {
|
||||
fn drop(&mut self) {
|
||||
self.handle.abort_all();
|
||||
}
|
||||
}
|
||||
@@ -1,56 +1,73 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use tokio::time::{interval, Duration};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [RfAlarmCfg] xml which contains the PIR status of the camera
|
||||
pub async fn get_pirstate(&self) -> Result<RfAlarmCfg> {
|
||||
self.has_ability_ro("rfAlarm").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PIR_ALARM,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
let mut reties: usize = 0;
|
||||
let mut retry_interval = interval(Duration::from_millis(500));
|
||||
loop {
|
||||
retry_interval.tick().await;
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PIR_ALARM,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
rf_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
rf_alarm_cfg: Some(pirstate),
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code == 400 {
|
||||
// Retryable
|
||||
if reties < 5 {
|
||||
reties += 1;
|
||||
continue;
|
||||
} else {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
} else if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
} else {
|
||||
// Valid message with response_code == 200
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
rf_alarm_cfg: Some(pirstate),
|
||||
..
|
||||
})),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(pirstate)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected PirSate xml but it was not recieved",
|
||||
})
|
||||
}) = msg.body
|
||||
{
|
||||
return Ok(pirstate);
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected PirSate xml but it was not recieved",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the PIR sensor using the [RfAlarmCfg] xml
|
||||
pub async fn set_pirstate(&self, rf_alarm_cfg: RfAlarmCfg) -> Result<()> {
|
||||
self.has_ability_rw("rfAlarm").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
@@ -66,7 +83,7 @@ impl BcCamera {
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
rf_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
|
||||
@@ -20,6 +20,7 @@ pub enum Direction {
|
||||
impl BcCamera {
|
||||
/// Send a PTZ message to the camera
|
||||
pub async fn send_ptz(&self, direction: Direction, amount: f32) -> Result<()> {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::bc::model::*;
|
||||
impl BcCamera {
|
||||
/// Reboot the camera
|
||||
pub async fn reboot(&self) -> Result<()> {
|
||||
self.has_ability_rw("reboot").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! This is a helper module to resolve either to a UID or a SockerAddr
|
||||
|
||||
use log::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
io::Error,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs},
|
||||
@@ -10,23 +11,37 @@ use std::{
|
||||
///
|
||||
/// This is used for UID lookup, it is unused with
|
||||
/// TPC/known ip address cameras
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum DiscoveryMethods {
|
||||
/// Forbid all discovery methods. Only TCP connections with known addresses will work
|
||||
#[serde(alias = "none")]
|
||||
None,
|
||||
/// Allow local discovery on the local network using broadcasts
|
||||
/// This method does NOT contact reolink servers
|
||||
#[serde(alias = "local")]
|
||||
Local,
|
||||
/// Allow contact with the reolink servers to learn the ip address but DO NOT
|
||||
/// allow the camera/clinet to communicate through the reolink servers.
|
||||
///
|
||||
/// **This also enabled `Local` discovery**
|
||||
#[serde(alias = "remote")]
|
||||
Remote,
|
||||
/// Allow contact with the reolink servers to learn the ip address and relay the connection
|
||||
/// through those servers.
|
||||
/// Allow contact with the reolink servers to learn the ip address and map the connection
|
||||
/// from dev to client through those servers.
|
||||
///
|
||||
/// **This also enabled `Local` and `Remote` discovery**
|
||||
#[serde(alias = "map")]
|
||||
Map,
|
||||
/// Allow contact with the reolink servers to learn the ip address and relay the connection
|
||||
/// client to dev through those servers.
|
||||
///
|
||||
/// **This also enabled `Local`, `Map` and `Remote` discovery**
|
||||
#[serde(alias = "relay")]
|
||||
Relay,
|
||||
#[doc(hidden)]
|
||||
#[serde(alias = "debug")]
|
||||
/// Used for debugging it is set to whatever the dev is currently testing
|
||||
Debug,
|
||||
}
|
||||
|
||||
/// Used to return either the SocketAddr or the UID
|
||||
@@ -34,7 +49,7 @@ pub enum SocketAddrOrUid {
|
||||
/// When the result is a addr it will be this
|
||||
SocketAddr(SocketAddr),
|
||||
/// When the result is a UID
|
||||
Uid(String, DiscoveryMethods),
|
||||
Uid(String, Option<Vec<SocketAddr>>, DiscoveryMethods),
|
||||
}
|
||||
|
||||
/// An extension of ToSocketAddrs that will also resolve to a camera UID
|
||||
@@ -75,6 +90,7 @@ impl ToSocketAddrsOrUid for str {
|
||||
if re.is_match(self) {
|
||||
Ok(vec![SocketAddrOrUid::Uid(
|
||||
self.to_string(),
|
||||
None,
|
||||
DiscoveryMethods::Local,
|
||||
)]
|
||||
.into_iter())
|
||||
@@ -102,6 +118,7 @@ impl ToSocketAddrsOrUid for String {
|
||||
if re.is_match(self) {
|
||||
Ok(vec![SocketAddrOrUid::Uid(
|
||||
self.to_string(),
|
||||
None,
|
||||
DiscoveryMethods::Local,
|
||||
)]
|
||||
.into_iter())
|
||||
|
||||
@@ -40,9 +40,27 @@ impl StreamData {
|
||||
/// Pull data from the camera's buffer
|
||||
/// This returns raw BcMedia packets
|
||||
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
|
||||
if let Some(handle) = self.handle.as_mut() {
|
||||
if handle.is_finished() {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
handle.await??;
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
} else {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
// debug!("StreamData: Get");
|
||||
match self.rx.recv().await {
|
||||
Some(data) => Ok(data),
|
||||
None => Err(Error::DroppedConnection),
|
||||
Some(data) => {
|
||||
// debug!("StreamData: Got");
|
||||
Ok(data)
|
||||
}
|
||||
None => {
|
||||
// debug!("StreamData: Drop");
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
Err(Error::DroppedConnection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,12 +68,6 @@ impl StreamData {
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
if let Some(h) = self.handle.take() {
|
||||
let backoff = crossbeam::utils::Backoff::new();
|
||||
while !h.is_finished() {
|
||||
backoff.snooze();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,11 +83,15 @@ impl BcCamera {
|
||||
/// The buffer_size represents number of compete messages so 1 would be one complete message
|
||||
/// which may be a single audio frame or a whole video key frame. If 0 a default of 100 is used
|
||||
///
|
||||
/// A value of scrict=true will mean that the stream will error if the underlying stream is not
|
||||
/// as expected
|
||||
pub async fn start_video(
|
||||
&self,
|
||||
stream: StreamKind,
|
||||
mut buffer_size: usize,
|
||||
strict: bool,
|
||||
) -> Result<StreamData> {
|
||||
self.has_ability_rw("preview").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
@@ -162,20 +178,26 @@ impl BcCamera {
|
||||
}
|
||||
|
||||
{
|
||||
let mut media_sub = sub_video.bcmedia_stream();
|
||||
let mut media_sub = sub_video.bcmedia_stream(strict);
|
||||
|
||||
while !abort_handle_thread.load(Ordering::Relaxed) {
|
||||
// debug!("Stream: Get");
|
||||
if let Some(bc_media) = media_sub.next().await {
|
||||
// debug!("Stream: Got");
|
||||
// We now have a complete interesting packet. Send it to on the callback
|
||||
// debug!("Stream: Send");
|
||||
if tx.send(bc_media).await.is_err() {
|
||||
// debug!("Stream: Dropped");
|
||||
break; // Connection dropped
|
||||
}
|
||||
// debug!("Stream: Sent");
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// debug!("Stream: Stopping");
|
||||
let stop_video = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
@@ -195,8 +217,9 @@ impl BcCamera {
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
// debug!("Stream: Send Stop");
|
||||
sub_video.send(stop_video).await?;
|
||||
// debug!("Stream: Sent Stop");
|
||||
|
||||
Ok(())
|
||||
});
|
||||
@@ -210,6 +233,7 @@ impl BcCamera {
|
||||
|
||||
/// Stop a camera from sending more stream data.
|
||||
pub async fn stop_video(&self, stream: StreamKind) -> Result<()> {
|
||||
self.has_ability_rw("preview").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use time::{date, Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use time::{
|
||||
macros::date, parsing::Parsed, Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset,
|
||||
};
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
@@ -11,6 +14,7 @@ impl BcCamera {
|
||||
/// returns either an error or an option with the offsetted date time
|
||||
///
|
||||
pub async fn get_time(&self) -> Result<Option<OffsetDateTime>> {
|
||||
self.has_ability_ro("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get_general = connection.subscribe(msg_num).await?;
|
||||
@@ -95,6 +99,7 @@ impl BcCamera {
|
||||
/// returns Ok(()) or error
|
||||
///
|
||||
pub async fn set_time(&self, timestamp: OffsetDateTime) -> Result<()> {
|
||||
self.has_ability_rw("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set_general = connection.subscribe(msg_num).await?;
|
||||
@@ -113,9 +118,9 @@ impl BcCamera {
|
||||
//osd_format: Some("MDY".to_string()),
|
||||
time_format: Some(0),
|
||||
// Reolink uses positive seconds to indicate a negative UTC offset:
|
||||
time_zone: Some(-timestamp.offset().as_seconds()),
|
||||
time_zone: Some(-timestamp.offset().whole_seconds()),
|
||||
year: Some(timestamp.year()),
|
||||
month: Some(timestamp.month()),
|
||||
month: Some(timestamp.month().into()),
|
||||
day: Some(timestamp.day()),
|
||||
hour: Some(timestamp.hour()),
|
||||
minute: Some(timestamp.minute()),
|
||||
@@ -151,14 +156,26 @@ fn try_build_timestamp(
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
second: u8,
|
||||
) -> std::result::Result<OffsetDateTime, time::ComponentRangeError> {
|
||||
let date = Date::try_from_ymd(year, month, day)?;
|
||||
let time = Time::try_from_hms(hour, minute, second)?;
|
||||
let offset = if timezone > 0 {
|
||||
UtcOffset::west_seconds(timezone as u32)
|
||||
} else {
|
||||
UtcOffset::east_seconds(-timezone as u32)
|
||||
};
|
||||
) -> std::result::Result<OffsetDateTime, crate::Error> {
|
||||
let date = Date::try_from(
|
||||
Parsed::new()
|
||||
.with_year(year)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_month(month.try_into()?)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_day(day.try_into()?)
|
||||
.ok_or(Error::TimeParse)?,
|
||||
)?;
|
||||
let time = Time::try_from(
|
||||
Parsed::new()
|
||||
.with_hour_24(hour)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_minute(minute)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_second(second)
|
||||
.ok_or(Error::TimeParse)?,
|
||||
)?;
|
||||
let offset = UtcOffset::from_whole_seconds(timezone)?;
|
||||
|
||||
Ok(PrimitiveDateTime::new(date, time).assume_offset(offset))
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use crate::bc::{model::*, xml::*};
|
||||
impl BcCamera {
|
||||
/// Request the [VersionInfo] xml
|
||||
pub async fn version(&self) -> Result<VersionInfo> {
|
||||
self.has_ability_ro("version").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_version = connection.subscribe(msg_num).await?;
|
||||
|
||||
@@ -5,13 +5,18 @@
|
||||
use crate::bcmedia::model::*;
|
||||
use crate::{Error, Result};
|
||||
use bytes::BytesMut;
|
||||
use log::*;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
pub struct BcMediaCodex {}
|
||||
pub struct BcMediaCodex {
|
||||
/// If true we will not search for the start of the next packet
|
||||
/// in the event that the stream appears to be corrupted
|
||||
strict: bool,
|
||||
}
|
||||
|
||||
impl BcMediaCodex {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {}
|
||||
pub(crate) fn new(strict: bool) -> Self {
|
||||
Self { strict }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,11 +36,48 @@ impl Decoder for BcMediaCodex {
|
||||
type Item = BcMedia;
|
||||
type Error = Error;
|
||||
|
||||
/// Since frames can cross EOF boundaries we overload this so it dosen't error if
|
||||
/// there are bytes left on the stream
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match self.decode(buf)? {
|
||||
Some(frame) => Ok(Some(frame)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match { BcMedia::deserialize(src) } {
|
||||
Ok(bc) => Ok(Some(bc)),
|
||||
Err(Error::NomIncomplete(_)) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
let mut amount_skipped: usize = 0;
|
||||
loop {
|
||||
match { BcMedia::deserialize(src) } {
|
||||
Ok(bc) => {
|
||||
if amount_skipped > 0 {
|
||||
debug!("Amount skipped to restore stream: {}", amount_skipped);
|
||||
}
|
||||
return Ok(Some(bc));
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) => {
|
||||
if amount_skipped > 0 {
|
||||
debug!("Amount skipped to restore stream: {}", amount_skipped);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => {
|
||||
if self.strict {
|
||||
return Err(e);
|
||||
} else if src.is_empty() {
|
||||
return Ok(None);
|
||||
} else {
|
||||
if amount_skipped == 0 {
|
||||
debug!("Error in stream attempting to restore");
|
||||
trace!(" Stream Error: {:?}", e);
|
||||
}
|
||||
// Drop the whole packet and wait for a packet that starts with magic
|
||||
amount_skipped += src.len();
|
||||
src.clear();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use super::model::BcMediaIframe;
|
||||
use super::model::*;
|
||||
use crate::Error;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use nom::{combinator::*, error::context, number::streaming::*, take};
|
||||
use nom::{bytes::streaming::take, combinator::*, error::context, number::streaming::*};
|
||||
|
||||
type IResult<I, O, E = nom::error::VerboseError<I>> = Result<(I, O), nom::Err<E>>;
|
||||
|
||||
@@ -182,18 +182,18 @@ fn bcmedia_iframe(buf: &[u8]) -> IResult<&[u8], BcMediaIframe> {
|
||||
};
|
||||
let (buf, _unknown_remained) = if additional_header_size > 4 {
|
||||
let remainder = additional_header_size - 4;
|
||||
let (buf, unknown_remained) = take!(buf, remainder)?;
|
||||
let (buf, unknown_remained) = take(remainder)(buf)?;
|
||||
(buf, Some(unknown_remained))
|
||||
} else {
|
||||
(buf, None)
|
||||
};
|
||||
|
||||
let (buf, data_slice) = take!(buf, payload_size)?;
|
||||
let (buf, data_slice) = take(payload_size)(buf)?;
|
||||
let pad_size = match payload_size % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take!(buf, pad_size)?;
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
assert_eq!(payload_size as usize, data_slice.len());
|
||||
|
||||
let video_type = match video_type_str {
|
||||
@@ -223,13 +223,13 @@ fn bcmedia_pframe(buf: &[u8]) -> IResult<&[u8], BcMediaPframe> {
|
||||
let (buf, additional_header_size) = le_u32(buf)?;
|
||||
let (buf, microseconds) = le_u32(buf)?;
|
||||
let (buf, _unknown_b) = le_u32(buf)?;
|
||||
let (buf, _additional_header) = take!(buf, additional_header_size)?;
|
||||
let (buf, data_slice) = take!(buf, payload_size)?;
|
||||
let (buf, _additional_header) = take(additional_header_size)(buf)?;
|
||||
let (buf, data_slice) = take(payload_size)(buf)?;
|
||||
let pad_size = match payload_size % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take!(buf, pad_size)?;
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
assert_eq!(payload_size as usize, data_slice.len());
|
||||
|
||||
let video_type = match video_type_str {
|
||||
@@ -252,12 +252,12 @@ fn bcmedia_pframe(buf: &[u8]) -> IResult<&[u8], BcMediaPframe> {
|
||||
fn bcmedia_aac(buf: &[u8]) -> IResult<&[u8], BcMediaAac> {
|
||||
let (buf, payload_size) = le_u16(buf)?;
|
||||
let (buf, _payload_size_b) = le_u16(buf)?;
|
||||
let (buf, data_slice) = take!(buf, payload_size)?;
|
||||
let (buf, data_slice) = take(payload_size)(buf)?;
|
||||
let pad_size = match payload_size as u32 % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take!(buf, pad_size)?;
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
@@ -281,12 +281,12 @@ fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> {
|
||||
// On other cameras is half the block size without the header
|
||||
let (buf, _half_block_size) = le_u16(buf)?;
|
||||
let block_size = payload_size - SUB_HEADER_SIZE;
|
||||
let (buf, data_slice) = take!(buf, block_size)?;
|
||||
let (buf, data_slice) = take(block_size)(buf)?;
|
||||
let pad_size = match payload_size as u32 % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take!(buf, pad_size)?;
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// Video streams encapsulate a stream of BcMedia
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BcMedia {
|
||||
/// Holds info on the stream
|
||||
InfoV1(BcMediaInfoV1),
|
||||
@@ -19,7 +19,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaInfoV1 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
@@ -63,7 +63,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaInfoV2 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
@@ -108,7 +108,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039;
|
||||
|
||||
/// Video Types for I/PFrame
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum VideoType {
|
||||
/// H264 video data
|
||||
H264,
|
||||
@@ -117,7 +117,7 @@ pub enum VideoType {
|
||||
}
|
||||
|
||||
/// This is a BcMedia video IFrame.
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone)]
|
||||
pub struct BcMediaIframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
@@ -134,12 +134,32 @@ pub struct BcMediaIframe {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BcMediaIframe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"video_type", &self.video_type)
|
||||
// .entry(&"payload_size", &self.payload_size)
|
||||
.entry(&"microseconds", &self.microseconds)
|
||||
.entry(&"time", &self.time)
|
||||
.entry(
|
||||
&"data[0..10]",
|
||||
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
|
||||
)
|
||||
.entry(
|
||||
&"data[-10..-1]",
|
||||
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
|
||||
)
|
||||
.entry(&"data.len()", &self.data.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// PFrame magics include the channel number in them
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139;
|
||||
|
||||
/// This is a BcMedia video PFrame.
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone)]
|
||||
pub struct BcMediaPframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
@@ -153,10 +173,29 @@ pub struct BcMediaPframe {
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BcMediaPframe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"video_type", &self.video_type)
|
||||
// .entry(&"payload_size", &self.payload_size)
|
||||
.entry(&"microseconds", &self.microseconds)
|
||||
.entry(
|
||||
&"data[0..20]",
|
||||
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
|
||||
)
|
||||
.entry(
|
||||
&"data[-20..-1]",
|
||||
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
|
||||
)
|
||||
.entry(&"data.len()", &self.data.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530;
|
||||
|
||||
/// This contains BcMedia audio data in AAC format
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaAac {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
@@ -171,7 +210,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100;
|
||||
|
||||
/// This contains BcMedia audio data in ADPCM format
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaAdpcm {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
|
||||
@@ -33,6 +33,15 @@ impl Decoder for BcUdpCodex {
|
||||
type Item = BcUdp;
|
||||
type Error = Error;
|
||||
|
||||
/// Since frames can cross EOF boundaries we overload this so it dosen't error if
|
||||
/// there are bytes left on the stream
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match self.decode(buf)? {
|
||||
Some(frame) => Ok(Some(frame)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match { BcUdp::deserialize(src) } {
|
||||
Ok(BcUdp::Discovery(UdpDiscovery {
|
||||
@@ -40,13 +49,19 @@ impl Decoder for BcUdpCodex {
|
||||
r2c_disc: Some(_), ..
|
||||
},
|
||||
..
|
||||
})) => Err(Error::RelayTerminate),
|
||||
})) => {
|
||||
// log::error!("Relay terminate");
|
||||
Err(Error::RelayTerminate)
|
||||
}
|
||||
Ok(BcUdp::Discovery(UdpDiscovery {
|
||||
payload: UdpXml {
|
||||
d2c_disc: Some(_), ..
|
||||
},
|
||||
..
|
||||
})) => Err(Error::CameraTerminate),
|
||||
})) => {
|
||||
// log::error!("Camera terminate");
|
||||
Err(Error::CameraTerminate)
|
||||
}
|
||||
Ok(bc) => Ok(Some(bc)),
|
||||
Err(Error::NomIncomplete(_)) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
|
||||
+14
-10
@@ -2,10 +2,11 @@ use super::{crc::calc_crc, model::*, xml::*, xml_crypto::decrypt};
|
||||
use crate::Error;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use nom::{
|
||||
bytes::streaming::take,
|
||||
combinator::*,
|
||||
error::{context as error_context, ContextError, ErrorKind, ParseError},
|
||||
number::streaming::*,
|
||||
take, Err,
|
||||
Err,
|
||||
};
|
||||
|
||||
type IResult<I, O, E = nom::error::VerboseError<I>> = Result<(I, O), nom::Err<E>>;
|
||||
@@ -67,7 +68,7 @@ fn udp_disc(buf: &[u8]) -> IResult<&[u8], UdpDiscovery> {
|
||||
)(buf)?;
|
||||
let (buf, tid) = error_context("DISC: Missing TID", le_u32)(buf)?;
|
||||
let (buf, checksum) = error_context("DISC: Missing checksum", le_u32)(buf)?;
|
||||
let (buf, enc_data_slice) = take!(buf, payload_size)?;
|
||||
let (buf, enc_data_slice) = take(payload_size)(buf)?;
|
||||
|
||||
let actual_checksum = calc_crc(enc_data_slice);
|
||||
assert_eq!(checksum, actual_checksum);
|
||||
@@ -89,18 +90,20 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
||||
let (buf, connection_id) = error_context("ACK: Missing connect ID", le_i32)(buf)?;
|
||||
let (buf, _unknown_a) =
|
||||
error_context("ACK: Unable to verify UnknowA", verify(le_u32, |&x| x == 0))(buf)?;
|
||||
let (buf, _unknown_b) =
|
||||
error_context("ACK: Unable to verify UnknowB", verify(le_u32, |&x| x == 0))(buf)?;
|
||||
let (buf, group_id) = error_context(
|
||||
"ACK: Unable to verify UnknowB",
|
||||
verify(le_u32, |&x| x == 0 || x == 0xffffffff),
|
||||
)(buf)?;
|
||||
let (buf, packet_id) = error_context("Missing packet_id", le_u32)(buf)?; // This is the point at which the camera has contigious
|
||||
// packets to
|
||||
let (buf, _unknown) = error_context("ACK: Missing unknown", le_u32)(buf)?;
|
||||
let (buf, payload_size) = error_context("ACK: Missing payload_size", le_u32)(buf)?;
|
||||
let (buf, payload) = if payload_size > 0 {
|
||||
let (buf, t_payload) = take!(buf, payload_size)?; // It is a binary payload of
|
||||
// `00 01 01 01 01 00 01`
|
||||
// This is a truth map of missing packets
|
||||
// since last contigious packet_id up
|
||||
// to the last packet we sent and it recieved
|
||||
let (buf, t_payload) = take(payload_size)(buf)?; // It is a binary payload of
|
||||
// `00 01 01 01 01 00 01`
|
||||
// This is a truth map of missing packets
|
||||
// since last contigious packet_id up
|
||||
// to the last packet we sent and it recieved
|
||||
(buf, t_payload.to_vec())
|
||||
} else {
|
||||
(buf, vec![])
|
||||
@@ -109,6 +112,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
|
||||
let data = UdpAck {
|
||||
connection_id,
|
||||
packet_id,
|
||||
group_id,
|
||||
payload,
|
||||
};
|
||||
Ok((buf, data))
|
||||
@@ -120,7 +124,7 @@ fn udp_data(buf: &[u8]) -> IResult<&[u8], UdpData> {
|
||||
error_context("DATA: Unable to verify UnownA", verify(le_u32, |&x| x == 0))(buf)?;
|
||||
let (buf, packet_id) = error_context("DATA: Missing packet_id", le_u32)(buf)?;
|
||||
let (buf, payload_size) = error_context("DATA: Missing payload_size", le_u32)(buf)?;
|
||||
let (buf, payload) = take!(buf, payload_size)?;
|
||||
let (buf, payload) = take(payload_size)(buf)?;
|
||||
|
||||
let data = UdpData {
|
||||
connection_id,
|
||||
|
||||
@@ -63,7 +63,9 @@ pub struct UdpAck {
|
||||
/// register and then download the same connection id from the register_address
|
||||
/// it comes back in an xml that is encoded as i32 (i.e. can be negative string)
|
||||
pub connection_id: i32,
|
||||
// Unknown 4 bytes always 0
|
||||
/// Unknown 4 bytes always 0 for normal ack or -1 for signalling no packets received yet
|
||||
/// Tentativly assigned as a kinda group id
|
||||
pub group_id: u32,
|
||||
/// The ID of the last data packet [`UdpData`]
|
||||
pub packet_id: u32,
|
||||
// 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000`
|
||||
@@ -76,6 +78,19 @@ pub struct UdpAck {
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl UdpAck {
|
||||
/// Create an empty ack packet to signifiy no packets recieved yet
|
||||
/// These are a little different in that they also set `group_id`
|
||||
pub fn empty(connection_id: i32) -> Self {
|
||||
Self {
|
||||
connection_id,
|
||||
group_id: 0xffffffff,
|
||||
packet_id: 0xffffffff,
|
||||
payload: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Magic for the UDP Data packet
|
||||
pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10;
|
||||
|
||||
@@ -107,7 +122,7 @@ impl std::fmt::Debug for UdpData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"connection_id", &self.connection_id)
|
||||
.entry(&"packet_id", &self.connection_id)
|
||||
.entry(&"packet_id", &self.packet_id)
|
||||
.entry(&"payload_len", &self.payload.len())
|
||||
.finish()
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
|
||||
le_u32(MAGIC_HEADER_UDP_ACK),
|
||||
le_i32(payload.connection_id),
|
||||
le_u32(0),
|
||||
le_u32(0),
|
||||
le_u32(payload.group_id),
|
||||
le_u32(payload.packet_id),
|
||||
le_u32(0),
|
||||
le_u32(binary_payload.len() as u32),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::io::{Read, Write};
|
||||
// YaSerde is currently naming the traits and the derive macros identically
|
||||
use yaserde::{ser::Config, YaDeserialize, YaSerialize};
|
||||
use yaserde::ser::Config;
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
/// The top level of the UDP xml is P2P
|
||||
@@ -57,6 +57,12 @@ pub struct UdpXml {
|
||||
/// C2D_A xml client to device accept
|
||||
#[yaserde(rename = "C2D_A")]
|
||||
pub c2d_a: Option<C2dA>,
|
||||
/// C2D_HB xml client to device heartbeat. This is the keep alive
|
||||
#[yaserde(rename = "C2D_HB")]
|
||||
pub c2d_hb: Option<C2dHb>,
|
||||
/// C2D_HB xml client to device heartbeat. This is the keep alive
|
||||
#[yaserde(rename = "C2R_HB")]
|
||||
pub c2r_hb: Option<C2rHb>,
|
||||
}
|
||||
|
||||
impl UdpXml {
|
||||
@@ -283,6 +289,8 @@ pub struct R2cT {
|
||||
///
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct R2cCr {
|
||||
/// Dev camera location (actual local ip)
|
||||
pub dev: IpPort,
|
||||
/// Dmap camera location
|
||||
pub dmap: IpPort,
|
||||
/// The location of the relay
|
||||
@@ -350,3 +358,29 @@ pub struct C2dA {
|
||||
/// Maximum size in bytes of a transmission
|
||||
pub mtu: u32,
|
||||
}
|
||||
|
||||
/// C2D_HB xml
|
||||
///
|
||||
/// Client to device heart beat.
|
||||
/// Seems to act as a keep alive
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct C2dHb {
|
||||
/// The client connection ID
|
||||
pub cid: i32,
|
||||
/// The camera connection ID
|
||||
pub did: i32,
|
||||
}
|
||||
|
||||
/// C2R_HB xml
|
||||
///
|
||||
/// Client to device heart beat.
|
||||
/// Seems to act as a keep alive
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
pub struct C2rHb {
|
||||
/// The connection ID
|
||||
pub sid: u32,
|
||||
/// The client connection ID
|
||||
pub cid: i32,
|
||||
/// The camera connection ID
|
||||
pub did: i32,
|
||||
}
|
||||
+2
-51
@@ -1,3 +1,4 @@
|
||||
#![warn(unused_crate_dependencies)]
|
||||
#![warn(missing_docs)]
|
||||
//! # Neolink-Core
|
||||
//!
|
||||
@@ -38,56 +39,6 @@ pub mod bcudp;
|
||||
/// Most commands will either return their `Ok(result)` or this `Err(Error)`
|
||||
pub use bc_protocol::Error;
|
||||
|
||||
pub(crate) use bc_protocol::Result;
|
||||
pub(crate) use bc_protocol::{Credentials, Result};
|
||||
|
||||
pub(crate) type NomErrorType<'a> = nom::error::VerboseError<&'a [u8]>;
|
||||
|
||||
// Used for caching the credentials
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Credentials {
|
||||
username: String,
|
||||
password: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Credentials {
|
||||
/// Default credentials for some reolink cameras
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
username: "admin".to_string(),
|
||||
password: Some("123456".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"username", &self.username)
|
||||
.entry(&"password", &"******")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
use std::convert::TryInto;
|
||||
impl Credentials {
|
||||
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
|
||||
Self {
|
||||
username: username.into(),
|
||||
password: password.map(|t| t.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to make an AES key from the login password and the NONCE
|
||||
/// negotiated during login
|
||||
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!(
|
||||
"{}-{}",
|
||||
nonce.as_ref(),
|
||||
self.password.clone().unwrap_or_default()
|
||||
);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "neolink_decoder"
|
||||
description = "A cli decoder for the AES encrypted packets"
|
||||
version = "0.0.1"
|
||||
authors = ["Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[dependencies]
|
||||
aes = "0.8.2"
|
||||
anyhow = "1.0.42"
|
||||
cfb-mode = "0.8.2"
|
||||
env_logger = "*"
|
||||
hex-string = "0.1.0"
|
||||
md5 = "0.7.0"
|
||||
requestty = "0.5.0"
|
||||
log = "0.4.17"
|
||||
@@ -0,0 +1,70 @@
|
||||
#![warn(unused_crate_dependencies)]
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::todo)]
|
||||
//! Use to decode AES packet data
|
||||
use hex_string::HexString;
|
||||
use requestty::Question;
|
||||
use std::convert::TryInto;
|
||||
|
||||
use aes::{
|
||||
cipher::{AsyncStreamCipher, KeyIvInit},
|
||||
Aes128,
|
||||
};
|
||||
use cfb_mode::Decryptor;
|
||||
|
||||
type Aes128CfbDec = Decryptor<Aes128>;
|
||||
|
||||
const IV: &[u8] = b"0123456789abcdef";
|
||||
|
||||
fn decrypt(buf: &[u8], aeskey: &[u8; 16]) -> Vec<u8> {
|
||||
let mut decrypted = buf.to_vec();
|
||||
Aes128CfbDec::new(aeskey.into(), IV.into()).decrypt(&mut decrypted);
|
||||
decrypted
|
||||
}
|
||||
|
||||
fn make_aeskey<T: AsRef<str>>(password: T, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!("{}-{}", nonce.as_ref(), password.as_ref(),);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
|
||||
fn main() -> Result<(), anyhow::Error> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
|
||||
let question = Question::input("hex")
|
||||
.message("Enter the hex string to decode")
|
||||
.build();
|
||||
|
||||
let source_str: String = requestty::prompt_one(question)?
|
||||
.as_string()
|
||||
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
|
||||
.to_string();
|
||||
|
||||
let question = Question::password("password")
|
||||
.message("Enter Camera Password")
|
||||
.mask('*')
|
||||
.build();
|
||||
let pass = requestty::prompt_one(question)?
|
||||
.as_string()
|
||||
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
|
||||
.to_string();
|
||||
|
||||
let question = Question::password("nonce")
|
||||
.message("Enter Login Nonce")
|
||||
.mask('*')
|
||||
.build();
|
||||
let nonce = requestty::prompt_one(question)?
|
||||
.as_string()
|
||||
.ok_or_else(|| anyhow::anyhow!("Did not get reply"))?
|
||||
.to_string();
|
||||
|
||||
let source_hex = HexString::from_string(&source_str).unwrap();
|
||||
|
||||
let decrypted = decrypt(&source_hex.as_bytes(), &make_aeskey(&pass, &nonce));
|
||||
log::info!("Bytes: {:X?}", decrypted);
|
||||
log::info!("Text: {}", String::from_utf8(decrypted)?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
# This template contains all of the possible sections and their default values
|
||||
|
||||
# Note that all fields that take a lint level have these possible values:
|
||||
# * deny - An error will be produced and the check will fail
|
||||
# * warn - A warning will be produced, but the check will not fail
|
||||
# * allow - No warning or error will be produced, though in some cases a note
|
||||
# will be
|
||||
|
||||
# The values provided in this template are the default values that will be used
|
||||
# when any section or field is not specified in your own configuration
|
||||
|
||||
# Root options
|
||||
|
||||
# If 1 or more target triples (and optionally, target_features) are specified,
|
||||
# only the specified targets will be checked when running `cargo deny check`.
|
||||
# This means, if a particular package is only ever used as a target specific
|
||||
# dependency, such as, for example, the `nix` crate only being used via the
|
||||
# `target_family = "unix"` configuration, that only having windows targets in
|
||||
# this list would mean the nix crate, as well as any of its exclusive
|
||||
# dependencies not shared by any other crates, would be ignored, as the target
|
||||
# list here is effectively saying which targets you are building for.
|
||||
targets = [
|
||||
# The triple can be any string, but only the target triples built in to
|
||||
# rustc (as of 1.40) can be checked against actual config expressions
|
||||
#{ triple = "x86_64-unknown-linux-musl" },
|
||||
# You can also specify which target_features you promise are enabled for a
|
||||
# particular target. target_features are currently not validated against
|
||||
# the actual valid features supported by the target architecture.
|
||||
#{ triple = "wasm32-unknown-unknown", features = ["atomics"] },
|
||||
]
|
||||
# When creating the dependency graph used as the source of truth when checks are
|
||||
# executed, this field can be used to prune crates from the graph, removing them
|
||||
# from the view of cargo-deny. This is an extremely heavy hammer, as if a crate
|
||||
# is pruned from the graph, all of its dependencies will also be pruned unless
|
||||
# they are connected to another crate in the graph that hasn't been pruned,
|
||||
# so it should be used with care. The identifiers are [Package ID Specifications]
|
||||
# (https://doc.rust-lang.org/cargo/reference/pkgid-spec.html)
|
||||
#exclude = []
|
||||
# If true, metadata will be collected with `--all-features`. Note that this can't
|
||||
# be toggled off if true, if you want to conditionally enable `--all-features` it
|
||||
# is recommended to pass `--all-features` on the cmd line instead
|
||||
all-features = false
|
||||
# If true, metadata will be collected with `--no-default-features`. The same
|
||||
# caveat with `all-features` applies
|
||||
no-default-features = false
|
||||
# If set, these feature will be enabled when collecting metadata. If `--features`
|
||||
# is specified on the cmd line they will take precedence over this option.
|
||||
#features = []
|
||||
# When outputting inclusion graphs in diagnostics that include features, this
|
||||
# option can be used to specify the depth at which feature edges will be added.
|
||||
# This option is included since the graphs can be quite large and the addition
|
||||
# of features from the crate(s) to all of the graph roots can be far too verbose.
|
||||
# This option can be overridden via `--feature-depth` on the cmd line
|
||||
feature-depth = 1
|
||||
|
||||
# This section is considered when running `cargo deny check advisories`
|
||||
# More documentation for the advisories section can be found here:
|
||||
# https://embarkstudios.github.io/cargo-deny/checks/advisories/cfg.html
|
||||
[advisories]
|
||||
# The path where the advisory database is cloned/fetched into
|
||||
db-path = "~/.cargo/advisory-db"
|
||||
# The url(s) of the advisory databases to use
|
||||
db-urls = ["https://github.com/rustsec/advisory-db"]
|
||||
# The lint level for security vulnerabilities
|
||||
vulnerability = "deny"
|
||||
# The lint level for unmaintained crates
|
||||
unmaintained = "warn"
|
||||
# The lint level for crates that have been yanked from their source registry
|
||||
yanked = "warn"
|
||||
# The lint level for crates with security notices. Note that as of
|
||||
# 2019-12-17 there are no security notice advisories in
|
||||
# https://github.com/rustsec/advisory-db
|
||||
notice = "warn"
|
||||
# A list of advisory IDs to ignore. Note that ignored advisories will still
|
||||
# output a note when they are encountered.
|
||||
ignore = [
|
||||
#"RUSTSEC-0000-0000",
|
||||
# This is rust-xml which is unmaintaned. Not much we can do since
|
||||
# all the xml serde like crates seem to use it
|
||||
"RUSTSEC-2022-0048",
|
||||
]
|
||||
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
|
||||
# lower than the range specified will be ignored. Note that ignored advisories
|
||||
# will still output a note when they are encountered.
|
||||
# * None - CVSS Score 0.0
|
||||
# * Low - CVSS Score 0.1 - 3.9
|
||||
# * Medium - CVSS Score 4.0 - 6.9
|
||||
# * High - CVSS Score 7.0 - 8.9
|
||||
# * Critical - CVSS Score 9.0 - 10.0
|
||||
#severity-threshold =
|
||||
|
||||
# If this is true, then cargo deny will use the git executable to fetch advisory database.
|
||||
# If this is false, then it uses a built-in git library.
|
||||
# Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support.
|
||||
# See Git Authentication for more information about setting up git authentication.
|
||||
#git-fetch-with-cli = true
|
||||
|
||||
# This section is considered when running `cargo deny check licenses`
|
||||
# More documentation for the licenses section can be found here:
|
||||
# https://embarkstudios.github.io/cargo-deny/checks/licenses/cfg.html
|
||||
[licenses]
|
||||
# The lint level for crates which do not have a detectable license
|
||||
unlicensed = "deny"
|
||||
# List of explicitly allowed licenses
|
||||
# See https://spdx.org/licenses/ for list of possible licenses
|
||||
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
|
||||
allow = [
|
||||
"MIT",
|
||||
"Apache-2.0",
|
||||
"Apache-2.0 WITH LLVM-exception",
|
||||
"BSD-3-Clause",
|
||||
"AGPL-3.0",
|
||||
"Unicode-DFS-2016",
|
||||
"ISC",
|
||||
"OpenSSL",
|
||||
"Zlib",
|
||||
]
|
||||
# List of explicitly disallowed licenses
|
||||
# See https://spdx.org/licenses/ for list of possible licenses
|
||||
# [possible values: any SPDX 3.11 short identifier (+ optional exception)].
|
||||
deny = [
|
||||
#"Nokia",
|
||||
]
|
||||
# Lint level for licenses considered copyleft
|
||||
copyleft = "allow"
|
||||
# Blanket approval or denial for OSI-approved or FSF Free/Libre licenses
|
||||
# * both - The license will be approved if it is both OSI-approved *AND* FSF
|
||||
# * either - The license will be approved if it is either OSI-approved *OR* FSF
|
||||
# * osi-only - The license will be approved if is OSI-approved *AND NOT* FSF
|
||||
# * fsf-only - The license will be approved if is FSF *AND NOT* OSI-approved
|
||||
# * neither - This predicate is ignored and the default lint level is used
|
||||
allow-osi-fsf-free = "neither"
|
||||
# Lint level used when no other predicates are matched
|
||||
# 1. License isn't in the allow or deny lists
|
||||
# 2. License isn't copyleft
|
||||
# 3. License isn't OSI/FSF, or allow-osi-fsf-free = "neither"
|
||||
default = "deny"
|
||||
# The confidence threshold for detecting a license from license text.
|
||||
# The higher the value, the more closely the license text must be to the
|
||||
# canonical license text of a valid SPDX license file.
|
||||
# [possible values: any between 0.0 and 1.0].
|
||||
confidence-threshold = 0.8
|
||||
# Allow 1 or more licenses on a per-crate basis, so that particular licenses
|
||||
# aren't accepted for every possible crate as with the normal allow list
|
||||
exceptions = [
|
||||
# Each entry is the crate and version constraint, and its specific allow
|
||||
# list
|
||||
#{ allow = ["Zlib"], name = "adler32", version = "*" },
|
||||
]
|
||||
|
||||
# Some crates don't have (easily) machine readable licensing information,
|
||||
# adding a clarification entry for it allows you to manually specify the
|
||||
# licensing information
|
||||
[[licenses.clarify]]
|
||||
# The name of the crate the clarification applies to
|
||||
name = "ring"
|
||||
# The optional version constraint for the crate
|
||||
version = "*"
|
||||
# The SPDX expression for the license requirements of the crate
|
||||
expression = "MIT AND ISC AND OpenSSL"
|
||||
|
||||
# One or more files in the crate's source used as the "source of truth" for
|
||||
# the license expression. If the contents match, the clarification will be used
|
||||
# when running the license check, otherwise the clarification will be ignored
|
||||
# and the crate will be checked normally, which may produce warnings or errors
|
||||
# depending on the rest of your configuration
|
||||
license-files = [
|
||||
# Each entry is a crate relative path, and the (opaque) hash of its contents
|
||||
{ path = "LICENSE", hash = 0xbd0eed23 }
|
||||
]
|
||||
|
||||
[licenses.private]
|
||||
# If true, ignores workspace crates that aren't published, or are only
|
||||
# published to private registries.
|
||||
# To see how to mark a crate as unpublished (to the official registry),
|
||||
# visit https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field.
|
||||
ignore = false
|
||||
# One or more private registries that you might publish crates to, if a crate
|
||||
# is only published to private registries, and ignore is true, the crate will
|
||||
# not have its license(s) checked
|
||||
registries = [
|
||||
#"https://sekretz.com/registry
|
||||
]
|
||||
|
||||
# This section is considered when running `cargo deny check bans`.
|
||||
# More documentation about the 'bans' section can be found here:
|
||||
# https://embarkstudios.github.io/cargo-deny/checks/bans/cfg.html
|
||||
[bans]
|
||||
# Lint level for when multiple versions of the same crate are detected
|
||||
multiple-versions = "allow"
|
||||
# Lint level for when a crate version requirement is `*`
|
||||
wildcards = "allow"
|
||||
# The graph highlighting used when creating dotgraphs for crates
|
||||
# with multiple versions
|
||||
# * lowest-version - The path to the lowest versioned duplicate is highlighted
|
||||
# * simplest-path - The path to the version with the fewest edges is highlighted
|
||||
# * all - Both lowest-version and simplest-path are used
|
||||
highlight = "all"
|
||||
# The default lint level for `default` features for crates that are members of
|
||||
# the workspace that is being checked. This can be overriden by allowing/denying
|
||||
# `default` on a crate-by-crate basis if desired.
|
||||
workspace-default-features = "allow"
|
||||
# The default lint level for `default` features for external crates that are not
|
||||
# members of the workspace. This can be overriden by allowing/denying `default`
|
||||
# on a crate-by-crate basis if desired.
|
||||
external-default-features = "allow"
|
||||
# List of crates that are allowed. Use with care!
|
||||
allow = [
|
||||
#{ name = "ansi_term", version = "=0.11.0" },
|
||||
]
|
||||
# List of crates to deny
|
||||
deny = [
|
||||
# Each entry the name of a crate and a version range. If version is
|
||||
# not specified, all versions will be matched.
|
||||
#{ name = "ansi_term", version = "=0.11.0" },
|
||||
#
|
||||
# Wrapper crates can optionally be specified to allow the crate when it
|
||||
# is a direct dependency of the otherwise banned crate
|
||||
#{ name = "ansi_term", version = "=0.11.0", wrappers = [] },
|
||||
]
|
||||
|
||||
# List of features to allow/deny
|
||||
# Each entry the name of a crate and a version range. If version is
|
||||
# not specified, all versions will be matched.
|
||||
#[[bans.features]]
|
||||
#name = "reqwest"
|
||||
# Features to not allow
|
||||
#deny = ["json"]
|
||||
# Features to allow
|
||||
#allow = [
|
||||
# "rustls",
|
||||
# "__rustls",
|
||||
# "__tls",
|
||||
# "hyper-rustls",
|
||||
# "rustls",
|
||||
# "rustls-pemfile",
|
||||
# "rustls-tls-webpki-roots",
|
||||
# "tokio-rustls",
|
||||
# "webpki-roots",
|
||||
#]
|
||||
# If true, the allowed features must exactly match the enabled feature set. If
|
||||
# this is set there is no point setting `deny`
|
||||
#exact = true
|
||||
|
||||
# Certain crates/versions that will be skipped when doing duplicate detection.
|
||||
skip = [
|
||||
#{ name = "ansi_term", version = "=0.11.0" },
|
||||
]
|
||||
# Similarly to `skip` allows you to skip certain crates during duplicate
|
||||
# detection. Unlike skip, it also includes the entire tree of transitive
|
||||
# dependencies starting at the specified crate, up to a certain depth, which is
|
||||
# by default infinite.
|
||||
skip-tree = [
|
||||
#{ name = "ansi_term", version = "=0.11.0", depth = 20 },
|
||||
]
|
||||
|
||||
# This section is considered when running `cargo deny check sources`.
|
||||
# More documentation about the 'sources' section can be found here:
|
||||
# https://embarkstudios.github.io/cargo-deny/checks/sources/cfg.html
|
||||
[sources]
|
||||
# Lint level for what to happen when a crate from a crate registry that is not
|
||||
# in the allow list is encountered
|
||||
unknown-registry = "warn"
|
||||
# Lint level for what to happen when a crate from a git repository that is not
|
||||
# in the allow list is encountered
|
||||
unknown-git = "warn"
|
||||
# List of URLs for allowed crate registries. Defaults to the crates.io index
|
||||
# if not specified. If it is specified but empty, no registries are allowed.
|
||||
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
|
||||
# List of URLs for allowed Git repositories
|
||||
allow-git = []
|
||||
|
||||
[sources.allow-org]
|
||||
# 1 or more github.com organizations to allow git sources for
|
||||
#github = [""]
|
||||
# 1 or more gitlab.com organizations to allow git sources for
|
||||
#gitlab = [""]
|
||||
# 1 or more bitbucket.org organizations to allow git sources for
|
||||
#bitbucket = [""]
|
||||
@@ -2,6 +2,20 @@
|
||||
-- Copy/symlink it into ~/.local/lib/wireshark/plugins/ and restart Wireshark; it should
|
||||
-- automatically attempt to decode TCP connections on port 9000.
|
||||
|
||||
-- Copyright (c) the Neolink contributors
|
||||
--
|
||||
-- This program is free software: you can redistribute it and/or modify it
|
||||
-- under the terms of the GNU Affero General Public License, version 3, as
|
||||
-- published by the Free Software Foundation.
|
||||
--
|
||||
-- This program is distributed in the hope that it will be useful, but WITHOUT
|
||||
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
-- FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
||||
-- more details.
|
||||
--
|
||||
-- You should have received a copy of the GNU General Public License along with
|
||||
-- this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
local bc_protocol = Proto("Baichuan", "Baichuan/Reolink IP Camera Protocol")
|
||||
|
||||
local magic_bytes = ProtoField.int32("baichuan.magic", "magic", base.DEC)
|
||||
@@ -151,6 +165,8 @@ local message_types = {
|
||||
[209]="<LedState> (write)",
|
||||
[210]="<PTOP>",
|
||||
[211]="<PTOP> (write)",
|
||||
[212]="<rfAlarmCfg>",
|
||||
[213]="<rfAlarmCfg> (write)",
|
||||
[216]="<EmailTask> (write)",
|
||||
[217]="<EmailTask>",
|
||||
[218]="<PushTask> (write)",
|
||||
@@ -158,9 +174,14 @@ local message_types = {
|
||||
[228]="<Crop>",
|
||||
[229]="<Crop> (write)",
|
||||
[230]="<cropSnap>",
|
||||
[234]="UDP Keep Alive",
|
||||
[252]="<BatteryInfoList>",
|
||||
[253]="<BatteryInfo>",
|
||||
[272]="<findAlarmVideo>",
|
||||
[273]="<alarmVideoInfo>",
|
||||
[274]="<findAlarmVideo>",
|
||||
[319]="<timelapseCfg>",
|
||||
[342]="<AiDetectCfg>",
|
||||
}
|
||||
|
||||
local message_classes = {
|
||||
|
||||
@@ -47,23 +47,23 @@ The config file tells Neolink how to connect to your camera and serve the video
|
||||
1. Create a simple text file (i.g. `config.toml`) in the same directory you have unpacked Neolink with the following format:
|
||||
|
||||
bind = "0.0.0.0"
|
||||
|
||||
|
||||
[[cameras]]
|
||||
name = "cameraname"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
address = "192.168.1.10:9000"
|
||||
stream = "both"
|
||||
|
||||
|
||||
2. Change `cameraname` to a legible, phonetic name that describes your camera. Leave the quotes around the name.
|
||||
|
||||
3. The default username is `admin`; leave this unless you've created another user.
|
||||
|
||||
4. Replace `password` with the password you set on the camera. If you chose to not use a password, remove this line from the config file. Again, leave the quotes.
|
||||
|
||||
5. Replace `192.168.1.10:9000` with the IP address you set for your camera.
|
||||
5. Replace `192.168.1.10:9000` with the IP address you set for your camera.
|
||||
Note: The port, `:9000`, should remain at the end of your IP address. This is the proprietary "media port" that Reolink uses.
|
||||
|
||||
|
||||
6. The `stream` line allows you to choose which stream type to use. Neolink supports streaming two streams, the main-stream, and the sub-stream. It can stream either one, or both. If you wish to stream both streams, leave this line as is. If you wish to stream _only_ the main-stream, change `both` to `mainStream`. If you wish to stream only the sub-stream, change `both` to `subStream`.
|
||||
|
||||
Note: Reolink D400/B400 Cameras **_do not support serving both streams at once_**, so you must manually choose which stream type to use. For best quality, choose the main stream.
|
||||
@@ -190,7 +190,7 @@ _The best way to have Neolink run at startup is create a Scheduled Task that sta
|
||||
|
||||
12. Check "If the task fails, restart every:"
|
||||
|
||||
13. For redundancy, enter `999` into the number of restart tries.
|
||||
13. For redundancy, enter `999` into the number of restart tries.
|
||||
|
||||
_The Settings tab should look something like this:_
|
||||
|
||||
|
||||
@@ -51,6 +51,30 @@ address = "192.168.1.187:9000"
|
||||
# If your device has user connection limits try a single stream instead.
|
||||
# stream = "mainStream"
|
||||
|
||||
# By default neolink will use any means to connect to the camera
|
||||
# from a UID
|
||||
# This include relaying via reolink servers
|
||||
# This variable `discovery` controls the method of UID discovery
|
||||
# - Possible values
|
||||
# "relay" # Any means including connecting and transmitting through reolink
|
||||
# "map" # Register our local ip address with reolink and ask the camera to connect to us but don't relay data through reolink
|
||||
# "remote" # Register our local ip address with reolink but only permit same network connections (useful if broadcast is not possible)
|
||||
# "local" # Do not contact reolink servers at all. Rely soley on local UDP broadcast based discovery
|
||||
#
|
||||
# discovery = "relay"
|
||||
|
||||
# Certain types of camera emit status messages (such as battery levels)
|
||||
#
|
||||
# By default we hide these status messages from the user but you can instead requst that
|
||||
# they be printed to stdout using print_format
|
||||
#
|
||||
# Valid values are:
|
||||
# - None
|
||||
# - Human
|
||||
# - Xml
|
||||
#
|
||||
# print_format = "None"
|
||||
|
||||
|
||||
[[cameras]]
|
||||
name = "storage shed"
|
||||
|
||||
+10
-9
@@ -1,21 +1,21 @@
|
||||
use clap::{crate_authors, crate_version, Parser};
|
||||
use std::path::PathBuf;
|
||||
use structopt::{clap::AppSettings, StructOpt};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// A standards-compliant bridge to Reolink IP cameras
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(
|
||||
name = "neolink",
|
||||
setting(AppSettings::ArgRequiredElseHelp),
|
||||
setting(AppSettings::UnifiedHelpMessage)
|
||||
)]
|
||||
///
|
||||
/// Neolink is free software released under the GNU AGPL v3.
|
||||
/// You can find its source code at https://github.com/thirtythreeforty/neolink
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "neolink", arg_required_else_help = true, version = crate_version!(), author = crate_authors!("\n"))]
|
||||
pub struct Opt {
|
||||
#[structopt(short, long, global(true), parse(from_os_str))]
|
||||
#[arg(short, long, global = true, value_parser = PathBuf::from_str)]
|
||||
pub config: Option<PathBuf>,
|
||||
#[structopt(subcommand)]
|
||||
pub cmd: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub enum Command {
|
||||
Rtsp(super::rtsp::Opt),
|
||||
StatusLight(super::statusled::Opt),
|
||||
@@ -23,4 +23,5 @@ pub enum Command {
|
||||
Pir(super::pir::Opt),
|
||||
Talk(super::talk::Opt),
|
||||
Mqtt(super::mqtt::Opt),
|
||||
Image(super::image::Opt),
|
||||
}
|
||||
+32
-11
@@ -1,4 +1,5 @@
|
||||
use lazy_static::lazy_static;
|
||||
use neolink_core::bc_protocol::{DiscoveryMethods, PrintFormat};
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::clone::Clone;
|
||||
@@ -10,7 +11,8 @@ lazy_static! {
|
||||
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
|
||||
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
|
||||
static ref RE_PAUSE_MODE: Regex = Regex::new(r"^(black|still|test|none)$").unwrap();
|
||||
static ref RE_DISC_SRC: Regex = Regex::new(r"^([nN]one|[lL]ocal|[rR]emote|[rR]elay)$").unwrap();
|
||||
static ref RE_MAXENC_SRC: Regex =
|
||||
Regex::new(r"^([nN]one|[Aa][Ee][Ss]|[Bb][Cc][Ee][Nn][Cc][Rr][Yy][Pp][Tt])$").unwrap();
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -78,12 +80,22 @@ pub(crate) struct CameraConfig {
|
||||
pub(crate) pause: PauseConfig,
|
||||
|
||||
#[serde(default = "default_discovery")]
|
||||
pub(crate) discovery: DiscoveryMethods,
|
||||
|
||||
#[serde(default = "default_maxenc")]
|
||||
#[validate(regex(
|
||||
path = "RE_DISC_SRC",
|
||||
message = "Invalid discovery method",
|
||||
code = "discovery"
|
||||
path = "RE_MAXENC_SRC",
|
||||
message = "Invalid maximum encryption method",
|
||||
code = "max_encryption"
|
||||
))]
|
||||
pub(crate) discovery: String,
|
||||
pub(crate) max_encryption: String,
|
||||
|
||||
#[serde(default = "default_strict")]
|
||||
/// If strict then the media stream will error in the event that the media packets are not as expected
|
||||
pub(crate) strict: bool,
|
||||
|
||||
#[serde(default = "default_print", alias = "print")]
|
||||
pub(crate) print_format: PrintFormat,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -128,8 +140,16 @@ fn default_mqtt() -> Option<MqttConfig> {
|
||||
None
|
||||
}
|
||||
|
||||
fn default_discovery() -> String {
|
||||
"Relay".to_string()
|
||||
fn default_print() -> PrintFormat {
|
||||
PrintFormat::None
|
||||
}
|
||||
|
||||
fn default_discovery() -> DiscoveryMethods {
|
||||
DiscoveryMethods::Relay
|
||||
}
|
||||
|
||||
fn default_maxenc() -> String {
|
||||
"Aes".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
@@ -137,7 +157,7 @@ pub(crate) struct PauseConfig {
|
||||
#[serde(default = "default_on_motion")]
|
||||
pub(crate) on_motion: bool,
|
||||
|
||||
#[serde(default = "default_on_disconnect")]
|
||||
#[serde(default = "default_on_disconnect", alias = "on_client")]
|
||||
pub(crate) on_disconnect: bool,
|
||||
|
||||
#[serde(default = "default_motion_timeout", alias = "timeout")]
|
||||
@@ -192,6 +212,10 @@ fn default_pause_mode() -> String {
|
||||
"none".to_string()
|
||||
}
|
||||
|
||||
fn default_strict() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn default_pause() -> PauseConfig {
|
||||
PauseConfig {
|
||||
on_motion: default_on_motion(),
|
||||
@@ -217,9 +241,6 @@ fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), Validation
|
||||
(None, None) => Err(ValidationError::new(
|
||||
"Either camera address or uid must be given",
|
||||
)),
|
||||
(Some(_), Some(_)) => Err(ValidationError::new(
|
||||
"Must provide either camera address or uid not both",
|
||||
)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// The image command will dump a still image from the camera
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera to get the image from. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// The path of the output.
|
||||
#[structopt(short, long, value_parser = PathBuf::from_str)]
|
||||
pub file_path: PathBuf,
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use gstreamer::{parse_launch, prelude::*, ClockTime, MessageView, Pipeline, State};
|
||||
use gstreamer_app::AppSrc;
|
||||
use neolink_core::bcmedia::model::VideoType;
|
||||
use tokio::{
|
||||
sync::{
|
||||
self,
|
||||
mpsc::{channel, Sender},
|
||||
},
|
||||
task::{self, JoinSet},
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum GstControl {
|
||||
Data(Vec<u8>),
|
||||
Eos,
|
||||
}
|
||||
|
||||
pub(super) struct GstSender {
|
||||
sender: Sender<GstControl>,
|
||||
#[allow(dead_code)] // It is used for its automatic drop
|
||||
set: JoinSet<Result<()>>,
|
||||
finished: sync::oneshot::Receiver<Result<()>>,
|
||||
}
|
||||
|
||||
impl GstSender {
|
||||
pub(super) async fn send(&self, buf: Vec<u8>) -> Result<()> {
|
||||
self.sender
|
||||
.send(GstControl::Data(buf))
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to send buffer: {:?}", e))
|
||||
}
|
||||
|
||||
pub(super) async fn eos(&self) -> Result<()> {
|
||||
self.sender
|
||||
.send(GstControl::Eos)
|
||||
.await
|
||||
.map_err(|e| anyhow!("Failed to send eos: {:?}", e))
|
||||
}
|
||||
|
||||
pub(super) async fn is_finished(&mut self) -> Option<Result<()>> {
|
||||
match self.finished.try_recv() {
|
||||
Ok(res) => Some(res),
|
||||
Err(sync::oneshot::error::TryRecvError::Empty) => None,
|
||||
Err(sync::oneshot::error::TryRecvError::Closed) => {
|
||||
Some(Err(anyhow!("Gstreamer finished channel is closed")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn from_input<T: AsRef<Path>>(
|
||||
format: VideoType,
|
||||
out_file: T,
|
||||
) -> Result<GstSender> {
|
||||
let pipeline = create_pipeline(format, out_file.as_ref())?;
|
||||
output(pipeline).await
|
||||
}
|
||||
|
||||
async fn output(pipeline: Pipeline) -> Result<GstSender> {
|
||||
let source = get_source(&pipeline)?;
|
||||
let (sender, mut reciever) = channel::<GstControl>(100);
|
||||
let mut set = JoinSet::new();
|
||||
set.spawn(async move {
|
||||
while let Some(control) = reciever.recv().await {
|
||||
match control {
|
||||
GstControl::Data(buf) => {
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(&buf);
|
||||
}
|
||||
source.push_buffer(gst_buf)?;
|
||||
}
|
||||
GstControl::Eos => {
|
||||
source.end_of_stream()?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let (tx, finished) = sync::oneshot::channel();
|
||||
task::spawn_blocking(move || {
|
||||
let res = start_pipeline(pipeline);
|
||||
if let Err(e) = &res {
|
||||
log::error!("Failed to run pipeline: {:?}", e);
|
||||
}
|
||||
tx.send(res)
|
||||
});
|
||||
|
||||
Ok(GstSender {
|
||||
sender,
|
||||
set,
|
||||
finished,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_pipeline(pipeline: Pipeline) -> Result<()> {
|
||||
pipeline.set_state(State::Playing)?;
|
||||
|
||||
let bus = pipeline
|
||||
.bus()
|
||||
.expect("Pipeline without bus. Shouldn't happen!");
|
||||
|
||||
for msg in bus.iter_timed(ClockTime::NONE) {
|
||||
match msg.view() {
|
||||
MessageView::Eos(..) => break,
|
||||
MessageView::Error(err) => {
|
||||
pipeline
|
||||
.set_state(State::Null)
|
||||
.context("Error in gstreamer when setting state to Null")?;
|
||||
log::warn!(
|
||||
"Error from gstreamer when setting the play state {:?} setting to Null instead",
|
||||
err
|
||||
);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
pipeline
|
||||
.set_state(State::Null)
|
||||
.context("Error in gstreamer when setting state to Null")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_source(pipeline: &Pipeline) -> Result<AppSrc> {
|
||||
let source = pipeline
|
||||
.by_name("thesource")
|
||||
.expect("There shoud be a `thesource`");
|
||||
source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot find appsource in gstreamer, check your gstreamer plugins"))
|
||||
}
|
||||
|
||||
fn create_pipeline(format: VideoType, file_path: &Path) -> Result<Pipeline> {
|
||||
gstreamer::init()
|
||||
.context("Unable to start gstreamer ensure it and all plugins are installed")?;
|
||||
let file_path = file_path.with_extension("jpeg");
|
||||
|
||||
let launch_str = match format {
|
||||
VideoType::H264 => {
|
||||
format!(
|
||||
"appsrc name=thesource \
|
||||
! h264parse \
|
||||
! decodebin \
|
||||
! jpegenc snapshot=TRUE
|
||||
! filesink location={}",
|
||||
file_path.display()
|
||||
)
|
||||
}
|
||||
VideoType::H265 => {
|
||||
format!(
|
||||
"appsrc name=thesource \
|
||||
! h265parse \
|
||||
! decodebin \
|
||||
! jpegenc snapshot=TRUE
|
||||
! filesink location={}",
|
||||
file_path.display()
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
log::info!("{}", launch_str);
|
||||
|
||||
// Parse the pipeline we want to probe from a static in-line string.
|
||||
// Here we give our audiotestsrc a name, so we can retrieve that element
|
||||
// from the resulting pipeline.
|
||||
let pipeline = parse_launch(&launch_str)
|
||||
.context("Unable to load gstreamer pipeline ensure all gstramer plugins are installed")?;
|
||||
let pipeline = pipeline.dynamic_cast::<Pipeline>().map_err(|_| {
|
||||
anyhow!("Unable to create gstreamer pipeline ensure all gstramer plugins are installed")
|
||||
})?;
|
||||
|
||||
// let appssource = get_source(&pipeline)?;
|
||||
|
||||
// Tell the appsink what format we produce.
|
||||
// let caps = match format {
|
||||
// VideoType::H264 => Caps::new_simple("video/x-h264", &[("parsed", &false)]),
|
||||
// VideoType::H265 => Caps::new_simple("video/x-h265", &[("parsed", &false)]),
|
||||
// };
|
||||
// appssource.set_caps(Some(&caps));
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
///
|
||||
/// # Neolink Image
|
||||
///
|
||||
/// This module can be used to dump a still image from the camera
|
||||
///
|
||||
///
|
||||
/// # Usage
|
||||
/// ```bash
|
||||
/// neolink image --config=config.toml --file-path=filepath CameraName
|
||||
/// ```
|
||||
///
|
||||
use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use neolink_core::{bc_protocol::*, bcmedia::model::*};
|
||||
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
|
||||
use super::config::Config;
|
||||
use crate::utils::{connect_and_login, find_camera_by_name};
|
||||
pub(crate) use cmdline::Opt;
|
||||
|
||||
/// Entry point for the image subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera_config = find_camera_by_name(&config, &opt.camera).context(
|
||||
"failed to load config file or find the camera. Check the path and name of the camera.",
|
||||
)?;
|
||||
|
||||
// Set up camera to recieve the stream
|
||||
let camera = connect_and_login(camera_config)
|
||||
.await
|
||||
.context("Failed to connect to the camera, check credentials and network")?;
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
.context("Failed to start video")?;
|
||||
|
||||
// Get one iframe at the start while also getting the the video type
|
||||
let buf;
|
||||
let vid_type;
|
||||
loop {
|
||||
if let BcMedia::Iframe(frame) = stream_data.get_data().await?? {
|
||||
vid_type = frame.video_type;
|
||||
buf = frame.data;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sender = gst::from_input(vid_type, &opt.file_path).await?;
|
||||
sender.send(buf).await?; // Send first iframe
|
||||
|
||||
// Keep sending both IFrame or PFrame until finished
|
||||
while sender.is_finished().await.is_none() {
|
||||
let buf = match stream_data.get_data().await?? {
|
||||
BcMedia::Iframe(frame) => frame.data,
|
||||
BcMedia::Pframe(frame) => frame.data,
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Sending frame data to gstreamer");
|
||||
if sender.send(buf).await.is_err() {
|
||||
// Assume that the sender is closed
|
||||
// because the pipeline is finished
|
||||
break;
|
||||
}
|
||||
}
|
||||
debug!("Sending EOS");
|
||||
let _ = sender.eos().await; // Ignore return because if pipeline is finished this will error
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+21
-2
@@ -1,4 +1,6 @@
|
||||
#![warn(unused_crate_dependencies)]
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::todo)]
|
||||
//!
|
||||
//! # Neolink
|
||||
//!
|
||||
@@ -7,15 +9,29 @@
|
||||
//! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras
|
||||
//! that do not nativly support RTSP.
|
||||
//!
|
||||
//! This program is free software: you can redistribute it and/or modify it under the terms of the
|
||||
//! GNU General Public License as published by the Free Software Foundation, either version 3 of
|
||||
//! the License, or (at your option) any later version.
|
||||
//!
|
||||
//! This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
||||
//! without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
|
||||
//! the GNU General Public License for more details.
|
||||
//!
|
||||
//! You should have received a copy of the GNU General Public License along with this program. If
|
||||
//! not, see <https://www.gnu.org/licenses/>.
|
||||
//!
|
||||
//! Neolink source code is available online at <https://github.com/thirtythreeforty/neolink>
|
||||
//!
|
||||
use anyhow::{Context, Result};
|
||||
use clap::Parser;
|
||||
use env_logger::Env;
|
||||
use log::*;
|
||||
use std::fs;
|
||||
use structopt::StructOpt;
|
||||
use validator::Validate;
|
||||
|
||||
mod cmdline;
|
||||
mod config;
|
||||
mod image;
|
||||
mod mqtt;
|
||||
mod pir;
|
||||
mod reboot;
|
||||
@@ -37,7 +53,7 @@ async fn main() -> Result<()> {
|
||||
env!("NEOLINK_PROFILE")
|
||||
);
|
||||
|
||||
let opt = Opt::from_args();
|
||||
let opt = Opt::parse();
|
||||
|
||||
let conf_path = opt.config.context("Must supply --config file")?;
|
||||
let config: Config = toml::from_str(
|
||||
@@ -76,6 +92,9 @@ async fn main() -> Result<()> {
|
||||
Some(Command::Mqtt(opts)) => {
|
||||
mqtt::main(opts, config).await?;
|
||||
}
|
||||
Some(Command::Image(opts)) => {
|
||||
image::main(opts, config).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
use structopt::StructOpt;
|
||||
use clap::Parser;
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {}
|
||||
+74
-8
@@ -25,6 +25,9 @@ pub(crate) enum Messages {
|
||||
IRLedOff,
|
||||
IRLedAuto,
|
||||
Battery,
|
||||
PIROn,
|
||||
PIROff,
|
||||
PIRQuery,
|
||||
Ptz(Direction),
|
||||
}
|
||||
|
||||
@@ -84,7 +87,7 @@ impl EventCam {
|
||||
.await
|
||||
.context("Failed to send message from camera")
|
||||
} else {
|
||||
Err(anyhow!("Failed to send camera data over crossbeam"))
|
||||
Err(anyhow!("Failed to send camera data over channel"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,11 +158,7 @@ impl EventCam {
|
||||
camera_config.name, camera_addr
|
||||
);
|
||||
let camera = camera_addr
|
||||
.connect_camera(
|
||||
camera_config.channel_id,
|
||||
&camera_config.username,
|
||||
camera_config.password.as_ref(),
|
||||
)
|
||||
.connect_camera(camera_config)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
@@ -322,8 +321,75 @@ impl MessageHandler {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::Battery => {
|
||||
todo!()
|
||||
Messages::Battery => match self.camera.battery_info().await {
|
||||
Err(_) => {
|
||||
error!("Failed to get battery status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
Ok(battery_info) => {
|
||||
let bytes_res = yaserde::ser::serialize_with_writer(
|
||||
&battery_info,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
);
|
||||
match bytes_res {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(str) => str,
|
||||
Err(_) => {
|
||||
error!("Failed to encode battery status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
error!("Failed to serialise battery status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Messages::PIRQuery => match self.camera.get_pirstate().await {
|
||||
Err(_) => {
|
||||
error!("Failed to get pir status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
Ok(pir_info) => {
|
||||
let bytes_res = yaserde::ser::serialize_with_writer(
|
||||
&pir_info,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
);
|
||||
match bytes_res {
|
||||
Ok(bytes) => match String::from_utf8(bytes) {
|
||||
Ok(str) => str,
|
||||
Err(_) => {
|
||||
error!("Failed to encode pir status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
error!("Failed to serialise pir status");
|
||||
"FAIL".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Messages::PIROn => {
|
||||
if self.camera.pir_set(true).await.is_err() {
|
||||
error!("Failed to turn on the pir");
|
||||
self.abort();
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::PIROff => {
|
||||
if self.camera.pir_set(false).await.is_err() {
|
||||
error!("Failed to turn on the pir");
|
||||
self.abort();
|
||||
"FAIL".to_string()
|
||||
} else {
|
||||
"OK".to_string()
|
||||
}
|
||||
}
|
||||
Messages::Ptz(direction) => {
|
||||
let (bc_direction, amount) = match direction {
|
||||
|
||||
+32
-3
@@ -11,6 +11,7 @@ use log::*;
|
||||
/// Control messages:
|
||||
///
|
||||
/// - `/control/led [on|off]` Turns status LED on/off
|
||||
/// - `/control/pir [on|off]` Turns PIR on/off
|
||||
/// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
|
||||
/// - `/control/reboot` Reboot the camera
|
||||
/// - `/control/ptz` [up|down|left|right|in|out] (amount) Control the PTZ movements, amount defaults to 32.0
|
||||
@@ -20,10 +21,12 @@ use log::*;
|
||||
/// `/status offline` Sent when the neolink goes offline this is a LastWill message
|
||||
/// `/status disconnected` Sent when the camera goes offline
|
||||
/// `/status/battery` Sent in reply to a `/query/battery`
|
||||
/// `/status/pir` Sent in reply to a `/query/pir`
|
||||
///
|
||||
/// Query Messages:
|
||||
///
|
||||
/// `/query/battery` Request that the camera reports its battery level (Not Yet Implemented)
|
||||
/// `/query/battery` Request that the camera reports its battery level
|
||||
/// `/query/pir` Request that the camera reports its pir status
|
||||
///
|
||||
///
|
||||
/// # Usage
|
||||
@@ -193,7 +196,7 @@ async fn listen_on_camera(
|
||||
message: "on",
|
||||
} => {
|
||||
if event_cam.send_message(Messages::IRLedOn).await.is_err() {
|
||||
error!("Failed to set camera status light off");
|
||||
error!("Failed to set camera status light on");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
@@ -255,6 +258,22 @@ async fn listen_on_camera(
|
||||
error!("No PTZ Direction given. Please add up/down/left/right/in/out");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/pir",
|
||||
message: "on",
|
||||
} => {
|
||||
if event_cam.send_message(Messages::PIROn).await.is_err() {
|
||||
error!("Failed to set pir on");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "control/pir",
|
||||
message: "off",
|
||||
} => {
|
||||
if event_cam.send_message(Messages::PIROff).await.is_err() {
|
||||
error!("Failed to set pir off");
|
||||
}
|
||||
}
|
||||
MqttReplyRef {
|
||||
topic: "query/battery",
|
||||
..
|
||||
@@ -264,7 +283,17 @@ async fn listen_on_camera(
|
||||
error!("Failed to send battery status reply");
|
||||
}
|
||||
}
|
||||
Err(_) => error!("Failed to set camera status light off"),
|
||||
Err(_) => error!("Failed to get battery status"),
|
||||
},
|
||||
MqttReplyRef {
|
||||
topic: "query/pir", ..
|
||||
} => match event_cam.send_message_with_reply(Messages::PIRQuery).await {
|
||||
Ok(reply) => {
|
||||
if mqtt.send_message("status/pir", &reply, false).is_err() {
|
||||
error!("Failed to send pir status reply");
|
||||
}
|
||||
}
|
||||
Err(_) => error!("Failed to get pir status"),
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
|
||||
+2
-1
@@ -8,6 +8,7 @@ use rumqttc::{
|
||||
MqttOptions, Publish, QoS, TlsConfiguration, Transport,
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) struct Mqtt {
|
||||
app: Arc<App>,
|
||||
@@ -80,7 +81,7 @@ impl Mqtt {
|
||||
mqttoptions.set_credentials(username, password);
|
||||
}
|
||||
|
||||
mqttoptions.set_keep_alive(5);
|
||||
mqttoptions.set_keep_alive(Duration::from_secs(5));
|
||||
|
||||
// On unclean disconnect send this
|
||||
mqttoptions.set_last_will(LastWill::new(
|
||||
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use structopt::StructOpt;
|
||||
use clap::Parser;
|
||||
|
||||
fn onoff_parse(src: &str) -> Result<bool> {
|
||||
match src {
|
||||
@@ -13,11 +13,11 @@ fn onoff_parse(src: &str) -> Result<bool> {
|
||||
}
|
||||
|
||||
/// The pir command will control the PIR status of the camera
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// Whether to turn the PIR ON or OFF
|
||||
#[structopt(parse(try_from_str = onoff_parse), name = "on|off")]
|
||||
pub on: bool,
|
||||
#[arg(value_parser = onoff_parse, name = "on|off")]
|
||||
pub on: Option<bool>,
|
||||
}
|
||||
+17
-4
@@ -27,9 +27,22 @@ pub(crate) use cmdline::Opt;
|
||||
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
let camera = find_and_connect(&config, &opt.camera).await?;
|
||||
|
||||
camera
|
||||
.pir_set(opt.on)
|
||||
.await
|
||||
.context("Unable to set camera PIR state")?;
|
||||
if let Some(on) = opt.on {
|
||||
camera
|
||||
.pir_set(on)
|
||||
.await
|
||||
.context("Unable to set camera PIR state")?;
|
||||
} else {
|
||||
let pir_state = camera
|
||||
.get_pirstate()
|
||||
.await
|
||||
.context("Unable to get camera PIR state")?;
|
||||
let pir_ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(&pir_state, vec![], &Default::default())
|
||||
.expect("Should Ser the struct"),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", pir_ser);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use structopt::StructOpt;
|
||||
use clap::Parser;
|
||||
|
||||
/// The reboot command will reboot the camera
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera to change the lights of. Must be a name in the config
|
||||
pub camera: String,
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct AbortHandle {
|
||||
live: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AbortHandle {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
live: Arc::new(AtomicBool::new(true)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn abort(&self) {
|
||||
self.live.store(false, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&self) {
|
||||
self.live.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn is_live(&self) -> bool {
|
||||
self.live.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
use structopt::StructOpt;
|
||||
use clap::Parser;
|
||||
|
||||
/// The rtsp command will serve all cameras in the config over the rtsp protocol
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {}
|
||||
+7
-645
@@ -1,651 +1,13 @@
|
||||
//! This module provides an "RtspServer" abstraction that allows consumers of its API to feed it
|
||||
//! data using an ordinary std::io::Write interface.
|
||||
mod maybe_app_src;
|
||||
mod maybe_inputselect;
|
||||
|
||||
pub(crate) use self::maybe_app_src::MaybeAppSrc;
|
||||
pub(crate) use self::maybe_inputselect::MaybeInputSelect;
|
||||
mod factory;
|
||||
mod sender;
|
||||
mod server;
|
||||
mod shared;
|
||||
|
||||
// use super::adpcm::adpcm_to_pcm;
|
||||
// use super::errors::Error;
|
||||
use gstreamer::prelude::Cast;
|
||||
use gstreamer::{Bin, ElementFactory, Structure};
|
||||
use gstreamer_app::AppSrc;
|
||||
//use gstreamer_rtsp::RTSPLowerTrans;
|
||||
use anyhow::{anyhow, Context};
|
||||
use gstreamer_rtsp::RTSPAuthMethod;
|
||||
pub use gstreamer_rtsp_server::gio::{TlsAuthenticationMode, TlsCertificate};
|
||||
use gstreamer_rtsp_server::glib;
|
||||
use gstreamer_rtsp_server::prelude::*;
|
||||
use gstreamer_rtsp_server::{
|
||||
RTSPAuth, RTSPMediaFactory, RTSPServer as GstRTSPServer, RTSPToken,
|
||||
RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT,
|
||||
RTSP_TOKEN_MEDIA_FACTORY_ROLE,
|
||||
};
|
||||
use log::*;
|
||||
use neolink_core::bcmedia::model::*;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use factory::*;
|
||||
|
||||
pub(crate) use self::server::NeoRtspServer;
|
||||
|
||||
type Result<T> = std::result::Result<T, ()>;
|
||||
type AnyResult<T> = std::result::Result<T, anyhow::Error>;
|
||||
|
||||
pub(crate) struct RtspServer {
|
||||
server: GstRTSPServer,
|
||||
main_loop: Arc<glib::MainLoop>,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
|
||||
pub(crate) enum InputMode {
|
||||
Live,
|
||||
Paused,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
|
||||
pub(crate) enum PausedSources {
|
||||
TestSrc,
|
||||
Still,
|
||||
Black,
|
||||
None,
|
||||
}
|
||||
|
||||
pub(crate) struct GstOutputs {
|
||||
pub(crate) audsrc: MaybeAppSrc,
|
||||
pub(crate) vidsrc: MaybeAppSrc,
|
||||
vid_inputselect: MaybeInputSelect,
|
||||
aud_inputselect: MaybeInputSelect,
|
||||
video_format: Option<StreamFormat>,
|
||||
audio_format: Option<StreamFormat>,
|
||||
factory: RTSPMediaFactory,
|
||||
when_paused: PausedSources,
|
||||
last_iframe: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
// The stream from the camera will be using one of these formats
|
||||
//
|
||||
// This is used as part of `StreamOutput` to give hints about
|
||||
// the format of the stream
|
||||
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
|
||||
enum StreamFormat {
|
||||
// H264 (AVC) video format
|
||||
H264,
|
||||
// H265 (HEVC) video format
|
||||
H265,
|
||||
// AAC audio
|
||||
Aac,
|
||||
// ADPCM in DVI-4 format
|
||||
Adpcm(u16),
|
||||
}
|
||||
|
||||
impl GstOutputs {
|
||||
pub(crate) fn from_appsrcs(
|
||||
vidsrc: MaybeAppSrc,
|
||||
audsrc: MaybeAppSrc,
|
||||
vid_inputselect: MaybeInputSelect,
|
||||
aud_inputselect: MaybeInputSelect,
|
||||
) -> GstOutputs {
|
||||
let result = GstOutputs {
|
||||
vidsrc,
|
||||
audsrc,
|
||||
vid_inputselect,
|
||||
aud_inputselect,
|
||||
video_format: None,
|
||||
audio_format: None,
|
||||
when_paused: PausedSources::None,
|
||||
factory: RTSPMediaFactory::new(),
|
||||
last_iframe: Default::default(),
|
||||
};
|
||||
result.apply_format();
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn stream_recv(&mut self, media: BcMedia) -> AnyResult<()> {
|
||||
// Ensure stream is on cam mode
|
||||
match media {
|
||||
BcMedia::Iframe(payload) => {
|
||||
let video_type = match payload.video_type {
|
||||
VideoType::H264 => StreamFormat::H264,
|
||||
VideoType::H265 => StreamFormat::H265,
|
||||
};
|
||||
self.set_format(Some(video_type));
|
||||
self.vidsrc
|
||||
.write_all(&payload.data)
|
||||
.with_context(|| "Cannot write IFrame to vidsrc")?;
|
||||
self.last_iframe = Some(payload.data);
|
||||
}
|
||||
BcMedia::Pframe(payload) => {
|
||||
let video_type = match payload.video_type {
|
||||
VideoType::H264 => StreamFormat::H264,
|
||||
VideoType::H265 => StreamFormat::H265,
|
||||
};
|
||||
self.set_format(Some(video_type));
|
||||
self.vidsrc
|
||||
.write_all(&payload.data)
|
||||
.with_context(|| "Cannot write PFrame to vidsrc")?;
|
||||
}
|
||||
BcMedia::Aac(payload) => {
|
||||
self.set_format(Some(StreamFormat::Aac));
|
||||
self.audsrc
|
||||
.write_all(&payload.data)
|
||||
.with_context(|| "Cannot write AAC to audsrc")?;
|
||||
}
|
||||
BcMedia::Adpcm(payload) => {
|
||||
self.set_format(Some(StreamFormat::Adpcm(payload.data.len() as u16)));
|
||||
self.audsrc
|
||||
.write_all(&payload.data)
|
||||
.with_context(|| "Cannot write ADPCM to audsrc")?;
|
||||
}
|
||||
_ => {
|
||||
//Ignore other BcMedia like InfoV1 and InfoV2
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_input_source(&mut self, input_source: InputMode) -> AnyResult<()> {
|
||||
// PausedSources::None is exceptional in that it dosen't swap the stream
|
||||
// to an alterntive source. It just repeats the last buffer meaning not re-encoding
|
||||
// at the cost some clients not handeling the repeating buffers well
|
||||
if self.when_paused != PausedSources::None {
|
||||
match &input_source {
|
||||
InputMode::Live => {
|
||||
self.vid_inputselect.set_input(0)?;
|
||||
self.aud_inputselect.set_input(0)?;
|
||||
}
|
||||
InputMode::Paused => {
|
||||
self.vid_inputselect.set_input(1)?;
|
||||
self.aud_inputselect.set_input(1)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// For PausedSources::None we still want to use the silence as we don't want to
|
||||
// repeat the audio buffers
|
||||
match &input_source {
|
||||
InputMode::Live => {
|
||||
self.aud_inputselect.set_input(0)?;
|
||||
}
|
||||
InputMode::Paused => {
|
||||
self.aud_inputselect.set_input(1)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_paused_source(&mut self, paused_source: PausedSources) {
|
||||
self.when_paused = paused_source;
|
||||
self.apply_format();
|
||||
}
|
||||
|
||||
pub(crate) fn has_last_iframe(&self) -> bool {
|
||||
self.last_iframe.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn write_last_iframe(&mut self) -> AnyResult<()> {
|
||||
self.vidsrc.write_all(
|
||||
self.last_iframe
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow!("No iframe data avaliable"))?
|
||||
.as_slice(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_format(&mut self, format: Option<StreamFormat>) {
|
||||
match format {
|
||||
Some(StreamFormat::H264) | Some(StreamFormat::H265) => {
|
||||
if format != self.video_format {
|
||||
self.video_format = format;
|
||||
self.apply_format();
|
||||
}
|
||||
}
|
||||
Some(StreamFormat::Aac) | Some(StreamFormat::Adpcm(_)) => {
|
||||
if format != self.audio_format {
|
||||
self.audio_format = format;
|
||||
self.apply_format();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_format(&self) {
|
||||
// This is the final sink prior to rtsp
|
||||
// - In the case of PausedSources::None we just pass through without encoding
|
||||
// - In the case of all other pause sources we need to recencode in order
|
||||
// to get smooth streams when the stream is paused/resumed
|
||||
// info!("self.video_format: {:?}", self.video_format);
|
||||
// info!("self.audio_format: {:?}", self.audio_format);
|
||||
let launch_vid_select = match self.when_paused {
|
||||
PausedSources::None => match self.video_format {
|
||||
Some(StreamFormat::H264) => "! rtph264pay name=pay0",
|
||||
Some(StreamFormat::H265) => "! rtph265pay name=pay0",
|
||||
_ => "! fakesink",
|
||||
},
|
||||
_ => match self.video_format {
|
||||
Some(StreamFormat::H264) => "! x264enc ! rtph264pay name=pay0",
|
||||
Some(StreamFormat::H265) => "! x265enc ! rtph265pay name=pay0",
|
||||
_ => "! fakesink",
|
||||
},
|
||||
};
|
||||
|
||||
// This is the part that deals with input from camera
|
||||
// - In the case of PausedSources::None it just passes the stream
|
||||
// - In the case of other Paused sources we decode it so that we can manipulate
|
||||
// the stream smoothly and swap the source on demand
|
||||
let launch_app_src = match self.when_paused {
|
||||
PausedSources::None => {
|
||||
match self.video_format {
|
||||
Some(StreamFormat::H264) => {
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! h264parse"
|
||||
}
|
||||
Some(StreamFormat::H265) => {
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! h265parse"
|
||||
}
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
match self.video_format {
|
||||
Some(StreamFormat::H264) => {
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! h264parse ! avdec_h264"
|
||||
}
|
||||
Some(StreamFormat::H265) => {
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! h265parse ! avdec_h265"
|
||||
}
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// This controls the alternaive source used when in paused state
|
||||
// PausedSources::None is the exception in that it is never swapped to this state
|
||||
let launch_alt_source = match self.when_paused {
|
||||
PausedSources::TestSrc => "videotestsrc ! video/x-raw,width=896,height=512,framerate=25/1",
|
||||
PausedSources::Black => "videotestsrc pattern=black ! video/x-raw,width=896,height=512,framerate=25/1",
|
||||
PausedSources::Still => "vid_src_tee. ! imagefreeze allow-replace=true is-live=true ! video/x-raw,framerate=25/1",
|
||||
PausedSources::None => "",
|
||||
};
|
||||
|
||||
// This is the final pipeline for the audio prior to rtsp
|
||||
let launch_aud_select = match self.audio_format {
|
||||
Some(StreamFormat::Adpcm(_)) | Some(StreamFormat::Aac) => {
|
||||
"! audioconvert ! rtpL16pay name=pay1"
|
||||
}
|
||||
_ => "! fakesink",
|
||||
};
|
||||
|
||||
// This is the audio source from the camera. We decode to xraw always as some clients
|
||||
// like blue iris only support raw audio
|
||||
let launch_aud = match self.audio_format {
|
||||
Some(StreamFormat::Adpcm(block_size)) => format!("caps=audio/x-adpcm,layout=dvi,block_align={},channels=1,rate=8000 ! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! adpcmdec", block_size), // DVI4 is converted to pcm in the appsrc
|
||||
Some(StreamFormat::Aac) => "! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! aacparse ! decodebin".to_string(),
|
||||
_ => "".to_string(),
|
||||
};
|
||||
|
||||
// The alternaive audio source is silence
|
||||
let launch_aud_alt = "audiotestsrc wave=silence";
|
||||
|
||||
let launch_str = &vec![
|
||||
"( ",
|
||||
// Video out pipe
|
||||
"(",
|
||||
"input-selector name=vid_inputselect",
|
||||
launch_vid_select,
|
||||
")",
|
||||
// Camera vid source
|
||||
"(",
|
||||
"appsrc name=vidsrc is-live=true block=true emit-signals=false max-bytes=52428800 do-timestamp=true format=GST_FORMAT_TIME", // 50MB max size so that it won't grow to infinite if the queue blocks
|
||||
launch_app_src,
|
||||
// Pipe it though a tee so that the image freeze can grab it
|
||||
"! tee name=vid_src_tee",
|
||||
"(",
|
||||
"vid_src_tee. ! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! vid_inputselect.sink_0",
|
||||
")",
|
||||
|
||||
")",
|
||||
// Alternaive vid source
|
||||
//
|
||||
// Used during paused mode
|
||||
"(",
|
||||
launch_alt_source,
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! vid_inputselect.sink_1",
|
||||
")",
|
||||
// Image freeze
|
||||
// Audio pipe
|
||||
// Audio out pipe
|
||||
"(",
|
||||
"input-selector name=aud_inputselect",
|
||||
launch_aud_select,
|
||||
")",
|
||||
// Camera aud source
|
||||
"(",
|
||||
"appsrc name=audsrc is-live=true block=true emit-signals=false max-bytes=52428800 do-timestamp=true format=GST_FORMAT_TIME",
|
||||
&launch_aud,
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! aud_inputselect.sink_0",
|
||||
")",
|
||||
// Camera aud alt source
|
||||
"(",
|
||||
launch_aud_alt,
|
||||
"! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024 ! aud_inputselect.sink_1",
|
||||
")",
|
||||
")"
|
||||
]
|
||||
.join(" ");
|
||||
debug!("Gstreamer launch str: {:?}", launch_str);
|
||||
self.factory.set_launch(launch_str);
|
||||
}
|
||||
|
||||
pub(crate) fn is_connected(&self) -> bool {
|
||||
self.vidsrc.is_connected() || self.audsrc.is_connected()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RtspServer {
|
||||
fn default() -> RtspServer {
|
||||
Self::new().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl RtspServer {
|
||||
pub(crate) fn new() -> AnyResult<RtspServer> {
|
||||
gstreamer::init().context("Gstreamer failed to initialise")?;
|
||||
let needed_elements = &[
|
||||
(
|
||||
"appsrc",
|
||||
"app (gst-plugins-base)",
|
||||
"Cannot run without an appsrc",
|
||||
),
|
||||
(
|
||||
"audioconvert",
|
||||
"audioconvert (gst-plugins-base)",
|
||||
"Required for audio",
|
||||
),
|
||||
("adpcmdec", "adpcmdec", "Required for audio"),
|
||||
(
|
||||
"h264parse",
|
||||
"videoparsersbad (gst-plugins-bad)",
|
||||
"Required for certain types of camera",
|
||||
),
|
||||
(
|
||||
"h265parse",
|
||||
"videoparsersbad (gst-plugins-bad)",
|
||||
"Required for certain types of camera",
|
||||
),
|
||||
(
|
||||
"rtph264pay",
|
||||
"rtp (gst-plugins-good)",
|
||||
"Required for certain types of camera",
|
||||
),
|
||||
(
|
||||
"rtph265pay",
|
||||
"rtp (gst-plugins-good)",
|
||||
"Required for certain types of camera",
|
||||
),
|
||||
(
|
||||
"aacparse",
|
||||
"audioparsers (gst-plugins-good)",
|
||||
"Required for certain types of camera's audio",
|
||||
),
|
||||
("rtpL16pay", "rtp (gst-plugins-good)", "Required for audio"),
|
||||
];
|
||||
let sometimes_needed_elements = &[
|
||||
(
|
||||
"x264enc",
|
||||
"x264 (gst-plugins-ugly)",
|
||||
"Required to paused certain cameras",
|
||||
),
|
||||
(
|
||||
"x265enc",
|
||||
"x265 (gst-plugins-bad)",
|
||||
"Required to paused certain cameras",
|
||||
),
|
||||
(
|
||||
"avdec_h264",
|
||||
"libav (gst-libav)",
|
||||
"Required to paused certain cameras",
|
||||
),
|
||||
(
|
||||
"avdec_h265",
|
||||
"libav (gst-libav)",
|
||||
"Required to paused certain cameras",
|
||||
),
|
||||
(
|
||||
"videotestsrc",
|
||||
"videotestsrc (gst-plugins-base)",
|
||||
"Required to paused certain cameras",
|
||||
),
|
||||
(
|
||||
"imagefreeze",
|
||||
"imagefreeze (gst-plugins-good)",
|
||||
"Required to paused certain cameras",
|
||||
),
|
||||
(
|
||||
"audiotestsrc",
|
||||
"audiotestsrc (gst-plugins-base)",
|
||||
"Required for pausing",
|
||||
),
|
||||
(
|
||||
"decodebin",
|
||||
"playback (gst-plugins-good)",
|
||||
"Required for pausing",
|
||||
),
|
||||
];
|
||||
let mut fatal = false;
|
||||
for (element, plugin, msg) in needed_elements.iter() {
|
||||
if ElementFactory::find(element).is_none() {
|
||||
error!(
|
||||
"Missing required gstreamer plugin `{}` for `{}` element. {}",
|
||||
plugin, element, msg
|
||||
);
|
||||
fatal = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (element, plugin, msg) in sometimes_needed_elements.iter() {
|
||||
if ElementFactory::find(element).is_none() {
|
||||
warn!(
|
||||
"Missing the gstreamer plugin `{}` for `{}` element. {}",
|
||||
plugin, element, msg
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if fatal {
|
||||
return Err(anyhow!(
|
||||
"Required Gstreamer Elements are missing. Ensure gstreamer is installed correctly"
|
||||
));
|
||||
}
|
||||
Ok(RtspServer {
|
||||
server: GstRTSPServer::new(),
|
||||
main_loop: Arc::new(glib::MainLoop::new(None, false)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn add_stream<T: AsRef<str>>(
|
||||
&self,
|
||||
paths: &[&str],
|
||||
permitted_users: &HashSet<T>,
|
||||
) -> Result<GstOutputs> {
|
||||
let mounts = self
|
||||
.server
|
||||
.mount_points()
|
||||
.expect("The server should have mountpoints");
|
||||
|
||||
// Create a MaybeAppSrc: Write which we will give the caller. When the backing AppSrc is
|
||||
// created by the factory, fish it out and give it to the waiting MaybeAppSrc via the
|
||||
// channel it provided. This callback may be called more than once by Gstreamer if it is
|
||||
// unhappy with the pipeline, so keep updating the MaybeAppSrc.
|
||||
let (maybe_app_src, tx) = MaybeAppSrc::new_with_tx();
|
||||
let (maybe_app_src_aud, tx_aud) = MaybeAppSrc::new_with_tx();
|
||||
|
||||
let (maybe_vid_inputselect, tx_vid_inputselect) = MaybeInputSelect::new_with_tx();
|
||||
let (maybe_aud_inputselect, tx_aud_inputselect) = MaybeInputSelect::new_with_tx();
|
||||
|
||||
let outputs = GstOutputs::from_appsrcs(
|
||||
maybe_app_src,
|
||||
maybe_app_src_aud,
|
||||
maybe_vid_inputselect,
|
||||
maybe_aud_inputselect,
|
||||
);
|
||||
|
||||
let factory = &outputs.factory;
|
||||
|
||||
debug!(
|
||||
"Permitting {} to access {}",
|
||||
// This is hashmap or (iter) equivalent of join, it requres itertools
|
||||
itertools::Itertools::intersperse(permitted_users.iter().map(|i| i.as_ref()), ", ")
|
||||
.collect::<String>(),
|
||||
paths.join(", ")
|
||||
);
|
||||
self.add_permitted_roles(factory, permitted_users);
|
||||
|
||||
factory.set_shared(true);
|
||||
|
||||
factory.connect_media_configure(move |_factory, media| {
|
||||
debug!("RTSP: media was configured");
|
||||
let bin = media
|
||||
.element()
|
||||
// .expect("Media should have an element")
|
||||
.dynamic_cast::<Bin>()
|
||||
.expect("Media source's element should be a bin");
|
||||
let app_src = bin
|
||||
.by_name_recurse_up("vidsrc")
|
||||
.expect("vidsrc must be present in created bin")
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.expect("Source element is expected to be an appsrc!");
|
||||
let _ = tx.send(app_src); // Receiver may be dropped, don't panic if so
|
||||
|
||||
let app_src_aud = bin
|
||||
.by_name_recurse_up("audsrc")
|
||||
.expect("audsrc must be present in created bin")
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.expect("Source element is expected to be an appsrc!");
|
||||
let _ = tx_aud.send(app_src_aud); // Receiver may be dropped, don't panic if so
|
||||
|
||||
let maybe_vid_inputselect = bin
|
||||
.by_name_recurse_up("vid_inputselect")
|
||||
.expect("vid_inputselect must be present in created bin");
|
||||
let _ = tx_vid_inputselect.send(maybe_vid_inputselect); // Receiver may be dropped, don't panic if so
|
||||
|
||||
let maybe_aud_inputselect = bin
|
||||
.by_name_recurse_up("aud_inputselect")
|
||||
.expect("aud_inputselect must be present in created bin");
|
||||
let _ = tx_aud_inputselect.send(maybe_aud_inputselect); // Receiver may be dropped, don't panic if so
|
||||
});
|
||||
|
||||
for path in paths {
|
||||
mounts.add_factory(path, factory);
|
||||
}
|
||||
|
||||
Ok(outputs)
|
||||
}
|
||||
|
||||
pub(crate) fn remove_stream(&self, paths: &[&str]) -> Result<()> {
|
||||
let mounts = self
|
||||
.server
|
||||
.mount_points()
|
||||
.expect("The server should have mountpoints");
|
||||
for path in paths {
|
||||
mounts.remove_factory(path);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn add_permitted_roles<T: AsRef<str>>(
|
||||
&self,
|
||||
factory: &RTSPMediaFactory,
|
||||
permitted_roles: &HashSet<T>,
|
||||
) {
|
||||
for permitted_role in permitted_roles {
|
||||
factory.add_role_from_structure(&Structure::new(
|
||||
permitted_role.as_ref(),
|
||||
&[
|
||||
(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true),
|
||||
(*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true),
|
||||
],
|
||||
));
|
||||
}
|
||||
// During auth, first it binds anonymously. At this point it checks
|
||||
// RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect
|
||||
// This is done before the auth token is loaded, possibliy an upstream bug there
|
||||
// After checking RTSP_PERM_MEDIA_FACTORY_ACCESS anonymously
|
||||
// It loads the auth token of the user and checks that users
|
||||
// RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play
|
||||
// As a result of this we must ensure that if anonymous is not granted RTSP_PERM_MEDIA_FACTORY_ACCESS
|
||||
// As a part of permitted users then we must allow it to access
|
||||
// at least RTSP_PERM_MEDIA_FACTORY_ACCESS but not RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// Watching Actually happens during RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// So this should be OK to do.
|
||||
// FYI: If no RTSP_PERM_MEDIA_FACTORY_ACCESS then server returns 404 not found
|
||||
// If yes RTSP_PERM_MEDIA_FACTORY_ACCESS but no RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// server returns 401 not authourised
|
||||
if !permitted_roles
|
||||
.iter()
|
||||
.map(|i| i.as_ref())
|
||||
.collect::<HashSet<&str>>()
|
||||
.contains(&"anonymous")
|
||||
{
|
||||
factory.add_role_from_structure(&Structure::new(
|
||||
"anonymous",
|
||||
&[(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true)],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> Result<()> {
|
||||
let auth = self.server.auth().unwrap_or_else(RTSPAuth::new);
|
||||
auth.set_supported_methods(RTSPAuthMethod::Basic);
|
||||
|
||||
let mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous")]);
|
||||
auth.set_default_token(Some(&mut un_authtoken));
|
||||
|
||||
for credential in credentials {
|
||||
let (user, pass) = credential;
|
||||
trace!("Setting credentials for user {}", user);
|
||||
let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]);
|
||||
let basic = RTSPAuth::make_basic(user, pass);
|
||||
auth.add_basic(basic.as_str(), &token);
|
||||
}
|
||||
|
||||
self.server.set_auth(Some(&auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_tls(
|
||||
&self,
|
||||
cert_file: &str,
|
||||
client_auth: TlsAuthenticationMode,
|
||||
) -> Result<()> {
|
||||
debug!("Setting up TLS using {}", cert_file);
|
||||
let auth = self.server.auth().unwrap_or_else(RTSPAuth::new);
|
||||
|
||||
// We seperate reading the file and changing to a PEM so that we get different error messages.
|
||||
let cert_contents = fs::read_to_string(cert_file).expect("TLS file not found");
|
||||
let cert = TlsCertificate::from_pem(&cert_contents).expect("Not a valid TLS certificate");
|
||||
auth.set_tls_certificate(Some(&cert));
|
||||
auth.set_tls_authentication_mode(client_auth);
|
||||
|
||||
self.server.set_auth(Some(&auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn run(&self, bind_addr: &str, bind_port: u16) {
|
||||
self.server.set_address(bind_addr);
|
||||
self.server.set_service(&format!("{}", bind_port));
|
||||
// Attach server to default Glib context
|
||||
let _ = self.server.attach(None);
|
||||
let main_loop = self.main_loop.clone();
|
||||
// Run the Glib main loop.
|
||||
let _ = tokio::task::spawn_blocking(move || main_loop.run()).await;
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn quit(&self) {
|
||||
self.main_loop.quit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
//! Attempts to subclass GstMediaFactory
|
||||
//!
|
||||
//! We are now messing with gstreamer glib objects
|
||||
//! expect issues
|
||||
|
||||
use super::{sender::*, shared::*, AnyResult};
|
||||
use anyhow::{anyhow, Context};
|
||||
use gstreamer::glib::object_subclass;
|
||||
use gstreamer::glib::subclass::types::ObjectSubclass;
|
||||
use gstreamer::{
|
||||
glib::{self, Object},
|
||||
Structure,
|
||||
};
|
||||
use gstreamer::{Bin, Caps, ClockTime, Element, ElementFactory};
|
||||
use gstreamer_app::{AppSrc, AppSrcCallbacks, AppStreamType};
|
||||
use gstreamer_rtsp::RTSPUrl;
|
||||
use gstreamer_rtsp_server::prelude::*;
|
||||
use gstreamer_rtsp_server::subclass::prelude::*;
|
||||
use gstreamer_rtsp_server::RTSPMediaFactory;
|
||||
use gstreamer_rtsp_server::{RTSPSuspendMode, RTSPTransportMode};
|
||||
use gstreamer_rtsp_server::{RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT};
|
||||
use log::*;
|
||||
use neolink_core::bcmedia::model::*;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
sync::{atomic::Ordering, Arc},
|
||||
};
|
||||
use tokio::{
|
||||
sync::mpsc::{channel, Sender},
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
glib::wrapper! {
|
||||
/// The wrapped RTSPMediaFactory
|
||||
pub(crate) struct NeoMediaFactory(ObjectSubclass<NeoMediaFactoryImpl>) @extends RTSPMediaFactory;
|
||||
}
|
||||
|
||||
impl Default for NeoMediaFactory {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl NeoMediaFactory {
|
||||
pub(crate) fn new() -> Self {
|
||||
let factory = Object::new::<NeoMediaFactory>();
|
||||
factory.set_shared(false);
|
||||
// factory.set_do_retransmission(false); // Can't use as the method is missing on the 32bit docker gst dll
|
||||
factory.set_launch("videotestsrc pattern=\"snow\" ! video/x-raw,width=896,height=512,framerate=25/1 ! textoverlay name=\"inittextoverlay\" text=\"Stream not Ready\" valignment=top halignment=left font-desc=\"Sans, 32\" ! jpegenc ! rtpjpegpay name=pay0");
|
||||
factory.set_suspend_mode(RTSPSuspendMode::None);
|
||||
factory.set_transport_mode(RTSPTransportMode::PLAY);
|
||||
factory
|
||||
}
|
||||
|
||||
pub(crate) fn get_sender(&self) -> Sender<BcMedia> {
|
||||
self.imp().sender.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn add_permitted_roles<T: AsRef<str>>(&self, permitted_roles: &HashSet<T>) {
|
||||
for permitted_role in permitted_roles {
|
||||
self.add_role_from_structure(
|
||||
&Structure::builder(permitted_role.as_ref())
|
||||
.field(RTSP_PERM_MEDIA_FACTORY_ACCESS, true)
|
||||
.field(RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, true)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
// During auth, first it binds anonymously. At this point it checks
|
||||
// RTSP_PERM_MEDIA_FACTORY_ACCESS to see if anyone can connect
|
||||
// This is done before the auth token is loaded, possibliy an upstream bug there
|
||||
// After checking RTSP_PERM_MEDIA_FACTORY_ACCESS anonymously
|
||||
// It loads the auth token of the user and checks that users
|
||||
// RTSP_PERM_MEDIA_FACTORY_CONSTRUCT allowing them to play
|
||||
// As a result of this we must ensure that if anonymous is not granted RTSP_PERM_MEDIA_FACTORY_ACCESS
|
||||
// As a part of permitted users then we must allow it to access
|
||||
// at least RTSP_PERM_MEDIA_FACTORY_ACCESS but not RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// Watching Actually happens during RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// So this should be OK to do.
|
||||
// FYI: If no RTSP_PERM_MEDIA_FACTORY_ACCESS then server returns 404 not found
|
||||
// If yes RTSP_PERM_MEDIA_FACTORY_ACCESS but no RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
|
||||
// server returns 401 not authourised
|
||||
if !permitted_roles
|
||||
.iter()
|
||||
.map(|i| i.as_ref())
|
||||
.collect::<HashSet<&str>>()
|
||||
.contains(&"anonymous")
|
||||
{
|
||||
self.add_role_from_structure(
|
||||
&Structure::builder("anonymous")
|
||||
.field(RTSP_PERM_MEDIA_FACTORY_ACCESS, true)
|
||||
.build(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// This works by counting the number of acive client datas
|
||||
pub(crate) fn number_of_clients(&self) -> usize {
|
||||
self.imp().number_of_clients()
|
||||
}
|
||||
|
||||
/// This returns true once an iframe + pframe set has been found
|
||||
pub(crate) fn buffer_ready(&self) -> bool {
|
||||
self.imp().buffer_ready()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for NeoMediaFactory {}
|
||||
unsafe impl Sync for NeoMediaFactory {}
|
||||
|
||||
pub(crate) struct NeoMediaFactoryImpl {
|
||||
sender: Sender<BcMedia>,
|
||||
clientsender: Sender<ClientPipelineData>,
|
||||
shared: Arc<NeoMediaShared>,
|
||||
#[allow(dead_code)] // Not dead just need a handle to keep it alive and drop with this obj
|
||||
threads: JoinSet<AnyResult<()>>,
|
||||
}
|
||||
|
||||
impl Drop for NeoMediaFactoryImpl {
|
||||
fn drop(&mut self) {
|
||||
log::info!("Dopping NeoMediaFactoryImpl");
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NeoMediaFactoryImpl {
|
||||
fn default() -> Self {
|
||||
debug!("Constructing Factor Impl");
|
||||
let (datasender, datarx) = channel(3);
|
||||
let (clientsender, rx_clientsender) = channel(3);
|
||||
let shared: Arc<NeoMediaShared> = Default::default();
|
||||
|
||||
// Prepare thread that sends data into the appsrcs
|
||||
let mut threads: JoinSet<AnyResult<()>> = Default::default();
|
||||
let mut sender = NeoMediaSender {
|
||||
data_source: ReceiverStream::new(datarx),
|
||||
clientsource: ReceiverStream::new(rx_clientsender),
|
||||
shared: shared.clone(),
|
||||
uid: Default::default(),
|
||||
clientdata: Default::default(),
|
||||
waiting_for_iframe: true,
|
||||
};
|
||||
threads.spawn(async move {
|
||||
loop {
|
||||
match sender.run().await {
|
||||
Err(e) => {
|
||||
warn!("Media send thead failed... restarting. Cause: {:?}", e);
|
||||
}
|
||||
Ok(()) => {
|
||||
break;
|
||||
}
|
||||
}
|
||||
sender.waiting_for_iframe = true;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Self {
|
||||
sender: datasender,
|
||||
clientsender,
|
||||
shared,
|
||||
threads,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObjectImpl for NeoMediaFactoryImpl {}
|
||||
impl RTSPMediaFactoryImpl for NeoMediaFactoryImpl {
|
||||
fn create_element(&self, url: &RTSPUrl) -> Option<Element> {
|
||||
self.parent_create_element(url)
|
||||
.map(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
}
|
||||
}
|
||||
|
||||
#[object_subclass]
|
||||
impl ObjectSubclass for NeoMediaFactoryImpl {
|
||||
const NAME: &'static str = "NeoMediaFactory";
|
||||
type Type = super::NeoMediaFactory;
|
||||
type ParentType = RTSPMediaFactory;
|
||||
}
|
||||
|
||||
// Convenice funcion to make an element or provide a message
|
||||
// about what plugin is missing
|
||||
fn make_element(kind: &str, name: &str) -> AnyResult<Element> {
|
||||
ElementFactory::make_with_name(kind, Some(name)).with_context(|| {
|
||||
let plugin = match kind {
|
||||
"appsrc" => "app (gst-plugins-base)",
|
||||
"audioconvert" => "audioconvert (gst-plugins-base)",
|
||||
"adpcmdec" => "Required for audio",
|
||||
"h264parse" => "videoparsersbad (gst-plugins-bad)",
|
||||
"h265parse" => "videoparsersbad (gst-plugins-bad)",
|
||||
"rtph264pay" => "rtp (gst-plugins-good)",
|
||||
"rtph265pay" => "rtp (gst-plugins-good)",
|
||||
"aacparse" => "audioparsers (gst-plugins-good)",
|
||||
"rtpL16pay" => "rtp (gst-plugins-good)",
|
||||
"x264enc" => "x264 (gst-plugins-ugly)",
|
||||
"x265enc" => "x265 (gst-plugins-bad)",
|
||||
"avdec_h264" => "libav (gst-libav)",
|
||||
"avdec_h265" => "libav (gst-libav)",
|
||||
"videotestsrc" => "videotestsrc (gst-plugins-base)",
|
||||
"imagefreeze" => "imagefreeze (gst-plugins-good)",
|
||||
"audiotestsrc" => "audiotestsrc (gst-plugins-base)",
|
||||
"decodebin" => "playback (gst-plugins-good)",
|
||||
_ => "Unknown",
|
||||
};
|
||||
format!(
|
||||
"Missing required gstreamer plugin `{}` for `{}` element",
|
||||
plugin, kind
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
impl NeoMediaFactoryImpl {
|
||||
pub(crate) fn buffer_ready(&self) -> bool {
|
||||
self.shared.buffer_ready.load(Ordering::Relaxed)
|
||||
}
|
||||
pub(crate) fn number_of_clients(&self) -> usize {
|
||||
self.shared.number_of_clients.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Element> {
|
||||
// debug!("Building PIPELINE");
|
||||
let bin = media
|
||||
.dynamic_cast::<Bin>()
|
||||
.map_err(|_| anyhow!("Media source's element should be a bin"))?;
|
||||
let clock = bin.clock();
|
||||
// Clear the autogenerated ones
|
||||
for element in bin.iterate_elements().into_iter().flatten() {
|
||||
bin.remove(&element)?;
|
||||
}
|
||||
|
||||
let mut client_data = ClientPipelineData {
|
||||
start_time: self.shared.microseconds.load(Ordering::Relaxed),
|
||||
clock,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Now contruct the actual ones
|
||||
match *self.shared.vid_format.blocking_read() {
|
||||
VidFormats::H265 => {
|
||||
debug!("Building H265 Pipeline");
|
||||
let source = make_element("appsrc", "vidsrc")?
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot cast to appsrc."))?;
|
||||
source.set_base_time(ClockTime::from_mseconds(
|
||||
self.shared.microseconds.load(Ordering::Relaxed),
|
||||
));
|
||||
source.set_is_live(true);
|
||||
source.set_block(false);
|
||||
source.set_property("emit-signals", false);
|
||||
source.set_max_bytes(52428800);
|
||||
source.set_do_timestamp(false);
|
||||
source.set_stream_type(AppStreamType::Stream);
|
||||
|
||||
let enough_data_start = client_data.enough_data.clone();
|
||||
let enough_data_stop = client_data.enough_data.clone();
|
||||
source.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.need_data(move |_appsrc, _amt| {
|
||||
if enough_data_stop.load(Ordering::Relaxed) {
|
||||
log::debug!("Client is in need of data");
|
||||
}
|
||||
enough_data_stop.store(false, Ordering::Relaxed);
|
||||
})
|
||||
.enough_data(move |_appsrc| {
|
||||
if !enough_data_start.load(Ordering::Relaxed) {
|
||||
log::debug!("Client is full of of data");
|
||||
}
|
||||
enough_data_start.store(true, Ordering::Relaxed);
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
// source.set_caps(Some(
|
||||
// &Caps::builder("video/x-h265").field("parsed", false).build(),
|
||||
// ));
|
||||
let source = source
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_element("queue", "source_queue")?;
|
||||
queue.set_property_from_str("leaky", "downstream");
|
||||
queue.set_property("max-size-bytes", 104857600u32);
|
||||
let parser = make_element("h265parse", "parser")?;
|
||||
let payload = make_element("rtph265pay", "pay0")?;
|
||||
bin.add_many(&[&source, &queue, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &payload])?;
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot convert appsrc"))?;
|
||||
client_data.vidsrc.replace(source);
|
||||
}
|
||||
VidFormats::H264 => {
|
||||
debug!("Building H264 Pipeline");
|
||||
let source = make_element("appsrc", "vidsrc")?
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot cast to appsrc."))?;
|
||||
source.set_base_time(ClockTime::from_mseconds(
|
||||
self.shared.microseconds.load(Ordering::Relaxed),
|
||||
));
|
||||
source.set_is_live(true);
|
||||
source.set_block(false);
|
||||
source.set_property("emit-signals", false);
|
||||
source.set_max_bytes(52428800);
|
||||
source.set_do_timestamp(false);
|
||||
source.set_stream_type(AppStreamType::Stream);
|
||||
|
||||
let enough_data_start = client_data.enough_data.clone();
|
||||
let enough_data_stop = client_data.enough_data.clone();
|
||||
source.set_callbacks(
|
||||
AppSrcCallbacks::builder()
|
||||
.need_data(move |_appsrc, _amt| {
|
||||
if enough_data_stop.load(Ordering::Relaxed) {
|
||||
log::debug!("Client is in need of data");
|
||||
}
|
||||
enough_data_stop.store(false, Ordering::Relaxed);
|
||||
})
|
||||
.enough_data(move |_appsrc| {
|
||||
if !enough_data_start.load(Ordering::Relaxed) {
|
||||
log::debug!("Client is full of of data");
|
||||
}
|
||||
enough_data_start.store(true, Ordering::Relaxed);
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
// source.set_caps(Some(
|
||||
// &Caps::builder("video/x-h264").field("parsed", false).build(),
|
||||
// ));
|
||||
let source = source
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_element("queue", "source_queue")?;
|
||||
queue.set_property_from_str("leaky", "downstream");
|
||||
|
||||
let parser = make_element("h264parse", "parser")?;
|
||||
let payload = make_element("rtph264pay", "pay0")?;
|
||||
bin.add_many(&[&source, &queue, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &payload])?;
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot convert appsrc"))?;
|
||||
client_data.vidsrc.replace(source);
|
||||
}
|
||||
VidFormats::Unknown => {
|
||||
debug!("Building Unknown Pipeline");
|
||||
let source = make_element("videotestsrc", "vidsrc")?;
|
||||
source.set_property_from_str("pattern", "snow");
|
||||
let queue = make_element("queue", "queue0")?;
|
||||
queue.set_property_from_str("leaky", "downstream");
|
||||
queue.set_property("max-size-bytes", 104857600u32);
|
||||
let overlay = make_element("textoverlay", "overlay")?;
|
||||
overlay.set_property("text", "Stream not Ready");
|
||||
overlay.set_property_from_str("valignment", "top");
|
||||
overlay.set_property_from_str("halignment", "left");
|
||||
overlay.set_property("font-desc", "Sans, 16");
|
||||
let encoder = make_element("jpegenc", "encoder")?;
|
||||
let payload = make_element("rtpjpegpay", "pay0")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &overlay, &encoder, &payload])?;
|
||||
source.link_filtered(
|
||||
&queue,
|
||||
&Caps::builder("video/x-raw")
|
||||
.field("format", "YUY2")
|
||||
.field("width", 896i32)
|
||||
.field("height", 512i32)
|
||||
.field("framerate", gstreamer::Fraction::new(25, 1))
|
||||
.build(),
|
||||
)?;
|
||||
// source.link(&queue)?;
|
||||
queue.link(&overlay)?;
|
||||
overlay.link(&encoder)?;
|
||||
encoder.link(&payload)?;
|
||||
}
|
||||
}
|
||||
|
||||
match *self.shared.aud_format.blocking_read() {
|
||||
AudFormats::Unknown => {}
|
||||
AudFormats::Aac => {
|
||||
debug!("Building Aac pipeline");
|
||||
let source = make_element("appsrc", "audsrc")?
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot cast to appsrc."))?;
|
||||
source.set_base_time(ClockTime::from_mseconds(
|
||||
self.shared.microseconds.load(Ordering::Relaxed),
|
||||
));
|
||||
source.set_is_live(true);
|
||||
source.set_block(false);
|
||||
source.set_property("emit-signals", false);
|
||||
source.set_max_bytes(52428800);
|
||||
source.set_do_timestamp(false);
|
||||
source.set_stream_type(AppStreamType::Stream);
|
||||
let source = source
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_element("queue", "audqueue")?;
|
||||
queue.set_property_from_str("leaky", "downstream");
|
||||
queue.set_property("max-size-bytes", 104857600u32);
|
||||
let parser = make_element("aacparse", "audparser")?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
let sink_pad = encoder
|
||||
.static_pad("sink")
|
||||
.expect("Encoder is missing its pad");
|
||||
pad.link(&sink_pad)
|
||||
.expect("Failed to link AAC decoder to encoder");
|
||||
});
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot convert appsrc"))?;
|
||||
client_data.audsrc.replace(source);
|
||||
}
|
||||
AudFormats::Adpcm(block_size) => {
|
||||
debug!("Building Adpcm pipeline");
|
||||
// Original command line
|
||||
// caps=audio/x-adpcm,layout=dvi,block_align={},channels=1,rate=8000
|
||||
// ! queue silent=true max-size-bytes=10485760 min-threshold-bytes=1024
|
||||
// ! adpcmdec
|
||||
// ! audioconvert
|
||||
// ! rtpL16pay name=pay1
|
||||
|
||||
let source = make_element("appsrc", "audsrc")?
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot cast to appsrc."))?;
|
||||
source.set_base_time(ClockTime::from_mseconds(
|
||||
self.shared.microseconds.load(Ordering::Relaxed),
|
||||
));
|
||||
source.set_is_live(true);
|
||||
source.set_block(false);
|
||||
source.set_property("emit-signals", false);
|
||||
source.set_max_bytes(52428800);
|
||||
source.set_do_timestamp(false);
|
||||
source.set_stream_type(AppStreamType::Stream);
|
||||
source.set_caps(Some(
|
||||
&Caps::builder("audio/x-adpcm")
|
||||
.field("layout", "div")
|
||||
.field("block_align", block_size as i32)
|
||||
.field("channels", 1i32)
|
||||
.field("rate", 8000i32)
|
||||
.build(),
|
||||
));
|
||||
let source = source
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_element("queue", "audqueue")?;
|
||||
queue.set_property_from_str("leaky", "downstream");
|
||||
queue.set_property("max-size-bytes", 104857600u32);
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &decoder])?;
|
||||
Element::link_many(&[&encoder, &payload])?;
|
||||
decoder.connect_pad_added(move |_element, pad| {
|
||||
debug!("Linking encoder to decoder: {:?}", pad.caps());
|
||||
let sink_pad = encoder
|
||||
.static_pad("sink")
|
||||
.expect("Encoder is missing its pad");
|
||||
pad.link(&sink_pad)
|
||||
.expect("Failed to link ADPCM decoder to encoder");
|
||||
});
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
.map_err(|_| anyhow!("Cannot convert appsrc"))?;
|
||||
client_data.audsrc.replace(source);
|
||||
}
|
||||
}
|
||||
|
||||
self.clientsender.blocking_send(client_data)?;
|
||||
// debug!("Pipeline built");
|
||||
bin.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
use super::*;
|
||||
use crossbeam_channel::{bounded, Receiver, Sender};
|
||||
|
||||
/// A Write implementation around AppSrc that also allows delaying the creation of the AppSrc
|
||||
/// until later, discarding written data until the AppSrc is provided.
|
||||
pub(crate) struct MaybeAppSrc {
|
||||
rx: Receiver<AppSrc>,
|
||||
app_src: Option<AppSrc>,
|
||||
}
|
||||
|
||||
impl MaybeAppSrc {
|
||||
/// Creates a MaybeAppSrc. Also returns a Sender that you must use to provide an AppSrc as
|
||||
/// soon as one is available. When it is received, the MaybeAppSrc will start pushing data
|
||||
/// into the AppSrc when write() is called.
|
||||
pub(crate) fn new_with_tx() -> (Self, Sender<AppSrc>) {
|
||||
let (tx, rx) = bounded(3); // The sender should not send very often
|
||||
(MaybeAppSrc { rx, app_src: None }, tx)
|
||||
}
|
||||
|
||||
/// Calls end of stream to Gstreamer, using during drop
|
||||
pub(crate) fn end_of_stream(&mut self) {
|
||||
if let Some(src) = self.try_get_src() {
|
||||
// Ignore "errors" from Gstreamer such as FLUSHING, which are not really errors.
|
||||
let _ = src.end_of_stream();
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to retrieve the AppSrc that should be passed in by the caller of new_with_tx
|
||||
/// at some point after this struct has been created. At that point, we swap over to
|
||||
/// owning the AppSrc directly. This function handles either case and returns the AppSrc,
|
||||
/// or None if the caller has not yet sent one.
|
||||
fn try_get_src(&mut self) -> Option<&AppSrc> {
|
||||
while let Ok(src) = self.rx.try_recv() {
|
||||
self.app_src = Some(src);
|
||||
}
|
||||
self.app_src.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn is_connected(&self) -> bool {
|
||||
self.app_src.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for MaybeAppSrc {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
// If we have no AppSrc yet, throw away the data and claim that it was written
|
||||
let app_src = match self.try_get_src() {
|
||||
Some(src) => src,
|
||||
None => return Ok(buf.len()),
|
||||
};
|
||||
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf);
|
||||
}
|
||||
|
||||
let res = app_src.push_buffer(gst_buf); //.map_err(|e| io::Error::new(io::ErrorKind::Other, Box::new(e)))?;
|
||||
if res.is_err() {
|
||||
self.app_src = None;
|
||||
}
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MaybeAppSrc {
|
||||
fn drop(&mut self) {
|
||||
self.end_of_stream();
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
use anyhow::{anyhow, Error as Anyhow};
|
||||
use crossbeam_channel::{bounded, Receiver, Sender};
|
||||
use gstreamer::prelude::ElementExt;
|
||||
use gstreamer::prelude::ObjectExt;
|
||||
use gstreamer::{Element, Pad};
|
||||
use log::*;
|
||||
|
||||
pub(crate) struct MaybeInputSelect {
|
||||
rx: Receiver<Element>,
|
||||
typefind: Option<Element>,
|
||||
}
|
||||
|
||||
impl MaybeInputSelect {
|
||||
pub(crate) fn new_with_tx() -> (Self, Sender<Element>) {
|
||||
let (tx, rx) = bounded(3); // The sender should not send very often
|
||||
(MaybeInputSelect { rx, typefind: None }, tx)
|
||||
}
|
||||
|
||||
pub(crate) fn try_get_src(&mut self) -> Option<&Element> {
|
||||
while let Ok(src) = self.rx.try_recv() {
|
||||
self.typefind = Some(src);
|
||||
}
|
||||
self.typefind.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn set_input(&mut self, path_num: u32) -> Result<(), Anyhow> {
|
||||
if let Some(element) = self.try_get_src() {
|
||||
let new_pad = element
|
||||
.static_pad(&format!("sink_{}", path_num))
|
||||
.ok_or_else(|| anyhow!("Unable to set input pad"))?;
|
||||
|
||||
match element.property_value("active-pad").get::<'_, Pad>() {
|
||||
Ok(active_pad) => {
|
||||
if active_pad != new_pad {
|
||||
debug!("Pad need changing");
|
||||
element.set_property("active-pad", new_pad);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
debug!("Pad need changing: Active pad invalid: {:?}", e);
|
||||
element.set_property("active-pad", new_pad);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.typefind = None;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
use gstreamer::Element;
|
||||
use crossbeam_channel::{sync_channel, Receiver, SyncSender};
|
||||
|
||||
pub(crate) struct MaybeOutputSelect {
|
||||
rx: Receiver<Element>,
|
||||
typefind: Option<Element>,
|
||||
}
|
||||
|
||||
impl MaybeOutputSelect {
|
||||
pub(crate) fn new_with_tx() -> (Self, SyncSender<Element>) {
|
||||
let (tx, rx) = sync_channel(3); // The sender should not send very often
|
||||
(MaybeOutputSelect { rx, typefind: None }, tx)
|
||||
}
|
||||
|
||||
pub(crate) fn try_get_src(&mut self) -> Option<&Element> {
|
||||
while let Some(src) = self.rx.try_recv().ok() {
|
||||
self.typefind = Some(src);
|
||||
}
|
||||
self.typefind.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.typefind = None;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
use gstreamer::Element;
|
||||
use crossbeam_channel::{sync_channel, Receiver, SyncSender};
|
||||
|
||||
pub(crate) struct MaybeTypeFind {
|
||||
rx: Receiver<Element>,
|
||||
typefind: Option<Element>,
|
||||
}
|
||||
|
||||
impl MaybeTypeFind {
|
||||
pub(crate) fn new_with_tx() -> (Self, SyncSender<Element>) {
|
||||
let (tx, rx) = sync_channel(3); // The sender should not send very often
|
||||
(MaybeTypeFind { rx, typefind: None }, tx)
|
||||
}
|
||||
|
||||
pub(crate) fn try_get_src(&mut self) -> Option<&Element> {
|
||||
while let Some(src) = self.rx.try_recv().ok() {
|
||||
self.typefind = Some(src);
|
||||
}
|
||||
self.typefind.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.typefind = None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
//! The component that handles passing BcMedia into
|
||||
//! gstreamer media stream
|
||||
use anyhow::anyhow;
|
||||
use futures::stream::StreamExt;
|
||||
use gstreamer::{prelude::*, ClockTime};
|
||||
use gstreamer_app::AppSrc;
|
||||
pub use gstreamer_rtsp_server::gio::{TlsAuthenticationMode, TlsCertificate};
|
||||
use log::*;
|
||||
use neolink_core::bcmedia::model::*;
|
||||
use std::collections::{hash_map::Entry, HashMap};
|
||||
use std::sync::{
|
||||
atomic::{AtomicU64, Ordering},
|
||||
Arc,
|
||||
};
|
||||
// use tokio::time::{interval, Duration, MissedTickBehavior};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use super::{shared::*, AnyResult};
|
||||
|
||||
pub(super) struct NeoMediaSender {
|
||||
pub(super) data_source: ReceiverStream<BcMedia>,
|
||||
pub(super) clientsource: ReceiverStream<ClientPipelineData>,
|
||||
pub(super) shared: Arc<NeoMediaShared>,
|
||||
// Used to generate the key for the hashmaps
|
||||
pub(super) uid: AtomicU64,
|
||||
// Hashmap so we can alter the data in ClientData while also allowing for remove at any point
|
||||
// If you know a better collections pm me
|
||||
pub(super) clientdata: HashMap<u64, ClientPipelineData>,
|
||||
pub(super) waiting_for_iframe: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct StampedData {
|
||||
ms: u64,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl NeoMediaSender {
|
||||
pub(super) async fn run(&mut self) -> AnyResult<()> {
|
||||
// let mut resend_pause = interval(Duration::from_secs_f32(1.0f32 / 5.0f32));
|
||||
// resend_pause.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut buffer_a: Vec<StampedData> = Default::default();
|
||||
let mut buffer_b: Vec<StampedData> = Default::default();
|
||||
let buffer_read = &mut buffer_a;
|
||||
let buffer_write = &mut buffer_b;
|
||||
|
||||
let mut audbuffer_a: Vec<StampedData> = Default::default();
|
||||
let mut audbuffer_b: Vec<StampedData> = Default::default();
|
||||
let audbuffer_read = &mut audbuffer_a;
|
||||
let audbuffer_write = &mut audbuffer_b;
|
||||
loop {
|
||||
self.shared
|
||||
.number_of_clients
|
||||
.store(self.clientdata.len(), Ordering::Relaxed);
|
||||
self.shared
|
||||
.buffer_ready
|
||||
.store(!buffer_read.is_empty(), Ordering::Relaxed);
|
||||
// debug!("Sender: Get");
|
||||
tokio::select! {
|
||||
v = self.data_source.next() => {
|
||||
// debug!("Sender: Got Data");
|
||||
// debug!("data_source recieved");
|
||||
if let Some(bc_media) = v {
|
||||
if ! self.skip_bcmedia(&bc_media) {
|
||||
// debug!("Not skipped");
|
||||
// resend_pause.reset();
|
||||
self.inspect_bcmedia(&bc_media).await;
|
||||
match bc_media {
|
||||
BcMedia::Iframe(frame) => {
|
||||
if buffer_write.len() > 100 {
|
||||
std::mem::swap(buffer_read, buffer_write);
|
||||
buffer_write.clear();
|
||||
std::mem::swap(audbuffer_read, audbuffer_write);
|
||||
audbuffer_write.clear();
|
||||
}
|
||||
let new_data = StampedData {
|
||||
ms: frame.microseconds as u64,
|
||||
data: frame.data,
|
||||
};
|
||||
self.process_vidbuffer(&new_data).await;
|
||||
buffer_write.push(new_data);
|
||||
}
|
||||
BcMedia::Pframe(frame) => {
|
||||
let new_data = StampedData {
|
||||
ms: frame.microseconds as u64,
|
||||
data: frame.data,
|
||||
};
|
||||
self.process_vidbuffer(&new_data).await;
|
||||
buffer_write.push(new_data);
|
||||
}
|
||||
BcMedia::Aac(aac) => {
|
||||
if let Some(last) = buffer_write.last().as_ref() {
|
||||
let new_data = StampedData {
|
||||
ms: last.ms,
|
||||
data: aac.data,
|
||||
};
|
||||
self.process_audbuffer(&new_data).await;
|
||||
audbuffer_write.push(new_data);
|
||||
}
|
||||
|
||||
}
|
||||
BcMedia::Adpcm(adpcm) => {
|
||||
if let Some(last) = buffer_write.last().as_ref() {
|
||||
let new_data = StampedData {
|
||||
ms: last.ms,
|
||||
data: adpcm.data,
|
||||
};
|
||||
self.process_audbuffer(&new_data).await;
|
||||
audbuffer_write.push(new_data);
|
||||
}
|
||||
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
v = self.clientsource.next() => {
|
||||
// debug!("Sender: Got Client");
|
||||
if let Some(mut clientdata) = v {
|
||||
// Resend the video and audio buffers
|
||||
if !clientdata.inited {
|
||||
clientdata.inited = true;
|
||||
let mut vid_resend = buffer_read.iter().chain(buffer_write.iter()).enumerate();
|
||||
let mut aud_resend = audbuffer_read.iter().chain(audbuffer_write.iter()).enumerate();
|
||||
loop {
|
||||
let next_vid = vid_resend.next();
|
||||
if let Some((idx, next_vid)) = next_vid.as_ref() {
|
||||
if let Some(src) = clientdata.vidsrc.as_ref() {
|
||||
if Self::send_buffer(
|
||||
src,
|
||||
next_vid.data.as_slice(),
|
||||
*idx as u64,
|
||||
0,
|
||||
).await.is_err() {
|
||||
break;
|
||||
};
|
||||
}
|
||||
}
|
||||
let next_aud = aud_resend.next();
|
||||
if let Some((idx, next_aud)) = next_aud.as_ref() {
|
||||
if let Some(src) = clientdata.audsrc.as_ref() {
|
||||
if Self::send_buffer(
|
||||
src,
|
||||
next_aud.data.as_slice(),
|
||||
*idx as u64,
|
||||
0,
|
||||
).await.is_err() {
|
||||
break;
|
||||
};
|
||||
}
|
||||
}
|
||||
if next_vid.is_none() && next_aud.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Save the client for future sends
|
||||
self.clientdata.insert(self.uid.fetch_add(1, Ordering::Relaxed) , clientdata);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
},
|
||||
// _ = resend_pause.tick() => {
|
||||
// if let Some(live) = buffer.last().cloned() {
|
||||
// self.process_vidbuffer(&ProcessData {
|
||||
// live,
|
||||
// resend: buffer.as_slice()
|
||||
// })?;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn process_vidbuffer(&mut self, stamped_data: &StampedData) {
|
||||
for key in self
|
||||
.clientdata
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.drain(..)
|
||||
{
|
||||
match self.clientdata.entry(key) {
|
||||
Entry::Occupied(data) => {
|
||||
if let Some(vidsrc) = data.get().vidsrc.as_ref() {
|
||||
if !data.get().enough_data.load(Ordering::Relaxed) {
|
||||
let ms = stamped_data.ms;
|
||||
let st = data.get().start_time;
|
||||
let micros = ms - st;
|
||||
if let Some(clock) = data.get().clock.as_ref() {
|
||||
if let Some(time) = clock.time() {
|
||||
let buffer_time = ClockTime::from_useconds(micros);
|
||||
log::debug!(
|
||||
"Buffer time: {:?}. Clock time: {:?}",
|
||||
buffer_time,
|
||||
time
|
||||
);
|
||||
}
|
||||
}
|
||||
debug!(
|
||||
"Pushed Video Buffer: ms: {}, st: {}, delta: {}",
|
||||
ms, st, micros
|
||||
);
|
||||
if Self::send_buffer(
|
||||
vidsrc,
|
||||
stamped_data.data.as_slice(),
|
||||
stamped_data.ms,
|
||||
data.get().start_time,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
data.remove();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
data.remove();
|
||||
}
|
||||
}
|
||||
Entry::Vacant(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn process_audbuffer(&mut self, stamped_data: &StampedData) {
|
||||
for key in self
|
||||
.clientdata
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.drain(..)
|
||||
{
|
||||
match self.clientdata.entry(key) {
|
||||
Entry::Occupied(data) => {
|
||||
if let Some(audsrc) = data.get().audsrc.as_ref() {
|
||||
if !data.get().enough_data.load(Ordering::Relaxed) {
|
||||
debug!("Pushed Audio Buffer");
|
||||
if Self::send_buffer(
|
||||
audsrc,
|
||||
stamped_data.data.as_slice(),
|
||||
stamped_data.ms,
|
||||
data.get().start_time,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
data.remove();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
data.remove();
|
||||
}
|
||||
}
|
||||
Entry::Vacant(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_buffer(
|
||||
appsrc: &AppSrc,
|
||||
buf: &[u8],
|
||||
frame_ms: u64,
|
||||
start_time: u64,
|
||||
) -> AnyResult<()> {
|
||||
let micros = if frame_ms > start_time {
|
||||
frame_ms - start_time
|
||||
} else {
|
||||
start_time
|
||||
};
|
||||
|
||||
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
|
||||
{
|
||||
let gst_buf_mut = gst_buf.get_mut().unwrap();
|
||||
|
||||
let time = ClockTime::from_useconds(micros);
|
||||
gst_buf_mut.set_pts(time);
|
||||
// debug!(
|
||||
// "PTS set to: {:?} ({}-{}={:?})",
|
||||
// time, frame_ms, start_time, micros
|
||||
// );
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf);
|
||||
}
|
||||
// debug!("Buffer pushed");
|
||||
let thread_appsrc = appsrc.clone(); // GObjects are refcounted
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
thread_appsrc
|
||||
.push_buffer(gst_buf.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Failed to send buffer: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res?
|
||||
}
|
||||
|
||||
fn skip_bcmedia(&mut self, bc_media: &BcMedia) -> bool {
|
||||
if self.waiting_for_iframe {
|
||||
if let BcMedia::Iframe(_) = bc_media {
|
||||
self.waiting_for_iframe = false;
|
||||
} else {
|
||||
log::debug!("Skipping bcmedia");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
async fn inspect_bcmedia(&mut self, bc_media: &BcMedia) {
|
||||
let old_vid = *self.shared.vid_format.read().await;
|
||||
let old_aud = *self.shared.aud_format.read().await;
|
||||
match bc_media {
|
||||
BcMedia::Iframe(frame) => {
|
||||
match frame.video_type {
|
||||
VideoType::H264 => {
|
||||
(*self.shared.vid_format.write().await) = VidFormats::H264;
|
||||
}
|
||||
VideoType::H265 => {
|
||||
(*self.shared.vid_format.write().await) = VidFormats::H265;
|
||||
}
|
||||
}
|
||||
self.shared
|
||||
.microseconds
|
||||
.store(frame.microseconds as u64, Ordering::Relaxed);
|
||||
// log::debug!(
|
||||
// "Time set to {}",
|
||||
// self.shared.microseconds.load(Ordering::Relaxed)
|
||||
// );
|
||||
}
|
||||
BcMedia::Pframe(frame) => {
|
||||
match frame.video_type {
|
||||
VideoType::H264 => {
|
||||
(*self.shared.vid_format.write().await) = VidFormats::H264;
|
||||
}
|
||||
VideoType::H265 => {
|
||||
(*self.shared.vid_format.write().await) = VidFormats::H265;
|
||||
}
|
||||
}
|
||||
self.shared
|
||||
.microseconds
|
||||
.store(frame.microseconds as u64, Ordering::Relaxed);
|
||||
// log::debug!(
|
||||
// "Time set to {}",
|
||||
// self.shared.microseconds.load(Ordering::Relaxed)
|
||||
// );
|
||||
}
|
||||
BcMedia::Aac(_aac) => {
|
||||
(*self.shared.aud_format.write().await) = AudFormats::Aac;
|
||||
}
|
||||
BcMedia::Adpcm(adpcm) => {
|
||||
(*self.shared.aud_format.write().await) = AudFormats::Adpcm(adpcm.data.len() as u16)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let new_vid = *self.shared.vid_format.read().await;
|
||||
if new_vid != old_vid {
|
||||
log::debug!("Video format set to: {:?} from {:?}", new_vid, old_vid);
|
||||
}
|
||||
let new_aud = *self.shared.aud_format.read().await;
|
||||
if old_aud != new_aud {
|
||||
log::debug!("Audio format set to: {:?} from {:?}", new_aud, old_aud);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
//! Attempts to subclass RtspServer
|
||||
//!
|
||||
//! We are now messing with gstreamer glib objects
|
||||
//! expect issues
|
||||
|
||||
use super::{factory::*, AnyResult};
|
||||
use crate::config::*;
|
||||
|
||||
use anyhow::{anyhow, Context};
|
||||
use gstreamer::glib::{self, object_subclass, subclass::types::ObjectSubclass, MainLoop, Object};
|
||||
use gstreamer_rtsp::RTSPAuthMethod;
|
||||
use gstreamer_rtsp_server::{
|
||||
gio::{TlsAuthenticationMode, TlsCertificate},
|
||||
prelude::*,
|
||||
subclass::prelude::*,
|
||||
RTSPAuth, RTSPServer, RTSPToken, RTSP_TOKEN_MEDIA_FACTORY_ROLE,
|
||||
};
|
||||
use log::*;
|
||||
use neolink_core::bcmedia::model::*;
|
||||
use std::{
|
||||
collections::{hash_map::Entry, HashMap, HashSet},
|
||||
fs,
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::{
|
||||
sync::{mpsc::Sender, RwLock},
|
||||
task::JoinHandle,
|
||||
};
|
||||
|
||||
glib::wrapper! {
|
||||
/// The wrapped RTSPServer
|
||||
pub(crate) struct NeoRtspServer(ObjectSubclass<NeoRtspServerImpl>) @extends RTSPServer;
|
||||
}
|
||||
|
||||
impl Default for NeoRtspServer {
|
||||
fn default() -> Self {
|
||||
Self::new().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl NeoRtspServer {
|
||||
pub(crate) fn new() -> AnyResult<Self> {
|
||||
gstreamer::init().context("Gstreamer failed to initialise")?;
|
||||
let factory = Object::new::<NeoRtspServer>();
|
||||
Ok(factory)
|
||||
}
|
||||
|
||||
pub(crate) async fn get_sender<T: Into<String>>(&self, tag: T) -> Option<Sender<BcMedia>> {
|
||||
self.imp().get_sender(tag).await
|
||||
}
|
||||
|
||||
pub(crate) async fn create_stream<U: Into<String>>(&self, tag: U) -> AnyResult<()> {
|
||||
self.imp().create_stream(tag).await
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) async fn remove_stream<T: Into<String>>(&self, tag: T) -> AnyResult<()> {
|
||||
self.imp().remove_stream(tag).await
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) async fn remove_path<T: Into<String>>(
|
||||
&self,
|
||||
tag: T,
|
||||
paths: &[&str],
|
||||
) -> AnyResult<()> {
|
||||
self.imp().remove_path(tag, paths).await
|
||||
}
|
||||
|
||||
pub(crate) async fn add_path<T: Into<String>>(
|
||||
&self,
|
||||
tag: T,
|
||||
paths: &[String],
|
||||
) -> AnyResult<()> {
|
||||
self.imp().add_path(tag, paths).await
|
||||
}
|
||||
|
||||
pub(crate) async fn add_permitted_roles<T: Into<String>, U: AsRef<str>>(
|
||||
&self,
|
||||
tag: T,
|
||||
permitted_users: &HashSet<U>,
|
||||
) -> AnyResult<()> {
|
||||
self.imp().add_permitted_roles(tag, permitted_users).await
|
||||
}
|
||||
|
||||
pub(crate) async fn run(
|
||||
&self,
|
||||
bind_addr: &str,
|
||||
bind_port: u16,
|
||||
) -> AnyResult<(JoinHandle<AnyResult<()>>, Arc<MainLoop>)> {
|
||||
let server = self;
|
||||
server.set_address(bind_addr);
|
||||
server.set_service(&format!("{}", bind_port));
|
||||
// Attach server to default Glib context
|
||||
let _ = server.attach(None);
|
||||
let main_loop = Arc::new(MainLoop::new(None, false));
|
||||
// Run the Glib main loop.
|
||||
let main_loop_thread = main_loop.clone();
|
||||
#[allow(clippy::unit_arg)]
|
||||
let handle = tokio::task::spawn_blocking(move || Ok(main_loop_thread.run()));
|
||||
|
||||
Ok((handle, main_loop))
|
||||
}
|
||||
|
||||
pub(crate) fn set_up_tls(&self, config: &Config) {
|
||||
self.imp().set_up_tls(config)
|
||||
}
|
||||
|
||||
pub(crate) fn set_up_users(&self, users: &[UserConfig]) {
|
||||
self.imp().set_up_users(users)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
/// This will return the total number of active clients
|
||||
pub(crate) fn num_clients(&self) -> usize {
|
||||
self.client_filter(None).len()
|
||||
}
|
||||
|
||||
/// This will get the number of users for any of the given paths
|
||||
///
|
||||
/// This function is not quite what we want as it only count when the media is active
|
||||
/// we want something that returns >0 when we want to build a media
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn num_path_users(&self, paths: &[&str]) -> usize {
|
||||
self.session_pool().map_or(0usize, |pool| {
|
||||
pool.filter(None).iter().fold(0usize, |acc, session| {
|
||||
acc + session
|
||||
.filter(None)
|
||||
.iter()
|
||||
.fold(0usize, |acc_b, media_session| {
|
||||
acc_b
|
||||
+ if paths.iter().any(|path| {
|
||||
media_session.matches(path).unwrap_or(0) == path.len() as i32
|
||||
}) {
|
||||
1usize
|
||||
} else {
|
||||
0usize
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the number of clients wanting data for a tag
|
||||
pub(crate) async fn get_number_of_clients<T: Into<String>>(&self, tag: T) -> Option<usize> {
|
||||
self.imp().get_number_of_clients(tag).await
|
||||
}
|
||||
|
||||
/// Returns true once the pause buffer is ready
|
||||
pub(crate) async fn buffer_ready<T: Into<String>>(&self, tag: T) -> Option<bool> {
|
||||
self.imp().buffer_ready(tag).await
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for NeoRtspServer {}
|
||||
unsafe impl Sync for NeoRtspServer {}
|
||||
|
||||
struct FactoryData {
|
||||
factory: NeoMediaFactory,
|
||||
paths: HashSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct NeoRtspServerImpl {
|
||||
medias: RwLock<HashMap<String, FactoryData>>,
|
||||
}
|
||||
|
||||
impl ObjectImpl for NeoRtspServerImpl {}
|
||||
impl RTSPServerImpl for NeoRtspServerImpl {}
|
||||
|
||||
#[object_subclass]
|
||||
impl ObjectSubclass for NeoRtspServerImpl {
|
||||
const NAME: &'static str = "NeoRtspServer";
|
||||
type Type = NeoRtspServer;
|
||||
type ParentType = RTSPServer;
|
||||
}
|
||||
|
||||
impl NeoRtspServerImpl {
|
||||
pub(crate) async fn create_stream<U: Into<String>>(&self, tag: U) -> AnyResult<()> {
|
||||
let key = tag.into();
|
||||
match self.medias.write().await.entry(key.clone()) {
|
||||
Entry::Occupied(_occ) => {}
|
||||
Entry::Vacant(vac) => {
|
||||
let media = NeoMediaFactory::new();
|
||||
vac.insert(FactoryData {
|
||||
factory: media,
|
||||
paths: Default::default(),
|
||||
});
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn get_sender<T: Into<String>>(&self, tag: T) -> Option<Sender<BcMedia>> {
|
||||
let key = tag.into();
|
||||
self.medias
|
||||
.read()
|
||||
.await
|
||||
.get(&key)
|
||||
.map(|k| k.factory.get_sender())
|
||||
}
|
||||
pub(crate) async fn buffer_ready<T: Into<String>>(&self, tag: T) -> Option<bool> {
|
||||
let key = tag.into();
|
||||
self.medias
|
||||
.read()
|
||||
.await
|
||||
.get(&key)
|
||||
.map(|k| k.factory.buffer_ready())
|
||||
}
|
||||
|
||||
pub(crate) async fn get_number_of_clients<T: Into<String>>(&self, tag: T) -> Option<usize> {
|
||||
let key = tag.into();
|
||||
self.medias
|
||||
.read()
|
||||
.await
|
||||
.get(&key)
|
||||
.map(|k| k.factory.number_of_clients())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) async fn remove_stream<T: Into<String>>(&self, tag: T) -> AnyResult<()> {
|
||||
if let Some(mut media) = self.medias.write().await.remove(&tag.into()) {
|
||||
let mounts = self
|
||||
.obj()
|
||||
.mount_points()
|
||||
.expect("The server should have mountpoints");
|
||||
for path in media.paths.iter() {
|
||||
mounts.remove_factory(path);
|
||||
}
|
||||
media.paths.clear();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn add_permitted_roles<T: Into<String>, U: AsRef<str>>(
|
||||
&self,
|
||||
tag: T,
|
||||
permitted_users: &HashSet<U>,
|
||||
) -> AnyResult<()> {
|
||||
let tag: String = tag.into();
|
||||
if let Some(media) = self.medias.write().await.get_mut(&tag) {
|
||||
media.factory.add_permitted_roles(permitted_users);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("No media with tag {} to add users to", &tag))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn add_path<T: Into<String>>(
|
||||
&self,
|
||||
tag: T,
|
||||
paths: &[String],
|
||||
) -> AnyResult<()> {
|
||||
let tag = tag.into();
|
||||
if let Some(media) = self.medias.write().await.get_mut(&tag) {
|
||||
let mounts = self
|
||||
.obj()
|
||||
.mount_points()
|
||||
.expect("The server should have mountpoints");
|
||||
for path in paths {
|
||||
media.paths.insert(path.clone());
|
||||
// We can clone here because GObjects are referernce counted
|
||||
mounts.add_factory(path, media.factory.clone());
|
||||
// debug!("Adding path: {}", path);
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"No media with tag {} to add the paths {:?} to",
|
||||
&tag,
|
||||
paths
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn remove_path<T: Into<String>>(
|
||||
&self,
|
||||
tag: T,
|
||||
paths: &[&str],
|
||||
) -> AnyResult<()> {
|
||||
let tag = tag.into();
|
||||
if let Some(media) = self.medias.write().await.get_mut(&tag) {
|
||||
let mounts = self
|
||||
.obj()
|
||||
.mount_points()
|
||||
.expect("The server should have mountpoints");
|
||||
for path in paths {
|
||||
if media.paths.contains(&path.to_string()) {
|
||||
media.paths.remove(&path.to_string());
|
||||
mounts.remove_factory(path);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!(
|
||||
"No media with tag {} to remove the paths from",
|
||||
&tag
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> AnyResult<()> {
|
||||
let auth = self.obj().auth().unwrap_or_else(RTSPAuth::new);
|
||||
auth.set_supported_methods(RTSPAuthMethod::Basic);
|
||||
|
||||
let mut un_authtoken = RTSPToken::new(&[(RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous")]);
|
||||
auth.set_default_token(Some(&mut un_authtoken));
|
||||
|
||||
for credential in credentials {
|
||||
let (user, pass) = credential;
|
||||
trace!("Setting credentials for user {}", user);
|
||||
let token = RTSPToken::new(&[(RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]);
|
||||
let basic = RTSPAuth::make_basic(user, pass);
|
||||
auth.add_basic(basic.as_str(), &token);
|
||||
}
|
||||
|
||||
self.obj().set_auth(Some(&auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_tls(
|
||||
&self,
|
||||
cert_file: &str,
|
||||
client_auth: TlsAuthenticationMode,
|
||||
) -> AnyResult<()> {
|
||||
debug!("Setting up TLS using {}", cert_file);
|
||||
let auth = self.obj().auth().unwrap_or_else(RTSPAuth::new);
|
||||
|
||||
// We seperate reading the file and changing to a PEM so that we get different error messages.
|
||||
let cert_contents = fs::read_to_string(cert_file).with_context(|| "TLS file not found")?;
|
||||
let cert = TlsCertificate::from_pem(&cert_contents)
|
||||
.with_context(|| "Not a valid TLS certificate")?;
|
||||
auth.set_tls_certificate(Some(&cert));
|
||||
auth.set_tls_authentication_mode(client_auth);
|
||||
|
||||
self.obj().set_auth(Some(&auth));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn set_up_tls(&self, config: &Config) {
|
||||
let tls_client_auth = match &config.tls_client_auth as &str {
|
||||
"request" => TlsAuthenticationMode::Requested,
|
||||
"require" => TlsAuthenticationMode::Required,
|
||||
"none" => TlsAuthenticationMode::None,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Some(cert_path) = &config.certificate {
|
||||
self.set_tls(cert_path, tls_client_auth)
|
||||
.expect("Failed to set up TLS");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_up_users(&self, users: &[UserConfig]) {
|
||||
// Setting up users
|
||||
let credentials: Vec<_> = users
|
||||
.iter()
|
||||
.map(|user| (&*user.name, &*user.pass))
|
||||
.collect();
|
||||
self.set_credentials(&credentials)
|
||||
.expect("Failed to set up users");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Data shared between the various
|
||||
//! components that manage a media stream
|
||||
use gstreamer::Clock;
|
||||
use gstreamer_app::AppSrc;
|
||||
pub use gstreamer_rtsp_server::gio::{TlsAuthenticationMode, TlsCertificate};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum VidFormats {
|
||||
Unknown,
|
||||
H264,
|
||||
H265,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum AudFormats {
|
||||
Unknown,
|
||||
Aac,
|
||||
Adpcm(u16),
|
||||
}
|
||||
|
||||
pub(super) struct NeoMediaShared {
|
||||
pub(super) vid_format: RwLock<VidFormats>,
|
||||
pub(super) aud_format: RwLock<AudFormats>,
|
||||
pub(super) microseconds: AtomicU64,
|
||||
pub(super) number_of_clients: AtomicUsize,
|
||||
pub(super) buffer_ready: AtomicBool,
|
||||
}
|
||||
|
||||
impl Default for NeoMediaShared {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
vid_format: RwLock::new(VidFormats::Unknown),
|
||||
aud_format: RwLock::new(AudFormats::Unknown),
|
||||
microseconds: AtomicU64::new(0),
|
||||
number_of_clients: AtomicUsize::new(0),
|
||||
buffer_ready: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct ClientPipelineData {
|
||||
pub(super) vidsrc: Option<AppSrc>,
|
||||
pub(super) audsrc: Option<AppSrc>,
|
||||
pub(super) start_time: u64,
|
||||
pub(super) inited: bool,
|
||||
pub(super) clock: Option<Clock>,
|
||||
pub(super) enough_data: Arc<AtomicBool>,
|
||||
}
|
||||
+172
-160
@@ -53,68 +53,74 @@
|
||||
// - `"none"`: Resends the last iframe the camera. This does not reencode at all. **Most use cases should use this one as it has the least effort on the cpu and gives what you would expect**
|
||||
//
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use crossbeam::utils::Backoff;
|
||||
use futures::stream::FuturesUnordered;
|
||||
use log::*;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
mod abort;
|
||||
mod cmdline;
|
||||
mod gst;
|
||||
mod states;
|
||||
|
||||
use abort::AbortHandle;
|
||||
use states::{RtspCamera, StateInfo};
|
||||
|
||||
use super::config::{CameraConfig, Config, UserConfig};
|
||||
use super::config::Config;
|
||||
pub(crate) use cmdline::Opt;
|
||||
use gst::{RtspServer, TlsAuthenticationMode};
|
||||
use gst::NeoRtspServer;
|
||||
use states::*;
|
||||
|
||||
/// Entry point for the rtsp subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
|
||||
let rtsp = Arc::new(RtspServer::new()?);
|
||||
let rtsp = Arc::new(NeoRtspServer::new()?);
|
||||
|
||||
set_up_tls(&config, &rtsp);
|
||||
rtsp.set_up_tls(&config);
|
||||
|
||||
set_up_users(&config.users, &rtsp);
|
||||
rtsp.set_up_users(&config.users);
|
||||
|
||||
if config.certificate.is_none() && !config.users.is_empty() {
|
||||
warn!(
|
||||
"Without a server certificate, usernames and passwords will be exchanged in plaintext!"
|
||||
)
|
||||
}
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
let abort = AbortHandle::new();
|
||||
|
||||
let arc_user_config = Arc::new(config.users);
|
||||
let mut cameras = vec![];
|
||||
for camera_config in config.cameras.drain(..) {
|
||||
// Spawn each camera controller in it's own thread
|
||||
let user_config = arc_user_config.clone();
|
||||
let arc_rtsp = rtsp.clone();
|
||||
let abort_handle = abort.clone();
|
||||
set.spawn(async move {
|
||||
let backoff = Backoff::new();
|
||||
cameras
|
||||
.push(Camera::<Disconnected>::new(camera_config, &config.users, rtsp.clone()).await?);
|
||||
}
|
||||
|
||||
while abort_handle.is_live() {
|
||||
let failure =
|
||||
camera_main(&camera_config, user_config.as_slice(), arc_rtsp.clone()).await;
|
||||
let mut set = tokio::task::JoinSet::new();
|
||||
for mut camera in cameras.drain(..) {
|
||||
// Spawn each camera controller in it's own thread
|
||||
set.spawn(async move {
|
||||
let shared = camera.shared.clone();
|
||||
let name = camera.get_name();
|
||||
let mut backoff = Duration::from_micros(125);
|
||||
loop {
|
||||
let failure = camera_main(camera).await;
|
||||
match failure {
|
||||
Err(CameraFailureKind::Fatal(e)) => {
|
||||
error!("{}: Fatal error: {:?}", camera_config.name, e);
|
||||
break;
|
||||
error!("{}: Fatal error: {:?}", name, e);
|
||||
return Err(e);
|
||||
}
|
||||
Err(CameraFailureKind::Retry(e)) => {
|
||||
warn!("{}: Retryable error: {:X?}", camera_config.name, e);
|
||||
backoff.spin();
|
||||
warn!("{}: Retryable error: {:X?}", name, e);
|
||||
tokio::time::sleep(backoff).await;
|
||||
if backoff < Duration::from_secs(5) {
|
||||
backoff *= 2;
|
||||
}
|
||||
camera = Camera {
|
||||
shared: shared.clone(),
|
||||
state: Disconnected {},
|
||||
};
|
||||
}
|
||||
Ok(()) => {
|
||||
info!("{}: Shutting down", camera_config.name);
|
||||
info!("{}: Shutting down", name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
info!(
|
||||
@@ -124,10 +130,20 @@ pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
|
||||
|
||||
let bind_addr = config.bind_addr.clone();
|
||||
let bind_port = config.bind_port;
|
||||
set.spawn(async move { rtsp.run(&bind_addr, bind_port).await });
|
||||
let (handle, main_loop) = rtsp.run(&bind_addr, bind_port).await?;
|
||||
set.spawn(async move { handle.await? });
|
||||
|
||||
if let Some(joined) = set.join_next().await {
|
||||
joined?
|
||||
while let Some(joined) = set.join_next().await {
|
||||
match &joined {
|
||||
Err(_) | Ok(Err(_)) => {
|
||||
// Panicked or error in task
|
||||
main_loop.quit();
|
||||
}
|
||||
Ok(Ok(_)) => {
|
||||
// All good
|
||||
}
|
||||
}
|
||||
joined??
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -138,153 +154,149 @@ enum CameraFailureKind {
|
||||
Retry(anyhow::Error),
|
||||
}
|
||||
|
||||
async fn camera_main(
|
||||
config: &CameraConfig,
|
||||
user_config: &[UserConfig],
|
||||
rtsp: Arc<RtspServer>,
|
||||
) -> Result<(), CameraFailureKind> {
|
||||
async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKind> {
|
||||
// Connect
|
||||
let mut camera = RtspCamera::new(config, user_config, rtsp)
|
||||
let name = camera.get_name();
|
||||
let connected = camera
|
||||
.connect()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not connect camera", config.name))
|
||||
.with_context(|| format!("{}: Could not connect to camera", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
camera
|
||||
|
||||
let loggedin = connected
|
||||
.login()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not login to camera", config.name))
|
||||
.map_err(CameraFailureKind::Fatal)?;
|
||||
.with_context(|| format!("{}: Could not login to camera", name))
|
||||
.map_err(|e| {
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>().unwrap();
|
||||
match e_inner {
|
||||
neolink_core::Error::CameraLoginFail => CameraFailureKind::Fatal(e),
|
||||
_ => CameraFailureKind::Retry(e),
|
||||
}
|
||||
})?;
|
||||
|
||||
let _ = camera.manage().await;
|
||||
let _ = loggedin.manage().await;
|
||||
|
||||
camera
|
||||
let mut streaming = loggedin
|
||||
.stream()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not start stream", config.name))
|
||||
.with_context(|| format!("{}: Could not start stream", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
|
||||
let backoff = Backoff::new();
|
||||
let mut motion = if config.pause.on_motion {
|
||||
Some(
|
||||
camera
|
||||
.motion_data()
|
||||
.await
|
||||
.with_context(|| {
|
||||
"Could not initialise motion detection. Is it supported with this camera?"
|
||||
})
|
||||
.map_err(CameraFailureKind::Retry)?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let tags = streaming.shared.get_tags();
|
||||
let rtsp_thread = streaming.get_rtsp();
|
||||
|
||||
let motion_timeout: Duration = Duration::from_secs_f64(config.pause.motion_timeout);
|
||||
let mut ready_to_pause_print = false;
|
||||
let mut waiter = tokio::time::interval(Duration::from_micros(500));
|
||||
loop {
|
||||
match camera.get_state() {
|
||||
StateInfo::Streaming => {
|
||||
let can_pause = camera.can_pause().await;
|
||||
if config.pause.on_disconnect {
|
||||
if let Some(false) = camera.client_connected().await {
|
||||
if can_pause {
|
||||
info!("Pause on disconnect");
|
||||
camera.pause().await.map_err(CameraFailureKind::Retry)?;
|
||||
} else if !ready_to_pause_print {
|
||||
ready_to_pause_print = true;
|
||||
warn!("Not ready to pause");
|
||||
}
|
||||
waiter.tick().await;
|
||||
if tags
|
||||
.iter()
|
||||
.map(|tag| rtsp_thread.buffer_ready(tag))
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.all(|f| f.unwrap_or(false))
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if streaming.get_config().pause.on_motion || streaming.get_config().pause.on_disconnect {
|
||||
log::info!("Pause buffer prepared");
|
||||
}
|
||||
|
||||
// tokio::task::spawn(async move {
|
||||
// let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
|
||||
// loop {
|
||||
// inter.tick().await;
|
||||
// log::info!(
|
||||
// "Users: {:?}, {}",
|
||||
// rtsp_thread.get_number_of_clients("Cammy01::Main").await,
|
||||
// rtsp_thread.num_path_users(&["/Cammy01/mainStream"])
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
loop {
|
||||
// Wait for error or reason to pause
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Wait for error
|
||||
streaming.join().await
|
||||
} => {
|
||||
info!("Join Pause");
|
||||
v
|
||||
},
|
||||
v = async {
|
||||
// Wait for motion stop
|
||||
let mut motion = streaming.get_camera().listen_on_motion().await?;
|
||||
motion.await_stop(Duration::from_secs_f64(streaming.get_config().pause.motion_timeout)).await
|
||||
}, if streaming.get_config().pause.on_motion => {
|
||||
info!("Motion Pause");
|
||||
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))
|
||||
},
|
||||
v = async {
|
||||
// Wait for client to disconnect
|
||||
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
|
||||
|
||||
info!("Await Client Pause");
|
||||
loop {
|
||||
inter.tick().await;
|
||||
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
|
||||
// info!("Num clients: {}", total_clients);
|
||||
if total_clients == 0 {
|
||||
return Ok(())
|
||||
}
|
||||
}
|
||||
if config.pause.on_motion {
|
||||
if let Some(motion) = motion.as_mut() {
|
||||
match motion
|
||||
.motion_detected_within(motion_timeout)
|
||||
.with_context(|| "Motion detection unexpectedly stopped")
|
||||
.map_err(CameraFailureKind::Retry)?
|
||||
{
|
||||
Some(false) => {
|
||||
if can_pause {
|
||||
info!("Pause on motion");
|
||||
camera.pause().await.map_err(CameraFailureKind::Retry)?;
|
||||
} else if !ready_to_pause_print {
|
||||
ready_to_pause_print = true;
|
||||
warn!("Not ready to pause");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if can_pause {
|
||||
info!("Pause on motion (start)");
|
||||
camera.pause().await.map_err(CameraFailureKind::Retry)?;
|
||||
} else if !ready_to_pause_print {
|
||||
ready_to_pause_print = true;
|
||||
warn!("Not ready to pause");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}, if streaming.get_config().pause.on_disconnect => {
|
||||
info!("Client Pause");
|
||||
v
|
||||
},
|
||||
}.with_context(|| format!("{}: Error while streaming", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
|
||||
let paused = streaming
|
||||
.stop()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not stop stream", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
// Wait for reason to restart
|
||||
tokio::select! {
|
||||
v = async {
|
||||
// Wait for motion start
|
||||
let mut motion = paused.get_camera().listen_on_motion().await?;
|
||||
motion.await_start(Duration::ZERO).await
|
||||
}, if paused.get_config().pause.on_motion => {
|
||||
info!("Motion Resume");
|
||||
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))
|
||||
},
|
||||
v = async {
|
||||
// Wait for client to connect
|
||||
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
|
||||
|
||||
loop {
|
||||
inter.tick().await;
|
||||
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
|
||||
if total_clients > 0 {
|
||||
return Ok(())
|
||||
}
|
||||
}
|
||||
if let Err(e) = camera.is_running().await {
|
||||
return Err(CameraFailureKind::Retry(anyhow!(
|
||||
"Camera has unexpectanely stopped the streaming state: {:?}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
}
|
||||
StateInfo::Paused => {
|
||||
if config.pause.on_disconnect {
|
||||
if let Some(true) = camera.client_connected().await {
|
||||
info!("Resume on disconnect");
|
||||
camera.stream().await.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
if config.pause.on_motion {
|
||||
if let Some(motion) = motion.as_mut() {
|
||||
if let Some(true) = motion
|
||||
.motion_detected_within(motion_timeout)
|
||||
.with_context(|| "Motion detection unexpectedly stopped")
|
||||
.map_err(CameraFailureKind::Retry)?
|
||||
{
|
||||
info!("Resume on motion");
|
||||
camera.stream().await.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = camera.is_running().await {
|
||||
return Err(CameraFailureKind::Retry(anyhow!(
|
||||
"Camera has unexpectanely stopped the paused state: {:?}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(CameraFailureKind::Retry(anyhow!(
|
||||
"Camera has unexpectanely stopped the paused state"
|
||||
)));
|
||||
}, if paused.get_config().pause.on_disconnect => {
|
||||
info!("Client Resume");
|
||||
v
|
||||
},
|
||||
else => {
|
||||
// No pause. This means that the stream stopped for some reason
|
||||
// but not because of an error
|
||||
info!("Generic Resume");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
backoff.spin();
|
||||
.with_context(|| format!("{}: Error while paused", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
|
||||
streaming = paused
|
||||
.stream()
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not start stream", name))
|
||||
.map_err(CameraFailureKind::Retry)?;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_up_tls(config: &Config, rtsp: &RtspServer) {
|
||||
let tls_client_auth = match &config.tls_client_auth as &str {
|
||||
"request" => TlsAuthenticationMode::Requested,
|
||||
"require" => TlsAuthenticationMode::Required,
|
||||
"none" => TlsAuthenticationMode::None,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Some(cert_path) = &config.certificate {
|
||||
rtsp.set_tls(cert_path, tls_client_auth)
|
||||
.expect("Failed to set up TLS");
|
||||
}
|
||||
}
|
||||
|
||||
fn set_up_users(users: &[UserConfig], rtsp: &RtspServer) {
|
||||
// Setting up users
|
||||
let credentials: Vec<_> = users
|
||||
.iter()
|
||||
.map(|user| (&*user.name, &*user.pass))
|
||||
.collect();
|
||||
rtsp.set_credentials(&credentials)
|
||||
.expect("Failed to set up users");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! Generic state
|
||||
//!
|
||||
//! This is the base state
|
||||
use super::shared::Shared;
|
||||
use crate::config::CameraConfig;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) struct Camera<T> {
|
||||
pub(crate) state: T,
|
||||
pub(crate) shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
impl<T> Camera<T> {
|
||||
pub(crate) fn get_name(&self) -> String {
|
||||
self.shared.config.name.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn get_config(&self) -> &CameraConfig {
|
||||
&self.shared.config
|
||||
}
|
||||
|
||||
pub(crate) fn get_rtsp(&self) -> Arc<super::super::gst::NeoRtspServer> {
|
||||
self.shared.rtsp.clone()
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,38 @@
|
||||
//
|
||||
// This state has formed the TCP/UDP tunnel
|
||||
// but has not logged in
|
||||
use super::{CameraState, Shared};
|
||||
use anyhow::{Error, Result};
|
||||
use async_trait::async_trait;
|
||||
use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn};
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Connected {}
|
||||
use neolink_core::bc_protocol::{BcCamera, MaxEncryption};
|
||||
|
||||
#[async_trait]
|
||||
impl CameraState for Connected {
|
||||
async fn setup(&mut self, _shared: &Shared) -> Result<(), Error> {
|
||||
Ok(())
|
||||
pub(crate) struct Connected {
|
||||
pub(crate) camera: BcCamera,
|
||||
}
|
||||
|
||||
impl Camera<Connected> {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) async fn disconnect(self) -> Result<Camera<Disconnected>> {
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: Disconnected {},
|
||||
})
|
||||
}
|
||||
async fn tear_down(&mut self, _shared: &Shared) -> Result<(), Error> {
|
||||
Ok(())
|
||||
|
||||
pub(crate) async fn login(self) -> Result<Camera<LoggedIn>> {
|
||||
let max_encryption = match self.shared.config.max_encryption.to_lowercase().as_str() {
|
||||
"none" => MaxEncryption::None,
|
||||
"bcencrypt" => MaxEncryption::BcEncrypt,
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
|
||||
self.state.camera.login_with_maxenc(max_encryption).await?;
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
camera: self.state.camera,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Data for the basic disconnected state
|
||||
//!
|
||||
//! This state has NOT formed the TCP/UDP tunnel
|
||||
//! it has all the data required to connect but
|
||||
//! has not estabilished the connection
|
||||
//!
|
||||
//! This is meant to be used to conserve battery
|
||||
//! by completely disconnecting
|
||||
use super::Shared;
|
||||
use super::{camera::Camera, connected::Connected};
|
||||
use crate::config::{CameraConfig, UserConfig};
|
||||
use crate::rtsp::gst::NeoRtspServer;
|
||||
use anyhow::{Context, Result};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Disconnected {}
|
||||
|
||||
impl Camera<Disconnected> {
|
||||
pub(crate) async fn new(
|
||||
config: CameraConfig,
|
||||
users: &[UserConfig],
|
||||
rtsp: Arc<NeoRtspServer>,
|
||||
) -> Result<Camera<Disconnected>> {
|
||||
Ok(Camera {
|
||||
state: Disconnected {},
|
||||
shared: Arc::new(Shared::new(config, users, rtsp).await?),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn connect(self) -> Result<Camera<Connected>> {
|
||||
let camera = {
|
||||
let camera_config = &self.shared.config;
|
||||
self.shared
|
||||
.addr
|
||||
.connect_camera(camera_config)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
camera_config.name, self.shared.addr, camera_config.channel_id
|
||||
)
|
||||
})
|
||||
}?;
|
||||
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: Connected { camera },
|
||||
})
|
||||
}
|
||||
}
|
||||
+78
-11
@@ -5,22 +5,89 @@
|
||||
//
|
||||
// It can be used to alter settings etc
|
||||
|
||||
use super::{CameraState, Shared};
|
||||
use super::{camera::Camera, connected::Connected, streaming::Streaming};
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use log::*;
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct LoggedIn {}
|
||||
pub(crate) struct LoggedIn {
|
||||
pub(crate) camera: BcCamera,
|
||||
}
|
||||
|
||||
impl Camera<LoggedIn> {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) async fn logout(self) -> Result<Camera<Connected>> {
|
||||
self.state.camera.logout().await?;
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: Connected {
|
||||
camera: self.state.camera,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn stream(self) -> Result<Camera<Streaming>> {
|
||||
Camera::<Streaming>::from_login(self).await
|
||||
}
|
||||
|
||||
pub(crate) async fn manage(&self) -> Result<()> {
|
||||
let cam_time = self.state.camera.get_time().await?;
|
||||
if let Some(time) = cam_time {
|
||||
info!(
|
||||
"{}: Camera time is already set: {}",
|
||||
self.shared.config.name, time
|
||||
);
|
||||
} else {
|
||||
use time::OffsetDateTime;
|
||||
// We'd like now_local() but it's deprecated - try to get the local time, but if no
|
||||
// time zone, fall back to UTC.
|
||||
let new_time =
|
||||
OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
|
||||
|
||||
warn!(
|
||||
"{}: Camera has no time set, setting to {}",
|
||||
self.shared.config.name, new_time
|
||||
);
|
||||
match self.state.camera.set_time(new_time).await {
|
||||
Ok(_) => {
|
||||
let cam_time = self.state.camera.get_time().await?;
|
||||
if let Some(time) = cam_time {
|
||||
info!(
|
||||
"{}: Camera time is now set: {}",
|
||||
self.shared.config.name, time
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!(
|
||||
"{}: Camera did not accept new time (is {} an admin?): Error: {:?}",
|
||||
self.shared.config.name, self.shared.config.username, e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use neolink_core::bc::xml::VersionInfo;
|
||||
if let Ok(VersionInfo {
|
||||
firmwareVersion: firmware_version,
|
||||
..
|
||||
}) = self.state.camera.version().await
|
||||
{
|
||||
info!(
|
||||
"{}: Camera reports firmware version {}",
|
||||
self.shared.config.name, firmware_version
|
||||
);
|
||||
} else {
|
||||
info!(
|
||||
"{}: Could not fetch version information",
|
||||
self.shared.config.name
|
||||
);
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CameraState for LoggedIn {
|
||||
async fn setup(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
|
||||
shared.camera.login().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tear_down(&mut self, shared: &Shared) -> Result<(), anyhow::Error> {
|
||||
shared.camera.logout().await?;
|
||||
Ok(())
|
||||
pub(crate) fn get_camera(&self) -> &BcCamera {
|
||||
&self.state.camera
|
||||
}
|
||||
}
|
||||
+3
-313
@@ -1,321 +1,11 @@
|
||||
//! Handles the camera in it's different states
|
||||
//!
|
||||
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use log::*;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use neolink_core::bc_protocol::{MotionData, StreamKind as Stream};
|
||||
|
||||
use crate::config::{CameraConfig, UserConfig};
|
||||
use crate::rtsp::gst::RtspServer;
|
||||
use crate::utils::AddressOrUid;
|
||||
|
||||
mod camera;
|
||||
mod connected;
|
||||
mod disconnected;
|
||||
mod loggedin;
|
||||
mod paused;
|
||||
mod shared;
|
||||
mod streaming;
|
||||
|
||||
pub(crate) use connected::Connected;
|
||||
pub(crate) use loggedin::LoggedIn;
|
||||
pub(crate) use paused::Paused;
|
||||
pub(crate) use shared::{CameraState, Shared};
|
||||
pub(crate) use streaming::Streaming;
|
||||
|
||||
pub(crate) enum StateInfo {
|
||||
Connected,
|
||||
LoggedIn,
|
||||
Streaming,
|
||||
Paused,
|
||||
}
|
||||
|
||||
enum State {
|
||||
Connected(Connected),
|
||||
LoggedIn(LoggedIn),
|
||||
Streaming(Streaming),
|
||||
Paused(Paused),
|
||||
}
|
||||
|
||||
///
|
||||
/// The state machine representation of the camera
|
||||
///
|
||||
pub(crate) struct RtspCamera {
|
||||
shared: Shared,
|
||||
state: State,
|
||||
}
|
||||
|
||||
impl RtspCamera {
|
||||
pub(crate) async fn new(
|
||||
config: &CameraConfig,
|
||||
users: &[UserConfig],
|
||||
rtsp: Arc<RtspServer>,
|
||||
) -> Result<Self, Error> {
|
||||
let camera_addr =
|
||||
AddressOrUid::new(&config.camera_addr, &config.camera_uid, &config.discovery)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Could not connect to camera {}. Please check UUID or IP:Port in the config",
|
||||
config.name
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("{}: Connecting to camera at {}", config.name, camera_addr);
|
||||
let camera = camera_addr
|
||||
.connect_camera(
|
||||
config.channel_id,
|
||||
&config.username,
|
||||
config.password.as_ref(),
|
||||
)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to connect to camera {} at {} on channel {}",
|
||||
config.name, camera_addr, config.channel_id
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut streams: HashSet<Stream> = Default::default();
|
||||
if ["all", "both", "mainStream", "mainstream"]
|
||||
.iter()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
streams.insert(Stream::Main);
|
||||
}
|
||||
if ["all", "both", "subStream", "substream"]
|
||||
.iter()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
streams.insert(Stream::Sub);
|
||||
}
|
||||
if ["all", "externStream", "externstream"]
|
||||
.iter()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
streams.insert(Stream::Extern);
|
||||
}
|
||||
|
||||
// Used to build the list of strings to pass to gtreamer for the allowed users
|
||||
let all_users_hash = || users.iter().map(|u| u.name.clone()).collect();
|
||||
let permitted_users = match &config.permitted_users {
|
||||
// If in the camera config there is the user "anyone", or if none is specified but users
|
||||
// are defined at all, then we add all users to the camera's allowed list.
|
||||
Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(),
|
||||
None if !users.is_empty() => all_users_hash(),
|
||||
|
||||
// The user specified permitted_users
|
||||
Some(p) => p.iter().cloned().collect(),
|
||||
|
||||
// The user didn't specify permitted_users, and there are none defined anyway
|
||||
None => ["anonymous".to_string()].iter().cloned().collect(),
|
||||
};
|
||||
|
||||
let shared = Shared {
|
||||
camera: Arc::new(camera),
|
||||
addr: camera_addr,
|
||||
name: config.name.clone(),
|
||||
channel: config.channel_id,
|
||||
username: config.username.clone(),
|
||||
password: config.password.clone(),
|
||||
pause: config.pause.clone(),
|
||||
streams,
|
||||
rtsp,
|
||||
permitted_users,
|
||||
};
|
||||
|
||||
let mut state: Connected = Default::default();
|
||||
state.setup(&shared).await?;
|
||||
|
||||
Ok(Self {
|
||||
shared,
|
||||
state: State::Connected(state),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn get_state(&self) -> StateInfo {
|
||||
match &self.state {
|
||||
State::Connected(_) => StateInfo::Connected,
|
||||
State::LoggedIn(_) => StateInfo::LoggedIn,
|
||||
State::Streaming(_) => StateInfo::Streaming,
|
||||
State::Paused(_) => StateInfo::Paused,
|
||||
}
|
||||
}
|
||||
pub(crate) async fn login(&mut self) -> Result<()> {
|
||||
match &mut self.state {
|
||||
State::Connected(ref mut connected) => {
|
||||
info!("{}: Logging in", &self.shared.name);
|
||||
connected.tear_down(&self.shared).await?;
|
||||
let mut state: LoggedIn = Default::default();
|
||||
state.setup(&self.shared).await?;
|
||||
self.state = State::LoggedIn(state);
|
||||
info!("{}: Successfully logged in", &self.shared.name);
|
||||
}
|
||||
State::Streaming(ref mut connected) => {
|
||||
info!("{}: Logging in", &self.shared.name);
|
||||
connected.tear_down(&self.shared).await?;
|
||||
let state: LoggedIn = Default::default();
|
||||
// state.setup(&self.shared).await?;
|
||||
self.state = State::LoggedIn(state);
|
||||
info!("{}: Successfully stopped straming", &self.shared.name);
|
||||
}
|
||||
State::Paused(ref mut connected) => {
|
||||
info!("{}: Logging in", &self.shared.name);
|
||||
connected.tear_down(&self.shared).await?;
|
||||
let state: LoggedIn = Default::default();
|
||||
// state.setup(&self.shared).await?;
|
||||
self.state = State::LoggedIn(state);
|
||||
info!(
|
||||
"{}: Successfully stopped paused streaming",
|
||||
&self.shared.name
|
||||
);
|
||||
}
|
||||
State::LoggedIn(_) => {
|
||||
info!("Already logged in");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn stream(&mut self) -> Result<()> {
|
||||
match &mut self.state {
|
||||
State::Connected(_) => {
|
||||
return Err(anyhow!("{}: Must login first", &self.shared.name));
|
||||
}
|
||||
State::Streaming(_) => {
|
||||
info!("{}: Already streaming", &self.shared.name);
|
||||
}
|
||||
State::Paused(ref mut paused) => {
|
||||
info!("{}: Resuming stream", &self.shared.name);
|
||||
let outputs = paused.take_outputs().await?;
|
||||
|
||||
paused.tear_down(&self.shared).await?;
|
||||
let mut state: Streaming = Default::default();
|
||||
|
||||
state.insert_outputs(outputs)?;
|
||||
|
||||
state.setup(&self.shared).await?;
|
||||
self.state = State::Streaming(state);
|
||||
info!("{}: Successfully resumed streaming", &self.shared.name);
|
||||
}
|
||||
State::LoggedIn(ref mut _loggedin) => {
|
||||
info!("{}: Starting stream", &self.shared.name);
|
||||
// loggedin.tear_down(&self.shared).await?;
|
||||
let mut state: Streaming = Default::default();
|
||||
state.setup(&self.shared).await?;
|
||||
self.state = State::Streaming(state);
|
||||
info!("{}: Successfully started streaming", &self.shared.name);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn pause(&mut self) -> Result<()> {
|
||||
match &mut self.state {
|
||||
State::Connected(_) => {
|
||||
return Err(anyhow!("{}: Must login first", &self.shared.name));
|
||||
}
|
||||
State::Streaming(ref mut old_state) => {
|
||||
info!("{}: Pausing stream", &self.shared.name);
|
||||
let outputs = old_state.take_outputs().await?;
|
||||
|
||||
old_state.tear_down(&self.shared).await?;
|
||||
let mut state: Paused = Default::default();
|
||||
|
||||
state.insert_outputs(outputs)?;
|
||||
|
||||
state.setup(&self.shared).await?;
|
||||
self.state = State::Paused(state);
|
||||
info!("{}: Successfully paused streaming", &self.shared.name);
|
||||
}
|
||||
State::Paused(_) => {
|
||||
info!("{}: Already paused", &self.shared.name);
|
||||
}
|
||||
State::LoggedIn(_) => {
|
||||
info!(
|
||||
"{}: Cannot pause a stream that has not started",
|
||||
&self.shared.name
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn client_connected(&self) -> Option<bool> {
|
||||
match &self.state {
|
||||
State::Streaming(state) => Some(state.client_connected().await),
|
||||
State::Paused(state) => Some(state.client_connected().await),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn motion_data(&self) -> Result<MotionData> {
|
||||
self.shared
|
||||
.camera
|
||||
.listen_on_motion()
|
||||
.await
|
||||
.with_context(|| "Cannot get motion data")
|
||||
}
|
||||
|
||||
pub(crate) async fn is_running(&mut self) -> Result<()> {
|
||||
match &mut self.state {
|
||||
State::Streaming(state) => state.is_running().await,
|
||||
State::Paused(state) => state.is_running().await,
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn can_pause(&self) -> bool {
|
||||
match &self.state {
|
||||
State::Streaming(state) => state.can_pause().await,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn manage(&self) -> Result<()> {
|
||||
if let State::Connected(_) = self.state {
|
||||
return Err(anyhow!("Cannot manage a camera that is not logged in"));
|
||||
}
|
||||
let cam_time = self.shared.camera.get_time().await?;
|
||||
if let Some(time) = cam_time {
|
||||
info!("{}: Camera time is already set: {}", self.shared.name, time);
|
||||
} else {
|
||||
use time::OffsetDateTime;
|
||||
// We'd like now_local() but it's deprecated - try to get the local time, but if no
|
||||
// time zone, fall back to UTC.
|
||||
let new_time =
|
||||
OffsetDateTime::try_now_local().unwrap_or_else(|_| OffsetDateTime::now_utc());
|
||||
|
||||
warn!(
|
||||
"{}: Camera has no time set, setting to {}",
|
||||
self.shared.name, new_time
|
||||
);
|
||||
self.shared.camera.set_time(new_time).await?;
|
||||
let cam_time = self.shared.camera.get_time().await?;
|
||||
if let Some(time) = cam_time {
|
||||
info!("{}: Camera time is now set: {}", self.shared.name, time);
|
||||
} else {
|
||||
error!(
|
||||
"{}: Camera did not accept new time (is {} an admin?)",
|
||||
self.shared.name, self.shared.username
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
use neolink_core::bc::xml::VersionInfo;
|
||||
if let Ok(VersionInfo {
|
||||
firmwareVersion: firmware_version,
|
||||
..
|
||||
}) = self.shared.camera.version().await
|
||||
{
|
||||
info!(
|
||||
"{}: Camera reports firmware version {}",
|
||||
self.shared.name, firmware_version
|
||||
);
|
||||
} else {
|
||||
info!("{}: Could not fetch version information", self.shared.name);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub(crate) use self::{camera::*, disconnected::*, loggedin::*, shared::*};
|
||||
@@ -1,191 +0,0 @@
|
||||
// This is the paused state
|
||||
//
|
||||
// Video data is not pulled from the camera
|
||||
// instead dummy data is sent into the gstreamer source
|
||||
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use async_trait::async_trait;
|
||||
use crossbeam::utils::Backoff;
|
||||
use log::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::{
|
||||
sync::Mutex,
|
||||
task::{self, JoinHandle},
|
||||
};
|
||||
|
||||
use neolink_core::bc_protocol::StreamKind as Stream;
|
||||
|
||||
use super::{CameraState, Shared};
|
||||
|
||||
use crate::rtsp::{
|
||||
abort::AbortHandle,
|
||||
gst::{GstOutputs, InputMode, PausedSources},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Paused {
|
||||
handles: HashMap<Stream, JoinHandle<Result<(), anyhow::Error>>>,
|
||||
outputs: HashMap<Stream, Arc<Mutex<GstOutputs>>>,
|
||||
abort_handle: AbortHandle,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CameraState for Paused {
|
||||
async fn setup(&mut self, shared: &Shared) -> Result<(), Error> {
|
||||
self.abort_handle.reset();
|
||||
// Create new gst outputs
|
||||
//
|
||||
// Otherwise use those already present
|
||||
if self.outputs.is_empty() {
|
||||
let paused_source = match shared.pause.mode.as_str() {
|
||||
"test" => PausedSources::TestSrc,
|
||||
"still" => PausedSources::Still,
|
||||
"black" => PausedSources::Black,
|
||||
"none" => PausedSources::None,
|
||||
_ => {
|
||||
unreachable!()
|
||||
}
|
||||
};
|
||||
|
||||
for stream in shared.streams.iter() {
|
||||
self.outputs.entry(*stream).or_insert_with_key(|stream| {
|
||||
let paths = shared.get_paths(stream);
|
||||
let mut output = shared
|
||||
.rtsp
|
||||
.add_stream(
|
||||
paths
|
||||
.iter()
|
||||
.map(|s| s.as_str())
|
||||
.collect::<Vec<&str>>()
|
||||
.as_slice(),
|
||||
&shared.permitted_users,
|
||||
)
|
||||
.unwrap();
|
||||
output.set_paused_source(paused_source);
|
||||
Arc::new(Mutex::new(output))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Start the streams on their own thread with a shared abort handle
|
||||
let abort_handle = self.abort_handle.clone();
|
||||
|
||||
for (stream, output) in &self.outputs {
|
||||
let stream_display_name = match stream {
|
||||
Stream::Main => "Main Stream (Clear)",
|
||||
Stream::Sub => "Sub Stream (Fluent)",
|
||||
Stream::Extern => "Extern Stream (Balanced)",
|
||||
};
|
||||
|
||||
// Lock and setup output
|
||||
{
|
||||
let mut locked_output = output.lock().await;
|
||||
locked_output.set_input_source(InputMode::Paused)?;
|
||||
}
|
||||
|
||||
info!(
|
||||
"{}: Starting paused stream {}",
|
||||
&shared.name, stream_display_name
|
||||
);
|
||||
|
||||
let arc_abort_handle = abort_handle.clone();
|
||||
let output_thread = output.clone();
|
||||
|
||||
let handle = task::spawn(async move {
|
||||
let backoff = Backoff::new();
|
||||
while arc_abort_handle.is_live() {
|
||||
let mut locked_output = output_thread.lock().await;
|
||||
locked_output.write_last_iframe()?;
|
||||
backoff.spin();
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.handles.entry(*stream).or_insert_with(|| handle);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tear_down(&mut self, shared: &Shared) -> Result<(), Error> {
|
||||
self.abort_handle.abort();
|
||||
|
||||
if !self.handles.is_empty() {
|
||||
for path in shared.get_all_paths().iter() {
|
||||
if let Err(e) = shared.rtsp.remove_stream(&[path]) {
|
||||
return Err(anyhow!("Failed to shutdown RTSP Path {}: {:?}", path, e));
|
||||
}
|
||||
}
|
||||
|
||||
for (stream, handle) in self.handles.drain() {
|
||||
info!("{}: Stopping paused stream {:?}", &shared.name, stream);
|
||||
|
||||
match handle.await {
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => return Err(anyhow!("Panicked while streaming {:?}", stream)),
|
||||
Ok(Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Paused {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl Paused {
|
||||
pub(crate) async fn is_running(&mut self) -> Result<()> {
|
||||
if self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.abort_handle.is_live() {
|
||||
return Err(anyhow!("Stream aborted"));
|
||||
}
|
||||
for (s, h) in self.handles.drain() {
|
||||
h.await?.context(format!("On stream: {:?}", s))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn take_outputs(&mut self) -> Result<HashMap<Stream, GstOutputs>> {
|
||||
self.abort_handle.abort();
|
||||
for (stream, handle) in self.handles.drain() {
|
||||
match handle.await {
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => return Err(anyhow!("Panicked while streaming {:?}", stream)),
|
||||
Ok(Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
let mut result: HashMap<_, _> = Default::default();
|
||||
for (stream, arc_mutex_output) in self.outputs.drain() {
|
||||
let mutex_output =
|
||||
Arc::try_unwrap(arc_mutex_output).map_err(|_| anyhow!("Failed to unwrap ARC"))?;
|
||||
let output = mutex_output.into_inner();
|
||||
result.insert(stream, output);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(crate) fn insert_outputs(&mut self, mut input: HashMap<Stream, GstOutputs>) -> Result<()> {
|
||||
self.outputs = input
|
||||
.drain()
|
||||
.map(|(s, o)| (s, Arc::new(Mutex::new(o))))
|
||||
.collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn client_connected(&self) -> bool {
|
||||
for (_, output) in self.outputs.iter() {
|
||||
if output.lock().await.is_connected() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
+140
-37
@@ -2,60 +2,163 @@
|
||||
//! Shared data between all states
|
||||
//!
|
||||
//!
|
||||
use anyhow::{Error, Result};
|
||||
use async_trait::async_trait;
|
||||
use anyhow::{Context, Result};
|
||||
use log::*;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream};
|
||||
use neolink_core::bc_protocol::StreamKind as Stream;
|
||||
|
||||
use crate::config::PauseConfig;
|
||||
use crate::rtsp::gst::RtspServer;
|
||||
use crate::config::{CameraConfig, UserConfig};
|
||||
use crate::rtsp::gst::NeoRtspServer;
|
||||
use crate::utils::AddressOrUid;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) struct Shared {
|
||||
pub(super) camera: Arc<BcCamera>,
|
||||
pub(super) name: String,
|
||||
pub(super) channel: u8,
|
||||
pub(super) addr: AddressOrUid,
|
||||
pub(super) username: String,
|
||||
pub(super) password: Option<String>,
|
||||
pub(super) streams: HashSet<Stream>,
|
||||
pub(super) rtsp: Arc<RtspServer>,
|
||||
pub(super) rtsp: Arc<NeoRtspServer>,
|
||||
pub(super) permitted_users: HashSet<String>,
|
||||
pub(super) pause: PauseConfig,
|
||||
pub(super) config: CameraConfig,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub(super) fn get_all_paths(&self) -> Vec<String> {
|
||||
self.streams
|
||||
pub(crate) async fn new(
|
||||
config: CameraConfig,
|
||||
users: &[UserConfig],
|
||||
rtsp: Arc<NeoRtspServer>,
|
||||
) -> Result<Self> {
|
||||
let addr = AddressOrUid::new(&config.camera_addr, &config.camera_uid, &config.discovery)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Could not connect to camera {}. Please check UUID or IP:Port in the config",
|
||||
config.name
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut streams: HashSet<Stream> = Default::default();
|
||||
if ["all", "both", "mainStream", "mainstream"]
|
||||
.iter()
|
||||
.flat_map(|s| self.get_paths(s))
|
||||
.collect()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
streams.insert(Stream::Main);
|
||||
}
|
||||
if ["all", "both", "subStream", "substream"]
|
||||
.iter()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
streams.insert(Stream::Sub);
|
||||
}
|
||||
if ["all", "externStream", "externstream"]
|
||||
.iter()
|
||||
.any(|&e| e == config.stream)
|
||||
{
|
||||
streams.insert(Stream::Extern);
|
||||
}
|
||||
|
||||
let all_users_hash = || users.iter().map(|u| u.name.clone()).collect();
|
||||
let permitted_users: HashSet<String> = match &config.permitted_users {
|
||||
// If in the camera config there is the user "anyone", or if none is specified but users
|
||||
// are defined at all, then we add all users to the camera's allowed list.
|
||||
Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(),
|
||||
None if !users.is_empty() => all_users_hash(),
|
||||
|
||||
// The user specified permitted_users
|
||||
Some(p) => p.iter().cloned().collect(),
|
||||
|
||||
// The user didn't specify permitted_users, and there are none defined anyway
|
||||
None => ["anonymous".to_string()].iter().cloned().collect(),
|
||||
};
|
||||
|
||||
let me = Shared {
|
||||
addr,
|
||||
streams,
|
||||
rtsp,
|
||||
permitted_users,
|
||||
config,
|
||||
};
|
||||
me.setup_streams().await?;
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
pub(super) fn get_paths(&self, stream: &Stream) -> Vec<String> {
|
||||
let mut streams = match stream {
|
||||
Stream::Main => vec![
|
||||
format!("/{}", &self.name),
|
||||
format!("/{}/mainStream", &self.name),
|
||||
],
|
||||
Stream::Sub => vec![format!("/{}/subStream", &self.name)],
|
||||
Stream::Extern => {
|
||||
vec![format!("/{}/externStream", &self.name)]
|
||||
}
|
||||
};
|
||||
// Later VLC clients seem to only support lower case streams
|
||||
let mut lowercase_streams: Vec<String> = streams.iter().map(|i| i.to_lowercase()).collect();
|
||||
streams.append(&mut lowercase_streams);
|
||||
// Set up streams on the RTSP camera
|
||||
pub(crate) async fn setup_streams(&self) -> Result<()> {
|
||||
for stream in self.streams.iter() {
|
||||
let tag = self.get_tag_for_stream(stream);
|
||||
self.rtsp.create_stream(&tag).await?;
|
||||
self.rtsp
|
||||
.add_permitted_roles(&tag, &self.permitted_users)
|
||||
.await?;
|
||||
let paths: Vec<String> = self.get_paths_for_stream(stream);
|
||||
debug!("Adding path {:?} for {}", paths, tag);
|
||||
self.rtsp.add_path(&tag, &paths).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn get_tags(&self) -> Vec<String> {
|
||||
self.streams
|
||||
.iter()
|
||||
.map(|k| self.get_tag_for_stream(k))
|
||||
.collect()
|
||||
}
|
||||
pub(crate) fn get_tag_for_stream(&self, stream: &Stream) -> String {
|
||||
format!("{}::{:?}", self.config.name, stream)
|
||||
}
|
||||
pub(crate) fn get_paths_for_stream(&self, stream: &Stream) -> Vec<String> {
|
||||
let mut streams = vec![
|
||||
// Normal case
|
||||
format!("/{}/{:?}", self.config.name, stream),
|
||||
format!("/{}/{:?}Stream", self.config.name, stream),
|
||||
format!("/{}/{:?}stream", self.config.name, stream),
|
||||
// Lower case name
|
||||
format!("/{}/{:?}", self.config.name.to_lowercase(), stream),
|
||||
format!("/{}/{:?}Stream", self.config.name.to_lowercase(), stream),
|
||||
format!("/{}/{:?}stream", self.config.name.to_lowercase(), stream),
|
||||
// Lower case stream
|
||||
format!(
|
||||
"/{}/{}",
|
||||
self.config.name,
|
||||
format!("{:?}", stream).to_lowercase()
|
||||
),
|
||||
format!(
|
||||
"/{}/{}Stream",
|
||||
self.config.name,
|
||||
format!("{:?}", stream).to_lowercase()
|
||||
),
|
||||
format!(
|
||||
"/{}/{}stream",
|
||||
self.config.name,
|
||||
format!("{:?}", stream).to_lowercase()
|
||||
),
|
||||
// Lower case both
|
||||
format!(
|
||||
"/{}/{}",
|
||||
self.config.name.to_lowercase(),
|
||||
format!("{:?}", stream).to_lowercase()
|
||||
),
|
||||
format!(
|
||||
"/{}/{}Stream",
|
||||
self.config.name.to_lowercase(),
|
||||
format!("{:?}", stream).to_lowercase()
|
||||
),
|
||||
format!(
|
||||
"/{}/{}stream",
|
||||
self.config.name.to_lowercase(),
|
||||
format!("{:?}", stream).to_lowercase()
|
||||
),
|
||||
];
|
||||
|
||||
if (self.streams.contains(&Stream::Main) && matches!(stream, Stream::Main))
|
||||
|| (!self.streams.contains(&Stream::Main) && matches!(stream, Stream::Sub))
|
||||
|| (!self.streams.contains(&Stream::Main)
|
||||
&& !self.streams.contains(&Stream::Sub)
|
||||
&& matches!(stream, Stream::Extern))
|
||||
{
|
||||
// If main stream add that
|
||||
streams.push(format!("/{}", self.config.name));
|
||||
streams.push(format!("/{}", self.config.name.to_lowercase()));
|
||||
}
|
||||
streams
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub(crate) trait CameraState: Default {
|
||||
async fn setup(&mut self, shared: &Shared) -> Result<(), Error>;
|
||||
|
||||
async fn tear_down(&mut self, shared: &Shared) -> Result<(), Error>;
|
||||
}
|
||||
+73
-159
@@ -2,199 +2,113 @@
|
||||
//
|
||||
// Data is streamed into a gstreamer source
|
||||
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use async_trait::async_trait;
|
||||
use anyhow::{anyhow, Error, Result};
|
||||
use log::*;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::{
|
||||
sync::Mutex,
|
||||
task::{self, JoinHandle},
|
||||
};
|
||||
use neolink_core::bcmedia::model::BcMedia;
|
||||
use tokio::time::{timeout, Duration};
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
use neolink_core::bc_protocol::StreamKind as Stream;
|
||||
use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream};
|
||||
|
||||
use super::{CameraState, Shared};
|
||||
use super::{camera::Camera, LoggedIn};
|
||||
|
||||
use crate::rtsp::{
|
||||
abort::AbortHandle,
|
||||
gst::{GstOutputs, InputMode, PausedSources},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Streaming {
|
||||
handles: HashMap<Stream, JoinHandle<Result<(), Error>>>,
|
||||
outputs: HashMap<Stream, Arc<Mutex<GstOutputs>>>,
|
||||
abort_handle: AbortHandle,
|
||||
pub(crate) camera: BcCamera,
|
||||
set: RwLock<JoinSet<Result<()>>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CameraState for Streaming {
|
||||
async fn setup(&mut self, shared: &Shared) -> Result<(), Error> {
|
||||
self.abort_handle.reset();
|
||||
impl Camera<Streaming> {
|
||||
pub(crate) async fn from_login(loggedin: Camera<LoggedIn>) -> Result<Camera<Streaming>, Error> {
|
||||
// Create new gst outputs
|
||||
//
|
||||
// Otherwise use those already present
|
||||
if self.outputs.is_empty() {
|
||||
let paused_source = match shared.pause.mode.as_str() {
|
||||
"test" => PausedSources::TestSrc,
|
||||
"still" => PausedSources::Still,
|
||||
"black" => PausedSources::Black,
|
||||
"none" => PausedSources::None,
|
||||
_ => {
|
||||
unreachable!()
|
||||
}
|
||||
};
|
||||
let mut set: JoinSet<Result<()>> = Default::default();
|
||||
for stream in loggedin.shared.streams.iter() {
|
||||
let tag = loggedin.shared.get_tag_for_stream(stream);
|
||||
let sender = loggedin
|
||||
.shared
|
||||
.rtsp
|
||||
.get_sender(&tag)
|
||||
.await
|
||||
.ok_or_else(|| anyhow!("Stream has not been created"))?;
|
||||
|
||||
for stream in shared.streams.iter() {
|
||||
self.outputs.entry(*stream).or_insert_with_key(|stream| {
|
||||
let paths = shared.get_paths(stream);
|
||||
let mut output = shared
|
||||
.rtsp
|
||||
.add_stream(
|
||||
paths
|
||||
.iter()
|
||||
.map(|s| s.as_str())
|
||||
.collect::<Vec<&str>>()
|
||||
.as_slice(),
|
||||
&shared.permitted_users,
|
||||
)
|
||||
.unwrap();
|
||||
output.set_paused_source(paused_source);
|
||||
Arc::new(Mutex::new(output))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Start the streams on their own thread with a shared abort handle
|
||||
let camera = &shared.camera;
|
||||
let abort_handle = self.abort_handle.clone();
|
||||
|
||||
for (stream, output) in &self.outputs {
|
||||
let stream_display_name = match stream {
|
||||
Stream::Main => "Main Stream (Clear)",
|
||||
Stream::Sub => "Sub Stream (Fluent)",
|
||||
Stream::Extern => "Extern Stream (Balanced)",
|
||||
};
|
||||
|
||||
// Lock and setup output
|
||||
{
|
||||
let mut locked_output = output.lock().await;
|
||||
locked_output.set_input_source(InputMode::Live)?;
|
||||
}
|
||||
|
||||
info!(
|
||||
"{}: Starting video stream {}",
|
||||
&shared.name, stream_display_name
|
||||
&loggedin.shared.config.name, stream_display_name
|
||||
);
|
||||
|
||||
let arc_camera = camera.clone();
|
||||
let arc_abort_handle = abort_handle.clone();
|
||||
let output_thread = output.clone();
|
||||
|
||||
let stream_thead = *stream;
|
||||
let handle = task::spawn(async move {
|
||||
let mut stream_data = arc_camera.start_video(stream_thead, 0).await?;
|
||||
while arc_abort_handle.is_live() {
|
||||
let data = stream_data.get_data().await?;
|
||||
let mut locked_output = output_thread.lock().await;
|
||||
locked_output.stream_recv(data?)?;
|
||||
let strict_thread = loggedin.shared.config.strict;
|
||||
let tag_thread = tag.clone();
|
||||
let mut stream_data = loggedin
|
||||
.state
|
||||
.camera
|
||||
.start_video(stream_thead, 0, strict_thread)
|
||||
.await?;
|
||||
set.spawn(async move {
|
||||
loop {
|
||||
// debug!("Straming: Get");
|
||||
let data = timeout(Duration::from_secs(15), stream_data.get_data()).await??;
|
||||
// debug!("Straming: Got");
|
||||
match &data {
|
||||
Ok(BcMedia::InfoV1(_)) => trace!("{}: - InfoV1", &tag_thread),
|
||||
Ok(BcMedia::InfoV2(_)) => trace!("{}: - InfoV2", &tag_thread),
|
||||
Ok(BcMedia::Iframe(_)) => trace!("{}: - Iframe", &tag_thread),
|
||||
Ok(BcMedia::Pframe(_)) => trace!("{}: - Pframe", &tag_thread),
|
||||
Ok(BcMedia::Aac(_)) => trace!("{}: - Aac", &tag_thread),
|
||||
Ok(BcMedia::Adpcm(_)) => trace!("{}: - Adpcm", &tag_thread),
|
||||
Err(_) => trace!(" - Error"),
|
||||
}
|
||||
// debug!("Straming: Send");
|
||||
sender.send(data?).await?;
|
||||
// debug!("Straming: Sent");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.handles.entry(*stream).or_insert_with(|| handle);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(Camera {
|
||||
shared: loggedin.shared,
|
||||
state: Streaming {
|
||||
camera: loggedin.state.camera,
|
||||
set: RwLock::new(set),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async fn tear_down(&mut self, shared: &Shared) -> Result<(), Error> {
|
||||
self.abort_handle.abort();
|
||||
pub(crate) async fn stop(self) -> Result<Camera<LoggedIn>> {
|
||||
self.state.set.into_inner().abort_all();
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
camera: self.state.camera,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if !self.handles.is_empty() {
|
||||
for path in shared.get_all_paths().iter() {
|
||||
if let Err(e) = shared.rtsp.remove_stream(&[path]) {
|
||||
return Err(anyhow!("Failed to shutdown RTSP Path {}: {:?}", path, e));
|
||||
pub(crate) async fn join(&self) -> Result<()> {
|
||||
let mut locked_threads = self.state.set.write().await;
|
||||
while let Some(res) = locked_threads.join_next().await {
|
||||
match res {
|
||||
Err(e) => {
|
||||
locked_threads.abort_all();
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
|
||||
for (stream, handle) in self.handles.drain() {
|
||||
match handle.await {
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => return Err(anyhow!("Panicked while streaming {:?}", stream)),
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(e)) => {
|
||||
locked_threads.abort_all();
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Streaming {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl Streaming {
|
||||
pub(crate) async fn is_running(&mut self) -> Result<()> {
|
||||
if self.handles.iter().all(|(_, h)| !h.is_finished()) && self.abort_handle.is_live() {
|
||||
return Ok(());
|
||||
}
|
||||
if !self.abort_handle.is_live() {
|
||||
return Err(anyhow!("Stream aborted"));
|
||||
}
|
||||
for (s, h) in self.handles.drain() {
|
||||
h.await?.context(format!("On stream: {:?}", s))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn take_outputs(&mut self) -> Result<HashMap<Stream, GstOutputs>> {
|
||||
info!("Streaming take_outputs");
|
||||
self.abort_handle.abort();
|
||||
for (stream, handle) in self.handles.drain() {
|
||||
match handle.await {
|
||||
Ok(Err(e)) => return Err(e),
|
||||
Err(_) => return Err(anyhow!("Panicked while streaming {:?}", stream)),
|
||||
Ok(Ok(_)) => {}
|
||||
}
|
||||
}
|
||||
let mut result: HashMap<_, _> = Default::default();
|
||||
for (stream, arc_mutex_output) in self.outputs.drain() {
|
||||
let mutex_output =
|
||||
Arc::try_unwrap(arc_mutex_output).map_err(|_| anyhow!("Failed to unwrap ARC"))?;
|
||||
let output = mutex_output.into_inner();
|
||||
result.insert(stream, output);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(crate) fn insert_outputs(&mut self, mut input: HashMap<Stream, GstOutputs>) -> Result<()> {
|
||||
self.outputs = input
|
||||
.drain()
|
||||
.map(|(s, o)| (s, Arc::new(Mutex::new(o))))
|
||||
.collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn client_connected(&self) -> bool {
|
||||
for (_, output) in self.outputs.iter() {
|
||||
if output.lock().await.is_connected() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) async fn can_pause(&self) -> bool {
|
||||
for (_, output) in self.outputs.iter() {
|
||||
if !output.lock().await.has_last_iframe() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
pub(crate) fn get_camera(&self) -> &BcCamera {
|
||||
&self.state.camera
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use structopt::StructOpt;
|
||||
use clap::Parser;
|
||||
|
||||
fn onoff_parse(src: &str) -> Result<bool> {
|
||||
match src {
|
||||
@@ -13,11 +13,11 @@ fn onoff_parse(src: &str) -> Result<bool> {
|
||||
}
|
||||
|
||||
/// The status-light command will control the blue status light on the camera
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera to change the lights of. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// Whether to turn the light on or off
|
||||
#[structopt(parse(try_from_str = onoff_parse), name = "on|off")]
|
||||
#[arg(value_parser = onoff_parse, name = "on|off")]
|
||||
pub on: bool,
|
||||
}
|
||||
+7
-6
@@ -1,5 +1,6 @@
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use structopt::StructOpt;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// The talk command will send audio for the camera to say
|
||||
///
|
||||
@@ -7,19 +8,19 @@ use structopt::StructOpt;
|
||||
/// This should be ok with most common formats.
|
||||
///
|
||||
/// `gst-launch` can be used to prepare this data
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera to talk through. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// The path to the audio file.
|
||||
#[structopt(short, long, parse(from_os_str), conflicts_with = "microphone")]
|
||||
#[arg(short, long, value_parser = PathBuf::from_str, conflicts_with = "microphone")]
|
||||
pub file_path: Option<PathBuf>,
|
||||
/// Use the microphone as the source. Defaults to autoaudiosrc - Which microphone depends
|
||||
/// on [gstreamer](https://gstreamer.freedesktop.org/documentation/autodetect/autoaudiosrc.html?gi-language=c#autoaudiosrc-page)
|
||||
#[structopt(short, long, conflicts_with = "file_path")]
|
||||
#[arg(short, long, conflicts_with = "file_path")]
|
||||
pub microphone: bool,
|
||||
/// Use a specific microphone like "alsasrc device=hw:1"
|
||||
#[structopt(
|
||||
#[arg(
|
||||
short,
|
||||
long,
|
||||
default_value = "autoaudiosrc",
|
||||
@@ -27,6 +28,6 @@ pub struct Opt {
|
||||
)]
|
||||
pub input_src: String,
|
||||
/// Use to change the volume of the input
|
||||
#[structopt(short, long, default_value = "1.0")]
|
||||
#[arg(short, long, default_value = "1.0")]
|
||||
pub volume: f32,
|
||||
}
|
||||
+8
-9
@@ -166,15 +166,14 @@ fn create_pipeline(
|
||||
// provide the format we request.
|
||||
// This can be set after linking the two objects, because format negotiation between
|
||||
// both elements will happen during pre-rolling of the pipeline.
|
||||
appsink.set_caps(Some(&Caps::new_simple(
|
||||
"audio/x-adpcm",
|
||||
&[
|
||||
("layout", &"dvi"),
|
||||
("block_align", &(block_align as i32)),
|
||||
("channels", &(1i32)),
|
||||
("rate", &(sample_rate as i32)),
|
||||
],
|
||||
)));
|
||||
appsink.set_caps(Some(
|
||||
&Caps::builder("audio/x-adpcm")
|
||||
.field("layout", "dvi")
|
||||
.field("block_align", block_align as i32)
|
||||
.field("channels", 1i32)
|
||||
.field("rate", sample_rate as i32)
|
||||
.build(),
|
||||
));
|
||||
|
||||
Ok(pipeline)
|
||||
}
|
||||
+69
-34
@@ -4,17 +4,27 @@ use log::*;
|
||||
|
||||
use super::config::{CameraConfig, Config};
|
||||
use anyhow::{anyhow, Context, Error, Result};
|
||||
use neolink_core::bc_protocol::{BcCamera, DiscoveryMethods};
|
||||
use std::fmt::{Display, Error as FmtError, Formatter};
|
||||
use neolink_core::bc_protocol::{
|
||||
BcCamera, BcCameraOpt, ConnectionProtocol, Credentials, DiscoveryMethods, MaxEncryption,
|
||||
};
|
||||
use std::{
|
||||
fmt::{Display, Error as FmtError, Formatter},
|
||||
net::{IpAddr, ToSocketAddrs},
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String, DiscoveryMethods),
|
||||
AddressWithUid(String, String, DiscoveryMethods),
|
||||
}
|
||||
|
||||
impl Display for AddressOrUid {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
|
||||
match self {
|
||||
AddressOrUid::AddressWithUid(addr, uid, _) => {
|
||||
write!(f, "Address: {}, UID: {}", addr, uid)
|
||||
}
|
||||
AddressOrUid::Address(host) => write!(f, "Address: {}", host),
|
||||
AddressOrUid::Uid(host, _) => write!(f, "UID: {}", host),
|
||||
}
|
||||
@@ -26,43 +36,66 @@ impl AddressOrUid {
|
||||
pub(crate) fn new(
|
||||
address: &Option<String>,
|
||||
uid: &Option<String>,
|
||||
disc_method: &str,
|
||||
method: &DiscoveryMethods,
|
||||
) -> Result<Self, Error> {
|
||||
match (address, uid) {
|
||||
(None, None) => Err(anyhow!("Neither address or uid given")),
|
||||
(Some(_), Some(_)) => Err(anyhow!("Either address or uid should be given not both")),
|
||||
(Some(host), Some(uid)) => Ok(AddressOrUid::AddressWithUid(
|
||||
host.clone(),
|
||||
uid.clone(),
|
||||
*method,
|
||||
)),
|
||||
(Some(host), None) => Ok(AddressOrUid::Address(host.clone())),
|
||||
(None, Some(host)) => {
|
||||
let method = match disc_method.to_lowercase().as_str() {
|
||||
"none" => DiscoveryMethods::None,
|
||||
"local" => DiscoveryMethods::Local,
|
||||
"remote" => DiscoveryMethods::Remote,
|
||||
"relay" => DiscoveryMethods::Relay,
|
||||
n => {
|
||||
warn!("Unrecognised discovery method: {}. Using Local", n);
|
||||
DiscoveryMethods::Local
|
||||
}
|
||||
};
|
||||
Ok(AddressOrUid::Uid(host.clone(), method))
|
||||
}
|
||||
(None, Some(host)) => Ok(AddressOrUid::Uid(host.clone(), *method)),
|
||||
}
|
||||
}
|
||||
|
||||
// Convience method to get the BcCamera with the appropiate method
|
||||
pub(crate) async fn connect_camera<T: Into<String>, U: Into<String>>(
|
||||
// from a camera_config
|
||||
pub(crate) async fn connect_camera(
|
||||
&self,
|
||||
channel_id: u8,
|
||||
username: T,
|
||||
passwd: Option<U>,
|
||||
camera_config: &CameraConfig,
|
||||
) -> Result<BcCamera, Error> {
|
||||
match self {
|
||||
AddressOrUid::Address(host) => {
|
||||
Ok(BcCamera::new_with_addr(host, channel_id, username, passwd).await?)
|
||||
let (port, addrs) = {
|
||||
if let Some(addr_str) = camera_config.camera_addr.as_ref() {
|
||||
match addr_str.to_socket_addrs() {
|
||||
Ok(addr_iter) => {
|
||||
let mut port = None;
|
||||
let mut ipaddrs = vec![];
|
||||
for addr in addr_iter {
|
||||
port = Some(addr.port());
|
||||
ipaddrs.push(addr.ip());
|
||||
}
|
||||
Ok((port, ipaddrs))
|
||||
}
|
||||
Err(_) => match IpAddr::from_str(addr_str) {
|
||||
Ok(ip) => Ok((None, vec![ip])),
|
||||
Err(_) => Err(anyhow!("Could not parse address in config")),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
Ok((None, vec![]))
|
||||
}
|
||||
AddressOrUid::Uid(host, method) => {
|
||||
Ok(BcCamera::new_with_uid(host, channel_id, username, passwd, *method).await?)
|
||||
}
|
||||
}
|
||||
}?;
|
||||
|
||||
let options = BcCameraOpt {
|
||||
name: camera_config.name.clone(),
|
||||
channel_id: camera_config.channel_id,
|
||||
addrs,
|
||||
port,
|
||||
uid: camera_config.camera_uid.clone(),
|
||||
protocol: ConnectionProtocol::TcpUdp,
|
||||
discovery: camera_config.discovery,
|
||||
aux_printing: camera_config.print_format,
|
||||
credentials: Credentials {
|
||||
username: camera_config.username.clone(),
|
||||
password: camera_config.password.clone(),
|
||||
},
|
||||
};
|
||||
|
||||
trace!("Camera Info: {:?}", options);
|
||||
|
||||
Ok(BcCamera::new(&options).await?)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,11 +117,7 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
);
|
||||
|
||||
let camera = camera_addr
|
||||
.connect_camera(
|
||||
camera_config.channel_id,
|
||||
&camera_config.username,
|
||||
camera_config.password.as_ref(),
|
||||
)
|
||||
.connect_camera(camera_config)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
@@ -97,9 +126,15 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
)
|
||||
})?;
|
||||
|
||||
let max_encryption = match camera_config.max_encryption.to_lowercase().as_str() {
|
||||
"none" => MaxEncryption::None,
|
||||
"bcencrypt" => MaxEncryption::BcEncrypt,
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login()
|
||||
.login_with_maxenc(max_encryption)
|
||||
.await
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
|
||||
|
||||
Reference in new issue
Block a user