diff --git a/Cargo.lock b/Cargo.lock index b0d6c31..57e041c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,12 +187,6 @@ dependencies = [ "smallvec", ] -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - [[package]] name = "cfg-if" version = "1.0.0" @@ -256,31 +250,21 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] name = "crossbeam" -version = "0.7.3" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" +checksum = "2801af0d36612ae591caa9568261fddce32ce6e08a7275ea334a06a4ad021a2c" dependencies = [ - "cfg-if 0.1.10", - "crossbeam-channel 0.4.4", + "cfg-if", + "crossbeam-channel", "crossbeam-deque", "crossbeam-epoch", "crossbeam-queue", - "crossbeam-utils 0.7.2", -] - -[[package]] -name = "crossbeam-channel" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" -dependencies = [ - "crossbeam-utils 0.7.2", - "maybe-uninit", + "crossbeam-utils", ] [[package]] @@ -289,56 +273,42 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" dependencies = [ - "cfg-if 1.0.0", - "crossbeam-utils 0.8.5", + "cfg-if", + "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.7.4" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" +checksum = "715e8152b692bba2d374b53d4875445368fdf21a94751410af607a5ac677d1fc" dependencies = [ + "cfg-if", "crossbeam-epoch", - "crossbeam-utils 0.7.2", - "maybe-uninit", + "crossbeam-utils", ] [[package]] name = "crossbeam-epoch" -version = "0.8.2" +version = "0.9.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" +checksum = "01a9af1f4c2ef74bb8aa1f7e19706bc72d03598c8a570bb5de72243c7a9d9d5a" dependencies = [ "autocfg", - "cfg-if 0.1.10", - "crossbeam-utils 0.7.2", - "lazy_static", - "maybe-uninit", + "cfg-if", + "crossbeam-utils", "memoffset", "scopeguard", ] [[package]] name = "crossbeam-queue" -version = "0.2.3" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" +checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" dependencies = [ - "cfg-if 0.1.10", - "crossbeam-utils 0.7.2", - "maybe-uninit", -] - -[[package]] -name = "crossbeam-utils" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3c7c73a2d1e9fc0886a08b93e98eb643461230d5f1925e4036204d5f2e261a8" -dependencies = [ - "autocfg", - "cfg-if 0.1.10", - "lazy_static", + "cfg-if", + "crossbeam-utils", ] [[package]] @@ -347,7 +317,7 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "lazy_static", ] @@ -520,7 +490,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "libc", "wasi", ] @@ -617,7 +587,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f71e8c163945a3e0140e6b1ed10d1507da7e71196fedec568cbad92db63d762" dependencies = [ "bitflags", - "cfg-if 1.0.0", + "cfg-if", "futures-channel", "futures-core", "futures-util", @@ -670,7 +640,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5cf50118e1933d9e9e043036f2306d0b9660182ea61a75f266cd9fb3607b7a19" dependencies = [ "bitflags", - "cfg-if 1.0.0", + "cfg-if", "glib", "gstreamer", "gstreamer-base-sys", @@ -942,7 +912,7 @@ checksum = "6607c62aa161d23d17a9072cc5da0be67cdfc89d3afb1e8d9c842bebc2525ffe" dependencies = [ "arrayvec", "bitflags", - "cfg-if 1.0.0", + "cfg-if", "ryu", "static_assertions", ] @@ -972,7 +942,7 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", ] [[package]] @@ -981,12 +951,6 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" -[[package]] -name = "maybe-uninit" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60302e4db3a61da70c0cb7991976248362f30319e88850c487b9b95bbf059e00" - [[package]] name = "md5" version = "0.7.0" @@ -1007,9 +971,9 @@ checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" [[package]] name = "memoffset" -version = "0.5.6" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043175f069eda7b85febe4a74abbaeff828d9f8b448515d3151a14a3542811aa" +checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" dependencies = [ "autocfg", ] @@ -1071,7 +1035,7 @@ dependencies = [ "cfb-mode", "cookie-factory", "crossbeam", - "crossbeam-channel 0.5.1", + "crossbeam-channel", "env_logger", "err-derive", "gstreamer", @@ -1108,7 +1072,7 @@ dependencies = [ "cfb-mode", "cookie-factory", "crc32fast", - "crossbeam-channel 0.5.1", + "crossbeam-channel", "env_logger", "err-derive", "get_if_addrs", @@ -1513,7 +1477,7 @@ version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "libc", "winapi 0.3.9", ] @@ -1946,7 +1910,7 @@ version = "0.2.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "632f73e236b219150ea279196e54e610f5dbafa5d61786303d4da54f84e47fce" dependencies = [ - "cfg-if 1.0.0", + "cfg-if", "wasm-bindgen-macro", ] diff --git a/Cargo.toml b/Cargo.toml index ea1dffd..c301f94 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,5 +42,4 @@ validator_derive = "0.10" byte-slice-cast = "1.0.0" rumqttc = "0.8.0" tokio = { version = "1.0", features = ["rt", "macros", "io-util"] } -crossbeam-channel = "0.5.1" anyhow = "1.0.42" diff --git a/build.rs b/build.rs index 801c327..53ee1d7 100644 --- a/build.rs +++ b/build.rs @@ -23,7 +23,7 @@ fn git_ver() -> Option { fn git_cmd_ver() -> Option { let mut git_cmd = Command::new("git"); - git_cmd.args(&["describe", "--tags"]); + git_cmd.args(["describe", "--tags"]); if let Some(true) = git_cmd.status().ok().map(|exit| exit.success()) { println!("cargo:rerun-if-changed=.git/HEAD"); diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index a25322a..b87a567 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -85,7 +85,7 @@ impl Bc { } } -fn bc_msg<'a, 'b>(context: &'a mut BcContext, buf: &'b [u8]) -> IResult<&'b [u8], Bc> { +fn bc_msg<'a>(context: &mut BcContext, buf: &'a [u8]) -> IResult<&'a [u8], Bc> { let (buf, header) = bc_header(buf)?; let (buf, body) = bc_body(context, &header, buf)?; @@ -97,11 +97,11 @@ fn bc_msg<'a, 'b>(context: &'a mut BcContext, buf: &'b [u8]) -> IResult<&'b [u8] Ok((buf, bc)) } -fn bc_body<'a, 'b, 'c>( - context: &'c mut BcContext, - header: &'a BcHeader, - buf: &'b [u8], -) -> IResult<&'b [u8], BcBody> { +fn bc_body<'a>( + context: &mut BcContext, + header: &BcHeader, + buf: &'a [u8], +) -> IResult<&'a [u8], BcBody> { if header.is_modern() { let (buf, body) = bc_modern_msg(context, header, buf)?; Ok((buf, BcBody::ModernMsg(body))) @@ -127,11 +127,11 @@ fn bc_legacy_login_msg(buf: &'_ [u8]) -> IResult<&'_ [u8], LegacyMsg> { Ok((buf, LegacyMsg::LoginMsg { username, password })) } -fn bc_modern_msg<'a, 'b>( +fn bc_modern_msg<'a>( context: &mut BcContext, - header: &'a BcHeader, - buf: &'b [u8], -) -> IResult<&'b [u8], ModernMsg> { + header: &BcHeader, + buf: &'a [u8], +) -> IResult<&'a [u8], ModernMsg> { use nom::{ error::{make_error, ErrorKind}, Err, diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index ca611b4..6b35384 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -26,10 +26,9 @@ use bc::model::*; pub(crate) use connection::*; pub use errors::Error; pub use ledstate::LightState; +pub use motion::{MotionOutput, MotionOutputError, MotionStatus}; pub use pirstate::PirState; -pub use motion::{MotionOutput, MotionOutputError, MotionStatus}; pub use resolution::*; -pub use motion::{MotionOutput, MotionOutputError, MotionStatus}; pub use stream::{Stream, StreamOutput, StreamOutputError}; type Result = std::result::Result; @@ -273,7 +272,7 @@ fn md5_string(input: &str, trunc: Md5Trunc) -> String { /// negotiated during login pub fn make_aes_key(nonce: &str, passwd: &str) -> [u8; 16] { let key_phrase = format!("{}-{}", nonce, passwd); - let key_phrase_hash = format!("{:X}\0", md5::compute(&key_phrase)) + let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase)) .to_uppercase() .into_bytes(); key_phrase_hash[0..16].try_into().unwrap() diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs index aabb873..8b5366b 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/discover.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -49,7 +49,7 @@ impl UdpDiscover { let mut bytes_send = 0; for addr in addrs.iter() { - bytes_send = socket.send_to(buf, &addr)?; + bytes_send = socket.send_to(buf, addr)?; } let thread_buffer = buf.to_vec(); @@ -66,7 +66,7 @@ impl UdpDiscover { break; } for addr in thread_addr.iter() { - let _ = thread_socket.send_to(&thread_buffer[..], &addr); + let _ = thread_socket.send_to(&thread_buffer[..], addr); } std::thread::sleep(WAIT_TIME); } diff --git a/crates/core/src/bc_protocol/connection/udpconn/mod.rs b/crates/core/src/bc_protocol/connection/udpconn/mod.rs index 6de04fd..046ec52 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/mod.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/mod.rs @@ -113,7 +113,7 @@ impl UdpSource { while !thread_aborter.is_aborted() { if let Err(err) = thread_transmit.poll_read( &thread_socket, - &(*thread_discovery_result), + &thread_discovery_result, &to_incoming, ) { if !thread_aborter.is_aborted() { @@ -145,7 +145,7 @@ impl UdpSource { while !thread_aborter.is_aborted() { if let Err(err) = thread_transmit.poll_write( &thread_socket, - &(*thread_discovery_result), + &thread_discovery_result, &from_outgoing, ) { if !thread_aborter.is_aborted() { diff --git a/crates/core/src/bc_protocol/errors.rs b/crates/core/src/bc_protocol/errors.rs index 35bff75..bd3d5f7 100644 --- a/crates/core/src/bc_protocol/errors.rs +++ b/crates/core/src/bc_protocol/errors.rs @@ -29,7 +29,7 @@ pub enum Error { #[error(display = "Communication error")] UnintelligibleReply { /// The Bc packet that was not understood - reply: Bc, + reply: Box, /// The message attached to the error why: &'static str, }, diff --git a/crates/core/src/bc_protocol/ledstate.rs b/crates/core/src/bc_protocol/ledstate.rs index feee738..75404fc 100644 --- a/crates/core/src/bc_protocol/ledstate.rs +++ b/crates/core/src/bc_protocol/ledstate.rs @@ -46,7 +46,7 @@ impl BcCamera { Ok(ledstate) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "Expected LEDState xml but it was not recieved", }) } @@ -96,7 +96,7 @@ impl BcCamera { Ok(()) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not except the LEDState xml", }) } diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index 3248275..aec7ba8 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -63,7 +63,7 @@ impl BcCamera { } _ => { return Err(Error::UnintelligibleReply { - reply: legacy_reply, + reply: Box::new(legacy_reply), why: "Expected an Encryption message back", }) } @@ -128,7 +128,7 @@ impl BcCamera { }) => return Err(Error::AuthFailed), _ => { return Err(Error::UnintelligibleReply { - reply: modern_reply, + reply: Box::new(modern_reply), why: "Expected a DeviceInfo message back from login", }) } diff --git a/crates/core/src/bc_protocol/logout.rs b/crates/core/src/bc_protocol/logout.rs index 76924d5..246598c 100644 --- a/crates/core/src/bc_protocol/logout.rs +++ b/crates/core/src/bc_protocol/logout.rs @@ -14,11 +14,7 @@ impl BcCamera { let sub_logout = connection.subscribe(msg_num)?; let username = credentials.username.clone(); - let password = credentials - .password - .as_ref() - .cloned() - .unwrap_or_else(|| "".to_string()); + let password = credentials.password.as_ref().cloned().unwrap_or_default(); let modern_logout = Bc::new_from_xml( BcMeta { diff --git a/crates/core/src/bc_protocol/motion.rs b/crates/core/src/bc_protocol/motion.rs index 5a33690..bd1a2ea 100644 --- a/crates/core/src/bc_protocol/motion.rs +++ b/crates/core/src/bc_protocol/motion.rs @@ -30,18 +30,19 @@ pub trait MotionOutput { impl BcCamera { /// This message tells the camera to send the motion events to us /// Which are the recieved on msgid 33 - fn start_motion_query(&self) -> Result<()> { + fn start_motion_query(&self) -> Result { let connection = self .connection .as_ref() .expect("Must be connected to listen to messages"); - let sub = connection.subscribe(MSG_ID_MOTION_REQUEST)?; + let msg_num = self.new_message_num(); + let sub = connection.subscribe(msg_num)?; let msg = Bc { meta: BcMeta { msg_id: MSG_ID_MOTION_REQUEST, channel_id: self.channel_id, - msg_num: self.new_message_num(), + msg_num, stream_type: 0, response_code: 0, class: 0x6414, @@ -59,10 +60,10 @@ impl BcCamera { response_code: 200, .. } = msg.meta { - Ok(()) + Ok(msg_num) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not accept the request to start motion", }) } @@ -73,7 +74,7 @@ impl BcCamera { /// /// The output structure must implement the [`MotionCallback`] trait pub fn listen_on_motion(&self, data_out: &mut T) -> Result<()> { - self.start_motion_query()?; + let msg_num = self.start_motion_query()?; let connection = self .connection @@ -82,7 +83,7 @@ impl BcCamera { // After start_motion_query (MSG_ID 31) the camera sends motion messages // when whenever motion is detected. - let sub = connection.subscribe(MSG_ID_MOTION)?; + let sub = connection.subscribe(msg_num)?; loop { // Mostly ignore when timout is reached because these messages are only diff --git a/crates/core/src/bc_protocol/pirstate.rs b/crates/core/src/bc_protocol/pirstate.rs index 7cd23cd..641fdbb 100644 --- a/crates/core/src/bc_protocol/pirstate.rs +++ b/crates/core/src/bc_protocol/pirstate.rs @@ -46,7 +46,7 @@ impl BcCamera { Ok(pirstate) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "Expected PirSate xml but it was not recieved", }) } @@ -95,7 +95,7 @@ impl BcCamera { Ok(()) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not except the RfAlarmCfg xml", }) } diff --git a/crates/core/src/bc_protocol/reboot.rs b/crates/core/src/bc_protocol/reboot.rs index cdc859d..1ce19cc 100644 --- a/crates/core/src/bc_protocol/reboot.rs +++ b/crates/core/src/bc_protocol/reboot.rs @@ -32,7 +32,7 @@ impl BcCamera { Ok(()) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not accept the reboot command", }) } diff --git a/crates/core/src/bc_protocol/resolution.rs b/crates/core/src/bc_protocol/resolution.rs index b89d701..9cb3e54 100644 --- a/crates/core/src/bc_protocol/resolution.rs +++ b/crates/core/src/bc_protocol/resolution.rs @@ -182,6 +182,6 @@ impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] { impl ToSocketAddrsOrUid for &T { type UidIter = T::UidIter; fn to_socket_addrs_or_uid(&self) -> Result { - (&**self).to_socket_addrs_or_uid() + (**self).to_socket_addrs_or_uid() } } diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 3c28258..3fdeb9d 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -137,13 +137,15 @@ impl BcCamera { { } else { return Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not accept the stream start command.", }); } let mut media_sub = BinarySubscriber::from_bc_sub(&sub_video); + let mut result = Ok(()); + 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 @@ -161,7 +163,10 @@ impl BcCamera { } // Aborted - Ok(()) + println!("Stopping video: {:?}", result); + self.stop_video(stream)?; + println!("Video stopped"); + result } /// Stop a camera from sending more stream data. @@ -202,13 +207,6 @@ impl BcCamera { 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, @@ -223,7 +221,7 @@ impl BcCamera { version: xml_ver(), channel_id: self.channel_id, handle, - stream_type: stream_name, + stream_type: None, }), ..Default::default() }, diff --git a/crates/core/src/bc_protocol/talk.rs b/crates/core/src/bc_protocol/talk.rs index 522ca37..b331c1e 100644 --- a/crates/core/src/bc_protocol/talk.rs +++ b/crates/core/src/bc_protocol/talk.rs @@ -46,7 +46,7 @@ impl BcCamera { { } else { return Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not accept the talk stop command.", }); } @@ -97,7 +97,7 @@ impl BcCamera { Ok(talk_ability) } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "Expected TalkAbility xml but it was not recieved", }) } @@ -177,7 +177,7 @@ impl BcCamera { { } else { return Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not accept the TalkConfig xml. Audio format is likely incorrect", }); @@ -318,7 +318,7 @@ impl BcCamera { { } else { return Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "The camera did not accept the TalkConfig xml. Audio format is likely incorrect", }); diff --git a/crates/core/src/bc_protocol/time.rs b/crates/core/src/bc_protocol/time.rs index a59a1ce..30d6cd5 100644 --- a/crates/core/src/bc_protocol/time.rs +++ b/crates/core/src/bc_protocol/time.rs @@ -59,7 +59,7 @@ impl BcCamera { Ok(dt) => dt, Err(_) => { return Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "Could not parse date", }) } @@ -80,7 +80,7 @@ impl BcCamera { } } else { Err(Error::UnintelligibleReply { - reply: msg, + reply: Box::new(msg), why: "Reply did not contain SystemGeneral with all time fields filled out", }) } diff --git a/crates/core/src/bc_protocol/version.rs b/crates/core/src/bc_protocol/version.rs index 9e6d166..1c6056e 100644 --- a/crates/core/src/bc_protocol/version.rs +++ b/crates/core/src/bc_protocol/version.rs @@ -45,7 +45,7 @@ impl BcCamera { } _ => { return Err(Error::UnintelligibleReply { - reply: modern_reply, + reply: Box::new(modern_reply), why: "Expected a VersionInfo message", }) } diff --git a/src/config.rs b/src/config.rs index afde0e6..77c0428 100644 --- a/src/config.rs +++ b/src/config.rs @@ -94,7 +94,6 @@ pub(crate) struct UserConfig { pub(crate) pass: String, } - #[derive(Debug, Deserialize, Clone, Validate)] #[validate(schema(function = "validate_mqtt_config", skip_on_field_errors = true))] pub(crate) struct MqttConfig { @@ -125,6 +124,7 @@ fn validate_mqtt_config(config: &MqttConfig) -> Result<(), ValidationError> { fn default_mqtt() -> Option { None +} #[derive(Debug, Deserialize, Validate, Clone)] pub(crate) struct PauseConfig { @@ -144,7 +144,6 @@ pub(crate) struct PauseConfig { code = "mode" ))] pub(crate) mode: String, - } fn default_bind_addr() -> String { diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 81e9851..5f6f3d6 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -151,7 +151,7 @@ impl<'a> EventCam<'a> { info!("{}: Setting up camera actions", camera_config.name); s.spawn(|_| { - let _ = message_handler.listen(); + message_handler.listen(); }); }); diff --git a/src/rtsp/gst.rs b/src/rtsp/gst.rs index 6d51b12..b693dfb 100644 --- a/src/rtsp/gst.rs +++ b/src/rtsp/gst.rs @@ -538,71 +538,3 @@ impl RtspServer { main_loop.run(); } } - -mod maybe_app_src { - use super::*; - use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; - - /// A Write implementation around AppSrc that also allows delaying the creation of the AppSrc - /// until later, discarding written data until the AppSrc is provided. - pub(crate) struct MaybeAppSrc { - rx: Receiver, - app_src: Option, - } - - impl MaybeAppSrc { - /// Creates a MaybeAppSrc. Also returns a Sender that you must use to provide an AppSrc as - /// soon as one is available. When it is received, the MaybeAppSrc will start pushing data - /// into the AppSrc when write() is called. - pub(crate) fn new_with_tx() -> (Self, SyncSender) { - let (tx, rx) = sync_channel(3); // The sender should not send very often - (MaybeAppSrc { rx, app_src: None }, tx) - } - - /// Flushes data to Gstreamer on a problem communicating with the underlying video source. - pub(crate) fn on_stream_error(&mut self) { - if let Some(src) = self.try_get_src() { - // Ignore "errors" from Gstreamer such as FLUSHING, which are not really errors. - let _ = src.end_of_stream(); - } - } - - /// Attempts to retrieve the AppSrc that should be passed in by the caller of new_with_tx - /// at some point after this struct has been created. At that point, we swap over to - /// 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 Ok(src) = self.rx.try_recv() { - self.app_src = Some(src); - } - self.app_src.as_ref() - } - } - - impl Write for MaybeAppSrc { - fn write(&mut self, buf: &[u8]) -> io::Result { - // If we have no AppSrc yet, throw away the data and claim that it was written - let app_src = match self.try_get_src() { - Some(src) => src, - None => return Ok(buf.len()), - }; - - let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap(); - { - let gst_buf_mut = gst_buf.get_mut().unwrap(); - let mut gst_buf_data = gst_buf_mut.map_writable().unwrap(); - gst_buf_data.copy_from_slice(buf); - } - - let res = app_src.push_buffer(gst_buf); //.map_err(|e| io::Error::new(io::ErrorKind::Other, Box::new(e)))?; - if res.is_err() { - self.app_src = None; - } - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } - } -} diff --git a/src/rtsp/gst/maybe_app_src.rs b/src/rtsp/gst/maybe_app_src.rs index 9a7f3d2..d001eb8 100644 --- a/src/rtsp/gst/maybe_app_src.rs +++ b/src/rtsp/gst/maybe_app_src.rs @@ -38,7 +38,7 @@ impl MaybeAppSrc { /// 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); if let Some(state) = self.state.as_ref() { state.set_client_connected(true); diff --git a/src/rtsp/gst/maybe_inputselect.rs b/src/rtsp/gst/maybe_inputselect.rs index 6dc508f..ecb053e 100644 --- a/src/rtsp/gst/maybe_inputselect.rs +++ b/src/rtsp/gst/maybe_inputselect.rs @@ -17,7 +17,7 @@ impl MaybeInputSelect { } pub(crate) fn try_get_src(&mut self) -> Option<&Element> { - while let Some(src) = self.rx.try_recv().ok() { + while let Ok(src) = self.rx.try_recv() { self.typefind = Some(src); } self.typefind.as_ref() diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 253580e..ed9d4f3 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -61,7 +61,7 @@ pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> { set_up_users(&config.users, rtsp); - if config.certificate == None && !config.users.is_empty() { + if config.certificate.is_none() && !config.users.is_empty() { warn!( "Without a server certificate, usernames and passwords will be exchanged in plaintext!" ) @@ -109,7 +109,7 @@ pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> { } let main_camera = arc_cam.clone(); - s.spawn(move |_| camera_loop(&*main_camera, stream_outputs, true)); + s.spawn(move |_| camera_loop(&main_camera, stream_outputs, true)); } rtsp.run(&config.bind_addr, config.bind_port); @@ -129,21 +129,32 @@ fn camera_loop( let mut current_backoff = min_backoff; loop { - 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; - } - if cam_err.login_fail { - error!( - "Authentication failed to camera {}, not retrying", - camera_config.name - ); - return Err(cam_err.err); + if let Err(cam_err) = camera_main(camera_config, &end_points, manage) { + 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; + } + 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 @@ -273,7 +284,7 @@ fn camera_main( 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)); + let camera_result = pausable_camera(camera_config, &camera, &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); @@ -295,6 +306,117 @@ fn camera_main( }) } +fn pausable_camera( + camera_config: &CameraConfig, + camera: &Arc, + data_outs: &mut GstOutputs, + stream: Stream, + abort_handle: Arc, +) -> Result<()> { + if !camera_config.pause.on_motion && !camera_config.pause.on_disconnect { + // Stream is always on + camera + .start_video(data_outs, stream, abort_handle) + .with_context(|| format!("Error while streaming {}", camera_config.name)) + } else { + let pause_config = &camera_config.pause; + // Used to get the error from the thread + let thread_error: Arc>> = Default::default(); + + // Used to abort all sub threads if any of them request closure + // and control the motion/client state info + let state = States::new_from_camera_config(camera_config); + data_outs.set_state(state.clone()); + let paused_source = match pause_config.mode.as_str() { + "test" => PausedSources::TestSrc, + "still" => PausedSources::Still, + "black" => PausedSources::Black, + "none" => PausedSources::None, + _ => { + unreachable!() + } + }; + data_outs.set_paused_source(paused_source); + + crossbeam::scope(|s| { + let mut motion = MotionStream::new(pause_config.motion_timeout, state.clone()); + + let arc_camera = Arc::new(camera); + + // Motion detection thread + let motion_camera = arc_camera.clone(); + let motion_camname = camera_config.name.to_string(); + let motion_error = thread_error.clone(); + let motion_state = state.clone(); + s.spawn(move |_| { + if let Err(e) = motion_camera + .listen_on_motion(&mut motion) + .with_context(|| format!("Error while reading motion {}", motion_camname)) + { + // When motion errors set the thread error + *motion_error.lock().unwrap() = Some(e); + } + // Always abort the streams/motion when motion stops regardless of why + // so that this thread can reset the camera + motion_state.abort(); + debug!("Motion stopped"); + }); + + // Stream thread + let stream_camera = arc_camera; + let stream_camname = camera_config.name.to_string(); + let stream_error = thread_error.clone(); + let stream_state = state.clone(); + s.spawn(move |_| { + while stream_state.is_live() { + if stream_state.should_stream() || !data_outs.has_last_iframe() { + if let Err(e) = data_outs.set_input_source(InputMode::Live) { + *stream_error.lock().unwrap() = Some(e); + break; + } + debug!("Stream resumed"); + // Will block until the rx thread send the abort + if let Err(e) = stream_camera + .start_video(data_outs, stream, abort_handle.clone()) + .with_context(|| format!("Error while streaming {}", stream_camname)) + { + error!("Stream error {:?}", e); + // When stream errors set the thread error and abort the motion + *stream_error.lock().unwrap() = Some(e); + break; + } + debug!("Stream paused"); + } else { + if let Err(e) = data_outs.set_input_source(InputMode::Paused) { + *stream_error.lock().unwrap() = Some(e); + break; + } + // While stream is aborted we send the last iframe + if let Err(e) = data_outs.write_last_iframe().with_context(|| { + format!("Failed to write no motion image for {}", stream_camname) + }) { + *stream_error.lock().unwrap() = Some(e); + break; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + stream_state.abort(); + debug!("Stream stopped"); + }); + }) + .unwrap(); + + // Should be the only one holding the thread_error so unwrap it + // all the way to an actual error + Err(Arc::try_unwrap(thread_error) + .unwrap() + .into_inner() + .unwrap() + .unwrap()) + } +} + fn do_camera_management(camera: &mut BcCamera, camera_config: &CameraConfig) -> Result<()> { let cam_time = camera.get_time()?; if let Some(time) = cam_time { diff --git a/src/utils.rs b/src/utils.rs index cd0e067..ae54885 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -73,10 +73,7 @@ pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result( - config: &'a Config, - name: &'b str, -) -> Result<&'a CameraConfig> { +pub(crate) fn find_camera_by_name<'a>(config: &'a Config, name: &str) -> Result<&'a CameraConfig> { config .cameras .iter()