use image_hasher::ImageHash;
pub(crate) type Hash = ImageHash<Box<[u8]>>;
#[derive(Clone, Debug)]
pub(crate) struct Sampled<P> {
pub ts_ms: u64,
pub hash: Hash,
pub payload: P,
}
pub(crate) struct Dedupe {
threshold: u32,
last_kept: Option<Hash>,
}
impl Dedupe {
pub(crate) fn new(threshold: u32) -> Self {
Self {
threshold,
last_kept: None,
}
}
pub(crate) fn consider(&mut self, hash: &Hash) -> bool {
let is_new = match &self.last_kept {
None => true,
Some(last) => last.dist(hash) >= self.threshold,
};
if is_new {
self.last_kept = Some(hash.clone());
}
is_new
}
}
pub(crate) fn hold_durations<P>(kept: &[Sampled<P>], duration_ms: Option<u64>) -> Vec<u64> {
kept.iter()
.enumerate()
.map(|(index, frame)| match kept.get(index + 1) {
Some(next) => next.ts_ms.saturating_sub(frame.ts_ms),
None => duration_ms.map_or(0, |duration| duration.saturating_sub(frame.ts_ms)),
})
.collect()
}
pub(crate) fn distances_from_previous<P>(kept: &[Sampled<P>]) -> Vec<u32> {
kept.iter()
.enumerate()
.map(|(index, frame)| match index {
0 => 0,
_ => kept[index - 1].hash.dist(&frame.hash),
})
.collect()
}
pub(crate) fn merge_flicker<P>(
mut kept: Vec<Sampled<P>>,
threshold: u32,
min_hold_ms: u64,
duration_ms: Option<u64>,
) -> (Vec<Sampled<P>>, usize) {
let mut dropped = 0usize;
loop {
if kept.len() < 3 {
break;
}
let holds = hold_durations(&kept, duration_ms);
let flicker_index = (1..kept.len() - 1).find(|&index| {
holds[index] < min_hold_ms
&& kept[index - 1].hash.dist(&kept[index + 1].hash) < threshold
});
match flicker_index {
Some(index) => {
kept.remove(index);
dropped += 1;
}
None => break,
}
}
(kept, dropped)
}
pub(crate) fn thin<P>(mut kept: Vec<Sampled<P>>, max_frames: usize) -> (Vec<Sampled<P>>, usize) {
let mut dropped = 0usize;
while kept.len() > max_frames && kept.len() > 2 {
let distances = distances_from_previous(&kept);
let smallest = (1..kept.len() - 1).min_by_key(|&index| distances[index]);
match smallest {
Some(index) => {
kept.remove(index);
dropped += 1;
}
None => break,
}
}
(kept, dropped)
}
pub(crate) fn thin_incremental<P>(kept: Vec<Sampled<P>>, cap: usize) -> (Vec<Sampled<P>>, usize) {
if kept.len() > cap {
thin(kept, cap)
} else {
(kept, 0)
}
}
#[cfg(test)]
mod tests;