Merge branch 'master' of github.com:thirtythreeforty/neolink into motion

This commit is contained in:
QuantumEntangledAndy committed 2021-08-31 20:37:13 +07:00
1 parent 10642b18d1
commit 1883e5362e
27 files changed
+875 -605

No files matched your search

Generated
+8
View File
@@ -63,6 +63,12 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b"
[[package]]
name = "assert_matches"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9"
[[package]]
name = "atty"
version = "0.2.14"
@@ -832,6 +838,7 @@ name = "neolink"
version = "0.4.0"
dependencies = [
"aes",
"anyhow",
"byte-slice-cast",
"cfb-mode",
"cookie-factory",
@@ -866,6 +873,7 @@ name = "neolink_core"
version = "0.4.0"
dependencies = [
"aes",
"assert_matches",
"cfb-mode",
"cookie-factory",
"env_logger",
+1
View File
@@ -39,3 +39,4 @@ xml-rs = "0.8"
validator = "0.10"
validator_derive = "0.10"
byte-slice-cast = "1.0.0"
anyhow = "1.0.42"
+72 -43
View File
@@ -29,7 +29,39 @@ Currently it has been tested on the following cameras:
Neolink does not support other cameras such as the RLC-420, since they already
[provide native RTSP](https://support.reolink.com/hc/en-us/articles/360007010473-How-to-Live-View-Reolink-Cameras-via-VLC-Media-Player).
## Installation
## Usage
1. First, write a configuration yaml file describing your cameras. See the
Configuration section below or the provided sample config.
2. Launch Neolink:
```bash
neolink rtsp --config=your_config.yaml
```
3. Then, connect your RTSP viewer to `rtsp://127.0.0.1:8554/your_camera_name`!
### Additional commands
Neolink also has some additional command line tools
for controlling the camera. They are all used through neolink subcommands like this:
```bash
neolink subcommand --config=...
```
The currently supported subcommands are
- **rtsp**: The standard neolink rtsp bridge
- **status-light**: Control the LED status light
- **reboot**: Reboot a camera
- **talk**: Enable talk back through either the microphone or by
reading a sound file.
For a full list of commands use `neolink help`, or use
`neolink help <subcommand>` for details on a subcommand of interest.
## Download & Installation
In the future Neolink will be much easier to install.
For now, follow these steps.
@@ -39,8 +71,8 @@ Builds are provided for the following platforms:
- macOS x86_64 ([download][macos-ci-download])
- Ubuntu x86_64 ([download][ubuntu-ci-download])
- Debian x86 ([download][debian-x86-ci-download])
- Debian aarch64 ([download][debian-aarch-ci-download])
- Debian armhf ([download][debian-armhf-ci-download])
- Debian aarch64 (Raspberry Pi 64-bit) ([download][debian-aarch-ci-download])
- Debian armhf (Raspberry Pi 32-bit) ([download][debian-armhf-ci-download])
- Arch Linux ([AUR](https://aur.archlinux.org/packages/neolink-git/))
- Docker x86 (see below)
@@ -48,6 +80,18 @@ Builds are provided for the following platforms:
1. [Install Gstreamer][gstreamer] from the most recent MSI installer on Windows,
or your package manager on Linux.
On Ubuntu/Debian machines gstreamer can be installed with:
```bash
sudo apt install \
libgstrtspserver-1.0-0 \
libgstreamer1.0-0 \
libgstreamer-plugins-bad1.0-0 \
gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad
```
2. If you are using Windows, add the following to your `PATH` environment variable:
@@ -58,12 +102,17 @@ or your package manager on Linux.
**Note:** If you use Chocolatey to install Gstreamer, it does this
automatically.
3. Download and extract a [prebuilt binary from continuous integration][ci-download]
(click on the topmost commit for the most recent build).
3. Download and unpack Neolink from the links above.
1. Note: you can also click on [this link][ci-download] to see all historical builds.
You will need to be logged in to GitHub to download directly from the builds page.
You will need to be logged in to GitHub to download directly from the builds page (wget doesn't work)
Raspberry Pi OS x64 example:
```bash
unzip release-arm64-buster.zip
sudo cp neolink /usr/local/bin/
sudo chmod +x /usr/local/bin/neolink
```
4. Write a configuration file for your cameras. See the section below.
5. Launch Neolink from a shell, passing your configuration file:
@@ -107,6 +156,22 @@ docker run \
thirtythreeforty/neolink
```
Here is an example docker-compose:
```yml
---
version: "2"
services:
neolink:
image: thirtythreeforty/neolink
container_name: neolink
ports:
- 8554:8554
volumes:
- $PWD/neolink.toml:/etc/neolink.toml
restart: unless-stopped
```
The Docker image is "best effort" and intended for advanced users; questions
about running Docker are outside the scope of Neolink.
@@ -126,11 +191,6 @@ path you should connect your client to.
Currently Neolink cannot auto-detect cameras like the official clients do; you
must specify their IP addresses directly.
By default the H265 video format is used. Some cameras, for example E1, provide
H264 streams. To use these you must specify `format = "h264"` in the
`[[cameras]]` config. Soon this will be auto-detected, and you will not have to know or care about
the format.
By default, the HD stream is available at the RTSP path `/name` or
`/name/mainStream`, and the SD stream is available at `/name/subStream`.
You can use only the HD stream by adding `stream = "mainStream"` to the
@@ -262,37 +322,6 @@ Currently the dissector does not attempt to decode the Baichuan "extension"
messages except `binaryData`.
This will change in the future as reverse engineering needs require.
## Additional Commands
Neolink also has some additional command line tools
for controlling the camera. They are all used through neolink subcommands like this:
```bash
neolink subcommand --config=...
```
The currently supported subcommands are
- **rtsp**: The standard neolink rtsp bridge
- **status-light**: A command to control the LED status light
- **reboot**: Will reboot a camera
- **talk**: Will enable talk back through either the microphone or by
reading a sound file.
For a full list of commands please use
```bash
neolink help
```
For further details on the subcommands please use the following
where `<subcommand>` is replaced with the subcommand of interest
```bash
neolink help <subcommand>
```
## License
Neolink is free software, released under the GNU Affero General Public License
+1
View File
@@ -20,5 +20,6 @@ yaserde_derive = "0.3.16"
xml-rs = "0.8"
[dev-dependencies]
assert_matches = "1.5.0"
env_logger = "*"
indoc = "0.3"
+272 -133
View File
@@ -232,150 +232,289 @@ fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> {
))
}
#[test]
fn test_bc_modern_login() {
let sample = include_bytes!("samples/model_sample_modern_login.bin");
#[cfg(test)]
mod tests {
use super::*;
use crate::bc::xml::*;
use assert_matches::assert_matches;
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
#[test]
fn test_bc_modern_login() {
let sample = include_bytes!("samples/model_sample_modern_login.bin");
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 145);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, None);
assert_eq!(header.response_code, 0xdd01);
assert_eq!(header.class, 0x6614);
match body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
encryption: Some(encryption),
..
})),
..
}) => assert_eq!(encryption.nonce, "9E6D1FCB9E69846D"),
_ => panic!(),
}
}
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
#[test]
fn test_bc_legacy_login() {
let sample = include_bytes!("samples/model_sample_legacy_login.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 1836);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, None);
assert_eq!(header.response_code, 0xdc01);
assert_eq!(header.class, 0x6514);
match body {
BcBody::LegacyMsg(LegacyMsg::LoginMsg { username, password }) => {
assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0");
assert_eq!(password, EMPTY_LEGACY_PASSWORD);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 145);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, None);
assert_eq!(header.response_code, 0xdd01);
assert_eq!(header.class, 0x6614);
match body {
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
encryption: Some(encryption),
..
})),
..
}) => assert_eq!(encryption.nonce, "9E6D1FCB9E69846D"),
_ => panic!(),
}
_ => panic!(),
}
}
#[test]
fn test_bc_modern_login_failed() {
let sample = include_bytes!("samples/modern_login_failed.bin");
#[test]
fn test_bc_legacy_login() {
let sample = include_bytes!("samples/model_sample_legacy_login.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 0);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, Some(0x0));
assert_eq!(header.response_code, 0x190); // 400
assert_eq!(header.class, 0x0000);
match body {
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: None,
}) => {}
_ => panic!(),
}
}
#[test]
fn test_bc_modern_login_success() {
let sample = include_bytes!("samples/modern_login_success.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 2949);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, Some(0x0));
assert_eq!(header.response_code, 0xc8); // 200
assert_eq!(header.class, 0x0000);
// Previously, we were not handling payload_offset == 0 (no bin offset) correctly.
// Test that we decoded XML and no binary.
match body {
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: Some(_),
}) => {}
_ => panic!(),
}
}
#[test]
fn test_bc_binary_mode() {
let sample1 = include_bytes!("samples/modern_video_start1.bin");
let sample2 = include_bytes!("samples/modern_video_start2.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let msg1 = Bc::deserialize(&mut context, &sample1[..]).unwrap();
match msg1.body {
BcBody::ModernMsg(ModernMsg {
extension:
Some(Extension {
binary_data: Some(1),
..
}),
payload: Some(BcPayloads::Binary(bin)),
}) => {
assert_eq!(bin.len(), 32);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 1836);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, None);
assert_eq!(header.response_code, 0xdc01);
assert_eq!(header.class, 0x6514);
match body {
BcBody::LegacyMsg(LegacyMsg::LoginMsg { username, password }) => {
assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0");
assert_eq!(password, EMPTY_LEGACY_PASSWORD);
}
_ => panic!(),
}
_ => panic!(),
}
context.in_bin_mode.insert(msg1.meta.msg_num);
let msg2 = Bc::deserialize(&mut context, &sample2[..]).unwrap();
match msg2.body {
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: Some(BcPayloads::Binary(bin)),
}) => {
assert_eq!(bin.len(), 30344);
#[test]
fn test_bc_modern_login_failed() {
let sample = include_bytes!("samples/modern_login_failed.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 0);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, Some(0x0));
assert_eq!(header.response_code, 0x190); // 400
assert_eq!(header.class, 0x0000);
match body {
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: None,
}) => {}
_ => panic!(),
}
_ => panic!(),
}
#[test]
fn test_bc_modern_login_success() {
let sample = include_bytes!("samples/modern_login_success.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let (buf, header) = bc_header(&sample[..]).unwrap();
let (_, body) = bc_body(&mut context, &header, buf).unwrap();
assert_eq!(header.msg_id, 1);
assert_eq!(header.body_len, 2949);
assert_eq!(header.channel_id, 0);
assert_eq!(header.stream_type, 0);
assert_eq!(header.payload_offset, Some(0x0));
assert_eq!(header.response_code, 0xc8); // 200
assert_eq!(header.class, 0x0000);
// Previously, we were not handling payload_offset == 0 (no bin offset) correctly.
// Test that we decoded XML and no binary.
match body {
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: Some(_),
}) => {}
_ => panic!(),
}
}
#[test]
fn test_bc_binary_mode() {
let sample1 = include_bytes!("samples/modern_video_start1.bin");
let sample2 = include_bytes!("samples/modern_video_start2.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let msg1 = Bc::deserialize(&mut context, &sample1[..]).unwrap();
match msg1.body {
BcBody::ModernMsg(ModernMsg {
extension:
Some(Extension {
binary_data: Some(1),
..
}),
payload: Some(BcPayloads::Binary(bin)),
}) => {
assert_eq!(bin.len(), 32);
}
_ => panic!(),
}
context.in_bin_mode.insert(msg1.meta.msg_num);
let msg2 = Bc::deserialize(&mut context, &sample2[..]).unwrap();
match msg2.body {
BcBody::ModernMsg(ModernMsg {
extension: None,
payload: Some(BcPayloads::Binary(bin)),
}) => {
assert_eq!(bin.len(), 30344);
}
_ => panic!(),
}
}
#[test]
// B800 seems to have a different header to the E1 and swann cameras
// the stream_type and message_num do not seem to set in the offical clients
//
// They also have extra streams
fn test_bc_b800_externstream() {
let sample = include_bytes!("samples/xml_externstream_b800.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let e = Bc::deserialize(&mut context, &sample[..]);
assert_matches!(
e,
Ok(Bc {
meta:
BcMeta {
msg_id: 3,
channel_id: 0x8c,
stream_type: 0,
response_code: 0,
msg_num: 0,
class: 0x6414,
},
body:
BcBody::ModernMsg(ModernMsg {
extension: None,
payload:
Some(BcPayloads::BcXml(BcXml {
preview:
Some(Preview {
version,
channel_id: 0,
handle: 1024,
stream_type,
}),
..
})),
}),
}) if version == "1.1" && stream_type == "externStream"
);
}
#[test]
// B800 seems to have a different header to the E1 and swann cameras
// the stream_type and message_num do not seem to set in the offical clients
//
// They also have extra streams
fn test_bc_b800_substream() {
let sample = include_bytes!("samples/xml_substream_b800.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let e = Bc::deserialize(&mut context, &sample[..]);
assert_matches!(
e,
Ok(Bc {
meta:
BcMeta {
msg_id: 3,
channel_id: 143,
stream_type: 0,
response_code: 0,
msg_num: 0,
class: 0x6414,
},
body:
BcBody::ModernMsg(ModernMsg {
extension: None,
payload:
Some(BcPayloads::BcXml(BcXml {
preview:
Some(Preview {
version,
channel_id: 0,
handle: 256,
stream_type,
}),
..
})),
}),
}) if version == "1.1" && stream_type == "subStream"
);
}
#[test]
// B800 seems to have a different header to the E1 and swann cameras
// the stream_type and message_num do not seem to set in the offical clients
//
// They also have extra streams
fn test_bc_b800_mainstream() {
let sample = include_bytes!("samples/xml_mainstream_b800.bin");
let encryption_protocol =
std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt));
let mut context = BcContext::new(encryption_protocol);
let e = Bc::deserialize(&mut context, &sample[..]);
assert_matches!(
e,
Ok(Bc {
meta:
BcMeta {
msg_id: 3,
channel_id: 138,
stream_type: 0,
response_code: 0,
msg_num: 0,
class: 0x6414,
},
body:
BcBody::ModernMsg(ModernMsg {
extension: None,
payload:
Some(BcPayloads::BcXml(BcXml {
preview:
Some(Preview {
version,
channel_id: 0,
handle: 0,
stream_type,
}),
..
})),
}),
}) if version == "1.1" && stream_type == "mainStream"
);
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -27,7 +27,7 @@ pub use binarysub::BinarySubscriber;
pub use errors::Error;
pub use ledstate::LightState;
pub use motion::{MotionOutput, MotionOutputError, MotionStatus};
pub use stream::{StreamOutput, StreamOutputError};
pub use stream::{Stream, StreamOutput, StreamOutputError};
type Result<T> = std::result::Result<T, Error>;
+56 -9
View File
@@ -21,6 +21,20 @@ pub trait StreamOutput {
fn stream_recv(&mut self, media: BcMedia) -> StreamOutputError;
}
/// The stream names supported by BC
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Stream {
/// This is the HD stream
Main,
/// This is the SD stream
Sub,
/// This stream represents a balance between SD and HD
///
/// It is only avaliable on some camera. If the camera dosen't
/// support it the stream will be the same as the SD stream
Extern,
}
impl BcCamera {
///
/// Starts the video stream
@@ -29,13 +43,16 @@ impl BcCamera {
///
/// * `data_outs` - This should be a struct that implements the [`StreamOutput`] trait
///
/// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD
/// * `stream_name` - This is a [`Stream`] that controls the stream to request from the camera.
/// Selecting [`Stream::Main`] will select the HD stream.
/// Selecting [`Stream::Sub`] will select the SD stream.
/// Selecting [`Stream::Extern`] will select the medium quality stream (only on some camera)
///
/// # Returns
///
/// This will block forever or return an error when the camera connection is dropped
///
pub fn start_video<Outputs>(&self, data_outs: &mut Outputs, stream_name: &str) -> Result<()>
pub fn start_video<Outputs>(&self, data_outs: &mut Outputs, stream: Stream) -> Result<()>
where
Outputs: StreamOutput,
{
@@ -45,18 +62,48 @@ impl BcCamera {
.expect("Must be connected to start video");
let sub_video = connection.subscribe(MSG_ID_VIDEO)?;
let stream_num = match stream_name {
"mainStream" => 0,
"subStream" => 1,
_ => 0,
// On an E1 and swann cameras:
// - mainStream always has a value of 0
// - subStream always has a value of 1
// - There is no externStram
// On a B800:
// - mainStream is 0
// - subStream is 0
// - externStream is 0
let stream_code = match stream {
Stream::Main => 0,
Stream::Sub => 1,
Stream::Extern => 0,
};
// Theses are the numbers used with the offical client
// On an E1 and swann cameras:
// - mainStream always has a value of 0
// - subStream always has a value of 1
// - There is no externStram
// On a B800:
// - mainStream is 0
// - subStream is 256
// - externStram is 1024
let handle = match stream {
Stream::Main => 0,
Stream::Sub => 256,
Stream::Extern => 1024,
};
let stream_name = match stream {
Stream::Main => "mainStream",
Stream::Sub => "subStream",
Stream::Extern => "externStream",
}
.to_string();
let start_video = Bc::new_from_xml(
BcMeta {
msg_id: MSG_ID_VIDEO,
channel_id: self.channel_id,
msg_num: self.new_message_num(),
stream_type: stream_num,
stream_type: stream_code,
response_code: 0,
class: 0x6414, // IDK why
},
@@ -64,8 +111,8 @@ impl BcCamera {
preview: Some(Preview {
version: xml_ver(),
channel_id: self.channel_id,
handle: 0,
stream_type: stream_name.to_string(),
handle,
stream_type: stream_name,
}),
..Default::default()
},
+161 -144
View File
File diff suppressed because it is too large. Load diff
+69 -36
View File
@@ -16,9 +16,9 @@ Each message has the general format:
The header has the format:
| magic | message id | message length | encryption offset | encrypt | unknown | message class |
|--------------|--------------|----------------|-------------------|---------|---------|---------------|
| f0 de bc 0a | 01 00 00 00 | 2c 07 00 00 | 00 00 00 01 | 01 | dc | 14 65 |
| magic | message id | message length | encryption offset | encrypt | message class |
|--------------|--------------|----------------|-------------------|------------|---------------|
| f0 de bc 0a | 01 00 00 00 | 2c 07 00 00 | 00 00 00 01 | 01 dc | 14 65 |
- Magic 4 bytes
- ID 4 bytes
@@ -30,9 +30,9 @@ The header has the format:
Or
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset |
|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------|
| f0 de bc 0a | 01 00 00 00 | 28 01 00 00 | 00 00 00 01 | c8 00 | 14 64 | 00 00 00 00 |
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|--------------|--------------|----------------|-------------------|-------------------|---------------|----------------|
| f0 de bc 0a | 01 00 00 00 | 28 01 00 00 | 00 00 00 01 | c8 00 | 14 64 | 00 00 00 00 |
- Magic 4 bytes
@@ -97,17 +97,24 @@ message_handle 1 byte - client increments per request, replies use request handl
#### Encryption Flag
This flag is 0 for unencrypted or non zero for encrypted.
Client will send the number `0xXXdc` and the server will reply `0xXXdd`.
Where `XX` is one of the following.
Clients should decide to use encryption or not based on this byte that the
camera sent during login. Then should use that same setting for all further
messages with the camera.
- 0 Unencrypted
- 1 BC Encryption
- 2 AES Encryption (Camera)
- 3 AES Encryption (Client)
#### Unknown
`dc` means this encryption protol or lower. So `0x01dc` means BC on no encryption
whereas `0x03dc` means AES, BC or Unencrypted.
The purpose of this byte is unknown.
Observed - `dc` = client request, `dd` = device reply
If you figure out what it does please submit a PR.
`dd` is the reply that the camera sends to the `dc` request. It is the chosen
protocol that will be used.
**Note:** When requesting AES the client sends `0x03dc` and the camera replies `0x02dc`.
We are not sure why.
Encryption is negotiated in the login request.
#### Status Code
@@ -129,20 +136,13 @@ and header lengths are known.
- 0x0000: "modern" 24 bytes
#### Binary offset
#### Payload offset
For messages that contain the binary offset field this represents where to start
the binary part of the message. The total length of XML + binary is equal
to the message length in the header so Binary Offset is
total_length - this_offset. Where as this field also represents the end of the
XML part of the message.
Some messages seems to not set this field correctly. For example message ID 1
sets this to zero meaning that all data in the message is binary, however
it contains XML. This best way to tell is this is binary or XML is to check the
message ID and determine from there. Alternatively you could look for `<xml?` at
the beginning of the message (although may need to decrypt first for this to
work)
For messages that contain the payload offset field this represents where to start
the payload part of the message. The total length of the message
(extension XML + payload) is equal to the message length in the header
so Payload Offset is total_length - this_offset. Where as this field also represents the end of the
extension XML part of the message.
# Login
@@ -189,10 +189,12 @@ streamType can be either
channelId is part of the NVR when multiple cameras use the same IP. In this
case each camera has its own channelId.
Not sure what handle does.
The `handle` is used when multiple streams are requested in a single login.
This number should be unique for each stream. If not then that stream
(Clear or Fluent) will not work until the camera is reset.
The reply is first a message with the following xml
The reply is first a message with the following Extension Xml
```xml
<?xml version="1.0" encoding="UTF-8" ?>
@@ -203,7 +205,7 @@ The reply is first a message with the following xml
After which all message bodies of type id 3 are binary.
The binary represents a stream of data. It can be interrupted by packet
The binary represents a stream of data that can be interrupted by packet
boundaries. Clients should create a buffer and pop bytes for processing when
complete media packets are received. Media packets descriptions can be found in
the [docs](dissector/mediapacket.md)
@@ -213,9 +215,9 @@ the [docs](dissector/mediapacket.md)
Other data can be received from the camera by sending the appropriate header to
the camera. For example sending the header for ID 78
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset |
|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------|
| f0 de bc 0a | 4e 00 00 00 | d3 00 00 00 | 08 db 9c 00 | c8 00 | 00 00 | 00 00 00 00 |
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|--------------|--------------|----------------|-------------------|-------------------|---------------|----------------|
| f0 de bc 0a | 4e 00 00 00 | d3 00 00 00 | 08 db 9c 00 | c8 00 | 00 00 | 00 00 00 00 |
The camera will reply with an xml with brightness and contrast
@@ -236,9 +238,9 @@ Some message IDs also require input along with the request header. For example
ID 151 which is the users ability info requires the header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset |
|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------|
| f0 de bc 0a | 97 00 00 00 | a7 00 00 00 | 00 00 00 02 | 00 00 | 14 64 | a7 00 00 00 |
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|--------------|--------------|----------------|-------------------|-------------------|---------------|----------------|
| f0 de bc 0a | 97 00 00 00 | a7 00 00 00 | 00 00 00 02 | 00 00 | 14 64 | a7 00 00 00 |
and the body of
@@ -255,3 +257,34 @@ abilities you want to know about.
Details of expected formats should be found from the
[docs](dissector/messages.md)
#### AES Encryption
If the encryption flag returned from the camera is `0x02dd` then AES encryption will be used.
The cameras use AES cfb128 with an IV of `0123456789abcdef` the key is made as follows
- Concatenated the `NONCE` from login with a `-` then with your plain text password
- MD5 Hash this concatenated string
- Represent the hash as hex string in all caps
- Take the first 16 characters as the encryption key
Here is an example:
```rust
use aes::Aes128;
use cfb_mode::cipher::{NewStreamCipher, StreamCipher};
use cfb_mode::Cfb;
const IV: &[u8] = b"0123456789abcdef";
let key_phrase = format!("{}-{}", nonce, passwd);
let key_phrase_hash = format!("{:X}\0", md5::compute(&key_phrase))
.to_uppercase()
.into_bytes();
let key = key_phrase_hash[0..16];
let mut decrypted = encrypted.to_vec();
Cfb::<Aes128>::new(key.into(), IV.into()).decrypt(&mut decrypted);
return decrypted;
```
Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 155 KiB

+6 -3
View File
@@ -1,11 +1,14 @@
use structopt::StructOpt;
use std::path::PathBuf;
use structopt::{clap::AppSettings, StructOpt};
/// A standards-compliant bridge to Reolink IP cameras
#[derive(StructOpt, Debug)]
#[structopt(name = "neolink")]
#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))]
pub struct Opt {
#[structopt(short, long, parse(from_os_str))]
pub config: Option<PathBuf>,
#[structopt(subcommand)]
pub cmd: Command,
pub cmd: Option<Command>,
}
#[derive(StructOpt, Debug)]
-14
View File
@@ -1,14 +0,0 @@
use err_derive::Error;
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
#[error(display = "RTSP Error")]
Rtsp(#[error(source)] super::rtsp::Error),
#[error(display = "Status LED Error")]
StatusLight(#[error(source)] super::statusled::Error),
#[error(display = "Reboot Error")]
Reboot(#[error(source)] super::reboot::Error),
#[error(display = "Talk Error")]
Talk(#[error(source)] super::talk::Error),
}
+19 -8
View File
@@ -7,21 +7,20 @@
//! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras
//! that do not nativly support RTSP.
//!
use anyhow::Result;
use env_logger::Env;
use log::*;
use structopt::StructOpt;
mod cmdline;
mod errors;
mod reboot;
mod rtsp;
mod statusled;
mod talk;
use cmdline::{Command, Opt};
use errors::Error;
fn main() -> Result<(), Error> {
fn main() -> Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
info!(
@@ -32,17 +31,29 @@ fn main() -> Result<(), Error> {
let opt = Opt::from_args();
match opt.cmd {
Command::Rtsp(opts) => {
match (opt.cmd, opt.config) {
(None, None) => {
// Should be caught at the clap validation
unreachable!();
}
(None, Some(config)) => {
warn!(
"Deprecated command line option. Please use: `neolink rtsp --config={:?}`",
config
);
rtsp::main(rtsp::Opt { config })?;
}
(Some(_), Some(_)) => error!("--config should be given after the subcommand"),
(Some(Command::Rtsp(opts)), None) => {
rtsp::main(opts)?;
}
Command::StatusLight(opts) => {
(Some(Command::StatusLight(opts)), None) => {
statusled::main(opts)?;
}
Command::Reboot(opts) => {
(Some(Command::Reboot(opts)), None) => {
reboot::main(opts)?;
}
Command::Talk(opts) => {
(Some(Command::Talk(opts)), None) => {
talk::main(opts)?;
}
}
-20
View File
@@ -1,20 +0,0 @@
use err_derive::Error;
/// The main error for the reboot subcommand
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Raised when the config file fails to deserlize
#[error(display = "Configuration parsing error")]
Config(#[error(source)] toml::de::Error),
/// Raised when `neolink_core` raises an error
#[error(display = "Communication error")]
Protocol(#[error(source)] neolink_core::Error),
/// Raised when there is an IO error such as unable to find
/// config file
#[error(display = "I/O error")]
Io(#[error(source)] std::io::Error),
/// Raised when the config file fails validataion
#[error(display = "Validation error")]
Validation(#[error(source)] validator::ValidationErrors),
}
+30 -14
View File
@@ -11,6 +11,7 @@
/// neolink reboot --config=config.toml CameraName
/// ```
///
use anyhow::{anyhow, Context, Result};
use log::*;
use neolink_core::bc_protocol::BcCamera;
use std::fs;
@@ -18,19 +19,23 @@ use validator::Validate;
mod cmdline;
mod config;
mod errors;
pub(crate) use cmdline::Opt;
use config::Config;
pub(crate) use errors::Error;
/// Entry point for the reboot subcommand
///
/// Opt is the command line options
pub fn main(opt: Opt) -> Result<(), Error> {
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
pub fn main(opt: Opt) -> Result<()> {
let config: Config = toml::from_str(
&fs::read_to_string(&opt.config)
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
)
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
config.validate()?;
config
.validate()
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
let mut cam_found = false;
for camera_config in &config.cameras {
@@ -42,23 +47,34 @@ pub fn main(opt: Opt) -> Result<(), Error> {
);
let mut camera =
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
camera_config.name, camera_config.camera_addr, camera_config.channel_id
)
})?;
info!("{}: Logging in", camera_config.name);
camera.login(&camera_config.username, camera_config.password.as_deref())?;
camera
.login(&camera_config.username, camera_config.password.as_deref())
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
info!("{}: Connected and logged in", camera_config.name);
camera.reboot()?;
camera
.reboot()
.context("Could not send reboot command to the camera")?;
}
}
if !cam_found {
error!(
"No camera with the name {} was found in the config",
opt.camera
);
Err(anyhow!(
"Camera {} was not in the config file {:?}",
&opt.camera,
&opt.config
))
} else {
Ok(())
}
Ok(())
}
+2 -1
View File
@@ -7,7 +7,8 @@ use validator::{Validate, ValidationError};
use validator_derive::Validate;
lazy_static! {
static ref RE_STREAM_SRC: Regex = Regex::new(r"^(mainStream|subStream|both)$").unwrap();
static ref RE_STREAM_SRC: Regex =
Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap();
static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap();
}
-23
View File
@@ -1,23 +0,0 @@
use err_derive::Error;
/// The main error for the rtsp subcommand
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Raised when the config file fails to deserlize
#[error(display = "Configuration parsing error")]
Config(#[error(source)] toml::de::Error),
/// Raised when `neolink_core` raises an error
#[error(display = "Communication error")]
Protocol(#[error(source)] neolink_core::Error),
/// Raised when there is an IO error such as unable to find
/// config file
#[error(display = "I/O error")]
Io(#[error(source)] std::io::Error),
/// Raised when the config file fails validataion
#[error(display = "Validation error")]
Validation(#[error(source)] validator::ValidationErrors),
// Raised when there is an ADPCM decoding error
// #[error(display = "ADPCM Decoding Error")]
// AdpcmDecoding(&'static str),
}
+74 -35
View File
@@ -28,8 +28,9 @@
/// neolink rtsp --config=config.toml
/// ```
///
use anyhow::{Context, Result};
use log::*;
use neolink_core::bc_protocol::BcCamera;
use neolink_core::bc_protocol::{BcCamera, Stream};
use std::collections::HashSet;
use std::fs;
use std::sync::Arc;
@@ -41,21 +42,25 @@ use validator::Validate;
mod cmdline;
mod config;
/// The errors this subcommand can raise
mod errors;
mod gst;
pub(crate) use cmdline::Opt;
use config::{CameraConfig, Config, UserConfig};
pub(crate) use errors::Error;
use gst::{GstOutputs, RtspServer, TlsAuthenticationMode};
/// Entry point for the rtsp subcommand
///
/// Opt is the command line options
pub fn main(opt: Opt) -> Result<(), Error> {
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
pub fn main(opt: Opt) -> Result<()> {
let config: Config = toml::from_str(
&fs::read_to_string(&opt.config)
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
)
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
config.validate()?;
config
.validate()
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
let rtsp = &RtspServer::new();
@@ -83,7 +88,7 @@ pub fn main(opt: Opt) -> Result<(), Error> {
get_permitted_users(config.users.as_slice(), &arc_cam.permitted_users);
// Set up each main and substream according to all the RTSP mount paths we support
if ["both", "mainStream"].iter().any(|&e| e == arc_cam.stream) {
if ["all", "both", "mainStream"].iter().any(|&e| e == arc_cam.stream) {
let paths = &[
&*format!("/{}", arc_cam.name),
&*format!("/{}/mainStream", arc_cam.name),
@@ -92,16 +97,25 @@ pub fn main(opt: Opt) -> Result<(), Error> {
.add_stream(paths, &permitted_users)
.unwrap();
let main_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true));
s.spawn(move |_| camera_loop(&*main_camera, Stream::Main, &mut outputs, true));
}
if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) {
if ["all", "both", "subStream"].iter().any(|&e| e == arc_cam.stream) {
let paths = &[&*format!("/{}/subStream", arc_cam.name)];
let mut outputs = rtsp
.add_stream(paths, &permitted_users)
.unwrap();
let sub_camera = arc_cam.clone();
let manage = arc_cam.stream == "subStream";
s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage));
s.spawn(move |_| camera_loop(&*sub_camera, Stream::Sub, &mut outputs, manage));
}
if ["all", "externStream"].iter().any(|&e| e == arc_cam.stream) {
let paths = &[&*format!("/{}/externStream", arc_cam.name)];
let mut outputs = rtsp
.add_stream(paths, &permitted_users)
.unwrap();
let sub_camera = arc_cam.clone();
let manage = arc_cam.stream == "externStream";
s.spawn(move |_| camera_loop(&*sub_camera, Stream::Extern, &mut outputs, manage));
}
}
@@ -114,10 +128,10 @@ pub fn main(opt: Opt) -> Result<(), Error> {
fn camera_loop(
camera_config: &CameraConfig,
stream_name: &str,
stream_name: Stream,
outputs: &mut GstOutputs,
manage: bool,
) -> Result<(), Error> {
) -> Result<(), anyhow::Error> {
let min_backoff = Duration::from_secs(1);
let max_backoff = Duration::from_secs(15);
let mut current_backoff = min_backoff;
@@ -130,25 +144,26 @@ fn camera_loop(
if cam_err.connected {
current_backoff = min_backoff;
}
match cam_err.err {
neolink_core::Error::AuthFailed => {
error!(
"Authentication failed to camera {}, not retrying",
camera_config.name
);
return Err(cam_err.err.into());
}
_ => error!(
if cam_err.login_fail {
error!(
"Authentication failed to camera {}, not retrying",
camera_config.name
);
return Err(cam_err.err);
} else {
error!(
"Error streaming from camera {}, will retry in {}s: {:?}",
camera_config.name,
current_backoff.as_secs(),
cam_err.err
),
)
}
std::thread::sleep(current_backoff);
current_backoff = std::cmp::min(max_backoff, current_backoff * 2);
} else {
// Should not occur because we don't set the callback up
// in such a way that it requests graceful shutdown
return Ok(());
}
}
@@ -156,7 +171,8 @@ fn camera_loop(
struct CameraErr {
connected: bool,
err: neolink_core::Error,
login_fail: bool,
err: anyhow::Error,
}
fn set_up_tls(config: &Config, rtsp: &RtspServer) {
@@ -206,13 +222,22 @@ fn get_permitted_users<'a>(
fn camera_main(
camera_config: &CameraConfig,
stream_name: &str,
stream_name: Stream,
outputs: &mut GstOutputs,
manage: bool,
) -> Result<(), CameraErr> {
let mut connected = false;
let mut login_fail = false;
(|| {
let mut camera = BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
let mut camera =
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
camera_config.name, camera_config.camera_addr, camera_config.channel_id
)
})?;
if camera_config.timeout.is_some() {
warn!("The undocumented `timeout` config option has been removed and is no longer needed.");
warn!("Please update your config file.");
@@ -223,28 +248,42 @@ fn camera_main(
camera_config.name, camera_config.camera_addr
);
camera.login(&camera_config.username, camera_config.password.as_deref())?;
info!("{}: Logging in", camera_config.name);
camera.login(&camera_config.username, camera_config.password.as_deref()).map_err(|e|
{
if let neolink_core::Error::AuthFailed = e {
login_fail = true;
}
e
}
).with_context(|| format!("Failed to login to {}", camera_config.name))?;
connected = true;
info!("{}: Connected and logged in", camera_config.name);
if manage {
do_camera_management(&mut camera, camera_config)?;
do_camera_management(&mut camera, camera_config).context("Failed to manage the camera settings")?;
}
let stream_display_name = match stream_name {
Stream::Main => "Main Stream (Clear)",
Stream::Sub => "Sub Stream (Fluent)",
Stream::Extern => "Extern Stream (Balanced)",
};
info!(
"{}: Starting video stream {}",
camera_config.name, stream_name
camera_config.name, stream_display_name
);
camera.start_video(outputs, stream_name)
})()
.map_err(|err| CameraErr { connected, err })
camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name))
})().map_err(|e| CameraErr{
connected,
login_fail,
err: e,
})
}
fn do_camera_management(
camera: &mut BcCamera,
camera_config: &CameraConfig,
) -> Result<(), neolink_core::Error> {
fn do_camera_management(camera: &mut BcCamera, camera_config: &CameraConfig) -> Result<()> {
let cam_time = camera.get_time()?;
if let Some(time) = cam_time {
info!(
+6 -3
View File
@@ -1,12 +1,15 @@
use super::errors::ParseOnOffError;
use anyhow::{anyhow, Result};
use std::path::PathBuf;
use structopt::StructOpt;
fn onoff_parse(src: &str) -> Result<bool, ParseOnOffError> {
fn onoff_parse(src: &str) -> Result<bool> {
match src {
"true" | "on" | "yes" => Ok(true),
"false" | "off" | "no" => Ok(false),
_ => Err(ParseOnOffError),
_ => Err(anyhow!(
"Could not understand {}, check your input, should be true/false, on/off or yes/no",
src
)),
}
}
-24
View File
@@ -1,24 +0,0 @@
use err_derive::Error;
/// The main error for the status-light subcommand
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Raised when the config file fails to deserlize
#[error(display = "Configuration parsing error")]
Config(#[error(source)] toml::de::Error),
/// Raised when `neolink_core` raises an error
#[error(display = "Communication error")]
Protocol(#[error(source)] neolink_core::Error),
/// Raised when there is an IO error such as unable to find
/// config file
#[error(display = "I/O error")]
Io(#[error(source)] std::io::Error),
/// Raised when the config file fails validataion
#[error(display = "Validation error")]
Validation(#[error(source)] validator::ValidationErrors),
}
#[derive(Error, Debug)]
#[error(display = "Failed to parse on/off flag")]
pub(super) struct ParseOnOffError;
+30 -14
View File
@@ -15,6 +15,7 @@
/// neolink status-light --config=config.toml CameraName off
/// ```
///
use anyhow::{anyhow, Context, Result};
use log::*;
use neolink_core::bc_protocol::BcCamera;
use std::fs;
@@ -22,19 +23,23 @@ use validator::Validate;
mod cmdline;
mod config;
mod errors;
pub(crate) use cmdline::Opt;
use config::Config;
pub(crate) use errors::Error;
/// Entry point for the ledstatus subcommand
///
/// Opt is the command line options
pub fn main(opt: Opt) -> Result<(), Error> {
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
pub fn main(opt: Opt) -> Result<()> {
let config: Config = toml::from_str(
&fs::read_to_string(&opt.config)
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
)
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
config.validate()?;
config
.validate()
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
let mut cam_found = false;
for camera_config in &config.cameras {
@@ -46,23 +51,34 @@ pub fn main(opt: Opt) -> Result<(), Error> {
);
let mut camera =
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
camera_config.name, camera_config.camera_addr, camera_config.channel_id
)
})?;
info!("{}: Logging in", camera_config.name);
camera.login(&camera_config.username, camera_config.password.as_deref())?;
camera
.login(&camera_config.username, camera_config.password.as_deref())
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
info!("{}: Connected and logged in", camera_config.name);
camera.led_light_set(opt.on)?;
camera
.led_light_set(opt.on)
.context("Unable to set camera light state")?;
}
}
if !cam_found {
error!(
"No camera with the name {} was found in the config",
opt.camera
);
Err(anyhow!(
"Camera {} was not in the config file {:?}",
&opt.camera,
&opt.config
))
} else {
Ok(())
}
Ok(())
}
-42
View File
@@ -1,42 +0,0 @@
use err_derive::Error;
use gstreamer::glib;
/// The main error for the status-light subcommand
#[derive(Debug, Error)]
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Raised when the config file fails to deserlize
#[error(display = "Configuration parsing error")]
Config(#[error(source)] toml::de::Error),
/// Raised when `neolink_core` raises an error
#[error(display = "Communication error")]
Protocol(#[error(source)] neolink_core::Error),
/// Raised when there is an IO error such as unable to find
/// config file
#[error(display = "I/O error")]
Io(#[error(source)] std::io::Error),
/// Raised when the config file fails validataion
#[error(display = "Validation error")]
Validation(#[error(source)] validator::ValidationErrors),
/// Raised when gstreamer fails to init
#[error(display = "Gstreamer init failed")]
GstreamerInit(#[error(source)] glib::Error),
/// Raised when a needed part of the gsteamer pipeline is not found
///
/// Usually this means missing pluings
#[error(display = "Gstreamer element not supported. Check your gstreamer plugins")]
GstreamerElement(gstreamer::Element),
/// Raised where there is an issue starting a audio playback in gstraemer
#[error(display = "Gstreamer Unable to play the file")]
GstreamerPlayback(#[error(source)] gstreamer::StateChangeError),
/// Generic gstreamer error
#[error(display = "Gstreamer raised an error")]
Gstreamer {
error: String,
debug: Option<String>,
},
/// Raised when talk back is unsupported
#[error(display = "This camera does not support talkback")]
TalkUnsupported,
}
+22 -19
View File
@@ -1,3 +1,4 @@
use anyhow::{anyhow, Context, Result};
use gstreamer::{
element_error, parse_launch, prelude::*, Caps, ClockTime, FlowError, FlowSuccess, MessageView,
Pipeline, ResourceError, State,
@@ -5,7 +6,6 @@ use gstreamer::{
use gstreamer_app::{AppSink, AppSinkCallbacks};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use super::errors::Error;
use byte_slice_cast::*;
pub(super) fn from_input(
@@ -13,12 +13,12 @@ pub(super) fn from_input(
volume: f32,
block_align: u16,
sample_rate: u16,
) -> Result<Receiver<Vec<u8>>, Error> {
) -> Result<Receiver<Vec<u8>>> {
let pipeline = create_pipeline(input_src, volume, block_align, sample_rate)?;
input(pipeline)
}
fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>, Error> {
fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>> {
let appsink = get_sink(&pipeline)?;
let (tx, rx) = sync_channel(30);
@@ -31,7 +31,7 @@ fn input(pipeline: Pipeline) -> Result<Receiver<Vec<u8>>, Error> {
Ok(rx)
}
fn start_pipeline(pipeline: Pipeline) -> Result<(), Error> {
fn start_pipeline(pipeline: Pipeline) -> Result<()> {
pipeline.set_state(State::Playing)?;
let bus = pipeline
@@ -42,30 +42,31 @@ fn start_pipeline(pipeline: Pipeline) -> Result<(), Error> {
match msg.view() {
MessageView::Eos(..) => break,
MessageView::Error(err) => {
pipeline.set_state(State::Null)?;
pipeline
.set_state(State::Null)
.context("Error in gstreamer when setting state to Null")?;
log::warn!(
"{:?}",
Error::Gstreamer {
error: err.error().to_string(),
debug: err.debug(),
}
"Error from gstreamer when setting the play state {:?} setting to Null instead",
err
);
}
_ => (),
}
}
pipeline.set_state(State::Null)?;
pipeline
.set_state(State::Null)
.context("Error in gstreamer when setting state to Null")?;
Ok(())
}
fn get_sink(pipeline: &Pipeline) -> Result<AppSink, Error> {
fn get_sink(pipeline: &Pipeline) -> Result<AppSink> {
let sink = pipeline
.by_name("thesink")
.expect("There shoud be a `thesink`");
sink.dynamic_cast::<AppSink>()
.map_err(Error::GstreamerElement)
.map_err(|_| anyhow!("Cannot find appsink in gstreamer, check your gstreamer plugins"))
}
fn set_data_channel(appsink: &AppSink, tx: SyncSender<Vec<u8>>) {
@@ -131,8 +132,9 @@ fn create_pipeline(
volume: f32,
block_align: u16,
sample_rate: u16,
) -> Result<Pipeline, Error> {
gstreamer::init()?;
) -> Result<Pipeline> {
gstreamer::init()
.context("Unable to start gstreamer ensure it and all plugins are installed")?;
let launch_str = format!(
"{} \
@@ -152,10 +154,11 @@ fn create_pipeline(
// 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)?;
let pipeline = pipeline
.dynamic_cast::<Pipeline>()
.map_err(Error::GstreamerElement)?;
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 appsink = get_sink(&pipeline)?;
+45 -19
View File
@@ -11,6 +11,7 @@
/// neolink status-light --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName
/// ```
///
use anyhow::{anyhow, Context, Result};
use log::*;
use neolink_core::{bc::xml::TalkConfig, bc_protocol::BcCamera};
use std::fs;
@@ -18,20 +19,24 @@ use validator::Validate;
mod cmdline;
mod config;
mod errors;
mod gst;
pub(crate) use cmdline::Opt;
use config::Config;
pub(crate) use errors::Error;
/// Entry point for the talk subcommand
///
/// Opt is the command line options
pub fn main(opt: Opt) -> Result<(), Error> {
let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?;
pub fn main(opt: Opt) -> Result<()> {
let config: Config = toml::from_str(
&fs::read_to_string(&opt.config)
.with_context(|| format!("Failed to read {:?}", &opt.config))?,
)
.with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?;
config.validate()?;
config
.validate()
.with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?;
let mut cam_found = false;
for camera_config in &config.cameras {
@@ -43,19 +48,32 @@ pub fn main(opt: Opt) -> Result<(), Error> {
);
let mut camera =
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?;
BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)
.with_context(|| {
format!(
"Failed to connect to camera {} at {} on channel {}",
camera_config.name, camera_config.camera_addr, camera_config.channel_id
)
})?;
info!("{}: Logging in", camera_config.name);
camera.login(&camera_config.username, camera_config.password.as_deref())?;
camera
.login(&camera_config.username, camera_config.password.as_deref())
.with_context(|| format!("Failed to login to {}", camera_config.name))?;
info!("{}: Connected and logged in", camera_config.name);
let talk_ability = camera.talk_ability()?;
let talk_ability = camera
.talk_ability()
.with_context(|| format!("Camera {} does not support talk", camera_config.name))?;
if talk_ability.duplex_list.is_empty()
|| talk_ability.audio_stream_mode_list.is_empty()
|| talk_ability.audio_config_list.is_empty()
{
return Err(Error::TalkUnsupported);
return Err(anyhow!(
"Camera {} does not support talk",
camera_config.name
));
}
// Just copy that data from the first talk ability in the config have never seen more
@@ -75,7 +93,10 @@ pub fn main(opt: Opt) -> Result<(), Error> {
let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4;
let sample_rate = talk_config.audio_config.sample_rate;
if block_size == 0 || sample_rate == 0 {
return Err(Error::TalkUnsupported);
return Err(anyhow!(
"The camera {} does not support talk with adpcm",
camera_config.name
));
}
let rx = match (&opt.file_path, &opt.microphone) {
@@ -87,23 +108,28 @@ pub fn main(opt: Opt) -> Result<(), Error> {
opt.volume,
block_size,
sample_rate,
)?,
)
.with_context(|| format!("Failed to setup gst with the file: {:?}", path))?,
(None, true) => {
gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate)?
gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate)
.context("Failed to setup gst using the microphone")?
}
_ => unreachable!(),
};
camera.talk_stream(rx, talk_config)?;
camera
.talk_stream(rx, talk_config)
.context("Talk stream ended early")?;
}
}
if !cam_found {
error!(
"No camera with the name {} was found in the config",
opt.camera
);
Err(anyhow!(
"Camera {} was not in the config file {:?}",
&opt.camera,
&opt.config
))
} else {
Ok(())
}
Ok(())
}