use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::Viewer;
use crate::record::{FeedRecorder, prune_recordings};
pub struct DashCamOptions {
pub every: Duration,
pub life: Duration,
pub after: Duration,
pub max_bytes: u64,
pub max_age: Duration,
pub active: Box<dyn Fn() -> bool + Send + Sync>,
}
impl Default for DashCamOptions {
fn default() -> Self {
DashCamOptions {
every: Duration::from_secs(120),
life: Duration::from_secs(240),
after: Duration::from_secs(60),
max_bytes: 512 << 20,
max_age: Duration::from_secs(14 * 86_400),
active: Box::new(|| true),
}
}
}
struct Clip {
rec: FeedRecorder,
until: Instant,
}
struct State {
segments: Vec<(FeedRecorder, Instant)>,
clip: Option<Clip>,
stopped: bool,
}
pub struct DashCam {
viewer: Viewer,
dir: PathBuf,
opts: DashCamOptions,
state: Mutex<State>,
}
impl DashCam {
pub fn start(viewer: &Viewer, dir: impl Into<PathBuf>, opts: DashCamOptions) -> Arc<DashCam> {
let cam = Arc::new(DashCam {
viewer: viewer.clone(),
dir: dir.into(),
opts,
state: Mutex::new(State {
segments: Vec::new(),
clip: None,
stopped: false,
}),
});
let weak = Arc::downgrade(&cam);
tokio::spawn(async move {
let mut t = tokio::time::interval(Duration::from_secs(1));
loop {
t.tick().await;
let Some(cam) = weak.upgrade() else { break };
if !cam.check(Instant::now()) {
break;
}
}
});
cam
}
fn lock(&self) -> std::sync::MutexGuard<'_, State> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[must_use]
pub fn buffering(&self) -> usize {
self.lock().segments.len()
}
pub fn check(&self, now: Instant) -> bool {
let mut ended = None;
{
let mut g = self.lock();
if g.stopped {
return false;
}
if g.clip
.as_ref()
.is_some_and(|c| now >= c.until || !c.rec.running())
{
ended = g.clip.take();
}
if !(self.opts.active)() {
g.segments.clear();
} else {
g.segments
.retain(|(_, at)| now.duration_since(*at) < self.opts.life);
let need = g
.segments
.last()
.is_none_or(|(_, at)| now.duration_since(*at) >= self.opts.every);
if need {
let rec = FeedRecorder::in_memory(&self.viewer, &self.dir);
g.segments.push((rec, now));
}
}
}
if let Some(c) = ended {
self.end_clip(c);
}
true
}
pub fn clip(&self, note: &str) -> Option<String> {
let now = Instant::now();
let mut g = self.lock();
if let Some(c) = g.clip.as_mut()
&& c.rec.running()
{
c.until = c.until.max(now + self.opts.after);
return Some(c.rec.meta().name);
}
if g.segments.is_empty() {
if g.stopped || !(self.opts.active)() {
return None;
}
g.segments
.push((FeedRecorder::in_memory(&self.viewer, &self.dir), now));
}
let (rec, at) = g.segments.remove(0);
let name = rec.spill(Some(note));
if name.is_empty() {
return None;
}
log::info!(
"[dashcam] {name} kept ({note}): {} s before, {} s after",
now.duration_since(at).as_secs(),
self.opts.after.as_secs()
);
g.clip = Some(Clip {
rec,
until: now + self.opts.after,
});
Some(name)
}
pub fn stop(&self) {
let clip = {
let mut g = self.lock();
g.stopped = true;
g.segments.clear();
g.clip.take()
};
if let Some(c) = clip {
self.end_clip(c);
}
}
fn end_clip(&self, mut c: Clip) {
let m = c.rec.stop();
log::info!(
"[dashcam] {} ended: {:.0} s, {:.2} MB",
m.name,
(m.end.unwrap_or(m.start) - m.start) / 1000.0,
m.bytes as f64 / 1_048_576.0
);
let gone = prune_recordings(
&self.dir,
self.opts.max_bytes,
self.opts.max_age,
Some(&m.name),
);
if !gone.is_empty() {
log::info!("[dashcam] removed old recordings: {}", gone.join(", "));
}
}
}
impl Drop for DashCam {
fn drop(&mut self) {
self.stop();
}
}