use std::time::Duration;
use tokio::time::Instant;
use super::wire::VisualSource;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FramePolicy {
Steady {
interval: Duration,
},
OnChange {
interval: Duration,
},
}
impl FramePolicy {
pub const GEMINI: Self = Self::Steady { interval: Duration::from_secs(1) };
pub const OPENAI: Self = Self::OnChange { interval: Duration::from_secs(5) };
fn interval(self) -> Duration {
match self {
Self::Steady { interval } | Self::OnChange { interval } => interval,
}
}
}
#[derive(Debug, Clone, Default)]
struct Switch {
on: bool,
last_at: Option<Instant>,
last_frame: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct VisualInputs {
policy: FramePolicy,
camera: Switch,
screen: Switch,
}
impl VisualInputs {
pub fn new(policy: FramePolicy) -> Self {
Self { policy, camera: Switch::default(), screen: Switch::default() }
}
fn of(&mut self, source: VisualSource) -> &mut Switch {
match source {
VisualSource::Camera => &mut self.camera,
VisualSource::Screen => &mut self.screen,
}
}
pub fn switch(&mut self, source: VisualSource, on: bool) {
let switch = self.of(source);
switch.on = on;
if !on {
switch.last_frame = None;
}
}
pub fn is_on(&self, source: VisualSource) -> bool {
match source {
VisualSource::Camera => self.camera.on,
VisualSource::Screen => self.screen.on,
}
}
pub fn offer(&mut self, source: VisualSource, frame: &[u8], at: Instant) -> bool {
let policy = self.policy;
let switch = self.of(source);
if !switch.on {
return false;
}
if switch.last_at.is_some_and(|last| at.saturating_duration_since(last) < policy.interval())
{
return false;
}
let digest = fingerprint(frame);
if matches!(policy, FramePolicy::OnChange { .. }) && switch.last_frame == Some(digest) {
return false;
}
switch.last_at = Some(at);
switch.last_frame = Some(digest);
true
}
}
fn fingerprint(frame: &[u8]) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::hash::DefaultHasher::new();
frame.hash(&mut hasher);
hasher.finish()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn on_change_skips_an_unchanged_frame() {
let mut gate = VisualInputs::new(FramePolicy::OPENAI);
let start = Instant::now();
gate.switch(VisualSource::Screen, true);
assert!(gate.offer(VisualSource::Screen, b"a", start));
assert!(!gate.offer(VisualSource::Screen, b"b", start + Duration::from_secs(1)));
assert!(!gate.offer(VisualSource::Screen, b"a", start + Duration::from_secs(6)));
assert!(gate.offer(VisualSource::Screen, b"b", start + Duration::from_secs(6)));
}
#[test]
fn the_sources_are_independent() {
let mut gate = VisualInputs::new(FramePolicy::GEMINI);
let start = Instant::now();
gate.switch(VisualSource::Camera, true);
assert!(gate.offer(VisualSource::Camera, b"a", start));
assert!(!gate.offer(VisualSource::Screen, b"a", start));
gate.switch(VisualSource::Screen, true);
assert!(gate.offer(VisualSource::Screen, b"a", start));
assert!(!gate.offer(VisualSource::Camera, b"b", start + Duration::from_millis(500)));
}
}