use std::sync::Arc;
use adk_artifact::InMemoryArtifactService;
use adk_core::egress::EgressPolicy;
use adk_core::{
AdkError, BudgetTracker, ErrorCategory, GOVERNANCE_FROZEN_CODE, GovernanceControl,
InMemorySpendLedger, RunBudget, UsageUnit,
};
use super::Target;
use super::probe::Harness;
use crate::backend::BackendDescriptor;
use crate::cx::VisionCx;
use crate::digest::Digest;
use crate::egress::{
EgressAction, EgressConfig, EgressGate, InMemoryEgressRecorder, ReleasedImage,
};
use crate::error::{Result, VisionError};
use crate::geometry::RegionSet;
use crate::media::{FrameMeta, MediaStore, SourceImage};
use crate::runtime::{VideoSource, VisionOutput, VisionRuntime};
use crate::traits::{Sampling, VideoAnalysis, VideoAnalyzer, VideoRequest};
use crate::video::SourceClip;
pub type VideoAnalyzerTarget = Target<dyn VideoAnalyzer, dyn VideoAnalyzer<ReleasedImage>>;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct VideoFixture {
pub clip: Option<SourceClip>,
pub frames: Vec<(FrameMeta, SourceImage)>,
pub sampling: Sampling,
pub request: VideoRequest,
pub refused: VideoRequest,
pub expected_event: Option<(u64, u64)>,
pub caption_chunk_ms: Option<u64>,
}
impl VideoFixture {
pub fn clip(clip: SourceClip, sampling: Sampling, request: VideoRequest) -> Self {
Self {
clip: Some(clip),
frames: Vec::new(),
sampling,
request,
refused: VideoRequest::Caption { chunk_ms: 10_000 },
expected_event: None,
caption_chunk_ms: None,
}
}
pub fn frames(
frames: Vec<(FrameMeta, SourceImage)>,
sampling: Sampling,
request: VideoRequest,
) -> Self {
Self {
clip: None,
frames,
sampling,
request,
refused: VideoRequest::Caption { chunk_ms: 10_000 },
expected_event: None,
caption_chunk_ms: None,
}
}
pub fn with_expected_event(mut self, start_ms: u64, tolerance_ms: u64) -> Self {
self.expected_event = Some((start_ms, tolerance_ms));
self
}
pub fn with_caption(mut self, chunk_ms: u64) -> Self {
self.caption_chunk_ms = Some(chunk_ms);
self
}
pub fn with_refused(mut self, request: VideoRequest) -> Self {
self.refused = request;
self
}
fn source(&self) -> VideoSource<'_> {
match &self.clip {
Some(clip) => VideoSource::clip(clip, self.sampling),
None => VideoSource::frames(&self.frames, self.sampling),
}
}
fn span(&self) -> (u64, u64) {
if let Some(clip) = &self.clip {
return (0, clip.info().duration_ms);
}
let step = if self.sampling.fps > 0.0 { (1_000.0 / self.sampling.fps) as u64 } else { 0 };
let first = self.frames.first().map_or(0, |(f, _)| f.pts_ms);
let last = self.frames.last().map_or(0, |(f, _)| f.pts_ms);
(first, last + step)
}
fn digests(&self) -> Vec<Digest> {
match &self.clip {
Some(clip) => vec![clip.digest()],
None => self.frames.iter().map(|(_, image)| image.digest()).collect(),
}
}
}
fn harness(target: &VideoAnalyzerTarget, gate: bool, budget: RunBudget) -> Harness {
let recorder = Arc::new(InMemoryEgressRecorder::new());
let mut builder = VisionRuntime::builder()
.media_store(MediaStore::new(Arc::new(InMemoryArtifactService::new())));
if gate {
builder = builder.egress_gate(EgressGate::new(
EgressPolicy::allow_private_networks(),
EgressConfig::default().with_default(EgressAction::Allow),
recorder.clone(),
));
}
builder = match target {
Target::Local(b) => builder.video_analyzer(Arc::clone(b)),
Target::Remote(b) => builder.remote_video_analyzer(Arc::clone(b)),
};
let runtime = builder.build().unwrap_or_else(|err| {
panic!("the runtime refused video analyzer `{}`: {err}", descriptor(target).id)
});
Harness {
runtime,
recorder,
budget: Arc::new(BudgetTracker::new(budget)),
ledger: Arc::new(InMemorySpendLedger::default()),
governance: GovernanceControl::new(),
}
}
fn descriptor(target: &VideoAnalyzerTarget) -> BackendDescriptor {
match target {
Target::Local(b) => b.descriptor().clone(),
Target::Remote(b) => b.descriptor().clone(),
}
}
async fn analyze(
harness: &Harness,
cx: &VisionCx,
fixture: &VideoFixture,
request: &VideoRequest,
) -> Result<VisionOutput<VideoAnalysis>> {
harness.runtime.analyze_video(cx, fixture.source(), request).await
}
pub async fn video_usage(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let descriptor = descriptor(&target);
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
let out = analyze(&harness, &cx, fixture, &fixture.request)
.await
.unwrap_or_else(|err| panic!("`{}` failed on the fixture: {err}", descriptor.id));
assert_eq!(out.calls.len(), 1, "`{}`: a video call is one call record", descriptor.id);
let frames = out.calls[0].units.get(UsageUnit::Frames);
assert!(frames > 0, "`{}`: the call recorded no frame unit", descriptor.id);
assert_eq!(
harness.budget.units().get(UsageUnit::Frames),
frames,
"`{}`: the run budget did not count the frames the call recorded",
descriptor.id
);
let usage = &out.value.usage;
assert!(usage.frames > 0 && usage.requests > 0, "`{}` reported {usage:?}", descriptor.id);
if descriptor.locality.is_remote() {
if let Some(unit_cost) = descriptor.price.as_ref().and_then(|p| p.request_cost(1)) {
assert!(
usage.cost_micro_usd.is_some_and(|c| c >= unit_cost),
"`{}` is priced per unit but reported cost {:?}",
descriptor.id,
usage.cost_micro_usd
);
}
if usage.cost_micro_usd.is_some_and(|c| c > 0) {
assert!(
harness.budget.usage().cost_micro_usd > 0,
"`{}` reported a cost but spent nothing",
descriptor.id
);
}
} else {
assert_eq!(usage.cost_micro_usd, Some(0), "`{}` is local but has a cost", descriptor.id);
assert_eq!(harness.budget.usage().cost_micro_usd, 0, "a local analyzer spent budget");
}
}
pub async fn video_egress(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let descriptor = descriptor(&target);
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
let out = analyze(&harness, &cx, fixture, &fixture.request)
.await
.unwrap_or_else(|err| panic!("`{}` failed on the fixture: {err}", descriptor.id));
let released = harness.recorder.released();
if descriptor.locality.is_remote() {
assert!(!released.is_empty(), "`{}`: a remote call released nothing", descriptor.id);
assert_eq!(
released.iter().map(|r| r.egress).collect::<Vec<_>>(),
out.calls[0].egress,
"`{}`: every release is in the call record, and only those",
descriptor.id
);
let digests = fixture.digests();
for receipt in &released {
assert!(
digests.contains(&receipt.source),
"`{}`: a release names media the call was not given",
descriptor.id
);
assert_eq!(receipt.backend, descriptor.id, "a release names another backend");
}
} else {
assert!(
harness.recorder.records().is_empty(),
"`{}` is local but the egress recorder holds {:?}",
descriptor.id,
harness.recorder.records()
);
assert!(out.calls[0].egress.is_empty(), "a local call recorded egress");
}
}
pub async fn video_normalisation(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let descriptor = descriptor(&target);
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
let out = analyze(&harness, &cx, fixture, &fixture.request)
.await
.unwrap_or_else(|err| panic!("`{}` failed on the fixture: {err}", descriptor.id));
let analysis = &out.value;
let (from, to) = fixture.span();
for event in &analysis.events {
assert!(
event.start_ms <= event.end_ms && event.start_ms >= from && event.end_ms <= to,
"`{}`: event {event:?} is not inside the video's {from}–{to} ms",
descriptor.id
);
}
assert!(
analysis.events.windows(2).all(|w| w[0].start_ms <= w[1].start_ms),
"`{}`: events are not in time order",
descriptor.id
);
if matches!(fixture.request, VideoRequest::Ask { .. }) {
assert!(analysis.answer.is_some(), "`{}` answered no `Ask`", descriptor.id);
}
if let Some((start, tolerance)) = fixture.expected_event {
let first = analysis.events.first().unwrap_or_else(|| {
panic!("`{}` named no event; expected one at {start} ms", descriptor.id)
});
assert!(
first.start_ms.abs_diff(start) <= tolerance,
"`{}`: the first event starts at {} ms, not within {tolerance} ms of {start} ms",
descriptor.id,
first.start_ms
);
}
assert!(
analysis.frames.windows(2).all(|w| w[0].index < w[1].index),
"`{}`: track frames are not in frame order",
descriptor.id
);
for frame in &analysis.frames {
let (digest, (w, h)) = match &fixture.clip {
Some(clip) => (clip.digest(), clip.size()),
None => {
let (_, image) = fixture
.frames
.iter()
.find(|(meta, _)| meta.index == frame.index)
.unwrap_or_else(|| panic!("regions name frame {}, never sent", frame.index));
(image.digest(), image.size())
}
};
if let Some(pts) = frame.pts_ms {
assert!(
pts <= to,
"`{}`: frame {} is at {pts} ms, after the video",
descriptor.id,
frame.index
);
}
RegionSet::new(digest, w, h, frame.regions.clone()).validate().unwrap_or_else(|err| {
panic!("`{}`: frame {} has a region outside it: {err}", descriptor.id, frame.index)
});
for region in &frame.regions {
assert_eq!(region.origin.backend, descriptor.id, "a region names another backend");
assert!(region.track.is_some(), "`{}`: a track region has no track", descriptor.id);
}
}
}
pub async fn video_caption(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let Some(chunk_ms) = fixture.caption_chunk_ms else { return };
let descriptor = descriptor(&target);
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
let request = VideoRequest::Caption { chunk_ms };
let out = analyze(&harness, &cx, fixture, &request)
.await
.unwrap_or_else(|err| panic!("`{}` did not caption the fixture: {err}", descriptor.id));
let events = &out.value.events;
let (from, to) = fixture.span();
assert!(!events.is_empty(), "`{}` captioned no chunk", descriptor.id);
for event in events {
let chunk = (event.start_ms.saturating_sub(from)) / chunk_ms;
let (lo, hi) = (from + chunk * chunk_ms, from + (chunk + 1) * chunk_ms);
assert!(
event.start_ms >= lo && event.end_ms <= hi.min(to) && event.start_ms <= event.end_ms,
"`{}`: caption {event:?} is not inside its chunk {lo}–{hi} ms of the video's \
{from}–{to} ms",
descriptor.id
);
assert!(!event.text.trim().is_empty(), "`{}`: a chunk has no caption", descriptor.id);
}
assert!(
events.windows(2).all(|w| w[0].end_ms <= w[1].start_ms),
"`{}`: captions overlap or are out of order",
descriptor.id
);
if fixture.clip.is_none() {
let mut chunks: Vec<u64> =
fixture.frames.iter().map(|(f, _)| f.pts_ms.saturating_sub(from) / chunk_ms).collect();
chunks.dedup();
assert_eq!(
events.len(),
chunks.len(),
"`{}`: one caption for each chunk that holds a frame",
descriptor.id
);
}
assert!(out.value.usage.requests > 0, "`{}` reported no request", descriptor.id);
}
pub async fn video_refuses_unsupported(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let descriptor = descriptor(&target);
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
let err = analyze(&harness, &cx, fixture, &fixture.refused).await.err().unwrap_or_else(|| {
panic!("`{}` answered {:?}, which it should refuse", descriptor.id, fixture.refused)
});
assert!(matches!(err, VisionError::Unsupported(_)), "`{}` refused with {err}", descriptor.id);
assert_eq!(
harness.budget.units().get(UsageUnit::Frames),
0,
"`{}`: a refused call kept its frames",
descriptor.id
);
}
pub async fn video_cancellation(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
cx.cancellation().cancel();
let err = analyze(&harness, &cx, fixture, &fixture.request).await.err();
assert!(
matches!(err, Some(VisionError::Cancelled)),
"`{}`: a cancelled call returned {err:?}",
descriptor(&target).id
);
assert!(harness.recorder.released().is_empty(), "a cancelled call released media");
}
pub async fn video_kill_switch(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let harness = harness(&target, true, RunBudget::new());
let cx = harness.cx();
harness.governance.freeze("conformance: kill switch");
let err = analyze(&harness, &cx, fixture, &fixture.request)
.await
.err()
.unwrap_or_else(|| panic!("`{}` ran while frozen", descriptor(&target).id));
let adk: AdkError = err.into();
assert_eq!(adk.code, GOVERNANCE_FROZEN_CODE, "a frozen call failed with {adk}");
assert!(harness.recorder.released().is_empty(), "media was released while frozen");
}
pub async fn video_frame_cap(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
let descriptor = descriptor(&target);
let harness = harness(&target, true, RunBudget::new().max_units(UsageUnit::Frames, 1));
let cx = harness.cx();
let err = analyze(&harness, &cx, fixture, &fixture.request)
.await
.err()
.unwrap_or_else(|| panic!("`{}` ran past a one-frame cap", descriptor.id));
let adk: AdkError = err.into();
assert!(adk.message.contains("frames"), "the cap refusal does not name the unit: {adk}");
assert!(harness.recorder.released().is_empty(), "media was released past the cap");
assert_eq!(harness.budget.units().get(UsageUnit::Frames), 0, "a refused call kept frames");
}
pub async fn video_unreleased(target: VideoAnalyzerTarget, fixture: &VideoFixture) {
if matches!(target, Target::Local(_)) {
return;
}
let harness = harness(&target, false, RunBudget::new());
let cx = harness.cx();
let err = analyze(&harness, &cx, fixture, &fixture.request).await.err().unwrap_or_else(|| {
panic!("remote `{}` ran without an egress gate", descriptor(&target).id)
});
assert!(matches!(err, VisionError::NotReleased { .. }), "expected NotReleased, got {err}");
assert_eq!(AdkError::from(err).category, ErrorCategory::Forbidden);
}