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

+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()