Added a timeout to the motion based stream

This commit is contained in:
QuantumEntangledAndy committed 2021-09-16 12:32:40 +07:00
1 parent 62a694fbe4
commit 13690d723f
4 files changed
+138 -82

No files matched your search

+13
View File
@@ -73,6 +73,9 @@ pub(crate) struct CameraConfig {
#[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))]
#[serde(default = "default_channel_id")]
pub(crate) channel_id: u8,
#[validate]
pub(crate) motion: Option<MotionConfig>,
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -85,6 +88,12 @@ pub(crate) struct UserConfig {
pub(crate) pass: String,
}
#[derive(Debug, Deserialize, Validate, Clone)]
pub(crate) struct MotionConfig {
#[serde(default = "default_motion_timeout", alias = "timeout_seconds")]
pub(crate) timeout: f64,
}
fn default_bind_addr() -> String {
"0.0.0.0".to_string()
}
@@ -109,6 +118,10 @@ fn default_channel_id() -> u8 {
0
}
fn default_motion_timeout() -> f64 {
1.
}
pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"];
fn validate_username(name: &str) -> Result<(), ValidationError> {
if name.trim().is_empty() {
+1 -2
View File
@@ -76,7 +76,6 @@ impl StreamOutput for GstOutputs {
// Only stop on an iframe so we have the
// last frame to show
should_continue = self.live.is_live();
debug!("Iframe continue: {}", should_continue);
}
BcMedia::Pframe(payload) => {
let video_type = match payload.video_type {
@@ -98,7 +97,7 @@ impl StreamOutput for GstOutputs {
//Ignore other BcMedia like InfoV1 and InfoV2
}
}
debug!("Output continue: {}", should_continue);
Ok(should_continue)
}
}
+88 -78
View File
@@ -285,94 +285,104 @@ fn camera_main(
// Used to get the error from the thread
let thread_error: Arc<Mutex<Option<anyhow::Error>>> = Default::default();
crossbeam::scope(|s| {
let (mut motion, rx) = MotionStream::new();
match &camera_config.motion {
Some(motion_config) => {
crossbeam::scope(|s| {
let (mut motion, rx) = MotionStream::new(motion_config.timeout);
let motionthread_motion_abort = motion.get_abort_handle();
let motionthread_stream_abort = outputs.get_abort_handle();
let rxthread_motion_abort = motion.get_abort_handle();
let rxthread_stream_abort = outputs.get_abort_handle();
let streamthread_stream_abort = outputs.get_abort_handle();
let streamthread_motion_abort = motion.get_abort_handle();
let motionthread_motion_abort = motion.get_abort_handle();
let motionthread_stream_abort = outputs.get_abort_handle();
let rxthread_motion_abort = motion.get_abort_handle();
let rxthread_stream_abort = outputs.get_abort_handle();
let streamthread_stream_abort = outputs.get_abort_handle();
let streamthread_motion_abort = motion.get_abort_handle();
// Start in the aborted state because motion defaults to still
streamthread_stream_abort.abort();
// Start in the aborted state because motion defaults to still
streamthread_stream_abort.abort();
let arc_camera = Arc::new(camera);
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();
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
motionthread_motion_abort.abort();
motionthread_stream_abort.abort();
debug!("Motion stopped");
});
// Motion detection thread
let motion_camera = arc_camera.clone();
let motion_camname = camera_config.name.to_string();
let motion_error = thread_error.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
motionthread_motion_abort.abort();
motionthread_stream_abort.abort();
debug!("Motion stopped");
});
// Motion rx -> stream thread
s.spawn(move |_| {
// Stops when motion is stopped
// which happens when either motion or stream errors
while rxthread_motion_abort.is_live() {
let msg = rx.try_recv();
if let Ok(msg) = msg {
match msg {
MotionStatus::Start => {
debug!("Motion start");
rxthread_stream_abort.reset();
// Motion rx -> stream thread
s.spawn(move |_| {
// Stops when motion is stopped
// which happens when either motion or stream errors
while rxthread_motion_abort.is_live() {
let msg = rx.try_recv();
if let Ok(msg) = msg {
match msg {
MotionStatus::Start => {
debug!("Motion start");
rxthread_stream_abort.reset();
}
MotionStatus::Stop => {
debug!("Motion stop");
rxthread_stream_abort.abort();
}
_ => {}
}
}
MotionStatus::Stop => {
debug!("Motion stop");
rxthread_stream_abort.abort();
}
println!("Motion RX Stopped");
});
// Stream thread
let stream_camera = arc_camera;
let stream_camname = camera_config.name.to_string();
let stream_error = thread_error.clone();
s.spawn(move |_| {
loop {
if streamthread_stream_abort.is_live() || ! outputs.has_last_iframe() {
debug!("Stream resumed: waiting for motion to stop");
// Will block until the rx thread send the abort
if let Err(e) = stream_camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", stream_camname)) {
// When stream errors set the thread error and abort the motion
*stream_error.lock().unwrap() = Some(e);
break;
}
debug!("Stream paused: waiting for motion to start");
} else {
// While stream is aborted we send the blank image
if let Err(e) = outputs.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));
}
_ => {}
}
}
}
println!("Motion RX Stopped");
});
streamthread_stream_abort.abort();
streamthread_motion_abort.abort();
println!("Stream stopped");
});
}).unwrap();
// Stream thread
let stream_camera = arc_camera;
let stream_camname = camera_config.name.to_string();
let stream_error = thread_error.clone();
s.spawn(move |_| {
loop {
if streamthread_stream_abort.is_live() || ! outputs.has_last_iframe() {
debug!("Stream resumed: waiting for motion to stop");
// Will block until the rx thread send the abort
if let Err(e) = stream_camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", stream_camname)) {
// When stream errors set the thread error and abort the motion
*stream_error.lock().unwrap() = Some(e);
break;
}
debug!("Stream paused: waiting for motion to start");
} else {
// While stream is aborted we send the blank image
if let Err(e) = outputs.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));
}
}
streamthread_stream_abort.abort();
streamthread_motion_abort.abort();
println!("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())
// 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())
}
None => {
// No motion config
//
// Just stream always
camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name))
}
}
})().map_err(|e| CameraErr{
connected,
+36 -2
View File
@@ -1,19 +1,24 @@
use super::abort::AbortHandle;
use crossbeam_channel::{unbounded, Receiver, Sender};
use neolink_core::bc_protocol::{MotionOutput, MotionOutputError, MotionStatus};
use std::time::Duration;
pub(crate) struct MotionStream {
tx: Sender<MotionStatus>,
live: AbortHandle,
timeout: Duration,
cooloff: Option<AbortHandle>,
}
impl MotionStream {
pub(crate) fn new() -> (Self, Receiver<MotionStatus>) {
pub(crate) fn new(timeout_seconds: f64) -> (Self, Receiver<MotionStatus>) {
let (tx, rx) = unbounded();
(
Self {
tx,
live: AbortHandle::new(),
timeout: Duration::from_secs_f64(timeout_seconds),
cooloff: None,
},
rx,
)
@@ -26,7 +31,36 @@ impl MotionStream {
impl MotionOutput for MotionStream {
fn motion_recv(&mut self, motion_status: MotionStatus) -> MotionOutputError {
let _ = self.tx.send(motion_status);
match motion_status {
MotionStatus::Start => {
if let Some(handle) = &self.cooloff {
handle.abort();
self.cooloff = None;
}
let _ = self.tx.send(motion_status);
}
MotionStatus::Stop => {
// Abort any current one
if let Some(handle) = &self.cooloff {
handle.abort();
self.cooloff = None;
}
let aborter = AbortHandle::new();
let thread_duration = self.timeout;
let thread_tx = self.tx.clone();
let thread_message = MotionStatus::Stop;
std::thread::spawn(move || {
std::thread::sleep(thread_duration);
if aborter.is_live() {
let _ = thread_tx.send(thread_message);
}
});
}
_ => {
let _ = self.tx.send(motion_status);
}
}
Ok(self.live.is_live())
}
}