use std::sync::Arc;
use std::io::{Read, Seek};
use super::{AreaIndex, Checkpoint, Plan, digest};
use crate::audio::{AreaCursor, AreaKey, MAX_MALFORMED_WARNINGS};
use crate::control::UnreadableSectors;
use crate::error::Error;
use crate::image::Image;
use crate::image::SECTOR_SIZE;
use crate::seek::ResumedFrom;
pub(crate) const MAX_DAMAGE_RUNS: usize = 4096;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DamageCheckpoint {
pub(crate) lsn: u64,
pub(crate) runs: u32,
pub(crate) checkpoint: Checkpoint,
pub(crate) lost_from: Option<u32>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Damage {
pub(crate) runs: Vec<(u64, u64)>,
pub(crate) checkpoints: Vec<DamageCheckpoint>,
pub(crate) malformed: Vec<u32>,
}
impl Damage {
pub(crate) fn is_empty(&self) -> bool {
self.checkpoints.is_empty()
}
pub(crate) fn memory(&self) -> usize {
self.runs.capacity() * std::mem::size_of::<(u64, u64)>()
+ self.checkpoints.capacity() * std::mem::size_of::<DamageCheckpoint>()
+ self.malformed.capacity() * std::mem::size_of::<u32>()
}
pub(crate) fn candidates(self: &Arc<Self>, first: u32) -> Option<DamageCandidates> {
let last =
self.checkpoints.partition_point(|c| c.checkpoint.next_acceptable <= first).checked_sub(1)?;
Some(DamageCandidates { damage: Arc::clone(self), last, read_to: 0 })
}
fn join(
&mut self,
runs: &[(u64, u64)],
checkpoints: &[DamageCheckpoint],
malformed: impl Iterator<Item = u32>,
replace: bool,
) {
let Some((kept, from)) = self.joins(runs, checkpoints, replace) else { return };
let last = checkpoints.last().map_or(0, |c| c.lsn);
self.checkpoints.truncate(kept);
self.checkpoints.extend_from_slice(&checkpoints[from..]);
self.runs.clear();
self.runs.extend_from_slice(runs);
self.malformed.clear();
self.malformed.extend(malformed.take_while(|&m| u64::from(m) < last).take(MAX_MALFORMED_WARNINGS));
}
fn joins(
&self,
runs: &[(u64, u64)],
checkpoints: &[DamageCheckpoint],
replace: bool,
) -> Option<(usize, usize)> {
let last = checkpoints.last()?.lsn;
let held = self.checkpoints.last().map_or(0, |c| c.lsn);
let upto = held.min(last) + 1;
let agree = !self.is_empty() && below(&self.runs, upto).eq(below(runs, upto));
let changes = if agree { last > held } else { replace || self.is_empty() };
if !changes {
return None;
}
let kept = if agree {
self.checkpoints.len()
} else {
let differ = first_difference(
&below(&self.runs, upto).collect::<Vec<_>>(),
&below(runs, upto).collect::<Vec<_>>(),
upto,
);
self.checkpoints.partition_point(|c| c.lsn < differ)
};
let prev = kept.checked_sub(1).map(|k| self.checkpoints[k]);
let from = checkpoints.partition_point(|c| c.lsn <= prev.map_or(0, |p| p.lsn));
let continues = |p: DamageCheckpoint, c: &DamageCheckpoint| {
c.checkpoint.next_acceptable >= p.checkpoint.next_acceptable
&& c.checkpoint.malformed_before >= p.checkpoint.malformed_before
};
if prev.zip(checkpoints.get(from)).is_some_and(|(p, c)| !continues(p, c)) {
return None;
}
Some((kept, from))
}
}
fn below(runs: &[(u64, u64)], upto: u64) -> impl Iterator<Item = (u64, u64)> + '_ {
runs.iter().take_while(move |&&(s, _)| s < upto).map(move |&(s, e)| (s, e.min(upto)))
}
fn first_difference(a: &[(u64, u64)], b: &[(u64, u64)], to: u64) -> u64 {
let mut i = 0;
loop {
let at = match (a.get(i), b.get(i)) {
(None, None) => to,
(Some(&x), Some(&y)) if x == y => {
i += 1;
continue;
}
(Some(&(s, e)), Some(&(t, f))) => {
if s == t {
e.min(f)
} else {
s.min(t)
}
}
(Some(&(s, _)), None) | (None, Some(&(s, _))) => s,
};
return at.min(to);
}
}
#[derive(Clone, Debug)]
pub(crate) struct DamageCandidates {
damage: Arc<Damage>,
last: usize,
pub(crate) read_to: u64,
}
impl DamageCandidates {
pub(crate) fn last(&self) -> &DamageCheckpoint {
&self.damage.checkpoints[self.last]
}
pub(crate) fn choose(&self, marked: impl FnOnce(u64) -> Vec<(u64, u64)>) -> Option<DamageStart> {
let d = &self.damage;
let to = self.last().lsn + 1;
let differ = first_difference(&marked(to), &below(&d.runs, to).collect::<Vec<_>>(), to);
let j = d.checkpoints[..=self.last].partition_point(|c| c.lsn < differ).checked_sub(1)?;
let at = d.checkpoints[j];
Some(DamageStart {
at,
runs: d.runs.get(..at.runs as usize)?.to_vec(),
malformed: d.malformed.iter().copied().take_while(|&m| u64::from(m) < at.lsn).collect(),
read_to: if j == self.last { self.read_to } else { 0 },
})
}
}
#[derive(Clone, Debug)]
pub(crate) struct DamageStart {
pub(crate) at: DamageCheckpoint,
pub(crate) runs: Vec<(u64, u64)>,
pub(crate) malformed: Vec<u32>,
pub(crate) read_to: u64,
}
#[derive(Clone, Debug)]
pub(crate) struct DamageRecorder {
key: AreaKey,
start: u64,
interval: u32,
pub(crate) kept: bool,
active: bool,
full: bool,
runs: Vec<(u64, u64)>,
next: u64,
pub(crate) checkpoints: Vec<DamageCheckpoint>,
}
impl DamageRecorder {
pub(crate) fn is_full(&self) -> bool {
self.full
}
pub(crate) fn has_news(&self) -> bool {
!self.checkpoints.is_empty()
}
fn boundary_after(&self, lsn: u64) -> u64 {
let k = u64::from(self.interval);
self.start + ((lsn.saturating_sub(self.start)) / k + 1) * k
}
pub(crate) fn restart(&mut self) {
(self.active, self.full, self.next) = (false, false, u64::MAX);
self.runs.clear();
self.checkpoints.clear();
}
pub(crate) fn resume(&mut self, from: &DamageStart) {
self.restart();
self.active = true;
self.runs.clone_from(&from.runs);
self.next = self.boundary_after(from.at.lsn);
}
pub(crate) fn unreadable(&mut self, lsn: u64) {
if self.full {
return;
}
let full = self.runs.len() == MAX_DAMAGE_RUNS;
match self.runs.last_mut() {
Some(run) if run.1 == lsn => run.1 += 1,
_ if full => {
(self.active, self.full, self.next) = (false, true, u64::MAX);
return;
}
_ => self.runs.push((lsn, lsn + 1)),
}
self.active = true;
self.next = self.boundary_after(lsn);
}
#[inline]
pub(crate) fn due(&self, lsn: u64) -> bool {
lsn == self.next
}
pub(crate) fn record(
&mut self,
lsn: u64,
(next_acceptable, back, malformed_before): (u32, u32, u64),
lost_from: Option<u32>,
sector: &[u8; SECTOR_SIZE],
) {
let runs = self.runs.len() as u32;
let checkpoint = Checkpoint { next_acceptable, back, malformed_before, digest: digest(sector) };
self.checkpoints.push(DamageCheckpoint { lsn, runs, checkpoint, lost_from });
self.next = self.boundary_after(lsn);
}
}
impl AreaIndex {
pub(crate) fn damage_recorder(&self) -> Box<DamageRecorder> {
Box::new(DamageRecorder {
key: self.key,
start: self.start,
interval: self.interval,
kept: false,
active: false,
full: false,
runs: Vec::new(),
next: u64::MAX,
checkpoints: Vec::new(),
})
}
pub fn without_damage(&self) -> AreaIndex {
AreaIndex { damage: Arc::default(), ..self.clone() }
}
pub(crate) fn damage_start(&self, first: u32) -> Option<DamageCandidates> {
self.damage.candidates(first)
}
pub fn extend_past_marks<R: Read + Seek>(
&mut self,
image: &mut Image<R>,
max_sectors: u64,
) -> Result<bool, Error> {
if image.sector_count() != self.key.image_sectors {
return Err(Error::InvalidArgument("seek index of another image size"));
}
if self.image_id.is_some_and(|id| id != image.id()) {
return Err(Error::InvalidArgument("seek index of another image"));
}
self.image_id = Some(image.id());
let Some((mark, from)) = self.past_marks_from(image.unreadable()) else { return Ok(true) };
let Some(need) = self.next_unmarked_boundary(from, image.unreadable()) else { return Ok(true) };
let mut cursor = AreaCursor::past_marks(self, mark);
let stop = from.saturating_add(max_sectors).max(need.saturating_add(1));
let scanned = cursor.scan_to(image, stop);
if let ResumedFrom::Discarded { .. } = cursor.resumed_from() {
return Err(Error::InvalidArgument("seek index does not match the image"));
}
self.take_from(&cursor)?;
scanned?;
if cursor.damage_recorder().is_some_and(DamageRecorder::is_full) {
return Ok(true);
}
Ok(self
.past_marks_from(image.unreadable())
.is_none_or(|(_, from)| self.next_unmarked_boundary(from, image.unreadable()).is_none()))
}
fn past_marks_from(&self, marks: &UnreadableSectors) -> Option<(u64, u64)> {
let (start, end) = self.key.audio_sector_range();
let mark = marks.first_in(start, end)?;
let from = self.damage_start(u32::MAX).and_then(|d| d.choose(|to| marks.runs_in(start, to)));
Some((mark, from.map_or(mark, |d| d.at.lsn)))
}
fn next_unmarked_boundary(&self, lsn: u64, marks: &UnreadableSectors) -> Option<u64> {
let k = u64::from(self.interval);
let mut b = self.start + (lsn.saturating_sub(self.start) / k + 1) * k;
while b < self.end {
if !marks.contains(b) {
return Some(b);
}
let run_end = marks.first_unmarked(b, self.end);
b = self.start + (run_end - self.start).div_ceil(k) * k;
}
None
}
pub(crate) fn start_lsn_with(&self, first: u32, marks: &UnreadableSectors) -> Option<u64> {
let (start, end) = self.key.audio_sector_range();
let upto = match self.plan(first) {
Plan::Start => None,
Plan::End(_) => Some(end),
Plan::At { lsn, .. } => Some(lsn.saturating_add(1)),
};
let marked = upto.and_then(|upto| marks.first_in(start, upto));
let from = upto.map_or(start, |u| u - 1);
let damage = self
.damage_start(first)
.and_then(|d| d.choose(|to| marks.runs_in(start, to)))
.filter(|d| marked.is_some() || d.at.lsn > from);
match (damage, marked) {
(Some(d), _) => Some(d.at.lsn),
(None, Some(_)) => Some(start),
(None, None) => self.plan_lsn(first),
}
}
pub(crate) fn take_damage(&mut self, r: &DamageRecorder, warnings: impl Iterator<Item = u32>) {
if r.key != self.key
|| r.interval != self.interval
|| r.start != self.start
|| r.checkpoints.is_empty()
{
return;
}
if self.damage.joins(&r.runs, &r.checkpoints, true).is_some() {
Arc::make_mut(&mut self.damage).join(&r.runs, &r.checkpoints, warnings, true);
}
}
pub(crate) fn join_damage(&mut self, other: &AreaIndex, replace: bool) {
if Arc::ptr_eq(&self.damage, &other.damage) || other.damage.is_empty() {
return;
}
let o = &other.damage;
if self.damage.joins(&o.runs, &o.checkpoints, replace).is_some() {
Arc::make_mut(&mut self.damage).join(
&o.runs,
&o.checkpoints,
o.malformed.iter().copied(),
replace,
);
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::{Checkpoint, Damage, DamageCheckpoint, first_difference};
fn record() -> Arc<Damage> {
let at = |lsn: u64| DamageCheckpoint {
lsn,
runs: 1,
checkpoint: Checkpoint { next_acceptable: lsn as u32, back: 0, malformed_before: 0, digest: 0 },
lost_from: None,
};
Arc::new(Damage {
runs: vec![(10, 12)],
checkpoints: vec![at(14), at(16), at(18)],
malformed: Vec::new(),
})
}
fn chosen(first: u32, marks: &[(u64, u64)]) -> Option<u64> {
let clip = |to: u64| -> Vec<(u64, u64)> {
marks.iter().filter(|r| r.0 < to).map(|&(s, e)| (s, e.min(to))).collect()
};
record().candidates(first)?.choose(clip).map(|d| d.at.lsn)
}
#[test]
fn fit_boundaries() {
let run = (10, 12);
assert_eq!(chosen(u32::MAX, &[run]), Some(18));
assert_eq!(chosen(u32::MAX, &[run, (18, 19)]), Some(16));
assert_eq!(chosen(u32::MAX, &[run, (16, 17)]), Some(14));
assert_eq!(chosen(u32::MAX, &[run, (14, 15)]), None);
assert_eq!(chosen(u32::MAX, &[run, (17, 18)]), Some(16));
assert_eq!(chosen(u32::MAX, &[run, (15, 16)]), Some(14));
assert_eq!(chosen(u32::MAX, &[run, (19, 20)]), Some(18));
for marks in [&[(10, 13)][..], &[(9, 12)], &[(10, 11)], &[(11, 12)], &[]] {
assert_eq!(chosen(u32::MAX, marks), None, "{marks:?}");
}
assert_eq!(chosen(16, &[run]), Some(16));
assert_eq!(chosen(17, &[run, (17, 18)]), Some(16));
assert_eq!(chosen(13, &[run]), None);
}
#[test]
fn first_differences() {
let to = 100;
assert_eq!(first_difference(&[], &[], to), to);
assert_eq!(first_difference(&[(5, 7)], &[(5, 7)], to), to);
assert_eq!(first_difference(&[(5, 7)], &[], to), 5);
assert_eq!(first_difference(&[(5, 7), (9, 10)], &[(5, 7)], to), 9);
assert_eq!(first_difference(&[(5, 7)], &[(6, 7)], to), 5);
assert_eq!(first_difference(&[(5, 7)], &[(5, 9)], to), 7);
assert_eq!(first_difference(&[(1, 2), (5, 7)], &[(1, 2), (4, 7)], to), 4);
}
}