Merge and clippy fixes

This commit is contained in:
QuantumEntangledAndy committed 2022-11-28 15:22:48 +07:00
1 parent 2114af085d
commit edf89dc993
26 files changed
+227 -220

No files matched your search

Generated
+32 -68
View File
@@ -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",
]
-1
View File
@@ -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"
+1 -1
View File
@@ -23,7 +23,7 @@ fn git_ver() -> Option<String> {
fn git_cmd_ver() -> Option<String> {
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");
+10 -10
View File
@@ -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,
+2 -3
View File
@@ -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<T> = std::result::Result<T, Error>;
@@ -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()
@@ -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);
}
@@ -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() {
+1 -1
View File
@@ -29,7 +29,7 @@ pub enum Error {
#[error(display = "Communication error")]
UnintelligibleReply {
/// The Bc packet that was not understood
reply: Bc,
reply: Box<Bc>,
/// The message attached to the error
why: &'static str,
},
+2 -2
View File
@@ -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",
})
}
+2 -2
View File
@@ -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",
})
}
+1 -5
View File
@@ -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 {
+8 -7
View File
@@ -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<u16> {
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<T: MotionOutput>(&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
+2 -2
View File
@@ -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",
})
}
+1 -1
View File
@@ -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",
})
}
+1 -1
View File
@@ -182,6 +182,6 @@ impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] {
impl<T: ToSocketAddrsOrUid + ?Sized> ToSocketAddrsOrUid for &T {
type UidIter = T::UidIter;
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
(&**self).to_socket_addrs_or_uid()
(**self).to_socket_addrs_or_uid()
}
}
+8 -10
View File
@@ -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()
},
+4 -4
View File
@@ -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",
});
+2 -2
View File
@@ -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",
})
}
+1 -1
View File
@@ -45,7 +45,7 @@ impl BcCamera {
}
_ => {
return Err(Error::UnintelligibleReply {
reply: modern_reply,
reply: Box::new(modern_reply),
why: "Expected a VersionInfo message",
})
}
+1 -2
View File
@@ -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<MqttConfig> {
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 {
+1 -1
View File
@@ -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();
});
});
-68
View File
@@ -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<AppSrc>,
app_src: Option<AppSrc>,
}
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<AppSrc>) {
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<usize> {
// 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(())
}
}
}
+1 -1
View File
@@ -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);
+1 -1
View File
@@ -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()
+140 -18
View File
@@ -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<BcCamera>,
data_outs: &mut GstOutputs,
stream: Stream,
abort_handle: Arc<AtomicBool>,
) -> 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<Mutex<Option<anyhow::Error>>> = 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 {
+1 -4
View File
@@ -73,10 +73,7 @@ pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result<BcCamera
Ok(camera)
}
pub(crate) fn find_camera_by_name<'a, 'b>(
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()