Skip to main content

adk_vision/video/
mod.rs

1//! Video clips and the video analyzers (spec 3.7 ยง7.13).
2//!
3//! A [`SourceClip`] is an MP4 or MOV file read once: its digest, and the codec, size,
4//! duration and frame count its container states. The runtime hands an on-device
5//! [`VideoAnalyzer`](crate::VideoAnalyzer) a [`SentClip`] and a remote one only a
6//! [`ReleasedClip`](crate::ReleasedClip), which the egress gate makes after it checked the
7//! destination and the rule and recorded the release.
8//!
9//! | Analyzer | Requests | Input | Feature |
10//! |----------|----------|-------|---------|
11//! | `FramesAnalyzer` | `Ask`, `Caption` | sampled frames, on any vision-language model (Qwen3-VL on this machine, or a remote one through the gate), optionally after a `VisibilityPass` | `cloud` |
12//! | `GeminiVideoAnalyzer` | `Ask` | a clip, as Gemini native video: inline up to 20 MB, else uploaded once through the File API and sent as a file part | `gemini-video` |
13//! | `sam::SamVideoTracker` | `Track` | a clip, through `sam-3.1` video: masks or boxes with stable object identifiers | `sam` |
14
15#[cfg(feature = "cloud")]
16pub(crate) mod answer;
17#[cfg(feature = "cloud")]
18mod frames;
19#[cfg(feature = "gemini-video")]
20mod gemini;
21mod mp4;
22
23use std::sync::Arc;
24
25use serde::{Deserialize, Serialize};
26
27#[cfg(feature = "cloud")]
28pub use frames::{DEFAULT_CAPTION_INSTRUCTIONS, FramesAnalyzer, VisibilityPass};
29#[cfg(feature = "gemini-video")]
30pub use gemini::{GEMINI_INLINE_LIMIT, GeminiVideoAnalyzer, MediaResolution};
31pub use mp4::VideoCodec;
32
33use crate::digest::Digest;
34use crate::error::{Result, VisionError};
35use crate::media::{ArtifactLocator, VideoRef};
36
37/// The largest clip accepted: Gemini's File API limit, 2 GB.
38pub const MAX_CLIP_BYTES: usize = 2 * 1024 * 1024 * 1024;
39
40/// What a clip's container states about its video track.
41#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct ClipInfo {
45    /// `video/mp4` or `video/quicktime`.
46    pub mime_type: String,
47    /// The codec.
48    pub codec: VideoCodec,
49    /// Coded width in pixels.
50    pub width: u32,
51    /// Coded height in pixels.
52    pub height: u32,
53    /// Duration in milliseconds.
54    pub duration_ms: u64,
55    /// Frames in the video track.
56    pub frames: u64,
57}
58
59impl ClipInfo {
60    /// Frames per second, from the frame count and duration.
61    pub fn frame_rate(&self) -> f64 {
62        if self.duration_ms == 0 {
63            return 0.0;
64        }
65        self.frames as f64 * 1_000.0 / self.duration_ms as f64
66    }
67
68    /// The frames a backend that samples at `fps` analyses: one per `1 / fps` seconds, at
69    /// least one, at most every frame.
70    pub fn sampled_frames(&self, fps: f32) -> u64 {
71        if !(fps.is_finite() && fps > 0.0) {
72            return self.frames;
73        }
74        let sampled = (self.duration_ms as f64 * f64::from(fps) / 1_000.0).ceil() as u64;
75        sampled.clamp(1, self.frames.max(1))
76    }
77}
78
79/// An MP4 or MOV clip, read once: its bytes, their digest, and what its container states.
80///
81/// # Example
82///
83/// ```no_run
84/// use adk_vision::SourceClip;
85///
86/// let clip = SourceClip::decode(std::fs::read("aisle.mp4").unwrap())?;
87/// println!("{} frames over {} ms", clip.info().frames, clip.info().duration_ms);
88/// # Ok::<(), adk_vision::VisionError>(())
89/// ```
90#[derive(Clone, Debug)]
91pub struct SourceClip {
92    bytes: Arc<[u8]>,
93    digest: Digest,
94    info: ClipInfo,
95    artifact: Option<ArtifactLocator>,
96}
97
98impl SourceClip {
99    /// Reads a clip, checking its container from the header before anything else: MP4 or
100    /// MOV with an H.264, H.265 or MPEG-4 video track, at most [`MAX_CLIP_BYTES`].
101    ///
102    /// # Errors
103    ///
104    /// [`VisionError::InvalidInput`] above the limit, for another container or codec, or
105    /// for a container that states no duration or frame count.
106    pub fn decode(bytes: impl Into<Arc<[u8]>>) -> Result<Self> {
107        let bytes: Arc<[u8]> = bytes.into();
108        if bytes.len() > MAX_CLIP_BYTES {
109            return Err(VisionError::InvalidInput(format!(
110                "the clip is {} bytes, over the {MAX_CLIP_BYTES}-byte cap; split or re-encode it",
111                bytes.len()
112            )));
113        }
114        let probe = mp4::probe(&bytes)
115            .map_err(|reason| VisionError::InvalidInput(format!("unsupported video: {reason}")))?;
116        let info = ClipInfo {
117            mime_type: probe.mime_type.to_string(),
118            codec: probe.codec,
119            width: probe.width,
120            height: probe.height,
121            duration_ms: probe.duration_ms,
122            frames: probe.frames,
123        };
124        Ok(Self { digest: Digest::of(&bytes), bytes, info, artifact: None })
125    }
126
127    /// Reads a clip stored as `video`, checking that the bytes are the ones it names.
128    ///
129    /// # Errors
130    ///
131    /// As [`decode`](Self::decode), and [`VisionError::InvalidInput`] when the bytes'
132    /// digest is not the reference's.
133    pub fn from_ref(video: &VideoRef, bytes: impl Into<Arc<[u8]>>) -> Result<Self> {
134        let mut clip = Self::decode(bytes)?;
135        if clip.digest != video.digest {
136            return Err(VisionError::InvalidInput(format!(
137                "the clip's bytes hash to {}, not to {} as its reference says",
138                clip.digest, video.digest
139            )));
140        }
141        clip.artifact = Some(video.artifact.clone());
142        Ok(clip)
143    }
144
145    /// The encoded bytes.
146    pub fn bytes(&self) -> &[u8] {
147        &self.bytes
148    }
149
150    /// `sha256:` of the bytes.
151    pub fn digest(&self) -> Digest {
152        self.digest
153    }
154
155    /// What the container states.
156    pub fn info(&self) -> &ClipInfo {
157        &self.info
158    }
159
160    /// `(width, height)` of the coded frames.
161    pub fn size(&self) -> (u32, u32) {
162        (self.info.width, self.info.height)
163    }
164
165    /// The artifact the clip is stored in, when it was read from one.
166    pub fn artifact(&self) -> Option<&ArtifactLocator> {
167        self.artifact.as_ref()
168    }
169
170    /// A reference to the clip stored as `artifact`.
171    pub fn to_video_ref(&self, artifact: ArtifactLocator) -> VideoRef {
172        VideoRef {
173            artifact,
174            digest: self.digest,
175            mime_type: self.info.mime_type.clone(),
176            duration_ms: self.info.duration_ms,
177            width: self.info.width,
178            height: self.info.height,
179        }
180    }
181}
182
183/// The clip an on-device video backend sees. Only the runtime constructs one.
184#[derive(Clone, Debug)]
185pub struct SentClip {
186    clip: SourceClip,
187}
188
189impl SentClip {
190    pub(crate) fn new(clip: SourceClip) -> Self {
191        Self { clip }
192    }
193
194    /// The clip.
195    pub fn clip(&self) -> &SourceClip {
196        &self.clip
197    }
198
199    /// The encoded bytes.
200    pub fn bytes(&self) -> &[u8] {
201        self.clip.bytes()
202    }
203
204    /// What the container states.
205    pub fn info(&self) -> &ClipInfo {
206        self.clip.info()
207    }
208}
209
210/// At most `n` of `items`, evenly spaced, the first and last always among them.
211#[cfg(feature = "cloud")]
212pub(crate) fn evenly_spaced<T>(items: &[T], n: usize) -> Vec<&T> {
213    if items.len() <= n {
214        return items.iter().collect();
215    }
216    if n <= 1 {
217        return items.get(items.len() / 2).into_iter().collect();
218    }
219    let last = items.len() - 1;
220    (0..n).map(|i| &items[(i * last + (n - 1) / 2) / (n - 1)]).collect()
221}
222
223/// `m:ss.s` for a time in milliseconds, the form timestamps take in prompts and answers.
224#[cfg(feature = "cloud")]
225pub(crate) fn timestamp(ms: u64) -> String {
226    let tenths = ms / 100;
227    format!("{}:{:02}.{}", tenths / 600, (tenths / 10) % 60, tenths % 10)
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn clips_are_read_once_and_digested() {
236        let bytes = mp4::tests::mp4(b"avc1", 1280, 720, 1_200_000, 36_000, 64);
237        let clip = SourceClip::decode(bytes.clone()).unwrap();
238        assert_eq!(clip.digest(), Digest::of(&bytes));
239        assert_eq!(clip.size(), (1280, 720));
240        assert!((clip.info().frame_rate() - 30.0).abs() < 1e-9);
241        // Twenty minutes at Gemini's default 1 fps is 1,200 frames.
242        assert_eq!(clip.info().sampled_frames(1.0), 1_200);
243        assert_eq!(clip.info().sampled_frames(60.0), 36_000);
244        assert_eq!(clip.info().sampled_frames(0.0), 36_000);
245        let video = clip.to_video_ref(ArtifactLocator::new("a", "u", "s", "aisle.mp4", 1));
246        assert!(SourceClip::from_ref(&video, bytes).is_ok());
247        let other = mp4::tests::mp4(b"avc1", 1280, 720, 1_000, 30, 1);
248        assert!(SourceClip::from_ref(&video, other).is_err());
249    }
250
251    #[cfg(feature = "cloud")]
252    #[test]
253    fn evenly_spaced_keeps_the_ends() {
254        assert_eq!(evenly_spaced(&[1, 2, 3, 4, 5, 6, 7, 8], 4), vec![&1, &3, &6, &8]);
255        assert_eq!(evenly_spaced(&[1, 2, 3], 1), vec![&2]);
256        assert_eq!(evenly_spaced(&[1, 2], 4), vec![&1, &2]);
257    }
258
259    #[cfg(feature = "cloud")]
260    #[test]
261    fn timestamps_read_as_minutes_and_seconds() {
262        assert_eq!(timestamp(0), "0:00.0");
263        assert_eq!(timestamp(83_450), "1:23.4");
264        assert_eq!(timestamp(1_200_000), "20:00.0");
265    }
266}