Skip to main content

adk_surface/voice/
visual.rs

1//! The camera and the screen as input only while their switches are on (spec 3.3 §5.6).
2//!
3//! The browser stops a track the moment its switch goes off, but the server does not rely on
4//! that: [`VisualInputs`] drops every frame of a source that is off, whatever arrives, and
5//! forwards the frames of a source that is on no faster than the provider takes them.
6//! Frames are never stored or logged.
7//!
8//! | Policy | Forwards |
9//! |---|---|
10//! | [`FramePolicy::Steady`] (Gemini Live) | one frame per interval, by default one a second |
11//! | [`FramePolicy::OnChange`] (OpenAI Realtime) | a frame that differs from the last one forwarded, by default at most one every 5 seconds |
12
13use std::time::Duration;
14
15use tokio::time::Instant;
16
17use super::wire::VisualSource;
18
19/// How often a provider takes a camera or screen frame (spec 3.3 §5.6).
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum FramePolicy {
22    /// Every frame, at most one per `interval`: Gemini Live takes about one frame a second.
23    Steady {
24        /// The least time between two forwarded frames of one source.
25        interval: Duration,
26    },
27    /// Only a frame that differs from the last one forwarded, at most one per `interval`:
28    /// the OpenAI Realtime API reads an image as part of the conversation, so an unchanged
29    /// screen is not sent again.
30    OnChange {
31        /// The least time between two forwarded frames of one source.
32        interval: Duration,
33    },
34}
35
36impl FramePolicy {
37    /// Gemini Live: one frame a second.
38    pub const GEMINI: Self = Self::Steady { interval: Duration::from_secs(1) };
39    /// The OpenAI Realtime API: on change, at most one frame every 5 seconds.
40    pub const OPENAI: Self = Self::OnChange { interval: Duration::from_secs(5) };
41
42    fn interval(self) -> Duration {
43        match self {
44            Self::Steady { interval } | Self::OnChange { interval } => interval,
45        }
46    }
47}
48
49/// One source's switch and what was last forwarded from it.
50#[derive(Debug, Clone, Default)]
51struct Switch {
52    on: bool,
53    /// When the last frame was forwarded.
54    last_at: Option<Instant>,
55    /// A digest of the last frame forwarded, for [`FramePolicy::OnChange`].
56    last_frame: Option<u64>,
57}
58
59/// The gate every camera and screen frame passes before it reaches the provider
60/// (spec 3.3 §5.6).
61///
62/// # Example
63///
64/// ```rust
65/// use adk_surface::voice::{FramePolicy, VisualInputs, VisualSource};
66/// use tokio::time::Instant;
67///
68/// let mut gate = VisualInputs::new(FramePolicy::GEMINI);
69/// let now = Instant::now();
70/// assert!(!gate.offer(VisualSource::Screen, b"frame", now), "off: dropped");
71/// gate.switch(VisualSource::Screen, true);
72/// assert!(gate.offer(VisualSource::Screen, b"frame", now));
73/// gate.switch(VisualSource::Screen, false);
74/// assert!(!gate.offer(VisualSource::Screen, b"frame", now + std::time::Duration::from_secs(5)));
75/// ```
76#[derive(Debug, Clone)]
77pub struct VisualInputs {
78    policy: FramePolicy,
79    camera: Switch,
80    screen: Switch,
81}
82
83impl VisualInputs {
84    /// Both switches off.
85    pub fn new(policy: FramePolicy) -> Self {
86        Self { policy, camera: Switch::default(), screen: Switch::default() }
87    }
88
89    fn of(&mut self, source: VisualSource) -> &mut Switch {
90        match source {
91            VisualSource::Camera => &mut self.camera,
92            VisualSource::Screen => &mut self.screen,
93        }
94    }
95
96    /// Turns `source` on or off. Off forgets the last frame, so the first frame after the next
97    /// on is new.
98    pub fn switch(&mut self, source: VisualSource, on: bool) {
99        let switch = self.of(source);
100        switch.on = on;
101        if !on {
102            switch.last_frame = None;
103        }
104    }
105
106    /// Whether `source` is on.
107    pub fn is_on(&self, source: VisualSource) -> bool {
108        match source {
109            VisualSource::Camera => self.camera.on,
110            VisualSource::Screen => self.screen.on,
111        }
112    }
113
114    /// Whether `frame`, received from `source` at `at`, goes to the provider: never while the
115    /// source is off, and no faster than the policy allows.
116    pub fn offer(&mut self, source: VisualSource, frame: &[u8], at: Instant) -> bool {
117        let policy = self.policy;
118        let switch = self.of(source);
119        if !switch.on {
120            return false;
121        }
122        if switch.last_at.is_some_and(|last| at.saturating_duration_since(last) < policy.interval())
123        {
124            return false;
125        }
126        let digest = fingerprint(frame);
127        if matches!(policy, FramePolicy::OnChange { .. }) && switch.last_frame == Some(digest) {
128            return false;
129        }
130        switch.last_at = Some(at);
131        switch.last_frame = Some(digest);
132        true
133    }
134}
135
136/// A cheap digest of a frame, to tell an unchanged screen from a new one. Not a security
137/// boundary: a collision only skips one frame.
138fn fingerprint(frame: &[u8]) -> u64 {
139    use std::hash::{Hash, Hasher};
140    let mut hasher = std::hash::DefaultHasher::new();
141    frame.hash(&mut hasher);
142    hasher.finish()
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    #[test]
150    fn on_change_skips_an_unchanged_frame() {
151        let mut gate = VisualInputs::new(FramePolicy::OPENAI);
152        let start = Instant::now();
153        gate.switch(VisualSource::Screen, true);
154        assert!(gate.offer(VisualSource::Screen, b"a", start));
155        assert!(!gate.offer(VisualSource::Screen, b"b", start + Duration::from_secs(1)));
156        assert!(!gate.offer(VisualSource::Screen, b"a", start + Duration::from_secs(6)));
157        assert!(gate.offer(VisualSource::Screen, b"b", start + Duration::from_secs(6)));
158    }
159
160    #[test]
161    fn the_sources_are_independent() {
162        let mut gate = VisualInputs::new(FramePolicy::GEMINI);
163        let start = Instant::now();
164        gate.switch(VisualSource::Camera, true);
165        assert!(gate.offer(VisualSource::Camera, b"a", start));
166        assert!(!gate.offer(VisualSource::Screen, b"a", start));
167        gate.switch(VisualSource::Screen, true);
168        assert!(gate.offer(VisualSource::Screen, b"a", start));
169        assert!(!gate.offer(VisualSource::Camera, b"b", start + Duration::from_millis(500)));
170    }
171}