use std::collections::BTreeSet;
use std::time::Duration;
use futures::StreamExt;
use super::FrameSource;
use crate::error::VisionError;
use crate::media::FramePixels;
use crate::traits::Sampling;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FrameSourceReport {
pub frames: usize,
pub min_gap: Option<Duration>,
pub sizes: BTreeSet<(u32, u32)>,
}
pub async fn check_frame_source(
source: &dyn FrameSource,
sampling: Sampling,
count: usize,
) -> FrameSourceReport {
let id = source.id().clone();
match source.frames(Sampling { fps: 0.0, max_long_edge: sampling.max_long_edge }).await {
Err(VisionError::InvalidInput(_)) => {}
Err(other) => {
panic!("`{}`: a zero sampling rate must be refused as invalid input, got {other}", id.0)
}
Ok(_) => panic!("`{}`: a zero sampling rate must be refused", id.0),
}
let interval = Duration::from_secs_f64(1.0 / f64::from(sampling.fps));
let stream = source
.frames(sampling)
.await
.unwrap_or_else(|err| panic!("`{}` did not open: {err}", id.0));
let frames: Vec<_> =
tokio::time::timeout(Duration::from_secs(60), stream.take(count).collect())
.await
.unwrap_or_else(|_| {
panic!("`{}` did not deliver {count} frames within a minute", id.0)
});
assert_eq!(frames.len(), count, "`{}` ended after {} of {count} frames", id.0, frames.len());
let mut report = FrameSourceReport { frames: count, ..FrameSourceReport::default() };
let mut previous: Option<(u64, Duration)> = None;
for frame in frames {
let frame = frame.unwrap_or_else(|err| panic!("`{}` yielded an error: {err}", id.0));
assert_eq!(frame.source, id, "a frame of `{}` names `{}`", id.0, frame.source.0);
let size = match &frame.pixels {
FramePixels::Ephemeral(pixels) => pixels.size(),
FramePixels::Stored(image) => {
panic!("`{}` stored frame {} as {}", id.0, frame.index, image.digest)
}
};
if let Some(max) = sampling.max_long_edge {
assert!(
size.0.max(size.1) <= max,
"`{}` frame {} is {size:?}, over {max} px",
id.0,
frame.index
);
}
report.sizes.insert(size);
if let Some((index, pts)) = previous {
assert!(
frame.index > index,
"`{}` frame indices went from {index} to {}",
id.0,
frame.index
);
assert!(
frame.pts > pts,
"`{}` presentation times went from {pts:?} to {:?}",
id.0,
frame.pts
);
let gap = frame.pts - pts;
assert!(
gap + interval / 8 >= interval,
"`{}` frames {:?} apart at {} fps",
id.0,
gap,
sampling.fps
);
report.min_gap = Some(report.min_gap.map_or(gap, |min| min.min(gap)));
}
previous = Some((frame.index, frame.pts));
}
report
}