use vk_video_ffi::DPB_SLOTS; const ANCHORS: usize = DPB_SLOTS - 2; const ANCHOR_EVERY: u64 = 16; const MAX_AGE: u64 = 120; #[derive(Debug, Clone, Copy)] pub(crate) struct Held { id: u64, acked: bool, pub(crate) data: T, } /// Where the next picture goes and what it references. #[derive(Debug, Clone, Copy)] pub(crate) struct Step { pub(crate) id: u64, pub(crate) key: bool, pub(crate) recovery: bool, pub(crate) slot: u32, pub(crate) reference: Option<(u32, T)>, } /// DPB slot bookkeeping: the first slots keep the keyframe and every sixteenth /// picture as anchors a recovery picture can reference once the receiver /// acknowledged them, the last two chain each picture to the previous one. pub(crate) struct History { next_id: u64, pub(crate) slots: [Option>; DPB_SLOTS], last: Option<(usize, T)>, next_anchor: usize, armed: bool, } impl History { pub(crate) fn new() -> Self { History { next_id: 0, slots: [None; DPB_SLOTS], last: None, next_anchor: 0, armed: false, } } pub(crate) fn arm(&mut self) { self.armed = true; } pub(crate) fn ack(&mut self, id: u64) { for held in self.slots.iter_mut().flatten() { if held.id <= id { held.acked = true; } } } pub(crate) fn next(&mut self, want_key: bool) -> Step { let id = self.next_id; self.next_id += 1; let armed = std::mem::take(&mut self.armed); let acked = if armed && !want_key { self.newest_acked(id) } else { None }; let key = want_key || self.last.is_none() || (armed && acked.is_none()); let reference = match (key, acked) { (true, _) => None, (false, Some(r)) => Some(r), (false, None) => self.last, }; let reference_slot = reference.map(|(slot, _)| slot); if key { self.slots = [None; DPB_SLOTS]; self.next_anchor = 0; } if let Some((slot, _)) = acked { let base = self.slots[slot].map_or(0, |h| h.id); for held in &mut self.slots { if held.is_some_and(|h| h.id > base) { *held = None; } } } let slot = if key || id % ANCHOR_EVERY == 0 { self.anchor_slot(reference_slot) } else { self.chain_slot(reference_slot) }; Step { id, key, recovery: !key && acked.is_some(), slot: slot as u32, reference: reference.map(|(slot, data)| (slot as u32, data)), } } pub(crate) fn store(&mut self, step: &Step, data: T) { let slot = step.slot as usize; self.slots[slot] = Some(Held { id: step.id, acked: false, data, }); self.last = Some((slot, data)); } fn newest_acked(&self, id: u64) -> Option<(usize, T)> { (0..DPB_SLOTS) .filter_map(|i| self.slots[i].map(|h| (i, h))) .filter(|(_, h)| h.acked && id - h.id < MAX_AGE) .max_by_key(|(_, h)| h.id) .map(|(i, h)| (i, h.data)) } fn anchor_slot(&mut self, reference: Option) -> usize { loop { let slot = self.next_anchor; self.next_anchor = (self.next_anchor + 1) % ANCHORS; if Some(slot) != reference { return slot; } } } fn chain_slot(&self, reference: Option) -> usize { (ANCHORS..DPB_SLOTS) .filter(|&i| Some(i) != reference) .min_by_key(|&i| self.slots[i].map_or(0, |h| h.id + 1)) .unwrap_or(ANCHORS) } }