Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42ee790512 | ||
|
|
ae9d204718 | ||
|
|
5c7de6181c | ||
|
|
268303a0a2 | ||
|
|
acc063e325 | ||
|
|
e384fb6153 | ||
|
|
f6085cff1f | ||
|
|
94ffc54325 | ||
|
|
ce89a6dfbc | ||
|
|
6925736030 | ||
|
|
edfacc7eba | ||
|
|
786218a114 | ||
|
|
52ad743bea | ||
|
|
0331945730 | ||
|
|
790807c016 | ||
|
|
45e08e6d7d | ||
|
|
5b3f845c83 | ||
|
|
4d6d5c5ac5 | ||
|
|
5583ea0f9a | ||
|
|
4286e75ca6 |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: qesoul
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
Generated
+43
-31
@@ -459,9 +459,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "delegate"
|
||||
version = "0.9.0"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d358e0ec5c59a5e1603b933def447096886121660fc680dc1e64a0753981fe3c"
|
||||
checksum = "0ee5df75c70b95bd3aacc8e2fd098797692fb1d54121019c4de481e42f04c8a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -1251,6 +1251,15 @@ dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.6"
|
||||
@@ -1408,7 +1417,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink"
|
||||
version = "0.5.13"
|
||||
version = "0.5.15"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.21.2",
|
||||
@@ -1424,7 +1433,7 @@ dependencies = [
|
||||
"gstreamer-rtsp-server",
|
||||
"heck",
|
||||
"is_sorted",
|
||||
"itertools",
|
||||
"itertools 0.11.0",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"neolink_core",
|
||||
@@ -1443,7 +1452,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "neolink_core"
|
||||
version = "0.5.13"
|
||||
version = "0.5.15"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"assert_matches",
|
||||
@@ -1641,12 +1650,6 @@ version = "0.3.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
|
||||
|
||||
[[package]]
|
||||
name = "pollster"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.17"
|
||||
@@ -1719,7 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools",
|
||||
"itertools 0.10.5",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 1.0.109",
|
||||
@@ -1860,17 +1863,17 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rumqttc"
|
||||
version = "0.20.0"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b616bf8b706c2a6235604f5d93f9578c37d0c6161e13898b68a1da4af2d812c"
|
||||
checksum = "f2433b134712bc17a6f85a35e06b901e6e8d0bb20b5367e1121e6fedc140c0ac"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"flume",
|
||||
"futures",
|
||||
"log",
|
||||
"pollster",
|
||||
"rustls-native-certs",
|
||||
"rustls-pemfile",
|
||||
"rustls-webpki 0.100.1",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
@@ -1892,14 +1895,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.20.8"
|
||||
version = "0.21.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"
|
||||
checksum = "79ea77c539259495ce8ca47f53e66ae0330a8819f67e23ac96ca02f50e7b7d36"
|
||||
dependencies = [
|
||||
"log",
|
||||
"ring",
|
||||
"rustls-webpki 0.101.1",
|
||||
"sct",
|
||||
"webpki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1923,6 +1926,26 @@ dependencies = [
|
||||
"base64 0.21.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.100.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6207cd5ed3d8dca7816f8f3725513a34609c0c765bf652b8c3cb4cfd87db46b"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.101.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15f36a6828982f422756984e47912a7a51dcbc2a197aa791158f8ca61cd8204e"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.12"
|
||||
@@ -2322,13 +2345,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-rustls"
|
||||
version = "0.23.4"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"
|
||||
checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
|
||||
dependencies = [
|
||||
"rustls",
|
||||
"tokio",
|
||||
"webpki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2740,16 +2762,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki"
|
||||
version = "0.22.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.2.8"
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.5.13"
|
||||
version = "0.5.15"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -26,12 +26,12 @@ gstreamer-rtsp = "0.20.0"
|
||||
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
|
||||
heck = "0.4.1"
|
||||
is_sorted = "0.1.1"
|
||||
itertools = "0.10.5"
|
||||
itertools = "0.11.0"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
neolink_core = { path = "crates/core", version = "0.5.13" }
|
||||
neolink_core = { path = "crates/core", version = "0.5.15" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.20.0"
|
||||
rumqttc = "0.22.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
serde_json = "1.0.96"
|
||||
time = "0.3.20"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Neolink
|
||||
|
||||

|
||||
[](https://deps.rs/repo/github/QuantumEntangledAndy/neolink)
|
||||
|
||||
Neolink is a small program that acts as a proxy between Reolink IP cameras and
|
||||
normal RTSP clients.
|
||||
@@ -31,7 +32,7 @@ features not yet in upstream master.
|
||||
|
||||
**Minor Features**:
|
||||
|
||||
- Improved error messages when your missing gstreamer plugins
|
||||
- Improved error messages when 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
|
||||
@@ -93,7 +94,7 @@ uid = "BCDEF0123456789A"
|
||||
address = "192.168.1.10"
|
||||
```
|
||||
|
||||
Create a text file with called `neolink.toml` in the same folder as the
|
||||
Create a text file called `neolink.toml` in the same folder as the
|
||||
neolink binary. With your config options.
|
||||
|
||||
When ready start `neolink` with the following command
|
||||
@@ -114,20 +115,20 @@ The IP is discovered with four methods
|
||||
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
|
||||
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.
|
||||
2. Remote discovery: Here we 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.
|
||||
for the camera to be able to contact reolink.
|
||||
|
||||
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 to connect to us. Once the camera either polls/recieves a connect
|
||||
request from the reolink servers the camera will initiate a connection
|
||||
to neolink. This requires that our IP and reolink are reachable from
|
||||
the camera.
|
||||
|
||||
4. Relay: In this case we request that reolink relay our connection. Neolink
|
||||
@@ -158,7 +159,7 @@ See the sample config file for more details.
|
||||
|
||||
### MQTT
|
||||
|
||||
To use mqtt you will to adjust your config file as such:
|
||||
To use mqtt you will need to adjust your config file as such:
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
@@ -193,7 +194,8 @@ Control messages:
|
||||
- `/control/ptz [up|down|left|right|in|out] (amount)` Control the PTZ
|
||||
movements, amount defaults to 32.0
|
||||
- `/control/ptz/preset [id]` Move the camera to a PTZ preset
|
||||
- `/control/ptz/assign [id] [name]` Set the current PTZ position to a preset ID and name
|
||||
- `/control/ptz/assign [id] [name]` Set the current PTZ position to a preset ID
|
||||
and name
|
||||
- `/control/pir [on|off]`
|
||||
|
||||
Status Messages:
|
||||
@@ -206,10 +208,13 @@ Status Messages:
|
||||
- `/status/battery_level` A simple % value of current battery level
|
||||
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||
pir status
|
||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion and `off` for still
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded version of the
|
||||
PTZ presets
|
||||
- `/status/preview` a base64 encoded camera image updated every 0.5s
|
||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion
|
||||
and `off` for still
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded
|
||||
version of the PTZ presets
|
||||
- `/status/preview` a base64 encoded camera image updated every 0.5s. Not
|
||||
every camera supports the snapshot command needed for this. In such cases
|
||||
there will be no `/status/preview` message.
|
||||
|
||||
Query Messages:
|
||||
|
||||
@@ -220,7 +225,7 @@ Query Messages:
|
||||
### MQTT Disable Features
|
||||
|
||||
Certain features like preview and motion detection may not be desired
|
||||
you can disable them by them with the following config options.
|
||||
you can disable them with the following config options.
|
||||
Disabling these may help to conserve battery
|
||||
|
||||
```toml
|
||||
@@ -241,8 +246,9 @@ enable_preview = false # preview image in `/status/preview`
|
||||
|
||||
#### MQTT Discovery
|
||||
|
||||
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery) is partially supported.
|
||||
Currently, discovery is opt-in and camera features must be manually specified.
|
||||
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery)
|
||||
is partially supported. Currently, discovery is opt-in and camera features
|
||||
must be manually specified.
|
||||
|
||||
```toml
|
||||
[cameras.mqtt]
|
||||
@@ -255,15 +261,20 @@ Currently, discovery is opt-in and camera features must be manually specified.
|
||||
Avaliable features are:
|
||||
|
||||
- `floodlight`: This adds a light control to home assistant
|
||||
- `camera`: This adds a camera preview to home assistant. It is only updated every 0.5s and cannot be much more than that since it is updated over mqtt not over RTSP
|
||||
- `led`: This adds a switch to chage the LED status light on/off to home assistant
|
||||
- `ir`: This adds a selection switch to chage the IR light on/off/auto to home assistant
|
||||
- `camera`: This adds a camera preview to home assistant. It is only updated
|
||||
every 0.5s and cannot be much more than that since it is updated over mqtt
|
||||
not over RTSP. Not every camera supports the snapshot command needed for
|
||||
this. In such cases there will be no `/status/preview` message.
|
||||
- `led`: This adds a switch to chage the LED status light on/off to home
|
||||
assistant
|
||||
- `ir`: This adds a selection switch to chage the IR light on/off/auto to home
|
||||
assistant
|
||||
- `motion`: This adds a motion detection binary sensor to home assistant
|
||||
- `reboot`: This adds a reboot button to home assistant
|
||||
- `pt`: This adds a selection of buttons to control the pan and tilt of the camera
|
||||
- `reboot`: This adds a reboot button to home assistant
|
||||
- `pt`: This adds a selection of buttons to control the pan and tilt of the
|
||||
camera
|
||||
- `battery`: This adds a battery level sensor to home assistant
|
||||
|
||||
|
||||
### Pause
|
||||
|
||||
To use the pause feature you will need to adjust your config file as such:
|
||||
@@ -290,8 +301,8 @@ Then start the rtsp server as usual:
|
||||
|
||||
### 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
|
||||
If you have a battery camera and would like to see the battery messages in the
|
||||
log, add the following to your config
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
@@ -299,8 +310,8 @@ log add the following to your config
|
||||
print_format = "Human"
|
||||
```
|
||||
|
||||
You can also print into xml format with `print_format = "Xml"` which can then b
|
||||
passed by a script for processing.
|
||||
You can also print into xml format with `print_format = "Xml"` which can then
|
||||
be passed by a script for processing.
|
||||
|
||||
### Docker
|
||||
|
||||
@@ -316,7 +327,8 @@ docker pull quantumentangledandy/neolink
|
||||
# --network host is only needed if you require to connect
|
||||
# via local broadcasts. If you can connect via any other
|
||||
# method then normal bridge mode should work fine
|
||||
# and you can ommit this option
|
||||
# and you can ommit this option. Not all OSes support
|
||||
# network=host, notably macos lacks this option.
|
||||
docker run --network host --volume=$PWD/config.toml:/etc/neolink.toml quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
@@ -334,6 +346,11 @@ 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.
|
||||
|
||||
Some cameras do not support the SNAP command that is used to generate the image
|
||||
on the camera. If this is the case with your camera you can try the
|
||||
`--use-stream` option which will instead create a jpeg by transcoding the video
|
||||
stream.
|
||||
|
||||
## License
|
||||
|
||||
Neolink is free software, released under the GNU Affero General Public License
|
||||
@@ -341,3 +358,9 @@ v3.
|
||||
|
||||
This means that if you incorporate it into a piece of software available over
|
||||
the network, you must offer that software's source code to your users.
|
||||
|
||||
# Donations
|
||||
|
||||
If you find this code helpful please consider supporting development.
|
||||
|
||||
[](https://ko-fi.com/G2G5HOYIZ)
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.13"
|
||||
version = "0.5.15"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
@@ -13,7 +13,7 @@ cfb-mode = "0.8.2"
|
||||
cookie-factory = "0.3.2"
|
||||
crc32fast = "1.3.2"
|
||||
crossbeam-channel = "0.5.8"
|
||||
delegate = "0.9.0"
|
||||
delegate = "0.10.0"
|
||||
err-derive = "0.3.1"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
|
||||
@@ -126,6 +126,7 @@ impl BcCamera {
|
||||
/// 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 discovery = Discovery::new().await?;
|
||||
if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol {
|
||||
let mut sockets = vec![];
|
||||
match options.port {
|
||||
@@ -145,7 +146,7 @@ impl BcCamera {
|
||||
info!("{}: Trying TCP discovery", options.name);
|
||||
for socket in sockets.drain(..) {
|
||||
let channel_id: u8 = options.channel_id;
|
||||
if let Ok(addr) = Discovery::check_tcp(socket, channel_id).await.map(|_| {
|
||||
if let Ok(addr) = discovery.check_tcp(socket, channel_id).await.map(|_| {
|
||||
info!("{}: TCP Discovery success at {:?}", options.name, &socket);
|
||||
socket
|
||||
}) {
|
||||
@@ -184,10 +185,16 @@ impl BcCamera {
|
||||
DiscoveryMethods::Debug => (false, false, false, true),
|
||||
};
|
||||
|
||||
let reg_result = if allow_remote || allow_map || allow_relay {
|
||||
Some(discovery.get_registration(uid).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if allow_local {
|
||||
let uid_local = uid.clone();
|
||||
info!("{}: Trying local discovery", options.name);
|
||||
let result = Discovery::local(&uid_local, Some(sockets)).await;
|
||||
let result = discovery.local(&uid_local, Some(sockets)).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Local discovery success {} at {}",
|
||||
@@ -201,7 +208,9 @@ impl BcCamera {
|
||||
if allow_remote {
|
||||
let uid_remote = uid.clone();
|
||||
info!("{}: Trying remote discovery", options.name);
|
||||
let result = Discovery::remote(&uid_remote).await;
|
||||
let result = discovery
|
||||
.remote(&uid_remote, reg_result.as_ref().unwrap())
|
||||
.await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Remote discovery success {} at {}",
|
||||
@@ -215,7 +224,7 @@ impl BcCamera {
|
||||
if allow_map {
|
||||
let uid_map = uid.clone();
|
||||
info!("{}: Trying map discovery", options.name);
|
||||
let result = Discovery::map(&uid_map).await;
|
||||
let result = discovery.map(reg_result.as_ref().unwrap()).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Map success {} at {}",
|
||||
@@ -229,7 +238,7 @@ impl BcCamera {
|
||||
if allow_relay {
|
||||
let uid_relay = uid.clone();
|
||||
info!("{}: Trying relay discovery", options.name);
|
||||
let result = Discovery::relay(&uid_relay).await;
|
||||
let result = discovery.relay(reg_result.as_ref().unwrap()).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Relay success {} at {}",
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::bcudp::xml::*;
|
||||
use crate::{Error, Result};
|
||||
use futures::{
|
||||
sink::SinkExt,
|
||||
stream::{FuturesUnordered, StreamExt},
|
||||
stream::{FuturesUnordered, Stream, StreamExt},
|
||||
};
|
||||
use lazy_static::lazy_static;
|
||||
use local_ip_address::local_ip;
|
||||
@@ -34,7 +34,7 @@ use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::udp::UdpFramed;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct RegisterResult {
|
||||
pub(crate) struct RegisterResult {
|
||||
reg: SocketAddr,
|
||||
dev: Option<SocketAddr>,
|
||||
dmap: Option<SocketAddr>,
|
||||
@@ -57,8 +57,6 @@ struct UidLookupResults {
|
||||
relay: SocketAddr,
|
||||
}
|
||||
|
||||
pub(crate) struct Discovery {}
|
||||
|
||||
const MTU: u32 = 1350;
|
||||
lazy_static! {
|
||||
static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [
|
||||
@@ -154,10 +152,8 @@ impl Discoverer {
|
||||
})
|
||||
}
|
||||
|
||||
async fn into_socket(self) -> (Arc<UdpSocket>, JoinSet<()>) {
|
||||
let socket = self.socket.clone();
|
||||
let handle = self.handle.into_inner();
|
||||
(socket, handle)
|
||||
async fn get_socket(&self) -> Arc<UdpSocket> {
|
||||
self.socket.clone()
|
||||
}
|
||||
|
||||
async fn subscribe(&self, tid: u32) -> Result<Receiver<Result<(UdpDiscovery, SocketAddr)>>> {
|
||||
@@ -214,32 +210,6 @@ impl Discoverer {
|
||||
&self.local_addr
|
||||
}
|
||||
|
||||
async fn retry_send_multi<F, T>(
|
||||
&self,
|
||||
mut disc: UdpDiscovery,
|
||||
dests: &[SocketAddr],
|
||||
map: F,
|
||||
) -> Result<T>
|
||||
where
|
||||
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
||||
{
|
||||
trace!("Retrying send");
|
||||
disc.tid = 0; // Must be random to avoid simulatenous subscription errors
|
||||
let mut set = FuturesUnordered::new();
|
||||
for dest in dests.iter() {
|
||||
set.push(self.retry_send(disc.clone(), *dest, &map));
|
||||
}
|
||||
|
||||
// Get what ever completes first
|
||||
while let Some(result) = set.next().await {
|
||||
trace!("Result: {}", result.is_ok());
|
||||
if let Ok(ret) = result {
|
||||
return Ok(ret);
|
||||
}
|
||||
}
|
||||
Err(Error::DiscoveryTimeout)
|
||||
}
|
||||
|
||||
async fn retry_send<F, T>(&self, mut disc: UdpDiscovery, dest: SocketAddr, map: F) -> Result<T>
|
||||
where
|
||||
F: Fn(UdpDiscovery, SocketAddr) -> Option<T>,
|
||||
@@ -357,13 +327,10 @@ impl Discoverer {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// This function will contact the p2p relay servers
|
||||
///
|
||||
/// It will ask each of the servers for details on a specific UID
|
||||
///
|
||||
/// On success it returns the M2cQr that the p2p relay
|
||||
/// server has about the UID
|
||||
async fn uid_loopup(&self, uid: &str) -> Result<UidLookupResults> {
|
||||
async fn uid_lookup_all<'a>(
|
||||
&'a self,
|
||||
uid: &'a str,
|
||||
) -> Result<impl Stream<Item = UidLookupResults> + 'a> {
|
||||
let task = tokio::task::spawn_blocking(move || {
|
||||
let mut addrs = vec![];
|
||||
for p2p_relay in P2P_RELAY_HOSTNAMES.iter() {
|
||||
@@ -376,8 +343,22 @@ impl Discoverer {
|
||||
}
|
||||
addrs
|
||||
});
|
||||
let addrs = timeout(*MAXIMUM_WAIT, task).await??;
|
||||
let mut addrs = timeout(*MAXIMUM_WAIT, task).await??;
|
||||
trace!("Uid lookup to: {:?}", addrs);
|
||||
|
||||
Ok(addrs
|
||||
.drain(..)
|
||||
.map(|addr| self.uid_lookup(uid, addr))
|
||||
.collect::<FuturesUnordered<_>>()
|
||||
.filter_map(|f| async { f.ok() }))
|
||||
}
|
||||
/// This function will contact the p2p relay servers
|
||||
///
|
||||
/// It will ask each of the servers for details on a specific UID
|
||||
///
|
||||
/// On success it will returns an async iter that yields the M2cQr that the p2p relay
|
||||
/// server has about the UID
|
||||
async fn uid_lookup(&self, uid: &str, addr: SocketAddr) -> Result<UidLookupResults> {
|
||||
let msg = UdpDiscovery {
|
||||
tid: 0,
|
||||
payload: UdpXml {
|
||||
@@ -390,7 +371,7 @@ impl Discoverer {
|
||||
};
|
||||
trace!("Sending look up {:?}", msg);
|
||||
let (packet, _) = self
|
||||
.retry_send_multi(msg, addrs.as_slice(), |bc, addr| match bc {
|
||||
.retry_send(msg, addr, |bc, addr| match bc {
|
||||
UdpDiscovery {
|
||||
tid: _,
|
||||
payload:
|
||||
@@ -939,11 +920,49 @@ impl Discoverer {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Discovery {
|
||||
discoverer: Discoverer,
|
||||
client_id: i32,
|
||||
}
|
||||
|
||||
impl Discovery {
|
||||
pub(crate) async fn new() -> Result<Self> {
|
||||
Ok(Self {
|
||||
discoverer: Discoverer::new().await?,
|
||||
client_id: generate_cid(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn get_registration(&self, uid: &str) -> Result<RegisterResult> {
|
||||
let lookups = self.discoverer.uid_lookup_all(uid).await?;
|
||||
|
||||
let reg_result = Box::pin(
|
||||
lookups
|
||||
.then(|lookup| {
|
||||
let discoverer = &self.discoverer;
|
||||
let client_id = self.client_id;
|
||||
async move {
|
||||
trace!("lookup: {:?}", lookup);
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
reg_result
|
||||
}
|
||||
})
|
||||
.filter_map(|f| async { f.ok() }),
|
||||
)
|
||||
.next()
|
||||
.await
|
||||
.ok_or(Error::Other(
|
||||
"No reolink registers returned valid device data.",
|
||||
))?;
|
||||
|
||||
Ok(reg_result)
|
||||
}
|
||||
|
||||
// Check if TCP is possible
|
||||
//
|
||||
// To do this we send a dummy login and see if it replies with any BC packet
|
||||
pub(crate) async fn check_tcp(addr: SocketAddr, channel_id: u8) -> Result<()> {
|
||||
pub(crate) async fn check_tcp(&self, addr: SocketAddr, channel_id: u8) -> Result<()> {
|
||||
let username = "admin";
|
||||
let password = Some("123456");
|
||||
let mut tcp_source =
|
||||
@@ -979,18 +998,17 @@ impl Discovery {
|
||||
|
||||
// Perform UDP broadcast lookup and connection
|
||||
pub(crate) async fn local(
|
||||
&self,
|
||||
uid: &str,
|
||||
mut optional_addrs: Option<Vec<SocketAddr>>,
|
||||
) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
let mut dests = get_broadcasts(&[2015, 2018])?;
|
||||
if let Some(mut optional_addrs) = optional_addrs.take() {
|
||||
trace!("Also sending to {:?}", optional_addrs);
|
||||
dests.append(&mut optional_addrs);
|
||||
}
|
||||
let discoverer_ref = &discoverer;
|
||||
let discoverer_ref = &self.discoverer;
|
||||
let client_id = self.client_id;
|
||||
let mut futures = FuturesUnordered::new();
|
||||
for addr in dests.iter().copied() {
|
||||
futures.push(async move {
|
||||
@@ -1018,10 +1036,9 @@ impl Discovery {
|
||||
drop(futures);
|
||||
// drop(discoverer_ref);
|
||||
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
camera_id: connect_result.camera_id,
|
||||
client_id: connect_result.client_id,
|
||||
@@ -1039,33 +1056,22 @@ impl Discovery {
|
||||
// This method is best when broadcasts are not possible but we can contact the camera
|
||||
// directly
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn remote(uid: &str) -> Result<DiscoveryResult> {
|
||||
pub(crate) async fn remote(
|
||||
&self,
|
||||
uid: &str,
|
||||
reg_result: &RegisterResult,
|
||||
) -> Result<DiscoveryResult> {
|
||||
trace!("Start remote");
|
||||
let mut discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
let reg_addr = lookup.reg;
|
||||
let relay_addr = lookup.relay;
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = tokio::select! {
|
||||
v = discoverer.client_initiated_dev(®_result) => {v},
|
||||
v = discoverer.device_initiated_dev(®_result) => {v},
|
||||
v = self.discoverer.client_initiated_dev(reg_result) => {v},
|
||||
v = self.discoverer.device_initiated_dev(reg_result) => {v},
|
||||
}?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
client_id,
|
||||
client_id: self.client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
@@ -1078,27 +1084,15 @@ impl Discovery {
|
||||
//
|
||||
// This method should be used when the camera is behind a NAT or firewall but we are
|
||||
// reachable
|
||||
pub(crate) async fn map(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
|
||||
let client_id = generate_cid();
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = discoverer.device_initiated_map(®_result).await?;
|
||||
pub(crate) async fn map(&self, reg_result: &RegisterResult) -> Result<DiscoveryResult> {
|
||||
let connect_result = self.discoverer.device_initiated_map(reg_result).await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
client_id,
|
||||
client_id: self.client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
@@ -1108,27 +1102,15 @@ impl Discovery {
|
||||
// This method should work if all else fails but it will require
|
||||
// us to trust reolink with our data once more...
|
||||
//
|
||||
pub(crate) async fn relay(uid: &str) -> Result<DiscoveryResult> {
|
||||
let discoverer = Discoverer::new().await?;
|
||||
let client_id = generate_cid();
|
||||
|
||||
trace!("client_id: {}", client_id);
|
||||
|
||||
let lookup = discoverer.uid_loopup(uid).await?;
|
||||
trace!("lookup: {:?}", lookup);
|
||||
|
||||
let reg_result = discoverer.register_address(uid, client_id, &lookup).await?;
|
||||
trace!("reg_result: {:?}", reg_result);
|
||||
|
||||
let connect_result = discoverer.client_initiated_relay(®_result).await?;
|
||||
pub(crate) async fn relay(&self, reg_result: &RegisterResult) -> Result<DiscoveryResult> {
|
||||
let connect_result = self.discoverer.client_initiated_relay(reg_result).await?;
|
||||
trace!("connect_result: {:?}", connect_result);
|
||||
|
||||
let (socket, keep_alive_tasks) = discoverer.into_socket().await;
|
||||
let socket = self.discoverer.get_socket().await;
|
||||
Ok(DiscoveryResult {
|
||||
socket,
|
||||
keep_alive_tasks,
|
||||
addr: connect_result.addr,
|
||||
client_id,
|
||||
client_id: self.client_id,
|
||||
camera_id: connect_result.camera_id,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//!
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::{net::UdpSocket, task::JoinSet};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
mod bcconn;
|
||||
mod bcsub;
|
||||
@@ -22,16 +22,11 @@ pub(crate) use self::{
|
||||
pub(crate) struct DiscoveryResult {
|
||||
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
|
||||
|
||||
@@ -49,13 +49,12 @@ impl UdpSource {
|
||||
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>>(
|
||||
mut discovery: DiscoveryResult,
|
||||
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,
|
||||
|
||||
@@ -52,7 +52,7 @@ fn bcudp_ack<'a, W: 'a + Write>(
|
||||
le_u32(0),
|
||||
le_u32(payload.group_id),
|
||||
le_u32(payload.packet_id),
|
||||
le_u32(0),
|
||||
le_u32(0xd7160000),
|
||||
le_u32(binary_payload.len() as u32),
|
||||
slice(binary_payload),
|
||||
))
|
||||
|
||||
@@ -120,6 +120,9 @@ pub(crate) struct CameraConfig {
|
||||
alias = "stretching"
|
||||
)]
|
||||
pub(crate) use_smoothing: bool,
|
||||
|
||||
#[serde(default = "default_true", alias = "splash")]
|
||||
pub(crate) use_splash: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Validate, Clone)]
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
|
||||
.await
|
||||
.context("Failed to connect to the camera, check credentials and network")?;
|
||||
|
||||
if (opt.use_stream) {
|
||||
if opt.use_stream {
|
||||
let mut stream_data = camera
|
||||
.start_video(StreamKind::Main, 0, camera_config.strict)
|
||||
.await
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::config::CameraConfig;
|
||||
use crate::utils::AddressOrUid;
|
||||
use crate::utils::{timeout, AddressOrUid};
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
@@ -193,10 +193,9 @@ impl EventCamThread {
|
||||
"aes" => MaxEncryption::Aes,
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
.await
|
||||
.context("Failed to login to the camera")?;
|
||||
.context("Failed to login to the camera")??;
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
self.tx.send(Messages::Login).await?;
|
||||
|
||||
+54
-46
@@ -41,17 +41,17 @@ glib::wrapper! {
|
||||
|
||||
impl Default for NeoMediaFactory {
|
||||
fn default() -> Self {
|
||||
Self::new(100, true)
|
||||
Self::new(100, true, true)
|
||||
}
|
||||
}
|
||||
|
||||
impl NeoMediaFactory {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
|
||||
pub(crate) fn new(buffer_size: usize, use_smoothing: bool, use_splash: bool) -> Self {
|
||||
let factory = Object::new::<NeoMediaFactory>();
|
||||
factory.set_shared(false);
|
||||
factory.imp().shared.set_buffer_size(buffer_size);
|
||||
factory.imp().shared.set_use_smoothing(use_smoothing);
|
||||
// factory.set_do_retransmission(false); // Can't use as the method is missing on the 32bit docker gst dll
|
||||
factory.imp().shared.set_use_splash(use_splash);
|
||||
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);
|
||||
@@ -184,7 +184,7 @@ 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"))
|
||||
.and_then(|orig| self.build_pipeline(orig).expect("Could not build pipeline"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,18 +239,18 @@ fn make_queue(name: &str) -> AnyResult<Element> {
|
||||
Ok(queue)
|
||||
}
|
||||
|
||||
fn make_queue2(name: &str) -> AnyResult<Element> {
|
||||
let queue = make_element("queue2", name)?;
|
||||
queue.set_property("use-buffering", true);
|
||||
queue.set_property("max-size-bytes", 0u32);
|
||||
queue.set_property("max-size-buffers", 0u32);
|
||||
queue.set_property(
|
||||
"max-size-time",
|
||||
std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
Ok(queue)
|
||||
}
|
||||
// fn make_queue2(name: &str) -> AnyResult<Element> {
|
||||
// let queue = make_element("queue2", name)?;
|
||||
// queue.set_property("use-buffering", true);
|
||||
// queue.set_property("max-size-bytes", 0u32);
|
||||
// queue.set_property("max-size-buffers", 0u32);
|
||||
// queue.set_property(
|
||||
// "max-size-time",
|
||||
// std::convert::TryInto::<u64>::try_into(tokio::time::Duration::from_secs(5).as_nanos())
|
||||
// .unwrap_or(0),
|
||||
// );
|
||||
// Ok(queue)
|
||||
// }
|
||||
|
||||
impl NeoMediaFactoryImpl {
|
||||
pub(crate) fn buffer_ready(&self) -> bool {
|
||||
@@ -260,15 +260,17 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.number_of_clients.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Element> {
|
||||
fn build_pipeline(&self, media: Element) -> AnyResult<Option<Element>> {
|
||||
// debug!("Building PIPELINE");
|
||||
let bin = media
|
||||
.dynamic_cast::<Bin>()
|
||||
.map_err(|_| anyhow!("Media source's element should be a bin"))?;
|
||||
// Clear the autogenerated ones
|
||||
log::debug!("Clearing old elements");
|
||||
for element in bin.iterate_elements().into_iter().flatten() {
|
||||
bin.remove(&element)?;
|
||||
}
|
||||
log::debug!("Cleared");
|
||||
|
||||
let mut client_data = NeoMediaSender::new(
|
||||
self.shared.get_buffer_size(),
|
||||
@@ -281,12 +283,15 @@ impl NeoMediaFactoryImpl {
|
||||
self.shared.buffer_ready.load(Ordering::Relaxed),
|
||||
) {
|
||||
(VidFormats::Unknown, true) | (_, false) => {
|
||||
if !self.shared.get_use_splash() {
|
||||
return Ok(None);
|
||||
}
|
||||
debug!("Building Unknown Pipeline");
|
||||
let source = make_element("videotestsrc", "testvidsrc")?;
|
||||
source.set_property_from_str("pattern", "snow");
|
||||
source.set_property("num-buffers", 500i32); // Send buffers then EOS
|
||||
let queue = make_queue("queue0")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let overlay = make_element("textoverlay", "overlay")?;
|
||||
overlay.set_property("text", "Stream not Ready");
|
||||
overlay.set_property_from_str("valignment", "top");
|
||||
@@ -295,7 +300,7 @@ impl NeoMediaFactoryImpl {
|
||||
let encoder = make_element("jpegenc", "encoder")?;
|
||||
let payload = make_element("rtpjpegpay", "pay0")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &overlay, &encoder, &payload])?;
|
||||
source.link_filtered(
|
||||
&queue,
|
||||
&Caps::builder("video/x-raw")
|
||||
@@ -306,7 +311,7 @@ impl NeoMediaFactoryImpl {
|
||||
.build(),
|
||||
)?;
|
||||
// source.link(&queue)?;
|
||||
Element::link_many(&[&queue, &queue2, &overlay, &encoder, &payload])?;
|
||||
Element::link_many(&[&queue, &overlay, &encoder, &payload])?;
|
||||
}
|
||||
(VidFormats::H265, true) => {
|
||||
debug!("Building H265 Pipeline");
|
||||
@@ -355,12 +360,12 @@ impl NeoMediaFactoryImpl {
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_queue("source_queue")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let parser = make_element("h265parse", "parser")?;
|
||||
// parser.set_property("config-interval", 5i32);
|
||||
let payload = make_element("rtph265pay", "pay0")?;
|
||||
bin.add_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &parser, &payload])?;
|
||||
bin.add_many(&[&source, &queue, &parser, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &payload])?;
|
||||
|
||||
let source = source
|
||||
.dynamic_cast::<AppSrc>()
|
||||
@@ -417,7 +422,7 @@ impl NeoMediaFactoryImpl {
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
let queue = make_queue("source_queue")?;
|
||||
let queue2 = make_queue2("queue2")?;
|
||||
// let queue2 = make_queue2("queue2")?;
|
||||
let parser = make_element("h264parse", "parser")?;
|
||||
// parser.set_property("update-timecode", true);
|
||||
let payload = make_element("rtph264pay", "pay0")?;
|
||||
@@ -429,13 +434,13 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
// payload.set_property("config-interval", 5i32);
|
||||
bin.add_many(&[
|
||||
&source, &queue, &queue2, &parser,
|
||||
&source, &queue, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
])?;
|
||||
Element::link_many(&[
|
||||
&source, &queue, &queue2, &parser,
|
||||
&source, &queue, &parser,
|
||||
&payload,
|
||||
// &storage,
|
||||
// &jitter,
|
||||
@@ -488,25 +493,26 @@ impl NeoMediaFactoryImpl {
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_queue("audqueue")?;
|
||||
let queue2 = make_queue2("audqueue2")?;
|
||||
// let queue2 = make_queue2("audqueue2")?;
|
||||
let parser = make_element("aacparse", "audparser")?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let decoder = match make_element("faad", "auddecoder_faad") {
|
||||
Ok(ele) => Ok(ele),
|
||||
Err(_) => make_element("avdec_aac", "auddecoder_avdec_aac"),
|
||||
}?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[
|
||||
&source, &queue, &queue2, &parser, &decoder, &encoder, &payload,
|
||||
])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &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");
|
||||
});
|
||||
bin.add_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &parser, &decoder, &encoder, &payload])?;
|
||||
// Element::link_many(&[])?;
|
||||
// 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>()
|
||||
@@ -560,13 +566,13 @@ impl NeoMediaFactoryImpl {
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
|
||||
let queue = make_queue("audqueue")?;
|
||||
let queue2 = make_queue2("audqueue2")?;
|
||||
// let queue2 = make_queue2("audqueue2")?;
|
||||
let decoder = make_element("decodebin", "auddecoder")?;
|
||||
let encoder = make_element("audioconvert", "audencoder")?;
|
||||
let payload = make_element("rtpL16pay", "pay1")?;
|
||||
|
||||
bin.add_many(&[&source, &queue, &queue2, &decoder, &encoder, &payload])?;
|
||||
Element::link_many(&[&source, &queue, &queue2, &decoder])?;
|
||||
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());
|
||||
@@ -586,8 +592,10 @@ impl NeoMediaFactoryImpl {
|
||||
|
||||
self.clientsender.blocking_send(client_data)?;
|
||||
// debug!("Pipeline built");
|
||||
bin.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))
|
||||
let element = bin
|
||||
.dynamic_cast::<Element>()
|
||||
.map_err(|_| anyhow!("Cannot cast back"))?;
|
||||
Ok(Some(element))
|
||||
}
|
||||
|
||||
async fn join(&self) -> AnyResult<()> {
|
||||
|
||||
+76
-147
@@ -444,8 +444,8 @@ pub(super) struct NeoMediaSender {
|
||||
start_time: Spring,
|
||||
live_offset: FrameTime,
|
||||
buffer: NeoBuffer,
|
||||
vid: Option<AppSrc>,
|
||||
aud: Option<AppSrc>,
|
||||
vid: Option<Arc<AppSrc>>,
|
||||
aud: Option<Arc<AppSrc>>,
|
||||
command_reciever: Receiver<NeoMediaSenderCommand>,
|
||||
command_sender: Sender<NeoMediaSenderCommand>,
|
||||
inited: bool,
|
||||
@@ -453,6 +453,11 @@ pub(super) struct NeoMediaSender {
|
||||
use_smoothing: bool,
|
||||
}
|
||||
|
||||
enum Buffer {
|
||||
Video(gstreamer::Buffer),
|
||||
Audio(gstreamer::Buffer),
|
||||
}
|
||||
|
||||
impl NeoMediaSender {
|
||||
pub(super) fn new(buffer_size: usize, use_smoothing: bool) -> Self {
|
||||
let (tx, rx) = channel(30);
|
||||
@@ -476,11 +481,11 @@ impl NeoMediaSender {
|
||||
}
|
||||
|
||||
pub(super) fn update_vid(&mut self, source: AppSrc) {
|
||||
self.vid.replace(source);
|
||||
self.vid.replace(Arc::new(source));
|
||||
}
|
||||
|
||||
pub(super) fn update_aud(&mut self, source: AppSrc) {
|
||||
self.aud.replace(source);
|
||||
self.aud.replace(Arc::new(source));
|
||||
}
|
||||
|
||||
pub(super) fn get_commader(&self) -> Sender<NeoMediaSenderCommand> {
|
||||
@@ -615,15 +620,22 @@ impl NeoMediaSender {
|
||||
self.buffer.buf.clear();
|
||||
|
||||
let mut buffer_iter = buffer.buf.iter().cloned();
|
||||
// The prebuffer should starts from an Iframe
|
||||
let preprocess = buffer_iter
|
||||
.take_while_ref(|item| item.time < target_time)
|
||||
.take_while_ref(|item| {
|
||||
item.time < target_time
|
||||
|| !matches!(
|
||||
item.data.first().map(|arc| arc.as_ref()),
|
||||
Some(BcMedia::Iframe(_))
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut buffer = buffer_iter.collect::<Vec<_>>();
|
||||
self.start_time.reset_to(target_time as f64);
|
||||
|
||||
// Send preprocess now
|
||||
self.send_buffers(preprocess.as_slice(), true).await?;
|
||||
trace!("Preprocessed: {}", preprocess.len());
|
||||
debug!("Preprocessed: {}", preprocess.len());
|
||||
// Send these later
|
||||
for frame in buffer.drain(..) {
|
||||
self.buffer.buf.push_back(frame);
|
||||
@@ -717,17 +729,11 @@ impl NeoMediaSender {
|
||||
if medias.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
let mut vid_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
let mut aud_buffers: Vec<(FrameTime, Vec<u8>)> = vec![];
|
||||
let mut buffers: Vec<Buffer> = vec![];
|
||||
|
||||
for media_sets in medias.iter() {
|
||||
tokio::task::yield_now().await;
|
||||
for media in media_sets.data.iter() {
|
||||
let buffer = match media.as_ref() {
|
||||
BcMedia::Iframe(_) | BcMedia::Pframe(_) => Some(&mut vid_buffers),
|
||||
BcMedia::Aac(_) | BcMedia::Adpcm(_) => Some(&mut aud_buffers),
|
||||
_ => None,
|
||||
};
|
||||
let data = match media.as_ref() {
|
||||
BcMedia::Iframe(data) => Some(&data.data),
|
||||
BcMedia::Pframe(data) => Some(&data.data),
|
||||
@@ -735,148 +741,71 @@ impl NeoMediaSender {
|
||||
BcMedia::Adpcm(data) => Some(&data.data),
|
||||
_ => None,
|
||||
};
|
||||
if let (Some(data), Some(buffer)) = (data, buffer) {
|
||||
let next_time = media_sets.time;
|
||||
if let Some(last) = buffer.last_mut() {
|
||||
let last_time = last.0;
|
||||
if next_time == last_time {
|
||||
last.1.extend(data.iter().copied());
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
if let Some(buf) = data {
|
||||
let time = media_sets.time;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
trace!(
|
||||
" - Sending vid frame at time {} ({:?} Expect: {:?})",
|
||||
time,
|
||||
Duration::from_micros(runtime as u64),
|
||||
self.get_runtime().map(|i| Duration::from_micros(i as u64))
|
||||
);
|
||||
|
||||
let gst_buf = {
|
||||
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(runtime.try_into().unwrap());
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data = gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
} else {
|
||||
buffer.push((next_time, data.clone()))
|
||||
gst_buf
|
||||
};
|
||||
match media.as_ref() {
|
||||
BcMedia::Iframe(_) | BcMedia::Pframe(_) => {
|
||||
buffers.push(Buffer::Video(gst_buf));
|
||||
}
|
||||
BcMedia::Aac(_) | BcMedia::Adpcm(_) => {
|
||||
buffers.push(Buffer::Audio(gst_buf));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
tokio::try_join!(
|
||||
async {
|
||||
if !vid_buffers.is_empty() {
|
||||
// debug!("Sending video buffers: {}", vid_buffers.len());
|
||||
if let Some(appsrc) = self.vid.clone() {
|
||||
let buffers = {
|
||||
let mut buffers = gstreamer::BufferList::new_sized(vid_buffers.len());
|
||||
{
|
||||
let buffers_ref = buffers.get_mut().unwrap();
|
||||
for (time, buf) in vid_buffers.drain(..) {
|
||||
tokio::task::yield_now().await;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
trace!(
|
||||
" - Sending vid frame at time {} ({:?} Expect: {:?})",
|
||||
time,
|
||||
Duration::from_micros(runtime as u64),
|
||||
self.get_runtime().map(|i| Duration::from_micros(i as u64))
|
||||
);
|
||||
|
||||
let gst_buf = {
|
||||
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(
|
||||
runtime.try_into().unwrap(),
|
||||
);
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data =
|
||||
gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
buffers_ref.add(gst_buf);
|
||||
}
|
||||
}
|
||||
buffers
|
||||
};
|
||||
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
// debug!(" - Pushing buffer: {}", buffers.len());
|
||||
appsrc
|
||||
.push_buffer_list(buffers.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
for buf in buffers.drain(..) {
|
||||
let buf_app = match (buf, self.vid.as_ref(), self.aud.as_ref()) {
|
||||
(Buffer::Video(buf), Some(app), _) => Some((buf, app.clone())),
|
||||
(Buffer::Audio(buf), _, Some(app)) => Some((buf, app.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((buf, appsrc)) = buf_app {
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer(buf.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
},
|
||||
async {
|
||||
if !aud_buffers.is_empty() {
|
||||
if let Some(appsrc) = self.aud.clone() {
|
||||
let buffers = {
|
||||
let mut buffers = gstreamer::BufferList::new_sized(aud_buffers.len());
|
||||
{
|
||||
let buffers_ref = buffers.get_mut().unwrap();
|
||||
for (time, buf) in aud_buffers.drain(..) {
|
||||
tokio::task::yield_now().await;
|
||||
let runtime = match (self.get_runtime(), ignore_stamps) {
|
||||
(None, _) | (_, false) => self.buftime_to_runtime(time),
|
||||
(Some(runtime), true) => runtime,
|
||||
};
|
||||
|
||||
let gst_buf = {
|
||||
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(
|
||||
runtime.try_into().unwrap(),
|
||||
);
|
||||
gst_buf_mut.set_dts(time);
|
||||
gst_buf_mut.set_pts(time);
|
||||
let mut gst_buf_data =
|
||||
gst_buf_mut.map_writable().unwrap();
|
||||
gst_buf_data.copy_from_slice(buf.as_slice());
|
||||
}
|
||||
gst_buf
|
||||
};
|
||||
buffers_ref.add(gst_buf);
|
||||
}
|
||||
}
|
||||
buffers
|
||||
};
|
||||
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
appsrc
|
||||
.push_buffer_list(buffers.copy())
|
||||
.map(|_| ())
|
||||
.map_err(|_| anyhow!("Could not push buffer to appsrc"))
|
||||
})
|
||||
.await;
|
||||
match &res {
|
||||
Err(e) => {
|
||||
debug!("Paniced on send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
Ok(Err(e)) => {
|
||||
debug!("Failed to send buffer list: {:?}", e);
|
||||
}
|
||||
}
|
||||
AnyResult::Ok(())
|
||||
Ok(Ok(_)) => {}
|
||||
};
|
||||
res??;
|
||||
}
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -363,7 +363,11 @@ impl NeoRtspServerImpl {
|
||||
match self.medias.write().await.entry(key.clone()) {
|
||||
Entry::Occupied(_occ) => {}
|
||||
Entry::Vacant(vac) => {
|
||||
let media = NeoMediaFactory::new(config.buffer_size, config.use_smoothing);
|
||||
let media = NeoMediaFactory::new(
|
||||
config.buffer_size,
|
||||
config.use_smoothing,
|
||||
config.use_splash,
|
||||
);
|
||||
let thread_media = media.clone();
|
||||
self.threads
|
||||
.write()
|
||||
|
||||
@@ -25,6 +25,7 @@ pub(super) struct NeoMediaShared {
|
||||
pub(super) buffer_ready: AtomicBool,
|
||||
pub(super) buffer_size: AtomicUsize,
|
||||
pub(super) use_smoothing: AtomicBool,
|
||||
pub(super) splash: AtomicBool,
|
||||
}
|
||||
|
||||
impl Default for NeoMediaShared {
|
||||
@@ -36,6 +37,7 @@ impl Default for NeoMediaShared {
|
||||
buffer_ready: AtomicBool::new(false),
|
||||
buffer_size: AtomicUsize::new(100),
|
||||
use_smoothing: AtomicBool::new(false),
|
||||
splash: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,4 +58,12 @@ impl NeoMediaShared {
|
||||
pub(super) fn set_use_smoothing(&self, new_value: bool) {
|
||||
self.use_smoothing.store(new_value, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(super) fn get_use_splash(&self) -> bool {
|
||||
self.splash.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(super) fn set_use_splash(&self, new_value: bool) {
|
||||
self.splash.store(new_value, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -174,10 +174,14 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
|
||||
.await
|
||||
.with_context(|| format!("{}: Could not login to camera", name))
|
||||
.map_err(|e| {
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>().unwrap();
|
||||
let e_inner = e.downcast_ref::<neolink_core::Error>();
|
||||
match e_inner {
|
||||
neolink_core::Error::CameraLoginFail => CameraFailureKind::Fatal(e),
|
||||
_ => CameraFailureKind::Retry(e),
|
||||
Some(neolink_core::Error::CameraLoginFail) => CameraFailureKind::Fatal(e),
|
||||
Some(_) => CameraFailureKind::Retry(e),
|
||||
None => {
|
||||
// Timout error usually
|
||||
CameraFailureKind::Retry(e)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// This state has formed the TCP/UDP tunnel
|
||||
// but has not logged in
|
||||
use super::{camera::Camera, disconnected::Disconnected, loggedin::LoggedIn};
|
||||
use crate::utils::timeout;
|
||||
use anyhow::Result;
|
||||
|
||||
use neolink_core::bc_protocol::{BcCamera, MaxEncryption};
|
||||
@@ -28,7 +29,7 @@ impl Camera<Connected> {
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
|
||||
self.state.camera.login_with_maxenc(max_encryption).await?;
|
||||
timeout(self.state.camera.login_with_maxenc(max_encryption)).await??;
|
||||
Ok(Camera {
|
||||
shared: self.shared,
|
||||
state: LoggedIn {
|
||||
|
||||
+9
-3
@@ -13,6 +13,13 @@ use std::{
|
||||
str::FromStr,
|
||||
};
|
||||
|
||||
pub(crate) fn timeout<F>(future: F) -> tokio::time::Timeout<F>
|
||||
where
|
||||
F: std::future::Future,
|
||||
{
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(5), future)
|
||||
}
|
||||
|
||||
pub(crate) enum AddressOrUid {
|
||||
Address(String),
|
||||
Uid(String, DiscoveryMethods),
|
||||
@@ -133,10 +140,9 @@ pub(crate) async fn connect_and_login(camera_config: &CameraConfig) -> Result<Bc
|
||||
_ => MaxEncryption::Aes,
|
||||
};
|
||||
info!("{}: Logging in", camera_config.name);
|
||||
camera
|
||||
.login_with_maxenc(max_encryption)
|
||||
timeout(camera.login_with_maxenc(max_encryption))
|
||||
.await
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
|
||||
.with_context(|| format!("Failed to login to {}", camera_config.name))??;
|
||||
|
||||
info!("{}: Connected and logged in", camera_config.name);
|
||||
|
||||
|
||||
Reference in new issue
Block a user