1use 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
25pub 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#[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 pub fn new() -> Self {
82 Self::default()
83 }
84
85 pub fn with_target(mut self, target: impl Into<String>) -> Self {
88 self.target = Some(target.into());
89 self
90 }
91
92 pub fn with_stride(mut self, frames: usize) -> Self {
95 self.stride = frames.max(1);
96 self
97 }
98
99 pub fn with_frames_per_check(mut self, frames: usize) -> Self {
102 self.frames_per_check = frames.max(1);
103 self
104 }
105}
106
107pub 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 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 pub fn remote(describer: &LlmDescriber<ReleasedImage>) -> Self {
164 Self::with(Arc::clone(describer.model()), Describer::descriptor(describer).clone())
165 }
166}
167
168enum Job<'a> {
170 Ask(&'a str),
171 Caption(u64),
172}
173
174struct 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 pub fn with_frames_per_call(mut self, frames: usize) -> Self {
197 self.frames_per_call = frames.max(1);
198 self
199 }
200
201 pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
203 self.max_output_tokens = tokens;
204 self
205 }
206
207 pub fn with_visibility_pass(mut self, pass: VisibilityPass) -> Self {
210 self.visibility = Some(pass);
211 self
212 }
213
214 pub fn with_caption_instructions(mut self, instructions: impl Into<String>) -> Self {
218 self.caption_instructions = instructions.into();
219 self
220 }
221
222 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 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 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 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 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 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 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 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 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 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 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 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 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 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}