Fix adpcm and add a test for swann cameras
This commit is contained in:
18 files changed
+185
-11
No files matched your search
@@ -66,7 +66,6 @@ where
|
||||
// We should just wait and try again
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("HERE {:?}", e);
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use Md5Trunc::*;
|
||||
mod binarysub;
|
||||
mod connection;
|
||||
mod errors;
|
||||
pub(crate) mod filesub;
|
||||
mod ledstate;
|
||||
mod login;
|
||||
mod logout;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// This is a test module so it will appear as unused most of the time
|
||||
#![allow(dead_code)]
|
||||
// This module is used to subscribe to raw bytes on disk
|
||||
//
|
||||
// It is mostly used for testing
|
||||
//
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufRead, Error, Read},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// A `FileSubscriber` is a helper util to read a binary stream
|
||||
/// from a series of files
|
||||
///
|
||||
/// This stream should be accessed via the [`BufRead`] and [`Read`] trait
|
||||
#[derive(Debug)]
|
||||
pub struct FileSubscriber {
|
||||
files: Vec<PathBuf>,
|
||||
buffer: Vec<u8>,
|
||||
consumed: usize,
|
||||
}
|
||||
|
||||
impl FileSubscriber {
|
||||
/// Creates a binary subsciber from a BcSubscrption.
|
||||
/// When reading the next packet it will skip over multiple
|
||||
/// Bc packets to fill the binary buffer so ensure you
|
||||
/// only want binary packets when calling read
|
||||
pub fn from_files<P: AsRef<Path>>(paths: Vec<P>) -> FileSubscriber {
|
||||
FileSubscriber {
|
||||
files: paths
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|p| {
|
||||
let path: &Path = p.as_ref();
|
||||
path.to_path_buf()
|
||||
})
|
||||
.collect(),
|
||||
buffer: vec![],
|
||||
consumed: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for FileSubscriber {
|
||||
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
|
||||
let buffer = self.fill_buf()?;
|
||||
let amt = std::cmp::min(buf.len(), buffer.len());
|
||||
|
||||
// First check if the amount of bytes we want to read is small:
|
||||
// `copy_from_slice` will generally expand to a call to `memcpy`, and
|
||||
// for a single byte the overhead is significant.
|
||||
if amt == 1 {
|
||||
buf[0] = buffer[0];
|
||||
} else {
|
||||
buf[..amt].copy_from_slice(&buffer[..amt]);
|
||||
}
|
||||
|
||||
self.consume(amt);
|
||||
|
||||
Ok(amt)
|
||||
}
|
||||
}
|
||||
impl BufRead for FileSubscriber {
|
||||
fn fill_buf(&mut self) -> Result<&[u8]> {
|
||||
const CLEAR_CONSUMED_AT: usize = 1024;
|
||||
// This is a trade off between caching too much dead memory
|
||||
// and calling the drain method too often
|
||||
if self.consumed > CLEAR_CONSUMED_AT {
|
||||
let _ = self.buffer.drain(0..self.consumed).collect::<Vec<u8>>();
|
||||
self.consumed = 0;
|
||||
}
|
||||
while self.buffer.len() <= self.consumed {
|
||||
let next_file = self.files.pop();
|
||||
log::error!("Next file: {:?}", next_file);
|
||||
if let Some(next_file) = next_file {
|
||||
let bytes = &fs::read(next_file)?;
|
||||
self.buffer.extend(bytes);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(&self.buffer.as_slice()[self.consumed..])
|
||||
}
|
||||
|
||||
fn consume(&mut self, amt: usize) {
|
||||
assert!(self.consumed + amt <= self.buffer.len());
|
||||
self.consumed += amt;
|
||||
}
|
||||
}
|
||||
@@ -153,8 +153,13 @@ impl BcCamera {
|
||||
sub.send(msg)?;
|
||||
let mut msg = sub.rx.recv_timeout(RX_TIMEOUT)?;
|
||||
|
||||
// If another client is already talking OR if we crashed before sending
|
||||
// msgid 11 the camera will reply 422
|
||||
//
|
||||
// The official client in this case just sends msgid 11 and retries so
|
||||
// we will do that too
|
||||
if let BcMeta {
|
||||
response_code: 442, ..
|
||||
response_code: 422, ..
|
||||
} = msg.meta
|
||||
{
|
||||
self.talk_stop()?;
|
||||
@@ -287,8 +292,13 @@ impl BcCamera {
|
||||
sub.send(msg)?;
|
||||
let mut msg = sub.rx.recv_timeout(RX_TIMEOUT)?;
|
||||
|
||||
// If another client is already talking OR if we crashed before sending
|
||||
// msgid 11 the camera will reply 422
|
||||
//
|
||||
// The official client in this case just sends msgid 11 and retries so
|
||||
// we will do that too
|
||||
if let BcMeta {
|
||||
response_code: 442, ..
|
||||
response_code: 422, ..
|
||||
} = msg.meta
|
||||
{
|
||||
self.talk_stop()?;
|
||||
|
||||
@@ -219,6 +219,7 @@ fn bcmedia_iframe(buf: &[u8]) -> IResult<&[u8], BcMediaIframe> {
|
||||
"H265" => VideoType::H265,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaIframe {
|
||||
@@ -282,14 +283,15 @@ fn bcmedia_aac(buf: &[u8]) -> IResult<&[u8], BcMediaAac> {
|
||||
}
|
||||
|
||||
fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> {
|
||||
const BLOCK_HEADER_SIZE: u16 = 4;
|
||||
const SUB_HEADER_SIZE: u16 = 4;
|
||||
|
||||
let (buf, payload_size) = le_u16(buf)?;
|
||||
let (buf, _payload_size_b) = le_u16(buf)?;
|
||||
let (buf, _magic) = verify(le_u16, |x| *x == MAGIC_HEADER_BCMEDIA_ADPCM_DATA)(buf)?;
|
||||
// This `sample_block_size` is bigendian for some reason. It is block size - BLOCK_HEADER_SIZE
|
||||
let (buf, sample_block_size) = be_u16(buf)?;
|
||||
let block_size = sample_block_size + BLOCK_HEADER_SIZE;
|
||||
// On some camera this value is just 2
|
||||
// On other cameras is half the block size without the header
|
||||
let (buf, _half_block_size) = le_u16(buf)?;
|
||||
let block_size = payload_size - SUB_HEADER_SIZE;
|
||||
let (buf, data_slice) = take!(buf, block_size)?;
|
||||
let pad_size = match payload_size as u32 % PAD_SIZE {
|
||||
0 => 0,
|
||||
@@ -306,3 +308,62 @@ fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> {
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Error;
|
||||
use crate::bc_protocol::filesub::FileSubscriber;
|
||||
use crate::bcmedia::model::*;
|
||||
use env_logger::Env;
|
||||
use log::*;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn init() {
|
||||
let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info"))
|
||||
.is_test(true)
|
||||
.try_init();
|
||||
}
|
||||
|
||||
fn sample(name: &str) -> PathBuf {
|
||||
let dir = std::env::current_dir().unwrap(); // This is crate root during cargo test
|
||||
dir.join("src").join("bcmedia").join("samples").join(name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
// This method will test the decoding on swann cameras output
|
||||
//
|
||||
// Crucially this contains adpcm
|
||||
fn test_swan_deser() {
|
||||
init();
|
||||
|
||||
let mut subsciber = FileSubscriber::from_files(vec![
|
||||
sample("video_stream_swan_00.raw"),
|
||||
sample("video_stream_swan_01.raw"),
|
||||
sample("video_stream_swan_02.raw"),
|
||||
sample("video_stream_swan_03.raw"),
|
||||
sample("video_stream_swan_04.raw"),
|
||||
sample("video_stream_swan_05.raw"),
|
||||
sample("video_stream_swan_06.raw"),
|
||||
sample("video_stream_swan_07.raw"),
|
||||
sample("video_stream_swan_08.raw"),
|
||||
sample("video_stream_swan_09.raw"),
|
||||
]);
|
||||
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut subsciber);
|
||||
match e {
|
||||
Err(Error::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("{:?}", e);
|
||||
panic!();
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
/// Video streams encapsulate a stream of BcMedia
|
||||
#[derive(Debug)]
|
||||
pub enum BcMedia {
|
||||
/// Holds info on the stream
|
||||
InfoV1(BcMediaInfoV1),
|
||||
@@ -18,6 +19,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug)]
|
||||
pub struct BcMediaInfoV1 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
@@ -61,6 +63,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug)]
|
||||
pub struct BcMediaInfoV2 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
@@ -103,6 +106,7 @@ pub struct BcMediaInfoV2 {
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
|
||||
|
||||
/// Video Types for I/PFrame
|
||||
#[derive(Debug)]
|
||||
pub enum VideoType {
|
||||
/// H264 video data
|
||||
H264,
|
||||
@@ -111,6 +115,7 @@ pub enum VideoType {
|
||||
}
|
||||
|
||||
/// This is a BcMedia video IFrame.
|
||||
#[derive(Debug)]
|
||||
pub struct BcMediaIframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
@@ -130,6 +135,7 @@ pub struct BcMediaIframe {
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
|
||||
|
||||
/// This is a BcMedia video PFrame.
|
||||
#[derive(Debug)]
|
||||
pub struct BcMediaPframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
@@ -146,6 +152,7 @@ pub struct BcMediaPframe {
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530;
|
||||
|
||||
/// This contains BcMedia audio data in AAC format
|
||||
#[derive(Debug)]
|
||||
pub struct BcMediaAac {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
@@ -160,6 +167,7 @@ pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100;
|
||||
|
||||
/// This contains BcMedia audio data in ADPCM format
|
||||
#[derive(Debug)]
|
||||
pub struct BcMediaAdpcm {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -183,6 +183,6 @@ fn bcmedia_adpcm<W: Write>(payload: &BcMediaAdpcm) -> impl SerializeFn<W> {
|
||||
le_u16((payload.data.len() + 4) as u16), // Payload + 2 byte magic + 2byte block size
|
||||
le_u16((payload.data.len() + 4) as u16), // Payload + 2 byte magic + 2byte block size
|
||||
le_u16(MAGIC_HEADER_BCMEDIA_ADPCM_DATA), // magic
|
||||
be_u16((payload.data.len() - 4) as u16), // sample_block_size = len - predictor state size (4bytes)
|
||||
le_u16(((payload.data.len() - 4) / 2) as u16), // Block size without the header halved
|
||||
))
|
||||
}
|
||||
@@ -8,16 +8,18 @@
|
||||
//! A camera can be initialised with
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use neolink_core::bc_protocol::BcCamera;
|
||||
//! let channel_id = 0; // Usually zero but can be non zero if uses a reolink NVR
|
||||
//! let camera = BcCamera::new_with_addr("camera_ip_address", channel_id);
|
||||
//! let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap();
|
||||
//! ```
|
||||
//!
|
||||
//! After that login can be conducted with
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # use neolink_core::bc_protocol::BcCamera;
|
||||
//! # let channel_id = 0;
|
||||
//! # let camera = BcCamera::new_with_addr("camera_ip_address", channel_id);
|
||||
//! camera.login("username", "password");
|
||||
//! # let mut camera = BcCamera::new_with_addr("camera_ip_address", channel_id).unwrap();
|
||||
//! camera.login("username", Some("password"));
|
||||
//! ```
|
||||
//! For further commands see the [`bc_protocol::BcCamera`] struct.
|
||||
//!
|
||||
|
||||
Reference in new issue
Block a user