Skip to main content

adk_vision/runtime/
video.rs

1//! The runtime's video call: [`VisionRuntime::analyze_video`].
2
3use adk_core::{UsageCall, UsageUnit, UsageVector};
4
5use super::{
6    Backend, CallOptions, Inputs, Preflight, Prepared, VisionOutput, VisionRuntime, mismatch,
7    planned_size,
8};
9use crate::backend::{BackendDescriptor, Locality};
10use crate::cx::VisionCx;
11use crate::egress::{ClipReleaseRequest, DataClass, ReleasedClip, ReleasedImage};
12use crate::error::{Result, VisionError};
13use crate::geometry::{RegionNormalizer, TransformChain};
14use crate::manifest::VisionTask;
15use crate::media::{FrameMeta, SourceImage};
16use crate::sent::SentImage;
17use crate::traits::{
18    Sampling, SegmentPrompt, VideoAnalysis, VideoFrame, VideoInput, VideoPlan, VideoRequest,
19};
20use crate::video::{SentClip, SourceClip};
21
22/// What a video call analyses: a clip, for a backend that reads video itself, or frames a
23/// frame source already sampled.
24///
25/// # Example
26///
27/// ```no_run
28/// use adk_vision::{Sampling, SourceClip, VideoSource};
29///
30/// let clip = SourceClip::decode(std::fs::read("aisle.mp4").unwrap()).unwrap();
31/// let video = VideoSource::clip(&clip, Sampling::at(1.0));
32/// assert!(matches!(video, VideoSource::Clip { .. }));
33/// ```
34#[derive(Clone, Copy, Debug)]
35#[non_exhaustive]
36pub enum VideoSource<'a> {
37    /// A clip, which a backend that samples video itself reads at `sampling`.
38    Clip {
39        /// The clip.
40        clip: &'a SourceClip,
41        /// How the backend samples it.
42        sampling: Sampling,
43    },
44    /// Frames already sampled, each with its stream identity and timing.
45    Frames {
46        /// `(frame, image)` pairs, in order.
47        frames: &'a [(FrameMeta, SourceImage)],
48        /// How they were sampled.
49        sampling: Sampling,
50    },
51}
52
53impl<'a> VideoSource<'a> {
54    /// A clip, read by the backend at `sampling`.
55    pub fn clip(clip: &'a SourceClip, sampling: Sampling) -> Self {
56        Self::Clip { clip, sampling }
57    }
58
59    /// Frames already sampled at `sampling`.
60    pub fn frames(frames: &'a [(FrameMeta, SourceImage)], sampling: Sampling) -> Self {
61        Self::Frames { frames, sampling }
62    }
63}
64
65impl VisionRuntime {
66    /// Analyses a video on the video route.
67    ///
68    /// # Errors
69    ///
70    /// As [`analyze_video_with`](Self::analyze_video_with).
71    pub async fn analyze_video(
72        &self,
73        cx: &VisionCx,
74        video: VideoSource<'_>,
75        request: &VideoRequest,
76    ) -> Result<VisionOutput<VideoAnalysis>> {
77        self.analyze_video_with(cx, video, request, &CallOptions::default()).await
78    }
79
80    /// Analyses a video with per-call options.
81    ///
82    /// The call opens one hold before anything is prepared (V-I6): the frames the backend
83    /// analyses as [`UsageUnit::Frames`], at its per-frame price (with its per-request
84    /// minimum), at zero cost on the device, or up to its own estimate for a token-billed
85    /// backend. Sampled frames are prepared as images are, released one by one through the
86    /// egress gate for a remote backend; a clip is released through
87    /// [`EgressGate::release_clip`](crate::EgressGate::release_clip) as data class `video`
88    /// unless the options name another. Track regions come back in source pixels of the
89    /// clip or of their frame, with their track identifiers.
90    ///
91    /// # Errors
92    ///
93    /// [`VisionError::InvalidInput`] for a call with no clip and no frame, and the errors
94    /// of [`detect_with`](Self::detect_with).
95    pub async fn analyze_video_with(
96        &self,
97        cx: &VisionCx,
98        video: VideoSource<'_>,
99        request: &VideoRequest,
100        options: &CallOptions,
101    ) -> Result<VisionOutput<VideoAnalysis>> {
102        let route = self.route_for(VisionTask::AnalyzeVideo, options, self.videos.default_id())?;
103        let (descriptor, backend) = self.videos.get(&route.primary)?;
104        let (clip, frames, sampling) = match video {
105            VideoSource::Clip { clip, sampling } => (Some(clip), &[][..], sampling),
106            VideoSource::Frames { frames, sampling } => (None, frames, sampling),
107        };
108        if clip.is_none() && frames.is_empty() {
109            return Err(VisionError::InvalidInput(
110                "a video call needs a clip or at least one frame".into(),
111            ));
112        }
113        let duration_ms = match clip {
114            Some(clip) => clip.info().duration_ms,
115            None => {
116                let first = frames.first().map_or(0, |(f, _)| f.pts_ms);
117                let last = frames.last().map_or(0, |(f, _)| f.pts_ms);
118                let step = if sampling.fps > 0.0 { (1_000.0 / sampling.fps) as u64 } else { 0 };
119                last.saturating_sub(first) + step
120            }
121        };
122        let plan = VideoPlan {
123            clip: clip.map(|c| c.info().clone()),
124            frame_sizes: frames
125                .iter()
126                .map(|(_, image)| planned_size(image.size(), options.region, &descriptor.limits))
127                .collect(),
128            duration_ms,
129            sampling,
130        };
131        let (billed, bound) = match backend {
132            Backend::Local(b) => (b.frames(&plan), b.max_cost_micro_usd(&plan, request)),
133            Backend::Remote(b) => (b.frames(&plan), b.max_cost_micro_usd(&plan, request)),
134        };
135        // A backend taking one concept per request reads the whole video once per request.
136        let requests = match request {
137            VideoRequest::Track { prompts } => {
138                let concepts =
139                    prompts.iter().filter(|p| matches!(p, SegmentPrompt::Concept { .. })).count();
140                descriptor.requests_for(concepts, concepts < prompts.len())
141            }
142            _ => 1,
143        };
144        let hold = self.preflight_frames(cx, descriptor, billed, requests, bound).await?;
145        let estimate = hold.cost.or(bound);
146        let mut prepared = Vec::with_capacity(frames.len());
147        for (_, image) in frames {
148            prepared.push(
149                self.prepare(cx, descriptor, backend.is_remote(), image, options.region, options)
150                    .await?,
151            );
152        }
153        let normalizers: Vec<(&FrameMeta, RegionNormalizer)> = frames
154            .iter()
155            .zip(&prepared)
156            .map(|((meta, _), p)| (meta, Self::normalizer(descriptor, p)))
157            .collect();
158        let mut inputs = Inputs::of(&prepared);
159        let metas: Vec<FrameMeta> = frames.iter().map(|(meta, _)| meta.clone()).collect();
160        let task = VisionTask::AnalyzeVideo;
161        let (raw, mut record) = match backend {
162            Backend::Local(b) => {
163                let images = prepared
164                    .into_iter()
165                    .map(|p| match p {
166                        Prepared::Local(image) => Ok(image),
167                        Prepared::Remote(_) => Err(mismatch(descriptor)),
168                    })
169                    .collect::<Result<Vec<SentImage>>>()?;
170                if let Some(clip) = clip {
171                    inputs.sources.push(clip.digest());
172                }
173                let input = VideoInput::new(
174                    metas.into_iter().zip(images).collect(),
175                    clip.map(|c| SentClip::new(c.clone())),
176                    sampling,
177                );
178                self.metered(cx, task, descriptor, inputs, hold, b.analyze(cx, &input, request))
179                    .await?
180            }
181            Backend::Remote(b) => {
182                let images = prepared
183                    .into_iter()
184                    .map(|p| match p {
185                        Prepared::Remote(released) => Ok(*released),
186                        Prepared::Local(_) => Err(mismatch(descriptor)),
187                    })
188                    .collect::<Result<Vec<ReleasedImage>>>()?;
189                let released = match clip {
190                    Some(clip) => {
191                        let released =
192                            self.release_clip(cx, descriptor, clip, estimate, options).await?;
193                        inputs.sources.push(clip.digest());
194                        inputs.egress.push(released.receipt().egress);
195                        Some(released)
196                    }
197                    None => None,
198                };
199                let input =
200                    VideoInput::new(metas.into_iter().zip(images).collect(), released, sampling);
201                self.metered(cx, task, descriptor, inputs, hold, b.analyze(cx, &input, request))
202                    .await?
203            }
204        };
205        let clip_normalizer = clip.map(|c| {
206            let (w, h) = c.size();
207            RegionNormalizer::new(
208                c.digest(),
209                TransformChain::new(w, h),
210                descriptor.frame,
211                descriptor.id.clone(),
212            )
213            .with_manifest(descriptor.manifest.clone())
214        });
215        let mut found = Vec::with_capacity(raw.frames.len());
216        let mut regions = 0usize;
217        for frame in raw.frames {
218            let (normalizer, pts) = match &clip_normalizer {
219                Some(normalizer) => (normalizer, frame.pts_ms),
220                None => {
221                    let (meta, normalizer) = normalizers
222                        .iter()
223                        .find(|(meta, _)| meta.index == frame.index)
224                        .ok_or_else(|| VisionError::Parse {
225                            backend: descriptor.id.to_string(),
226                            message: format!(
227                                "regions name frame {}, which the call did not send",
228                                frame.index
229                            ),
230                        })?;
231                    (normalizer, frame.pts_ms.or(Some(meta.pts_ms)))
232                }
233            };
234            let mapped = normalizer.regions(frame.regions)?;
235            regions += mapped.len();
236            found.push(VideoFrame { index: frame.index, pts_ms: pts, regions: mapped });
237        }
238        record.regions = regions;
239        let mut usage = raw.usage;
240        if usage.frames == 0 {
241            usage.frames = billed.saturating_mul(requests);
242        }
243        if usage.cost_micro_usd.is_none() {
244            usage.cost_micro_usd = record.cost_micro_usd;
245        }
246        let value = VideoAnalysis { answer: raw.answer, events: raw.events, frames: found, usage };
247        Ok(VisionOutput { value, calls: vec![record] })
248    }
249
250    async fn release_clip(
251        &self,
252        cx: &VisionCx,
253        descriptor: &BackendDescriptor,
254        clip: &SourceClip,
255        estimate: Option<u64>,
256        options: &CallOptions,
257    ) -> Result<ReleasedClip> {
258        let gate = self
259            .gate
260            .as_ref()
261            .ok_or_else(|| VisionError::NotReleased { backend: descriptor.id.to_string() })?;
262        let class = options.data_class.clone().unwrap_or_else(|| DataClass::new("video"));
263        let mut request =
264            ClipReleaseRequest::new(clip, descriptor, class).with_estimated_cost(estimate);
265        for digest in &options.approved {
266            request = request.approved(*digest);
267        }
268        gate.release_clip(cx, request).await
269    }
270
271    /// Opens the hold of one video call of `requests` requests reading `frames` frames
272    /// each: the frames as [`UsageUnit::Frames`], and the cost bound — zero on the device,
273    /// the per-frame price of every request (each with its minimum) for a per-unit backend,
274    /// the backend's estimate for a token-billed one.
275    async fn preflight_frames(
276        &self,
277        cx: &VisionCx,
278        descriptor: &BackendDescriptor,
279        frames: u64,
280        requests: u64,
281        estimate: Option<u64>,
282    ) -> Result<Preflight> {
283        cx.check()?;
284        let units = UsageVector::new().with(UsageUnit::Frames, frames.saturating_mul(requests));
285        let (vendor, model, cost, bound) = match &descriptor.price {
286            None => {
287                let vendor = match &descriptor.locality {
288                    Locality::Remote { hosts } => hosts.first().cloned(),
289                    Locality::InProcess | Locality::Loopback => None,
290                };
291                (vendor.unwrap_or_else(|| "local".into()), descriptor.id.to_string(), Some(0), 0)
292            }
293            Some(price) => match price.unit() {
294                Some(unit) => {
295                    let amount = if unit == UsageUnit::Requests { 1 } else { frames };
296                    let cost = price.request_cost(amount).map(|c| c.saturating_mul(requests));
297                    (price.vendor().to_string(), price.model().to_string(), cost, cost.unwrap_or(0))
298                }
299                None => (
300                    price.vendor().to_string(),
301                    price.model().to_string(),
302                    None,
303                    estimate.unwrap_or(0),
304                ),
305            },
306        };
307        let scope = cx.scope();
308        if scope.is_unmetered() {
309            return Ok(Preflight { hold: None, units, cost });
310        }
311        let call =
312            UsageCall::new(vendor, model).with_max_cost_micro_usd(bound).with_units(units.clone());
313        let hold = scope.begin_usage(&call).await?;
314        Ok(Preflight { hold: Some(hold), units, cost })
315    }
316}