diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 32de4cf..6ce7d6f 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -66,7 +66,6 @@ where // We should just wait and try again } Err(e) => { - log::error!("HERE {:?}", e); return Err(e.into()); } } diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index e0286c5..c6dda1c 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -11,6 +11,7 @@ use Md5Trunc::*; mod binarysub; mod connection; mod errors; +pub(crate) mod filesub; mod ledstate; mod login; mod logout; diff --git a/crates/core/src/bc_protocol/filesub.rs b/crates/core/src/bc_protocol/filesub.rs new file mode 100644 index 0000000..7e5f6ec --- /dev/null +++ b/crates/core/src/bc_protocol/filesub.rs @@ -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 = std::result::Result; + +/// 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, + buffer: Vec, + 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>(paths: Vec

) -> 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 { + 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::>(); + 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; + } +} diff --git a/crates/core/src/bc_protocol/talk.rs b/crates/core/src/bc_protocol/talk.rs index 343e73b..5d2b08a 100644 --- a/crates/core/src/bc_protocol/talk.rs +++ b/crates/core/src/bc_protocol/talk.rs @@ -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()?; diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index e57bc2b..404a9b3 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -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(_) => {} + } + } + } +} diff --git a/crates/core/src/bcmedia/model.rs b/crates/core/src/bcmedia/model.rs index 0127b67..3edc8a5 100644 --- a/crates/core/src/bcmedia/model.rs +++ b/crates/core/src/bcmedia/model.rs @@ -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, diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_00.raw b/crates/core/src/bcmedia/samples/video_stream_swan_00.raw new file mode 100644 index 0000000..394dd04 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_00.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_01.raw b/crates/core/src/bcmedia/samples/video_stream_swan_01.raw new file mode 100644 index 0000000..f1bbca0 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_01.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_02.raw b/crates/core/src/bcmedia/samples/video_stream_swan_02.raw new file mode 100644 index 0000000..cc62b07 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_02.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_03.raw b/crates/core/src/bcmedia/samples/video_stream_swan_03.raw new file mode 100644 index 0000000..4c17574 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_03.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_04.raw b/crates/core/src/bcmedia/samples/video_stream_swan_04.raw new file mode 100644 index 0000000..be592bc Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_04.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_05.raw b/crates/core/src/bcmedia/samples/video_stream_swan_05.raw new file mode 100644 index 0000000..57e534d Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_05.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_06.raw b/crates/core/src/bcmedia/samples/video_stream_swan_06.raw new file mode 100644 index 0000000..4842c5f Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_06.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_07.raw b/crates/core/src/bcmedia/samples/video_stream_swan_07.raw new file mode 100644 index 0000000..b46bdbb Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_07.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_08.raw b/crates/core/src/bcmedia/samples/video_stream_swan_08.raw new file mode 100644 index 0000000..709aa73 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_08.raw differ diff --git a/crates/core/src/bcmedia/samples/video_stream_swan_09.raw b/crates/core/src/bcmedia/samples/video_stream_swan_09.raw new file mode 100644 index 0000000..52427f5 Binary files /dev/null and b/crates/core/src/bcmedia/samples/video_stream_swan_09.raw differ diff --git a/crates/core/src/bcmedia/ser.rs b/crates/core/src/bcmedia/ser.rs index 9173589..c5328cc 100644 --- a/crates/core/src/bcmedia/ser.rs +++ b/crates/core/src/bcmedia/ser.rs @@ -183,6 +183,6 @@ fn bcmedia_adpcm(payload: &BcMediaAdpcm) -> impl SerializeFn { 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 )) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 3c25ab8..4b6076a 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -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. //!