diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 1943cfb..4b5ebc9 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -169,8 +169,7 @@ fn bc_modern_msg<'a, 'b>( }; // Now we'll take the buffer that Nom gave a ref to and parse it. - let extension; - if ext_len > 0 { + let extension = if ext_len > 0 { // Apply the XML parse function, but throw away the reference to decrypted in the Ok and // Err case. This error-error-error thing is the same idiom Nom uses internally. let parsed = Extension::try_parse(processed_ext_buf) @@ -182,10 +181,10 @@ fn bc_modern_msg<'a, 'b>( { context.in_bin_mode.insert(header.msg_num); } - extension = Some(parsed); + Some(parsed) } else { - extension = None; - } + None + }; // Now to handle the payload block // This block can either be xml or binary depending on what the message expects. diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 6f1b8be..ee6ade4 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -10,6 +10,8 @@ pub const MSG_ID_LOGIN: u32 = 1; pub const MSG_ID_LOGOUT: u32 = 2; /// Video and Audio Streams messages have this ID pub const MSG_ID_VIDEO: u32 = 3; +/// Video and Audio Streams messages have this ID when a stop is requested +pub const MSG_ID_VIDEO_STOP: u32 = 4; /// TalkAbility messages have this ID pub const MSG_ID_TALKABILITY: u32 = 10; /// TalkReset messages have this ID diff --git a/crates/core/src/bc/ser.rs b/crates/core/src/bc/ser.rs index f2770ff..a56de4f 100644 --- a/crates/core/src/bc/ser.rs +++ b/crates/core/src/bc/ser.rs @@ -164,7 +164,7 @@ where { move |buf: WriteContext| { if let Some(ref val) = opt { - ser(&*val)(buf) + ser(val)(buf) } else { do_nothing()(buf) } @@ -173,7 +173,7 @@ where /// A serializer combinator that does nothing with its input fn do_nothing() -> impl SerializeFn { - move |out: WriteContext| Ok(out) + Ok } #[test] diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 908bb41..ce0f1d0 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -12,6 +12,7 @@ use indoc::indoc; /// There are two types of payloads xml and binary #[derive(PartialEq, Eq, Debug, YaDeserialize)] #[yaserde(flatten)] +#[allow(clippy::large_enum_variant)] pub enum BcPayloads { /// XML payloads are the more common ones and include payloads for camera controls #[yaserde(rename = "body")] diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 40e099b..2fad5d3 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -31,7 +31,7 @@ pub use stream::{Stream, StreamOutput, StreamOutputError}; type Result = std::result::Result; -impl<'a> From for Error { +impl From for Error { fn from(k: std::sync::mpsc::RecvTimeoutError) -> Self { match k { std::sync::mpsc::RecvTimeoutError::Timeout => Error::Timeout, diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index e6ee85e..3efe3ce 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -14,13 +14,13 @@ use std::thread::JoinHandle; use std::time::{Duration, Instant}; /// A shareable connection to a camera. Handles serialization of messages. To send/receive, call -/// .[subscribe()] with a message ID. You can use the BcSubscription to send or receive only -/// messages with that ID; each incoming message is routed to its appropriate subscriber. +/// .[subscribe()] with a message number. You can use the BcSubscription to send or receive only +/// messages with that number; each incoming message is routed to its appropriate subscriber. /// /// There can be only one subscriber per kind of message at a time. pub struct BcConnection { sink: Arc>, - subscribers: Arc>>>, + subscribers: Arc>>>, rx_thread: Option>, // Arc> because it is shared between context // and connection for deserialisation and serialistion respectivly @@ -31,7 +31,7 @@ pub struct BcConnection { impl BcConnection { pub fn new(source: BcSource) -> Result { - let subscribers: Arc>>> = Default::default(); + let subscribers: Arc>>> = Default::default(); let mut subs = subscribers.clone(); @@ -96,17 +96,18 @@ impl BcConnection { Ok(()) } - pub fn subscribe(&self, msg_id: u32) -> Result { + #[allow(clippy::significant_drop_in_scrutinee)] + pub fn subscribe(&self, msg_num: u16) -> Result { let (tx, rx) = channel(); - match self.subscribers.lock().unwrap().entry(msg_id) { + match self.subscribers.lock().unwrap().entry(msg_num) { Entry::Vacant(vac_entry) => vac_entry.insert(tx), - Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_id }), + Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_num }), }; - Ok(BcSubscription::new(rx, msg_id, self)) + Ok(BcSubscription::new(rx, msg_num, self)) } - pub fn unsubscribe(&self, msg_id: u32) -> Result<()> { - self.subscribers.lock().unwrap().remove(&msg_id); + pub fn unsubscribe(&self, msg_num: u16) -> Result<()> { + self.subscribers.lock().unwrap().remove(&msg_num); Ok(()) } @@ -126,10 +127,11 @@ impl BcConnection { self.sink.lock().unwrap().is_udp() } + #[allow(clippy::significant_drop_in_scrutinee)] fn poll( context: &mut BcContext, connection: &BcSource, - subscribers: &mut Arc>>>, + subscribers: &mut Arc>>>, connections_keep_alive_msg: &Arc>>, ) -> Result<()> { // Don't hold the lock during deserialization so we don't poison the subscribers mutex if @@ -139,10 +141,11 @@ impl BcConnection { subscribers.lock().unwrap().clear(); err })?; + let msg_num = response.meta.msg_num; let msg_id = response.meta.msg_id; let mut locked_subs = subscribers.lock().unwrap(); - match locked_subs.entry(msg_id) { + match locked_subs.entry(msg_num) { Entry::Occupied(mut occ) => { if occ.get_mut().send(response).is_err() { // Exceedingly unlikely, unless you mishandle the subscription object @@ -152,7 +155,7 @@ impl BcConnection { } Entry::Vacant(_) => { if msg_id != MSG_ID_UDP_KEEP_ALIVE { - debug!("Ignoring uninteresting message ID {}", msg_id); + debug!("Ignoring uninteresting message num {}", msg_id); trace!("Contents: {:?}", response); } else { // This is a keep alive message let see what the camera says about it diff --git a/crates/core/src/bc_protocol/connection/bcsub.rs b/crates/core/src/bc_protocol/connection/bcsub.rs index d84fd39..307cff3 100644 --- a/crates/core/src/bc_protocol/connection/bcsub.rs +++ b/crates/core/src/bc_protocol/connection/bcsub.rs @@ -4,17 +4,17 @@ use std::sync::mpsc::Receiver; pub struct BcSubscription<'a> { pub rx: Receiver, - msg_id: u32, + msg_num: u16, conn: &'a BcConnection, } impl<'a> BcSubscription<'a> { - pub fn new(rx: Receiver, msg_id: u32, conn: &'a BcConnection) -> BcSubscription<'a> { - BcSubscription { rx, msg_id, conn } + pub fn new(rx: Receiver, msg_num: u16, conn: &'a BcConnection) -> BcSubscription<'a> { + BcSubscription { rx, msg_num, conn } } pub fn send(&self, bc: Bc) -> Result<()> { - assert!(bc.meta.msg_id == self.msg_id); + assert!(bc.meta.msg_num == self.msg_num); self.conn.send(bc)?; Ok(()) } @@ -24,6 +24,6 @@ impl<'a> BcSubscription<'a> { impl<'a> Drop for BcSubscription<'a> { fn drop(&mut self) { // It's fine if we can't unsubscribe as that means we already have - let _ = self.conn.unsubscribe(self.msg_id); + let _ = self.conn.unsubscribe(self.msg_num); } } diff --git a/crates/core/src/bc_protocol/connection/mod.rs b/crates/core/src/bc_protocol/connection/mod.rs index 4d6a235..a6de4b8 100644 --- a/crates/core/src/bc_protocol/connection/mod.rs +++ b/crates/core/src/bc_protocol/connection/mod.rs @@ -55,7 +55,7 @@ pub enum Error { UdpSerialization(#[error(source)] bcudp::ser::Error), #[error(display = "Simultaneous subscription")] - SimultaneousSubscription { msg_id: u32 }, + SimultaneousSubscription { msg_num: u16 }, #[error(display = "Timeout")] Timeout, diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs index f17c805..aabb873 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/discover.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -40,12 +40,11 @@ impl UdpDiscover { let addrs: Vec = addrs .iter() - .map(|a| { + .flat_map(|a| { a.to_socket_addrs() .ok() .and_then(|mut a_iter| a_iter.next()) }) - .flatten() .collect(); let mut bytes_send = 0; @@ -120,13 +119,12 @@ impl UdpDiscover { let ports: [u16; 2] = [2015, 2018]; let destinations: Vec<(Ipv4Addr, u16)> = broadcasts .iter() - .map(|&addr| { + .flat_map(|&addr| { ports .iter() .map(|&port| (addr, port)) .collect::>() }) - .flatten() .collect(); debug!("Broadcasting to: {:?}", destinations); diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs index 0125b86..37982f1 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -288,6 +288,7 @@ impl UdpTransmit { Ok(()) } + #[allow(clippy::significant_drop_in_scrutinee)] pub fn poll_write( &self, socket: &UdpSocket, diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index ef79712..20db6a7 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -38,6 +38,10 @@ pub enum Error { why: &'static str, }, + /// Raised when the camera responds with a status code over than OK + #[error(display = "Camera responded with Service Unavaliable")] + CameraServiceUnavaliable, + /// Raised when a connection is dropped. #[error(display = "Dropped connection")] DroppedConnection(#[error(source)] std::sync::mpsc::RecvError), diff --git a/crates/core/src/bc_protocol/ledstate.rs b/crates/core/src/bc_protocol/ledstate.rs index 6be34d8..e42be82 100644 --- a/crates/core/src/bc_protocol/ledstate.rs +++ b/crates/core/src/bc_protocol/ledstate.rs @@ -8,12 +8,13 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get time"); - let sub_get = connection.subscribe(MSG_ID_GET_LED_STATUS)?; + let msg_num = self.new_message_num(); + let sub_get = connection.subscribe(msg_num)?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_GET_LED_STATUS, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, @@ -29,6 +30,9 @@ impl BcCamera { sub_get.send(get)?; let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } if let BcBody::ModernMsg(ModernMsg { payload: @@ -54,7 +58,9 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get time"); - let sub_set = connection.subscribe(MSG_ID_SET_LED_STATUS)?; + + let msg_num = self.new_message_num(); + let sub_set = connection.subscribe(msg_num)?; // led_version is a field recieved from the camera but not sent // we set to None to ensure we don't send it to the camera @@ -63,7 +69,7 @@ impl BcCamera { meta: BcMeta { msg_id: MSG_ID_SET_LED_STATUS, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index 2a61ad0..3248275 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -13,7 +13,8 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to log in"); - let sub_login = connection.subscribe(MSG_ID_LOGIN)?; + let msg_num = self.new_message_num(); + let sub_login = connection.subscribe(msg_num)?; // Login flow is: Send legacy login message, expect back a modern message with Encryption // details. Then, re-send the login as a modern login message. Expect back a device info @@ -33,7 +34,7 @@ impl BcCamera { meta: BcMeta { msg_id: MSG_ID_LOGIN, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0xdc02, class: 0x6514, @@ -85,7 +86,7 @@ impl BcCamera { BcMeta { msg_id: MSG_ID_LOGIN, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, @@ -104,6 +105,9 @@ impl BcCamera { sub_login.send(modern_login)?; let modern_reply = sub_login.rx.recv_timeout(RX_TIMEOUT)?; + if modern_reply.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } match modern_reply.body { BcBody::ModernMsg(ModernMsg { diff --git a/crates/core/src/bc_protocol/logout.rs b/crates/core/src/bc_protocol/logout.rs index b6f3749..76924d5 100644 --- a/crates/core/src/bc_protocol/logout.rs +++ b/crates/core/src/bc_protocol/logout.rs @@ -10,7 +10,8 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to log in"); - let sub_logout = connection.subscribe(MSG_ID_LOGOUT)?; + let msg_num = self.new_message_num(); + let sub_logout = connection.subscribe(msg_num)?; let username = credentials.username.clone(); let password = credentials @@ -23,7 +24,7 @@ impl BcCamera { BcMeta { msg_id: MSG_ID_LOGOUT, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, diff --git a/crates/core/src/bc_protocol/ping.rs b/crates/core/src/bc_protocol/ping.rs index 0c63b0e..8c75905 100644 --- a/crates/core/src/bc_protocol/ping.rs +++ b/crates/core/src/bc_protocol/ping.rs @@ -6,13 +6,14 @@ impl BcCamera { /// or error pub fn ping(&self) -> Result<()> { let connection = self.connection.as_ref().expect("Must be connected to ping"); - let sub_ping = connection.subscribe(MSG_ID_PING)?; + let msg_num = self.new_message_num(); + let sub_ping = connection.subscribe(msg_num)?; let ping = Bc { meta: BcMeta { msg_id: MSG_ID_PING, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, diff --git a/crates/core/src/bc_protocol/pirstate.rs b/crates/core/src/bc_protocol/pirstate.rs index 98e5281..7cd23cd 100644 --- a/crates/core/src/bc_protocol/pirstate.rs +++ b/crates/core/src/bc_protocol/pirstate.rs @@ -8,12 +8,13 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get time"); - let sub_get = connection.subscribe(MSG_ID_GET_PIR_ALARM)?; + let msg_num = self.new_message_num(); + let sub_get = connection.subscribe(msg_num)?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_GET_PIR_ALARM, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, @@ -29,6 +30,9 @@ impl BcCamera { sub_get.send(get)?; let msg = sub_get.rx.recv_timeout(RX_TIMEOUT)?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } if let BcBody::ModernMsg(ModernMsg { payload: @@ -54,13 +58,14 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get time"); - let sub_set = connection.subscribe(MSG_ID_START_PIR_ALARM)?; + let msg_num = self.new_message_num(); + let sub_set = connection.subscribe(msg_num)?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_START_PIR_ALARM, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, @@ -79,6 +84,9 @@ impl BcCamera { sub_set.send(get)?; let msg = sub_set.rx.recv_timeout(RX_TIMEOUT)?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } if let BcMeta { response_code: 200, .. diff --git a/crates/core/src/bc_protocol/reboot.rs b/crates/core/src/bc_protocol/reboot.rs index ce6fe47..de696c3 100644 --- a/crates/core/src/bc_protocol/reboot.rs +++ b/crates/core/src/bc_protocol/reboot.rs @@ -5,13 +5,14 @@ impl BcCamera { /// Reboot the camera pub fn reboot(&self) -> Result<()> { let connection = self.connection.as_ref().expect("Must be connected to ping"); - let sub = connection.subscribe(MSG_ID_REBOOT)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; let msg = Bc { meta: BcMeta { msg_id: MSG_ID_REBOOT, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 0f5cd1d..7baab61 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -2,7 +2,10 @@ use super::{BcCamera, BinarySubscriber, Result}; use crate::{ bc::{model::*, xml::*}, bcmedia::model::*, - Never, +}; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, }; /// Convience type for the error raised by the [StreamOutput] trait @@ -46,7 +49,12 @@ impl BcCamera { /// /// This will block forever or return an error when the camera connection is dropped /// - pub fn start_video(&self, data_outs: &mut Outputs, stream: Stream) -> Result + pub fn start_video( + &self, + data_outs: &mut Outputs, + stream: Stream, + abort_handle: Arc, + ) -> Result<()> where Outputs: StreamOutput, { @@ -54,7 +62,8 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to start video"); - let sub_video = connection.subscribe(MSG_ID_VIDEO)?; + let msg_num = self.new_message_num(); + let sub_video = connection.subscribe(msg_num)?; // On an E1 and swann cameras: // - mainStream always has a value of 0 @@ -96,7 +105,7 @@ impl BcCamera { BcMeta { msg_id: MSG_ID_VIDEO, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: stream_code, response_code: 0, class: 0x6414, // IDK why @@ -116,10 +125,88 @@ impl BcCamera { let mut media_sub = BinarySubscriber::from_bc_sub(&sub_video); - loop { + while !abort_handle.load(Ordering::Relaxed) { let bc_media = BcMedia::deserialize(&mut media_sub)?; // We now have a complete interesting packet. Send it to on the callback data_outs.write(bc_media)?; } + + // Aborted + Ok(()) + } + + /// Stop a camera from sending more stream data. + pub fn stop_video(&self, stream: Stream) -> Result<()> { + let connection = self + .connection + .as_ref() + .expect("Must be connected to stop video"); + let msg_num = self.new_message_num(); + let sub_video = connection.subscribe(msg_num)?; + + // 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 stop_video = Bc::new_from_xml( + BcMeta { + msg_id: MSG_ID_VIDEO_STOP, + channel_id: self.channel_id, + msg_num, + stream_type: stream_code, + response_code: 0, + class: 0x6414, // IDK why + }, + BcXml { + preview: Some(Preview { + version: xml_ver(), + channel_id: self.channel_id, + handle, + stream_type: stream_name, + }), + ..Default::default() + }, + ); + + sub_video.send(stop_video)?; + + let reply = sub_video.rx.recv_timeout(crate::RX_TIMEOUT)?; + if reply.meta.response_code != 200 { + return Err(super::Error::CameraServiceUnavaliable); + } + + Ok(()) } } diff --git a/crates/core/src/bc_protocol/talk.rs b/crates/core/src/bc_protocol/talk.rs index 5d2b08a..522ca37 100644 --- a/crates/core/src/bc_protocol/talk.rs +++ b/crates/core/src/bc_protocol/talk.rs @@ -16,13 +16,14 @@ impl BcCamera { pub fn talk_stop(&self) -> Result<()> { let connection = self.connection.as_ref().expect("Must be connected"); - let sub = connection.subscribe(MSG_ID_TALKRESET)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; let msg = Bc { meta: BcMeta { msg_id: MSG_ID_TALKRESET, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, @@ -61,12 +62,13 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get time"); - let sub_get = connection.subscribe(MSG_ID_TALKABILITY)?; + let msg_num = self.new_message_num(); + let sub_get = connection.subscribe(msg_num)?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_TALKABILITY, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, @@ -120,7 +122,8 @@ impl BcCamera { pub fn talk(&self, adpcm: &[u8], talk_config: TalkConfig) -> Result<()> { let connection = self.connection.as_ref().expect("Must be connected"); - let sub = connection.subscribe(MSG_ID_TALKCONFIG)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; if &talk_config.audio_config.audio_type != "adpcm" { return Err(Error::UnknownTalkEncoding); @@ -133,7 +136,7 @@ impl BcCamera { meta: BcMeta { msg_id: MSG_ID_TALKCONFIG, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, @@ -181,7 +184,8 @@ impl BcCamera { } let full_block_size = block_size + 4; // Block size + predictor state - let sub = connection.subscribe(MSG_ID_TALK)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; const BLOCK_PER_PAYLOAD: usize = 4; const BLOCK_HEADER_SIZE: usize = 4; @@ -200,7 +204,7 @@ impl BcCamera { meta: BcMeta { msg_id: MSG_ID_TALK, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, @@ -259,7 +263,8 @@ impl BcCamera { pub fn talk_stream(&self, rx: Receiver>, talk_config: TalkConfig) -> Result<()> { let connection = self.connection.as_ref().expect("Must be connected"); - let sub = connection.subscribe(MSG_ID_TALKCONFIG)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; if &talk_config.audio_config.audio_type != "adpcm" { return Err(Error::UnknownTalkEncoding); @@ -272,7 +277,7 @@ impl BcCamera { meta: BcMeta { msg_id: MSG_ID_TALKCONFIG, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, @@ -320,7 +325,8 @@ impl BcCamera { } let full_block_size = block_size + 4; // Block size + predictor state - let sub = connection.subscribe(MSG_ID_TALK)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; const BLOCK_PER_PAYLOAD: usize = 1; const BLOCK_HEADER_SIZE: usize = 4; @@ -379,7 +385,7 @@ impl BcCamera { meta: BcMeta { msg_id: MSG_ID_TALK, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, diff --git a/crates/core/src/bc_protocol/time.rs b/crates/core/src/bc_protocol/time.rs index bba2cd1..a59a1ce 100644 --- a/crates/core/src/bc_protocol/time.rs +++ b/crates/core/src/bc_protocol/time.rs @@ -15,12 +15,13 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get time"); - let sub_get_general = connection.subscribe(MSG_ID_GET_GENERAL)?; + let msg_num = self.new_message_num(); + let sub_get_general = connection.subscribe(msg_num)?; let get = Bc { meta: BcMeta { msg_id: MSG_ID_GET_GENERAL, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, @@ -30,6 +31,9 @@ impl BcCamera { sub_get_general.send(get)?; let msg = sub_get_general.rx.recv_timeout(RX_TIMEOUT)?; + if msg.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } if let BcBody::ModernMsg(ModernMsg { payload: @@ -98,12 +102,13 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to set time"); - let sub_set_general = connection.subscribe(MSG_ID_SET_GENERAL)?; + let msg_num = self.new_message_num(); + let sub_set_general = connection.subscribe(msg_num)?; let set = Bc::new_from_xml( BcMeta { msg_id: MSG_ID_SET_GENERAL, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, response_code: 0, stream_type: 0, class: 0x6414, diff --git a/crates/core/src/bc_protocol/version.rs b/crates/core/src/bc_protocol/version.rs index 2781421..9e6d166 100644 --- a/crates/core/src/bc_protocol/version.rs +++ b/crates/core/src/bc_protocol/version.rs @@ -8,13 +8,14 @@ impl BcCamera { .connection .as_ref() .expect("Must be connected to get version info"); - let sub_version = connection.subscribe(MSG_ID_VERSION)?; + let msg_num = self.new_message_num(); + let sub_version = connection.subscribe(msg_num)?; let version = Bc { meta: BcMeta { msg_id: MSG_ID_VERSION, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, // IDK why @@ -27,6 +28,9 @@ impl BcCamera { sub_version.send(version)?; let modern_reply = sub_version.rx.recv_timeout(RX_TIMEOUT)?; + if modern_reply.meta.response_code != 200 { + return Err(Error::CameraServiceUnavaliable); + } let version_info; match modern_reply.body { BcBody::ModernMsg(ModernMsg { diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index 2d4627c..d563872 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -87,7 +87,7 @@ where impl BcMedia { pub(crate) fn deserialize(r: R) -> Result { // Throw away the nom-specific return types - read_from_reader(|reader| bcmedia(reader), r) + read_from_reader(bcmedia, r) } } diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index ab4479c..a691f32 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -84,7 +84,7 @@ where impl BcUdp { pub(crate) fn deserialize(r: R) -> Result { // Throw away the nom-specific return types - read_from_reader(|reader| bcudp(reader), r) + read_from_reader(bcudp, r) } } diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index b82c2d5..ecdd6d5 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -5,6 +5,7 @@ use super::xml::*; /// Top level udp packet #[derive(Debug, PartialEq, Eq)] +#[allow(clippy::large_enum_variant)] pub enum BcUdp { /// Packet from the negotiate stage when connection info is exchanged Discovery(UdpDiscovery), diff --git a/crates/core/src/bcudp/xml_crypto.rs b/crates/core/src/bcudp/xml_crypto.rs index 147f575..e5e69ef 100644 --- a/crates/core/src/bcudp/xml_crypto.rs +++ b/crates/core/src/bcudp/xml_crypto.rs @@ -5,8 +5,7 @@ const XML_KEY: [u32; 8] = [ pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { let key = XML_KEY .iter() - .map(|i| (i + offset).to_le_bytes()) - .flatten() + .flat_map(|i| (i + offset).to_le_bytes()) .cycle(); buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() } diff --git a/src/rtsp/gst.rs b/src/rtsp/gst.rs index 2955c07..4f052d5 100644 --- a/src/rtsp/gst.rs +++ b/src/rtsp/gst.rs @@ -347,7 +347,7 @@ mod maybe_app_src { /// owning the AppSrc directly. This function handles either case and returns the AppSrc, /// or None if the caller has not yet sent one. fn try_get_src(&mut self) -> Option<&AppSrc> { - while let Some(src) = self.rx.try_recv().ok() { + while let Ok(src) = self.rx.try_recv() { self.app_src = Some(src); } self.app_src.as_ref() diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 6c11129..cfc1def 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -31,9 +31,11 @@ use anyhow::{Context, Result}; use log::*; use neolink_core::bc_protocol::{BcCamera, Stream}; -use neolink_core::Never; use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex, +}; use std::time::Duration; // mod adpcm; @@ -76,36 +78,36 @@ pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> { let permitted_users = get_permitted_users(config.users.as_slice(), &arc_cam.permitted_users); + let mut stream_outputs: Vec<(Stream, Arc>)> = vec![]; + // Set up each main and substream according to all the RTSP mount paths we support if ["all", "both", "mainStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[ &*format!("/{}", arc_cam.name), &*format!("/{}/mainStream", arc_cam.name), ]; - let mut outputs = rtsp + let outputs = rtsp .add_stream(paths, &permitted_users) .unwrap(); - let main_camera = arc_cam.clone(); - s.spawn(move |_| camera_loop(&*main_camera, Stream::Main, &mut outputs, true)); + stream_outputs.push((Stream::Main, Arc::new(Mutex::new(outputs)))); } if ["all", "both", "subStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[&*format!("/{}/subStream", arc_cam.name)]; - let mut outputs = rtsp + let 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, Stream::Sub, &mut outputs, manage)); + stream_outputs.push((Stream::Sub, Arc::new(Mutex::new(outputs)))); } if ["all", "externStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[&*format!("/{}/externStream", arc_cam.name)]; - let mut outputs = rtsp + let 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)); + stream_outputs.push((Stream::Extern, Arc::new(Mutex::new(outputs)))); } + + let main_camera = arc_cam.clone(); + s.spawn(move |_| camera_loop(&*main_camera, stream_outputs, true)); } rtsp.run(&config.bind_addr, config.bind_port); @@ -117,18 +119,19 @@ pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> { fn camera_loop( camera_config: &CameraConfig, - stream_name: Stream, - outputs: &mut GstOutputs, + end_points: Vec<(Stream, Arc>)>, manage: bool, -) -> Result { +) -> Result<()> { let min_backoff = Duration::from_secs(1); let max_backoff = Duration::from_secs(15); let mut current_backoff = min_backoff; loop { - let cam_err = camera_main(camera_config, stream_name, outputs, manage).unwrap_err(); - outputs.vidsrc.on_stream_error(); - outputs.audsrc.on_stream_error(); + let cam_err = camera_main(camera_config, &end_points, manage).unwrap_err(); + for (_, outputs) in end_points.iter() { + (*outputs.lock().unwrap()).vidsrc.on_stream_error(); + (*outputs.lock().unwrap()).audsrc.on_stream_error(); + } // Authentication failures are permanent; we retry everything else if cam_err.connected { current_backoff = min_backoff; @@ -206,13 +209,12 @@ fn get_permitted_users<'a>( fn camera_main( camera_config: &CameraConfig, - stream_name: Stream, - outputs: &mut GstOutputs, + end_points: &[(Stream, Arc>)], manage: bool, -) -> Result { +) -> Result<(), CameraErr> { let mut connected = false; let mut login_fail = false; - (|| { + (|| -> Result<(), anyhow::Error> { let camera_addr = AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); let mut camera = @@ -251,17 +253,45 @@ fn camera_main( 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)", - }; + let arc_camera_results: Arc>>> = Default::default(); + let arc_camera = Arc::new(camera); + + crossbeam::scope(|s| { + let arc_abort_handle = Arc::new(AtomicBool::new(false)); + for (stream_name, arc_outputs) in end_points.iter() { + 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_display_name + ); + + let camera_results = arc_camera_results.clone(); + let camera = arc_camera.clone(); + let outputs = arc_outputs.clone(); + let abort_handle = arc_abort_handle.clone(); + let abort_handle_2 = arc_abort_handle.clone(); + + s.spawn(move |_| { + let camera_result = camera.start_video(&mut *outputs.lock().unwrap(), *stream_name, abort_handle).with_context(|| format!("Error while streaming {}", camera_config.name)); + (*camera_results.lock().unwrap()).push(camera_result); + + let _ = camera.stop_video(*stream_name); + abort_handle_2.store(true, Ordering::Relaxed); + }); + } + }).unwrap(); + + let mut camera_results = arc_camera_results.lock().unwrap(); + while camera_results.len() > 0 { + camera_results.pop().unwrap()?; // Need to take ownership + } + unreachable!(); // Should always error before this - info!( - "{}: Starting video stream {}", - camera_config.name, stream_display_name - ); - camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name)) })().map_err(|e| CameraErr{ connected, login_fail,