adk_vision/stream/mod.rs
1//! Frame ingestion: sources, sampling, the frame governor, retention and the stream pipeline
2//! (spec 3.7 §7.9, §7.13).
3//!
4//! A [`FrameSource`] turns a camera, a file, a screen, a browser or the web home's camera
5//! into a [`FrameStream`] of decoded frames at the rate and size a [`Sampling`] asks for. A
6//! source never buffers without bound: when the consumer falls behind, the source drops the
7//! oldest frames it holds and keeps the newest.
8//!
9//! | Source | Feature | Ingest | Decode |
10//! |--------|---------|--------|--------|
11//! | `RtspSource` | `rtsp` | RTSP through `retina`: H.264, H.265, MJPEG | MJPEG in process; H.264 and H.265 through `ffmpeg` |
12//! | `FileSource` | `ffmpeg` | MP4 and MOV files | a user-installed `ffmpeg` binary |
13//! | `DeviceSource` | `device` | a camera on this machine: AVFoundation (macOS), v4l2 (Linux), DirectShow (Windows) | a user-installed `ffmpeg` binary |
14//! | `ScreenSource` | `screen` | a `ComputerActuator` screenshot or a computer-use-mcp observation, at an interval; with `computer-use`, `RuntimeObserver` and `screen_source` over any `ComputerUseRuntime` | PNG, JPEG |
15//! | `BrowserSource` | `browser` | the `browser_screenshot` tool, at an interval | PNG |
16//! | `SurfaceCameraSource` | `surface-camera` | frames the web home pushes through a `CameraFeed` | JPEG |
17//!
18//! [`StreamPipeline`] runs one source through the fixed stages of §7.13:
19//!
20//! ```text
21//! source → sampler → frame governor → privacy hook → detector → tracker → observation sink
22//! ```
23//!
24//! - **Sampling.** [`Sampler`] keeps frames at most `fps` apart by presentation time and
25//! downscales them to `max_long_edge`.
26//! - **The frame governor.** [`FrameGovernor`] holds a stream to its [`FrameBudget`]: a local
27//! rate, escalations per minute and frame quotas per period. Under pressure it steps down
28//! in a fixed order — lower the local rate, stop escalating, pause the source — writes a
29//! `vision.governor.step` audit record at each step, and resumes when the next period
30//! starts.
31//! - **Privacy.** Every frame passes a [`PrivacyHook`] before any other stage sees it. The
32//! only way to a [`RedactedFrame`] is [`FramePrivacy::apply`], and [`FrameKeeper`] stores
33//! nothing else, so a frame is blurred before any artifact write (V-I9, S18).
34//! - **Retention.** Frames stay ephemeral unless they become a wake payload, evidence on a
35//! card, or a sample a person kept; [`FrameKeeper`] stores those for 30 days by default
36//! (Q13), purges them after, and writes `vision.evidence.kept` and `.purged` records.
37//! - **Detection and tracking.** The detector runs through [`VisionRuntime`], so each frame
38//! is metered — in `UsageUnit::Frames`, at zero cost on the device — and its regions come
39//! back in source pixels; the
40//! [`Tracker`] gives them anonymous track identifiers that reset with the source session.
41//! - **Observations.** Each processed frame reaches an [`ObservationSink`]: watch
42//! conditions, wakes and the live camera surface consume the stream there.
43//! - **Watches and wakes.** [`StreamWatch`] is the watch stage: it holds watch conditions
44//! against every observation, keeps the frame of each event as its wake payload, and
45//! delivers the event to a [`WatchSink`](crate::WatchSink) such as the kernel's
46//! `VisionWakeSource`. [`FrameSources`] holds an operator's named sources and streams each
47//! only while a watch is registered on it; the `vision_watch` tool starts and stops those
48//! watches (spec 3.7 §7.8, §7.10).
49//!
50//! With the `conformance` feature, [`check_frame_source`] checks any source against the
51//! [`FrameSource`] contract: refused bad rates, rising indices and times, the sampling rate,
52//! the size cap, and ephemeral frames.
53//!
54//! The kill switch pauses a stream at its next frame (V-I17): while the run's governance
55//! control is frozen, frames are dropped unprocessed, and the pipeline records
56//! `vision.source.paused` and, after the thaw, `vision.source.resumed`.
57//!
58//! [`VisionRuntime`]: crate::VisionRuntime
59//! [`Tracker`]: crate::Tracker
60//! [`Sampling`]: crate::Sampling
61
62mod governor;
63mod pipeline;
64mod privacy;
65#[cfg(any(
66 feature = "rtsp",
67 feature = "ffmpeg",
68 feature = "screen",
69 feature = "browser",
70 feature = "surface-camera"
71))]
72mod queue;
73mod records;
74mod retention;
75mod sampler;
76mod sources;
77mod watching;
78
79#[cfg(feature = "browser")]
80mod browser;
81#[cfg(feature = "surface-camera")]
82mod camera;
83#[cfg(any(feature = "screen", feature = "browser"))]
84mod capture;
85#[cfg(all(feature = "screen", feature = "computer-use"))]
86mod computer_use;
87#[cfg(feature = "conformance")]
88mod conformance;
89#[cfg(feature = "device")]
90mod device;
91#[cfg(feature = "ffmpeg")]
92mod ffmpeg;
93#[cfg(feature = "stream-fixtures")]
94pub mod fixtures;
95#[cfg(feature = "rtsp")]
96mod rtsp;
97#[cfg(feature = "screen")]
98mod screen;
99
100use std::pin::Pin;
101
102use async_trait::async_trait;
103use futures::Stream;
104
105use crate::error::Result;
106use crate::media::{Frame, FrameSourceId};
107use crate::traits::Sampling;
108
109#[cfg(feature = "browser")]
110pub use browser::BrowserSource;
111#[cfg(feature = "surface-camera")]
112pub use camera::{CameraFeed, SurfaceCameraSource};
113#[cfg(any(feature = "screen", feature = "browser"))]
114pub use capture::observation_image;
115#[cfg(all(feature = "screen", feature = "computer-use"))]
116pub use computer_use::{RuntimeObserver, screen_source};
117#[cfg(feature = "conformance")]
118pub use conformance::{FrameSourceReport, check_frame_source};
119#[cfg(feature = "device")]
120pub use device::{
121 CaptureDevice, DEFAULT_CAPTURE_RATE, DeviceApi, DeviceKind, DeviceSelector, DeviceSource,
122};
123#[cfg(feature = "ffmpeg")]
124pub use ffmpeg::{FFMPEG_ENV, FfmpegBinary, FileSource};
125pub use governor::{
126 Admission, EscalationDecision, EscalationRefusal, EscalationVerdict, FrameBudget,
127 FrameGovernor, FrameVerdict, GovernorChange, GovernorState, GovernorStep, StopReason,
128};
129pub use pipeline::{
130 GovernorHandle, Observation, ObservationSink, SourceEvent, StopCause, StreamPipeline,
131 StreamPipelineBuilder, StreamSummary,
132};
133pub use privacy::{
134 FramePrivacy, NoRedaction, PrivacyHook, RedactedFrame, RedactionMethod, RedactorPrivacy,
135};
136pub use records::{
137 VISION_EVIDENCE_KEPT, VISION_EVIDENCE_PURGED, VISION_GOVERNOR_STEP, VISION_SOURCE_PAUSED,
138 VISION_SOURCE_RESUMED, VISION_SOURCE_STARTED, VISION_SOURCE_STOPPED,
139};
140pub use retention::{
141 EVIDENCE_RETENTION, FrameKeeper, KeepReason, PurgeCause, PurgedFrame, RetentionEntry,
142 RetentionPolicy,
143};
144#[cfg(feature = "rtsp")]
145pub use rtsp::{RtspSource, RtspTransport};
146pub use sampler::Sampler;
147#[cfg(feature = "screen")]
148pub use screen::{ScreenSource, VisualObserver};
149pub use sources::{
150 FrameSources, SourceSpec, SourceStatus, StreamEnd, TrackerFactory, WatchChange, WatchOutcome,
151};
152pub use watching::StreamWatch;
153
154/// How many decoded frames a source holds for a consumer that has fallen behind, before it
155/// drops the oldest.
156pub const SOURCE_QUEUE_FRAMES: usize = 4;
157
158/// Decoded frames from a [`FrameSource`], in presentation order. The stream ends when the
159/// source does; dropping it stops the source and any process it spawned.
160pub type FrameStream = Pin<Box<dyn Stream<Item = Result<Frame>> + Send>>;
161
162/// A source of decoded frames: a camera, a file, a screen, a browser or the web home's
163/// camera (spec 3.7 §7.13).
164///
165/// # Example
166///
167/// ```
168/// use adk_vision::stream::{FrameSource, FrameStream};
169/// use adk_vision::{DecodedImage, Frame, FramePixels, FrameSourceId, Sampling};
170/// use futures::StreamExt;
171/// use std::sync::Arc;
172/// use std::time::Duration;
173///
174/// /// Ten grey frames, 100 ms apart, sampled at the rate asked for.
175/// struct Grey(FrameSourceId);
176///
177/// #[async_trait::async_trait]
178/// impl FrameSource for Grey {
179/// fn id(&self) -> &FrameSourceId {
180/// &self.0
181/// }
182///
183/// async fn frames(&self, sampling: Sampling) -> adk_vision::Result<FrameStream> {
184/// let mut sampler = adk_vision::stream::Sampler::new(sampling)?;
185/// let source = self.0.clone();
186/// let frames = (0..10u64).filter_map(move |index| {
187/// let pts = Duration::from_millis(index * 100);
188/// sampler.admit(pts).then(|| {
189/// Ok(Frame {
190/// source: source.clone(),
191/// index,
192/// pts,
193/// captured_at: chrono::Utc::now(),
194/// pixels: FramePixels::Ephemeral(Arc::new(DecodedImage::filled(4, 4, [128; 4]))),
195/// })
196/// })
197/// });
198/// Ok(futures::stream::iter(frames.collect::<Vec<_>>()).boxed())
199/// }
200/// }
201///
202/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
203/// let source = Grey(FrameSourceId("grey".into()));
204/// let frames: Vec<_> = source
205/// .frames(Sampling { fps: 5.0, max_long_edge: None })
206/// .await
207/// .unwrap()
208/// .collect()
209/// .await;
210/// // 10 frames a second sampled at 5 a second.
211/// assert_eq!(frames.len(), 5);
212/// # });
213/// ```
214#[async_trait]
215pub trait FrameSource: Send + Sync {
216 /// The source's identifier, which names it in frames, records and wakes. It never holds
217 /// a credential.
218 fn id(&self) -> &FrameSourceId;
219
220 /// Decoded frames at the requested rate and size; the source drops what it cannot keep
221 /// up with.
222 ///
223 /// # Errors
224 ///
225 /// [`VisionError::InvalidInput`](crate::VisionError::InvalidInput) for a sampling rate
226 /// that is not a positive number, or the source's own refusal to open: an unreachable
227 /// camera, a missing `ffmpeg`, a file that is not a video.
228 async fn frames(&self, sampling: Sampling) -> Result<FrameStream>;
229}