1#[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
37pub const MAX_CLIP_BYTES: usize = 2 * 1024 * 1024 * 1024;
39
40#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct ClipInfo {
45 pub mime_type: String,
47 pub codec: VideoCodec,
49 pub width: u32,
51 pub height: u32,
53 pub duration_ms: u64,
55 pub frames: u64,
57}
58
59impl ClipInfo {
60 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 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#[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 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 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 pub fn bytes(&self) -> &[u8] {
147 &self.bytes
148 }
149
150 pub fn digest(&self) -> Digest {
152 self.digest
153 }
154
155 pub fn info(&self) -> &ClipInfo {
157 &self.info
158 }
159
160 pub fn size(&self) -> (u32, u32) {
162 (self.info.width, self.info.height)
163 }
164
165 pub fn artifact(&self) -> Option<&ArtifactLocator> {
167 self.artifact.as_ref()
168 }
169
170 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#[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 pub fn clip(&self) -> &SourceClip {
196 &self.clip
197 }
198
199 pub fn bytes(&self) -> &[u8] {
201 self.clip.bytes()
202 }
203
204 pub fn info(&self) -> &ClipInfo {
206 self.clip.info()
207 }
208}
209
210#[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#[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 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}