Skip to main content

adk_vision/video/
frames.rs

1//! [`FramesAnalyzer`]: questions over sampled frames on any vision-language model.
2
3use std::marker::PhantomData;
4use std::sync::Arc;
5
6use adk_core::{Content, GenerateContentConfig, Llm, LlmRequest, Part};
7use async_trait::async_trait;
8use serde_json::{Value, json};
9
10use super::answer::{ModelAnswer, add_usage, ask_schema, generate};
11use super::{evenly_spaced, timestamp};
12use crate::backend::BackendDescriptor;
13use crate::cloud::{LlmDescriber, extract_json};
14use crate::cx::VisionCx;
15use crate::egress::ReleasedImage;
16use crate::error::{Result, VisionError};
17use crate::geometry::RawRegion;
18use crate::media::FrameMeta;
19use crate::sent::{SentImage, VisionInput};
20use crate::traits::{
21    Describer, Sampling, VideoAnalysis, VideoAnalyzer, VideoEvent, VideoInput, VideoPlan,
22    VideoRequest, VideoUsage,
23};
24
25/// What a `Caption` chunk's description names unless
26/// [`with_caption_instructions`](FramesAnalyzer::with_caption_instructions) says otherwise.
27pub const DEFAULT_CAPTION_INSTRUCTIONS: &str = "Describe what happens in this part of the \
28     video, for a log that is searched later. Name each person, vehicle and object that moves, \
29     appears, disappears or changes, and say what it does and where; say so when the picture \
30     itself changes, such as the light. Leave out what stays the same in every image. When \
31     nothing happens, the caption is only \"Nothing happens.\" Describe only what the images \
32     show.";
33
34/// How [`FramesAnalyzer`] finds when something is first seen, for questions such as "when
35/// does the forklift enter the aisle?" that a small model answers poorly over many frames
36/// at once: it names events in frames without the subject, or misplaces them.
37///
38/// 1. **Target.** The thing the question is about: [`with_target`](Self::with_target), or
39///    named by the model from the question in one text-only call.
40/// 2. **Visibility.** Every [`stride`](Self::with_stride)-th frame, in order, is checked for
41///    the target — one yes-or-no question per image, or
42///    [`frames_per_check`](Self::with_frames_per_check) images a call — until one shows it.
43/// 3. **Refine.** The question is asked over every frame from the last check that did not
44///    show the target to `stride` frames after the first that did. When the model names an
45///    event there, that is the answer; when it names none, the positive counts as a false
46///    alarm and the checks resume after it.
47///
48/// An event's time is still the presentation time of the frame the model names. When no
49/// frame shows the target, or none of the frames around those that do answers the question,
50/// the answer says so and names no event.
51///
52/// # Example
53///
54/// ```
55/// use std::sync::Arc;
56/// use adk_model::MockLlm;
57/// use adk_vision::{FramesAnalyzer, LlmDescriber, VisibilityPass};
58///
59/// let model = Arc::new(MockLlm::new("claude-sonnet-5-5"));
60/// let describer = LlmDescriber::remote_with_hosts(model, ["api.anthropic.com"]).unwrap();
61/// // Frames sampled at 1 fps: check one in five, then ask over the eleven seconds around
62/// // the first that shows the forklift.
63/// let pass = VisibilityPass::new().with_target("the orange forklift").with_stride(5);
64/// let analyzer = FramesAnalyzer::remote(&describer).with_visibility_pass(pass);
65/// ```
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct VisibilityPass {
68    target: Option<String>,
69    stride: usize,
70    frames_per_check: usize,
71}
72
73impl Default for VisibilityPass {
74    fn default() -> Self {
75        Self { target: None, stride: 1, frames_per_check: 1 }
76    }
77}
78
79impl VisibilityPass {
80    /// Checks every frame, one per call, for the target the model names from the question.
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    /// Checks for `target`, a short noun phrase such as "the orange forklift", instead of
86    /// asking the model what the question is about.
87    pub fn with_target(mut self, target: impl Into<String>) -> Self {
88        self.target = Some(target.into());
89        self
90    }
91
92    /// Checks every `frames`-th frame, at least 1 (every frame, the default); the refine
93    /// step then reads every frame within `frames` of the first positive.
94    pub fn with_stride(mut self, frames: usize) -> Self {
95        self.stride = frames.max(1);
96        self
97    }
98
99    /// Checks `frames` images per call, at least 1 (the default); one asks the simplest
100    /// question, more costs fewer calls.
101    pub fn with_frames_per_check(mut self, frames: usize) -> Self {
102        self.frames_per_check = frames.max(1);
103        self
104    }
105}
106
107/// Answers `Ask` and `Caption` over frames a frame source sampled, on the model of an
108/// [`LlmDescriber`]:
109/// Qwen3-VL in this process ([`LlmDescriber::mistralrs`], feature `mistralrs`), a model
110/// on a loopback server, or a remote model whose frames each pass the egress gate.
111///
112/// The frames go in batches of [`frames_per_call`](Self::with_frames_per_call), each image
113/// numbered and stamped with its time in the prompt; the model names events by image
114/// number, so their times come from the frames' presentation timestamps, never from the
115/// model's arithmetic. A [`VisibilityPass`] first finds the frames that show what the
116/// question is about and asks only over those. A `Caption` request captions each chunk of
117/// `chunk_ms` in one call over at most `frames_per_call` of its frames, evenly spaced,
118/// naming what the chunk shows as the event's labels. Each call's tokens are reported in
119/// [`VideoUsage`](crate::VideoUsage), at zero cost on the device.
120///
121/// # Example
122///
123/// ```
124/// use std::sync::Arc;
125/// use adk_model::MockLlm;
126/// use adk_vision::{FramesAnalyzer, LlmDescriber, VideoAnalyzer};
127///
128/// let claude = Arc::new(MockLlm::new("claude-sonnet-5-5"));
129/// let describer = LlmDescriber::remote_with_hosts(claude, ["api.anthropic.com"]).unwrap();
130/// let analyzer = FramesAnalyzer::remote(&describer).with_frames_per_call(16);
131/// assert!(analyzer.descriptor().locality.is_remote());
132/// ```
133pub struct FramesAnalyzer<I = SentImage> {
134    llm: Arc<dyn Llm>,
135    descriptor: BackendDescriptor,
136    frames_per_call: usize,
137    max_output_tokens: u32,
138    visibility: Option<VisibilityPass>,
139    caption_instructions: String,
140    input: PhantomData<fn() -> I>,
141}
142
143impl<I> std::fmt::Debug for FramesAnalyzer<I> {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        f.debug_struct("FramesAnalyzer")
146            .field("model", &self.llm.name())
147            .field("descriptor", &self.descriptor)
148            .field("frames_per_call", &self.frames_per_call)
149            .field("visibility", &self.visibility)
150            .finish_non_exhaustive()
151    }
152}
153
154impl FramesAnalyzer<SentImage> {
155    /// Asks `describer`'s model, on this machine, over frames as the runtime prepared them.
156    pub fn local(describer: &LlmDescriber<SentImage>) -> Self {
157        Self::with(Arc::clone(describer.model()), Describer::descriptor(describer).clone())
158    }
159}
160
161impl FramesAnalyzer<ReleasedImage> {
162    /// Asks `describer`'s remote model over frames the egress gate released to it.
163    pub fn remote(describer: &LlmDescriber<ReleasedImage>) -> Self {
164        Self::with(Arc::clone(describer.model()), Describer::descriptor(describer).clone())
165    }
166}
167
168/// What one call does.
169enum Job<'a> {
170    Ask(&'a str),
171    Caption(u64),
172}
173
174/// One frame as the model receives it.
175struct Shown {
176    meta: FrameMeta,
177    size: (u32, u32),
178    part: Part,
179}
180
181impl<I> FramesAnalyzer<I> {
182    fn with(llm: Arc<dyn Llm>, descriptor: BackendDescriptor) -> Self {
183        Self {
184            llm,
185            descriptor,
186            frames_per_call: 8,
187            max_output_tokens: 1_024,
188            visibility: None,
189            caption_instructions: DEFAULT_CAPTION_INSTRUCTIONS.to_string(),
190            input: PhantomData,
191        }
192    }
193
194    /// Sends at most `frames` images per model call; 8 by default, at least 1. With a
195    /// [`VisibilityPass`] this caps the refine step's frames.
196    pub fn with_frames_per_call(mut self, frames: usize) -> Self {
197        self.frames_per_call = frames.max(1);
198        self
199    }
200
201    /// Caps each call's output at `tokens`; 1,024 by default.
202    pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
203        self.max_output_tokens = tokens;
204        self
205    }
206
207    /// Finds the frames that show what the question is about before asking it; see
208    /// [`VisibilityPass`].
209    pub fn with_visibility_pass(mut self, pass: VisibilityPass) -> Self {
210        self.visibility = Some(pass);
211        self
212    }
213
214    /// Asks for captions with `instructions` instead of [`DEFAULT_CAPTION_INSTRUCTIONS`]:
215    /// what a `Caption` chunk's description should name, such as "the forklifts, pallets
216    /// and people, and anything that falls or spills". The answer format stays fixed.
217    pub fn with_caption_instructions(mut self, instructions: impl Into<String>) -> Self {
218        self.caption_instructions = instructions.into();
219        self
220    }
221
222    /// Names the backend `id` instead of the model name.
223    pub fn with_id(mut self, id: impl Into<String>) -> Self {
224        self.descriptor.id = crate::backend::BackendId::new(id);
225        self
226    }
227
228    fn prompt(question: &str, frames: &[&Shown], fps: f32) -> String {
229        let stamps: Vec<String> = frames
230            .iter()
231            .enumerate()
232            .map(|(i, f)| format!("image {} at {}", i + 1, timestamp(f.meta.pts_ms)))
233            .collect();
234        format!(
235            "These {} images are frames sampled in order from one video at {} frames per \
236             second: {}.\n\nQuestion: {question}\n\nAnswer with JSON only: {{\"answer\": \
237             <the answer in words>, \"events\": [{{\"start\": <first image number>, \"end\": \
238             <last image number>, \"text\": <what happens>}}]}}. List an event only for what \
239             the question asks about, naming the first and last image in which it is seen. If \
240             it is not seen in these images, say so in the answer and give no events.",
241            frames.len(),
242            fps,
243            stamps.join(", ")
244        )
245    }
246
247    /// One model call over `frames` with `prompt`, its usage added to `usage`: the answer's
248    /// JSON.
249    async fn call(
250        &self,
251        cx: &VisionCx,
252        frames: &[&Shown],
253        prompt: String,
254        schema: Value,
255        usage: &mut VideoUsage,
256    ) -> Result<Value> {
257        let backend = self.descriptor.id.to_string();
258        let sizes: Vec<(u32, u32)> = frames.iter().map(|f| f.size).collect();
259        let bound = self
260            .descriptor
261            .token_estimate
262            .map(|e| e.estimate_micro_usd(&sizes, prompt.len(), Some(self.max_output_tokens)));
263        let mut parts: Vec<Part> = frames.iter().map(|f| f.part.clone()).collect();
264        parts.push(Part::Text { text: prompt });
265        let config = GenerateContentConfig {
266            max_output_tokens: i32::try_from(self.max_output_tokens).ok(),
267            response_schema: Some(schema),
268            ..GenerateContentConfig::default()
269        };
270        let llm_request = LlmRequest {
271            config: Some(config),
272            ..LlmRequest::new(self.llm.name(), vec![Content { role: "user".into(), parts }])
273        };
274        let ModelAnswer { text, usage: reported } =
275            generate(cx, &self.llm, bound, llm_request, &backend).await?;
276        add_usage(usage, &self.descriptor, reported.as_ref());
277        extract_json(&text).ok_or_else(|| VisionError::Parse {
278            backend,
279            message: format!("the answer holds no JSON: {text}"),
280        })
281    }
282
283    /// The question over `frames`: its answer in words, and the events it names, timed by
284    /// the frames they name.
285    async fn ask(
286        &self,
287        cx: &VisionCx,
288        question: &str,
289        frames: &[&Shown],
290        fps: f32,
291        usage: &mut VideoUsage,
292    ) -> Result<(Option<String>, Vec<VideoEvent>)> {
293        let prompt = Self::prompt(question, frames, fps);
294        let root = self.call(cx, frames, prompt, ask_schema("image"), usage).await?;
295        let at = |value: Option<&Value>| -> Option<u64> {
296            let n = value?.as_u64().or_else(|| value?.as_str()?.trim().parse().ok())?;
297            frames.get(usize::try_from(n).ok()?.checked_sub(1)?).map(|f| f.meta.pts_ms)
298        };
299        let mut events = Vec::new();
300        for event in root.get("events").and_then(Value::as_array).into_iter().flatten() {
301            let Some(start) = at(event.get("start")) else { continue };
302            let end = at(event.get("end")).unwrap_or(start).max(start);
303            let text = event.get("text").and_then(Value::as_str).unwrap_or_default();
304            events.push(VideoEvent::new(start, end, text));
305        }
306        let answer = root.get("answer").and_then(Value::as_str).map(str::to_string);
307        Ok((answer, events))
308    }
309
310    fn caption_prompt(&self, frames: &[&Shown], start_ms: u64, end_ms: u64) -> String {
311        let stamps: Vec<String> = frames
312            .iter()
313            .enumerate()
314            .map(|(i, f)| format!("image {} at {}", i + 1, timestamp(f.meta.pts_ms)))
315            .collect();
316        format!(
317            "These {} images are frames sampled in order from one part of a video, from {} to \
318             {}: {}.\n\n{}\n\nAnswer with JSON only: {{\"caption\": <one to three sentences>, \
319             \"objects\": [<a short noun phrase for each person, vehicle or object the caption \
320             names>]}}.",
321            frames.len(),
322            timestamp(start_ms),
323            timestamp(end_ms),
324            stamps.join(", "),
325            self.caption_instructions
326        )
327    }
328
329    /// Captions every chunk of `chunk_ms`, counted from the first frame: one call per chunk
330    /// that holds a frame, over at most `frames_per_call` of its frames, evenly spaced.
331    async fn caption_chunks(
332        &self,
333        cx: &VisionCx,
334        shown: &[Shown],
335        chunk_ms: u64,
336        sampling: Sampling,
337        analysis: &mut VideoAnalysis<RawRegion>,
338    ) -> Result<()> {
339        if chunk_ms == 0 {
340            return Err(VisionError::InvalidInput(
341                "a caption chunk must be at least one millisecond long".into(),
342            ));
343        }
344        let first = shown.first().map_or(0, |f| f.meta.pts_ms);
345        let step = if sampling.fps > 0.0 { (1_000.0 / sampling.fps) as u64 } else { 0 };
346        let video_end = shown.last().map_or(0, |f| f.meta.pts_ms) + step;
347        let chunk_of = |f: &Shown| f.meta.pts_ms.saturating_sub(first) / chunk_ms;
348        let schema = json!({
349            "type": "object",
350            "properties": {
351                "caption": {"type": "string"},
352                "objects": {"type": "array", "items": {"type": "string"}}
353            },
354            "required": ["caption", "objects"]
355        });
356        let mut from = 0;
357        while from < shown.len() {
358            let chunk = chunk_of(&shown[from]);
359            let to = from + shown[from..].iter().take_while(|f| chunk_of(f) == chunk).count();
360            let frames = evenly_spaced(&shown[from..to], self.frames_per_call);
361            let start = first + chunk * chunk_ms;
362            let end = (start + chunk_ms).min(video_end).max(start);
363            let prompt = self.caption_prompt(&frames, start, end);
364            let root = self.call(cx, &frames, prompt, schema.clone(), &mut analysis.usage).await?;
365            let caption = root
366                .get("caption")
367                .and_then(Value::as_str)
368                .map(str::trim)
369                .filter(|c| !c.is_empty())
370                .ok_or_else(|| VisionError::Parse {
371                    backend: self.descriptor.id.to_string(),
372                    message: format!("the caption answer names no caption: {root}"),
373                })?;
374            let mut labels: Vec<String> = Vec::new();
375            for label in root.get("objects").and_then(Value::as_array).into_iter().flatten() {
376                let Some(label) = label.as_str().map(str::trim).filter(|l| !l.is_empty()) else {
377                    continue;
378                };
379                if !labels.iter().any(|l| l.eq_ignore_ascii_case(label)) {
380                    labels.push(label.to_string());
381                }
382            }
383            analysis.events.push(VideoEvent::new(start, end, caption).with_labels(labels));
384            from = to;
385        }
386        Ok(())
387    }
388
389    /// The question over every frame, in batches of `frames_per_call`.
390    async fn ask_in_batches(
391        &self,
392        cx: &VisionCx,
393        question: &str,
394        shown: &[Shown],
395        sampling: Sampling,
396        analysis: &mut VideoAnalysis<RawRegion>,
397    ) -> Result<()> {
398        let mut answers: Vec<(u64, String)> = Vec::new();
399        for batch in shown.chunks(self.frames_per_call) {
400            let frames: Vec<&Shown> = batch.iter().collect();
401            let (answer, events) =
402                self.ask(cx, question, &frames, sampling.fps, &mut analysis.usage).await?;
403            if let Some(answer) = answer {
404                let from = if events.is_empty() { u64::MAX } else { batch[0].meta.pts_ms };
405                answers.push((from, answer));
406            }
407            analysis.events.extend(events);
408        }
409        // One batch answers for itself; across batches, the batches that saw the event do.
410        analysis.answer = match answers.len() {
411            0 => None,
412            1 => Some(answers.remove(0).1),
413            _ if answers.iter().all(|(from, _)| *from == u64::MAX) => Some(answers.remove(0).1),
414            _ => Some(
415                answers
416                    .into_iter()
417                    .filter(|(from, _)| *from != u64::MAX)
418                    .map(|(from, answer)| format!("[{}] {answer}", timestamp(from)))
419                    .collect::<Vec<_>>()
420                    .join(" "),
421            ),
422        };
423        Ok(())
424    }
425
426    /// The visibility pass, then the question around the first frame that shows its target.
427    async fn ask_after_visibility(
428        &self,
429        cx: &VisionCx,
430        question: &str,
431        pass: &VisibilityPass,
432        shown: &[Shown],
433        sampling: Sampling,
434        analysis: &mut VideoAnalysis<RawRegion>,
435    ) -> Result<()> {
436        let target = match &pass.target {
437            Some(target) => target.clone(),
438            None => {
439                let prompt = format!(
440                    "A question about a video: {question}\n\nWhat must be visible in a frame of \
441                     the video to answer it? Name that object, person or thing as a short noun \
442                     phrase. Answer with JSON only: {{\"target\": <the noun phrase>}}."
443                );
444                let schema = json!({
445                    "type": "object",
446                    "properties": {"target": {"type": "string"}},
447                    "required": ["target"]
448                });
449                let root = self.call(cx, &[], prompt, schema, &mut analysis.usage).await?;
450                root.get("target")
451                    .and_then(Value::as_str)
452                    .map(str::trim)
453                    .filter(|t| !t.is_empty())
454                    .map(str::to_string)
455                    .ok_or_else(|| VisionError::Parse {
456                        backend: self.descriptor.id.to_string(),
457                        message: format!("the model named no target for the question: {root}"),
458                    })?
459            }
460        };
461        let stride = pass.stride;
462        let checked: Vec<usize> = (0..shown.len()).step_by(stride).collect();
463        // `seen[i]` is whether `checked[i]` showed the target, once asked.
464        let mut seen: Vec<Option<bool>> = vec![None; checked.len()];
465        let (mut next, mut dismissed) = (0, 0);
466        while next < checked.len() {
467            if seen[next].is_none() {
468                let end = (next + pass.frames_per_check).min(checked.len());
469                let frames: Vec<&Shown> = checked[next..end].iter().map(|&i| &shown[i]).collect();
470                let visible = self.visible(cx, &target, &frames, &mut analysis.usage).await?;
471                for (offset, slot) in seen[next..end].iter_mut().enumerate() {
472                    *slot = Some(visible.contains(&(offset + 1)));
473                }
474            }
475            if seen[next] != Some(true) {
476                next += 1;
477                continue;
478            }
479            // From the last frame checked without the target to `stride` frames past the
480            // first with it, at most `frames_per_call` of them, evenly spaced.
481            let first = checked[next];
482            let lo = first.saturating_sub(stride);
483            let hi = (first + stride).min(shown.len() - 1);
484            let step = (hi - lo + 1).div_ceil(self.frames_per_call);
485            let frames: Vec<&Shown> = (lo..=hi).step_by(step).map(|i| &shown[i]).collect();
486            let fps = sampling.fps / step as f32;
487            let (answer, events) =
488                self.ask(cx, question, &frames, fps, &mut analysis.usage).await?;
489            tracing::debug!(
490                vision.backend = %self.descriptor.id,
491                vision.target = %target,
492                frame.pts_ms = shown[first].meta.pts_ms,
493                vision.events = events.len(),
494                "visibility pass refined a positive"
495            );
496            if !events.is_empty() {
497                analysis.answer = answer;
498                analysis.events = events;
499                return Ok(());
500            }
501            dismissed += 1;
502            next += 1;
503        }
504        analysis.answer = Some(match dismissed {
505            0 => format!("{target} is not seen in any of the {} frames checked.", checked.len()),
506            n => format!(
507                "{target} is seen in {n} of the {} frames checked, but the frames around them do \
508                 not answer the question.",
509                checked.len()
510            ),
511        });
512        Ok(())
513    }
514
515    /// The numbers, from 1, of the frames in `frames` that the model says show `target`.
516    async fn visible(
517        &self,
518        cx: &VisionCx,
519        target: &str,
520        frames: &[&Shown],
521        usage: &mut VideoUsage,
522    ) -> Result<Vec<usize>> {
523        let (prompt, schema) = if frames.len() == 1 {
524            (
525                format!(
526                    "Is {target} visible in this image? Answer with JSON only: {{\"visible\": \
527                     true}} or {{\"visible\": false}}."
528                ),
529                json!({
530                    "type": "object",
531                    "properties": {"visible": {"type": "boolean"}},
532                    "required": ["visible"]
533                }),
534            )
535        } else {
536            (
537                format!(
538                    "These {} images are frames from one video, numbered 1 to {} in order. In \
539                     which of them is {target} visible? Answer with JSON only: {{\"visible\": \
540                     [<the numbers of the images that show it>]}}, an empty list when none does.",
541                    frames.len(),
542                    frames.len()
543                ),
544                json!({
545                    "type": "object",
546                    "properties": {"visible": {"type": "array", "items": {"type": "integer"}}},
547                    "required": ["visible"]
548                }),
549            )
550        };
551        let root = self.call(cx, frames, prompt, schema, usage).await?;
552        let visible = match root.get("visible") {
553            Some(Value::Bool(true)) => vec![1],
554            Some(Value::Array(numbers)) => numbers
555                .iter()
556                .filter_map(|n| n.as_u64().or_else(|| n.as_str()?.trim().parse().ok()))
557                .filter_map(|n| usize::try_from(n).ok())
558                .filter(|n| (1..=frames.len()).contains(n))
559                .collect(),
560            _ => Vec::new(),
561        };
562        Ok(visible)
563    }
564
565    async fn run<T: VisionInput>(
566        &self,
567        cx: &VisionCx,
568        video: &VideoInput<T>,
569        request: &VideoRequest,
570        part: impl Fn(&T) -> Result<Part>,
571    ) -> Result<VideoAnalysis<RawRegion>> {
572        let job = match request {
573            VideoRequest::Ask { question } => Job::Ask(question),
574            VideoRequest::Caption { chunk_ms } => Job::Caption(*chunk_ms),
575            VideoRequest::Track { .. } => {
576                return Err(VisionError::Unsupported(format!(
577                    "`{}` answers `Ask` and `Caption` over sampled frames; track with a \
578                     `Tracker` or `sam-3.1` video",
579                    self.descriptor.id
580                )));
581            }
582        };
583        if video.frames.is_empty() {
584            return Err(VisionError::Unsupported(format!(
585                "`{}` reads sampled frames, not clips; sample the clip with a frame source first",
586                self.descriptor.id
587            )));
588        }
589        cx.check()?;
590        let shown = video
591            .frames
592            .iter()
593            .map(|(meta, image)| {
594                Ok(Shown { meta: meta.clone(), size: image.sent().size(), part: part(image)? })
595            })
596            .collect::<Result<Vec<_>>>()?;
597        let mut analysis = VideoAnalysis::default();
598        match (job, &self.visibility) {
599            (Job::Caption(chunk_ms), _) => {
600                self.caption_chunks(cx, &shown, chunk_ms, video.sampling, &mut analysis).await?;
601            }
602            (Job::Ask(question), None) => {
603                self.ask_in_batches(cx, question, &shown, video.sampling, &mut analysis).await?;
604            }
605            (Job::Ask(question), Some(pass)) => {
606                self.ask_after_visibility(
607                    cx,
608                    question,
609                    pass,
610                    &shown,
611                    video.sampling,
612                    &mut analysis,
613                )
614                .await?;
615            }
616        }
617        analysis.events.sort_by_key(|e| e.start_ms);
618        analysis.usage.frames = video.frames.len() as u64;
619        Ok(analysis)
620    }
621
622    /// The most the calls on `plan` can cost: every batch, or with a visibility pass, the
623    /// target call, a check of every `stride`-th frame and a refine call after each.
624    fn estimate(&self, plan: &VideoPlan, request: &VideoRequest) -> Option<u64> {
625        let estimate = self.descriptor.token_estimate?;
626        let cost = |sizes: &[(u32, u32)]| {
627            estimate.estimate_micro_usd(sizes, 1_024, Some(self.max_output_tokens))
628        };
629        if let VideoRequest::Caption { chunk_ms } = request {
630            // Every chunk the time covers, each at most `frames_per_call` of the largest frame.
631            let chunks = plan.duration_ms.div_ceil((*chunk_ms).max(1)).max(1);
632            let largest = plan
633                .frame_sizes
634                .iter()
635                .copied()
636                .max_by_key(|(w, h)| u64::from(*w) * u64::from(*h))
637                .unwrap_or_default();
638            let per_chunk = self.frames_per_call.min(plan.frame_sizes.len());
639            return Some(cost(&vec![largest; per_chunk]).saturating_mul(chunks));
640        }
641        let Some(pass) = &self.visibility else {
642            return Some(
643                plan.frame_sizes
644                    .chunks(self.frames_per_call)
645                    .map(cost)
646                    .fold(0, u64::saturating_add),
647            );
648        };
649        let largest =
650            plan.frame_sizes.iter().copied().max_by_key(|(w, h)| u64::from(*w) * u64::from(*h));
651        let largest = largest.unwrap_or_default();
652        let checked = plan.frame_sizes.len().div_ceil(pass.stride);
653        let refine = vec![largest; (2 * pass.stride + 1).min(self.frames_per_call)];
654        let checks = vec![largest; checked]
655            .chunks(pass.frames_per_check)
656            .map(cost)
657            .fold(cost(&[]), u64::saturating_add);
658        let refines = cost(&refine).saturating_mul(checked as u64);
659        Some(checks.saturating_add(refines))
660    }
661}
662
663fn check_inline(len: usize, backend: &str) -> Result<()> {
664    if len > adk_core::MAX_INLINE_DATA_SIZE {
665        return Err(VisionError::InputTooLarge {
666            backend: backend.to_string(),
667            limit: format!("{} bytes inline", adk_core::MAX_INLINE_DATA_SIZE),
668            actual: format!("{len} bytes"),
669        });
670    }
671    Ok(())
672}
673
674#[async_trait]
675impl VideoAnalyzer<SentImage> for FramesAnalyzer<SentImage> {
676    fn descriptor(&self) -> &BackendDescriptor {
677        &self.descriptor
678    }
679
680    fn max_cost_micro_usd(&self, plan: &VideoPlan, request: &VideoRequest) -> Option<u64> {
681        self.estimate(plan, request)
682    }
683
684    async fn analyze(
685        &self,
686        cx: &VisionCx,
687        video: &VideoInput<SentImage>,
688        request: &VideoRequest,
689    ) -> Result<VideoAnalysis<RawRegion>> {
690        let backend = self.descriptor.id.to_string();
691        self.run(cx, video, request, |image| {
692            let data = image.encode_png()?;
693            check_inline(data.len(), &backend)?;
694            Ok(Part::InlineData {
695                mime_type: "image/png".into(),
696                data,
697                uri: None,
698                annotations: None,
699            })
700        })
701        .await
702    }
703}
704
705#[async_trait]
706impl VideoAnalyzer<ReleasedImage> for FramesAnalyzer<ReleasedImage> {
707    fn descriptor(&self) -> &BackendDescriptor {
708        &self.descriptor
709    }
710
711    fn max_cost_micro_usd(&self, plan: &VideoPlan, request: &VideoRequest) -> Option<u64> {
712        self.estimate(plan, request)
713    }
714
715    async fn analyze(
716        &self,
717        cx: &VisionCx,
718        video: &VideoInput<ReleasedImage>,
719        request: &VideoRequest,
720    ) -> Result<VideoAnalysis<RawRegion>> {
721        if let Some((_, other)) = video.frames.iter().find(|(_, i)| !i.is_for(&self.descriptor.id))
722        {
723            return Err(VisionError::NotReleased {
724                backend: format!(
725                    "{} (the frame was released to `{}`)",
726                    self.descriptor.id,
727                    other.receipt().backend
728                ),
729            });
730        }
731        self.run(cx, video, request, |image| {
732            check_inline(image.bytes().len(), image.receipt().backend.as_str())?;
733            Ok(image.to_part())
734        })
735        .await
736    }
737}
738
739#[cfg(test)]
740mod tests {
741    use super::*;
742    use crate::backend::Locality;
743    use crate::budget::{ImageTokens, TokenEstimate};
744    use crate::geometry::CoordFrame;
745
746    #[test]
747    fn the_hold_covers_every_check_and_refine_of_a_visibility_pass() {
748        let estimate = TokenEstimate::new(ImageTokens::Claude, 3_000_000, 15_000_000);
749        let descriptor = BackendDescriptor::new(
750            "claude-sonnet-5-5",
751            Locality::Remote { hosts: vec!["api.anthropic.com".into()] },
752            CoordFrame::SentPixels,
753        )
754        .with_token_estimate(estimate);
755        let llm: Arc<dyn Llm> = Arc::new(adk_model::MockLlm::new("claude-sonnet-5-5"));
756        let plan = VideoPlan {
757            clip: None,
758            frame_sizes: vec![(448, 252); 24],
759            duration_ms: 120_000,
760            sampling: Sampling::at(0.2),
761        };
762        let cost = |frames: usize| {
763            estimate.estimate_micro_usd(&vec![(448, 252); frames], 1_024, Some(1_024))
764        };
765        let ask = VideoRequest::Ask { question: "When?".into() };
766        let direct = FramesAnalyzer::<ReleasedImage>::with(Arc::clone(&llm), descriptor.clone());
767        assert_eq!(direct.estimate(&plan, &ask), Some(3 * cost(8)));
768        // The target, 24 checks of one frame, and a refine of three frames after each.
769        let pass = FramesAnalyzer::<ReleasedImage>::with(Arc::clone(&llm), descriptor.clone())
770            .with_visibility_pass(VisibilityPass::new());
771        assert_eq!(pass.estimate(&plan, &ask), Some(cost(0) + 24 * cost(1) + 24 * cost(3)));
772        // Every fifth frame, four a check, and refines of at most eight frames.
773        let strided = FramesAnalyzer::<ReleasedImage>::with(llm, descriptor)
774            .with_visibility_pass(VisibilityPass::new().with_stride(5).with_frames_per_check(4));
775        assert_eq!(strided.estimate(&plan, &ask), Some(cost(0) + cost(4) + cost(1) + 5 * cost(8)));
776    }
777}