mod persist;
use std::io::{Read, Seek};
use crate::audio::{
AreaCursor, AreaKey, FrameKind, MAX_FRAME_BYTES, MAX_MALFORMED_WARNINGS, audio_sector_range,
};
use crate::error::Error;
use crate::image::{Image, SECTOR_SIZE};
use crate::log::sb_log;
use crate::toc::Area;
pub const DEFAULT_INTERVAL: u32 = 64;
pub const MAX_INTERVAL: u32 = 65_536;
pub const DEFAULT_INLINE_BUDGET: usize = 1 << 20;
pub const REPLAY_SECTORS: u64 = 32;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct IndexOptions {
pub interval: u32,
pub inline_budget: usize,
pub hint_spacing: u32,
pub max_hints: usize,
}
impl Default for IndexOptions {
fn default() -> Self {
IndexOptions {
interval: DEFAULT_INTERVAL,
inline_budget: DEFAULT_INLINE_BUDGET,
hint_spacing: DEFAULT_HINT_SPACING,
max_hints: DEFAULT_MAX_HINTS,
}
}
}
impl IndexOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_interval(self, interval: u32) -> Self {
IndexOptions { interval, ..self }
}
pub fn with_inline_budget(self, bytes: usize) -> Self {
IndexOptions { inline_budget: bytes, ..self }
}
pub fn with_hints(self, spacing: u32, max: usize) -> Self {
IndexOptions { hint_spacing: spacing, max_hints: max, ..self }
}
}
pub const DEFAULT_HINT_SPACING: u32 = 8;
pub const DEFAULT_MAX_HINTS: usize = 2048;
pub const MAX_HINTS: usize = 65_536;
pub const HINT_REACH: u32 = 64;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResumedFrom {
Start,
Checkpoint {
lsn: u64,
replay_from: u64,
},
End,
Discarded {
lsn: u64,
},
Speculative {
lsn: u64,
probes: u32,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeekPolicy {
#[default]
Exact,
Speculative(SpeculativeOptions),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SpeculativeOptions {
pub min_gap_sectors: u64,
pub probe_sectors: u32,
pub max_probes: u32,
pub exact_when_suspect: bool,
pub(crate) layout_suspect: bool,
}
impl Default for SpeculativeOptions {
fn default() -> Self {
SpeculativeOptions {
min_gap_sectors: 2048,
probe_sectors: 8,
max_probes: 48,
exact_when_suspect: false,
layout_suspect: false,
}
}
}
impl SpeculativeOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_min_gap_sectors(self, sectors: u64) -> Self {
SpeculativeOptions { min_gap_sectors: sectors, ..self }
}
pub fn with_probe_sectors(self, sectors: u32) -> Self {
SpeculativeOptions { probe_sectors: sectors, ..self }
}
pub fn with_max_probes(self, probes: u32) -> Self {
SpeculativeOptions { max_probes: probes, ..self }
}
pub fn with_exact_when_suspect(self, exact: bool) -> Self {
SpeculativeOptions { exact_when_suspect: exact, ..self }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Speculation {
Exact,
Pending {
lsn: u64,
first: u32,
},
Confirmed {
lsn: u64,
first: u32,
},
Refuted {
lsn: u64,
first: u32,
last_returned: Option<u32>,
exact_from: u32,
},
Unverified {
lsn: u64,
first: u32,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Suspect {
AreaLayout,
FrameNumbersDecrease,
}
pub const MAX_CLAIMS: usize = 256;
pub const MAX_EVENTS: usize = 4 * MAX_CLAIMS;
pub(crate) fn queue_events(queue: &mut Vec<SeekEvent>, events: impl IntoIterator<Item = SeekEvent>) {
queue.extend(events);
if queue.len() > MAX_EVENTS {
queue.drain(..queue.len() - MAX_EVENTS);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SeekEvent {
pub slot: crate::Slot,
pub claim: u64,
pub speculation: Speculation,
}
static NEXT_CLAIM: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Verdict {
Confirmed,
Refuted { exact_from: u32 },
Unverified,
}
#[derive(Debug)]
pub(crate) struct Claim {
pub(crate) id: u64,
slot: crate::Slot,
first: u32,
lsn: std::sync::atomic::AtomicU64,
returned: std::sync::atomic::AtomicU32,
verdict: std::sync::Mutex<Option<Verdict>>,
image: std::sync::atomic::AtomicU64,
}
impl Claim {
pub(crate) fn new(slot: crate::Slot, first: u32) -> std::sync::Arc<Self> {
std::sync::Arc::new(Claim {
id: NEXT_CLAIM.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
slot,
first,
lsn: std::sync::atomic::AtomicU64::new(0),
returned: std::sync::atomic::AtomicU32::new(0),
verdict: std::sync::Mutex::new(None),
image: std::sync::atomic::AtomicU64::new(0),
})
}
pub(crate) fn set_image(&self, id: u64) {
self.image.store(id, std::sync::atomic::Ordering::Relaxed);
}
fn image(&self) -> Option<u64> {
Some(self.image.load(std::sync::atomic::Ordering::Relaxed)).filter(|&id| id != 0)
}
pub(crate) fn set_lsn(&self, lsn: u64) {
self.lsn.store(lsn, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn lsn(&self) -> u64 {
self.lsn.load(std::sync::atomic::Ordering::Relaxed)
}
#[inline]
pub(crate) fn returned(&self, t: u32) {
self.returned.fetch_max(t.saturating_add(1), std::sync::atomic::Ordering::Relaxed);
}
fn verdict(&self) -> Option<Verdict> {
*self.verdict.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn confirm_saved(&self) {
self.settle(Verdict::Confirmed);
}
fn settle(&self, verdict: Verdict) -> bool {
let mut v = self.verdict.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if v.is_some() {
return false;
}
*v = Some(verdict);
true
}
pub(crate) fn speculation(&self) -> Speculation {
let (lsn, first) = (self.lsn(), self.first);
match self.verdict() {
None => Speculation::Pending { lsn, first },
Some(Verdict::Confirmed) => Speculation::Confirmed { lsn, first },
Some(Verdict::Refuted { exact_from }) => {
let r = self.returned.load(std::sync::atomic::Ordering::Relaxed);
Speculation::Refuted { lsn, first, last_returned: r.checked_sub(1), exact_from }
}
Some(Verdict::Unverified) => Speculation::Unverified { lsn, first },
}
}
fn event(&self) -> SeekEvent {
SeekEvent { slot: self.slot, claim: self.id, speculation: self.speculation() }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Provisional {
pub(crate) back: u32,
pub(crate) digest: u64,
pub(crate) seen: u32,
pub(crate) under: Option<u32>,
}
#[derive(Debug)]
pub(crate) struct ProvisionalRecorder {
interval: u64,
next: u64,
pub(crate) list: Vec<(u64, Provisional)>,
}
impl ProvisionalRecorder {
pub(crate) fn new(start: u64, from: u64, interval: u32) -> Box<Self> {
let k = u64::from(interval.max(1));
let next = start + (from - start) / k * k + k;
Box::new(ProvisionalRecorder { interval: k, next, list: Vec::new() })
}
#[inline]
pub(crate) fn due(&self, lsn: u64) -> bool {
lsn == self.next
}
pub(crate) fn record(
&mut self,
lsn: u64,
under: Option<(u64, u32)>,
seen: u32,
sector: &[u8; SECTOR_SIZE],
) {
self.next += self.interval;
let back = under.map_or(0, |(b, _)| b);
if seen > 0 && back <= REPLAY_SECTORS {
let back = back as u32;
let under = under.map(|(_, n)| n);
self.list.push((lsn, Provisional { back, digest: digest(sector), seen, under }));
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct HintRecorder {
spacing: u32,
last: Option<u32>,
pub(crate) list: Vec<(u32, u32)>,
tail: Option<(u32, u32)>,
flushed: bool,
}
const HINTS_PER_TAKE: usize = 64;
impl HintRecorder {
#[inline]
pub(crate) fn see(&mut self, lsn: u64, sector: &[u8; SECTOR_SIZE]) {
let Some(t) = first_record(sector) else { return };
let Ok(lsn) = u32::try_from(lsn) else { return };
if self.last.is_none_or(|l| t >= l.saturating_add(self.spacing) || t < l)
&& self.list.len() < MAX_HINTS
{
self.list.push((lsn, t));
self.last = Some(t);
self.tail = None;
} else {
self.tail = Some((lsn, t));
}
}
pub(crate) fn flush(&mut self) {
if let Some(tail) = self.tail.take() {
if self.list.len() < MAX_HINTS {
self.list.push(tail);
}
}
self.flushed = true;
}
pub(crate) fn take(&mut self) -> Vec<(u32, u32)> {
self.flushed = false;
std::mem::take(&mut self.list)
}
#[inline]
pub(crate) fn has_news(&self) -> bool {
self.list.len() >= HINTS_PER_TAKE || (self.flushed && !self.list.is_empty())
}
}
pub(crate) type Hint = (u64, u32, u64, Option<u64>);
#[derive(Debug)]
pub(crate) struct Speculate {
pub(crate) first: u32,
pub(crate) end: u32,
pub(crate) playtime: u32,
pub(crate) interval: u32,
pub(crate) options: SpeculativeOptions,
pub(crate) knots: Vec<(u64, u32)>,
pub(crate) exact: Box<AreaCursor>,
pub(crate) from: u64,
pub(crate) hint: Option<Hint>,
}
pub(crate) fn first_record(sector: &[u8]) -> Option<u32> {
let header = *sector.first()?;
let (f, k) = ((header >> 2) & 7, usize::from(header >> 5));
if f == 0 {
return None;
}
let r = 1 + 2 * k;
let tc = sector.get(r..r + 3)?;
Some((u32::from(tc[0]) * 60 + u32::from(tc[1])) * 75 + u32::from(tc[2]))
}
const PROBE_SPAN: u64 = 32;
const ILLINOIS_MARGIN: u64 = 4;
const CLOSE_SECTORS: u64 = 16;
pub(crate) const FIRST_FRAME_BUDGET: u64 = 72;
const SEARCH_CALLS: u32 = 5;
const LAST_READ_BUDGET: u64 = 80;
pub const MAX_READ_SECTORS: u64 = 512;
#[derive(Debug)]
pub(crate) struct Located {
pub(crate) lsn: u64,
pub(crate) reads: u32,
pub(crate) chunk: Option<(u64, Vec<u8>)>,
pub(crate) frame: u32,
pub(crate) density: (u64, u32),
pub(crate) decreasing: bool,
pub(crate) used: u64,
}
fn bracket(lo: (u64, u32), hi: (u64, u32), knots: &[(u64, u32)], first: u32) -> ((u64, u32), (u64, u32)) {
let inside = |&&(l, t): &&(u64, u32)| l > lo.0 && l < hi.0 && t >= lo.1 && t <= hi.1;
let a = knots
.iter()
.filter(inside)
.filter(|k| k.1 <= first)
.max_by_key(|k| (k.1, k.0))
.copied()
.unwrap_or(lo);
let b = knots
.iter()
.filter(inside)
.filter(|k| k.1 > first && k.0 > a.0)
.min_by_key(|k| (k.1, k.0))
.copied()
.unwrap_or(hi);
if b.1 > a.1 { (a, b) } else { (lo, hi) }
}
pub(crate) fn locate<R: Read + Seek>(
image: &mut Image<R>,
(mut lo, mut hi): (u64, u64),
(first, playtime): (u32, u32),
knots: &[(u64, u32)],
options: &SpeculativeOptions,
on_read: &mut dyn FnMut(u64),
) -> Result<Located, Error> {
let per = u64::from(options.probe_sectors.clamp(1, 32));
let n = hi.saturating_sub(lo);
let log = u64::BITS - n.leading_zeros();
let max = options.max_probes.min(2 * log + 4);
let end = hi;
let mut buf = vec![0u8; per.max(LAST_READ_BUDGET) as usize * SECTOR_SIZE];
let (mut lo_t, mut hi_t) = (0u32, playtime.max(first.saturating_add(1)));
let mut hi_probed = false;
let (mut halved_lo, mut halved_hi, mut moved) = (0u32, 0u32, None::<bool>);
let (mut reads, mut halve, mut found_lo, mut slow) = (0u32, false, false, 0u32);
let mut chunk: Option<(u64, Vec<u8>)> = None;
let (mut anchor, mut previous) = (None::<(u64, u32)>, None::<(u64, u32)>);
let mut local: Option<(u64, u32)> = None;
let average = (n, playtime.max(1));
let density = |anchor: Option<(u64, u32)>, previous: Option<(u64, u32)>, local: Option<(u64, u32)>| {
let secant = anchor.zip(previous).and_then(|((m, t), (pm, pt))| {
let (s, f) = (m.abs_diff(pm), t.abs_diff(pt));
(f >= 3 && (m > pm) == (t > pt)).then_some((s, f))
});
secant.or(local).unwrap_or(average)
};
let sectors = |(s, f): (u64, u32), frames: u32| {
u64::try_from(u128::from(frames) * u128::from(s) / u128::from(f.max(1))).unwrap_or(u64::MAX)
};
let mut records: Vec<(u64, u32)> = Vec::new();
let mut used = 0u64;
let want = first.saturating_sub(1);
while hi - lo > PROBE_SPAN && reads < max {
let mut d = density(anchor, previous, local);
if found_lo && sectors(d, first - lo_t) <= CLOSE_SECTORS {
break;
}
let ((a, a_t), (b, b_t)) = bracket((lo, lo_t), (hi, hi_t), knots, first);
if previous.is_none() {
if let (Some((m, t)), Some((ls, lf))) = (anchor, local) {
let (om, ot) = if t > first { (a, a_t) } else { (b, b_t) };
if ot != t && om != m {
let avg = m.abs_diff(om) as f64 / f64::from(t.abs_diff(ot));
let mean = (avg * ls as f64 / f64::from(lf)).sqrt();
d = ((mean * 1024.0) as u64, 1024);
}
}
}
let guess = if found_lo && hi_probed {
let fl = u128::from(want - lo_t) << (32 - halved_lo.min(32));
let fh = u128::from(hi_t.saturating_sub(want)) << (32 - halved_hi.min(32));
let x = lo + (u128::from(hi - lo) * fl / (fl + fh).max(1)) as u64;
x.saturating_sub(per / 2 + ILLINOIS_MARGIN)
} else if halve {
a + (b - a) / 2
} else if let Some((m, t)) = anchor {
let dist = sectors(d, want.abs_diff(t));
if want >= t { m.saturating_add(dist) } else { m.saturating_sub(dist) }.saturating_sub(per / 2)
} else {
let num = u128::from(first.saturating_sub(a_t));
let den = u128::from(b_t.saturating_sub(a_t).max(1));
(a + (u128::from(b - a) * num / den) as u64).saturating_sub(per / 2)
}
.clamp(lo + 1, hi - 1);
let gap = |a_t: u32, b_t: u32| first.saturating_sub(a_t).min(b_t.saturating_sub(first));
let before = gap(a_t, b_t);
let (mut below, mut above, mut any) = (None, None, None);
let mut last: Option<(u64, u32)> = None;
let (mut guess, mut size, mut final_read) = (guess, per, false);
let left = FIRST_FRAME_BUDGET.saturating_sub(used);
if hi_probed {
let dense = [d, average, local.unwrap_or(average)]
.into_iter()
.max_by(|x, y| (u128::from(x.0) * u128::from(y.1)).cmp(&(u128::from(y.0) * u128::from(x.1))))
.unwrap_or(average);
let back = sectors(dense, hi_t.saturating_sub(first) + 1);
let start = hi.saturating_sub(back + back / 8 + 4).max(if found_lo { lo } else { 0 });
if hi + 1 - start <= left {
(guess, size, final_read) = (start, hi + 1 - start, true);
} else if found_lo && hi - lo <= left && left > per {
(guess, size, final_read) = (lo, hi - lo, true);
}
}
let rest = LAST_READ_BUDGET.saturating_sub(used);
let mut chance = false;
if reads + 1 == SEARCH_CALLS && rest > size {
if final_read {
size = rest.min(hi.saturating_add(PROBE_SPAN) - guess).max(size);
} else {
guess = (guess + per / 2).saturating_sub(rest * 5 / 8).max(lo + 1);
(size, final_read, chance) = (rest, true, true);
}
}
let mut at = guess;
while any.is_none() && at < hi.min(guess + PROBE_SPAN.max(size)) && reads < max {
let count = size.min(if final_read { end } else { hi } - at);
let read = &mut buf[..count as usize * SECTOR_SIZE];
image.check_cancel()?;
if image.read_into(at, read)? == crate::image::ReadOutcome::OutOfRange {
return Err(Error::InvalidArgument("audio sectors outside the image"));
}
on_read(count);
reads += 1;
used += count;
for i in 0..count {
let Some(t) = first_record(&read[i as usize * SECTOR_SIZE..]) else { continue };
records.push((at + i, t));
any = any.or(Some((at + i, t)));
last = Some((at + i, t));
if t < first {
(below, above) = (Some((at + i, t)), None);
} else if below.is_some() && above.is_none() {
above = Some((at + i, t));
}
}
if below.is_some() {
chunk = Some((at, read.to_vec()));
}
at += count;
}
if let (Some((m1, t1)), Some((m2, t2))) = (any, last) {
previous = anchor;
anchor = Some(below.unwrap_or((m1, t1)));
local = (m2 > m1 && t2 > t1).then(|| (m2 - m1, t2 - t1));
}
let found_now = below.is_some();
match (below, any.map(|(_, t)| t)) {
(Some((m, t)), _) => {
(lo, lo_t, found_lo) = (m, t, true);
(halved_lo, halved_hi) = (0, if moved == Some(false) { halved_hi + 1 } else { 0 });
moved = Some(false);
if above.is_some() {
break;
}
}
(None, Some(t)) => {
(hi, hi_t, hi_probed) = (guess, t.max(lo_t.saturating_add(1)), true);
(halved_hi, halved_lo) = (0, if moved == Some(true) { halved_lo + 1 } else { 0 });
moved = Some(true);
}
(None, None) => hi = guess,
}
if final_read && (found_now || !chance) {
break;
}
let ((_, a_t), (_, b_t)) = bracket((lo, lo_t), (hi, hi_t), knots, first);
slow = if halve || gap(a_t, b_t).saturating_mul(2) <= before { 0 } else { slow + 1 };
halve = slow >= 2;
}
let chunk =
chunk.filter(|(at, bytes)| found_lo && (*at..*at + (bytes.len() / SECTOR_SIZE) as u64).contains(&lo));
let density = [density(anchor, previous, local), average]
.into_iter()
.max_by(|a, b| (u128::from(a.0) * u128::from(b.1)).cmp(&(u128::from(b.0) * u128::from(a.1))))
.unwrap_or(average);
records.sort_unstable_by_key(|r| r.0);
let decreasing = records.windows(2).any(|w| w[1].1 < w[0].1);
Ok(Located { lsn: lo, reads, chunk, frame: lo_t, density, decreasing, used })
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Checkpoint {
pub(crate) next_acceptable: u32,
pub(crate) back: u32,
pub(crate) malformed_before: u64,
pub(crate) digest: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Frame {
pub(crate) start: u64,
pub(crate) bytes: Vec<u8>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Held {
pub(crate) at: u32,
pub(crate) frame: u32,
pub(crate) len: u32,
pub(crate) number: u32,
pub(crate) kind: FrameKind,
pub(crate) remaining: i32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Stored {
pub(crate) frames: Vec<Frame>,
pub(crate) held: Vec<Held>,
pub(crate) used: usize,
}
impl Stored {
pub(crate) fn add(
&mut self,
at: u32,
start: u64,
(number, kind, remaining): (u32, FrameKind, i32),
data: &[u8],
budget: usize,
) -> bool {
if data.len() > MAX_FRAME_BYTES {
return false;
}
let frame = match self.frames.last_mut() {
Some(f) if f.start == start => {
let common = f.bytes.len().min(data.len());
if f.bytes[..common] != data[..common] {
return false;
}
let grow = data.len() - common;
if self.used + grow > budget {
return false;
}
f.bytes.extend_from_slice(&data[common..]);
self.used += grow;
self.frames.len() - 1
}
_ => {
if self.used + data.len() > budget {
return false;
}
self.frames.push(Frame { start, bytes: data.to_vec() });
self.used += data.len();
self.frames.len() - 1
}
};
let (frame, len) = (frame as u32, data.len() as u32);
self.held.push(Held { at, frame, len, number, kind, remaining });
true
}
pub(crate) fn get(&self, at: u32) -> Option<(&Held, &[u8])> {
let h = &self.held[self.held.binary_search_by_key(&at, |h| h.at).ok()?];
Some((h, self.bytes(h)))
}
pub(crate) fn bytes(&self, h: &Held) -> &[u8] {
self.frames.get(h.frame as usize).and_then(|f| f.bytes.get(..h.len as usize)).unwrap_or(&[])
}
fn memory(&self) -> usize {
self.held.capacity() * std::mem::size_of::<Held>()
+ self.frames.capacity() * std::mem::size_of::<Frame>()
+ self.frames.iter().map(|f| f.bytes.capacity()).sum::<usize>()
}
fn take(&mut self, other: &Stored, at: u32, start: u64, budget: usize) {
if let Some((h, bytes)) = other.get(at) {
self.add(at, start, (h.number, h.kind, h.remaining), bytes, budget);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct EndState {
pub(crate) next_acceptable: u32,
pub(crate) malformed: u64,
}
#[derive(Debug)]
pub(crate) enum Plan<'a> {
Start,
At {
lsn: u64,
checkpoint: Checkpoint,
held: Option<(&'a Held, &'a [u8])>,
},
End(EndState),
}
pub(crate) struct Assembling<'a> {
pub(crate) start_lsn: u64,
pub(crate) number: u32,
pub(crate) kind: FrameKind,
pub(crate) remaining: i32,
pub(crate) data: &'a [u8],
}
pub(crate) fn digest(sector: &[u8; SECTOR_SIZE]) -> u64 {
sector.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))
}
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<AreaIndex>();
};
#[derive(Clone, Debug)]
pub struct AreaIndex {
key: AreaKey,
start: u64,
end: u64,
interval: u32,
inline_budget: usize,
checkpoints: Vec<Checkpoint>,
stored: Stored,
end_state: Option<EndState>,
malformed: Vec<u32>,
image_id: Option<u64>,
claims: Vec<std::sync::Arc<Claim>>,
provisional: std::collections::BTreeMap<u64, Provisional>,
events: Vec<SeekEvent>,
samples: Vec<(u32, u32)>,
hint_spacing: u32,
max_hints: usize,
fingerprint: Option<u64>,
fingerprint_checked: bool,
confirmed: Vec<(u32, u32, u64)>,
}
impl PartialEq for AreaIndex {
fn eq(&self, other: &Self) -> bool {
(self.key, self.start, self.end, self.interval, self.inline_budget)
== (other.key, other.start, other.end, other.interval, other.inline_budget)
&& self.checkpoints == other.checkpoints
&& self.stored == other.stored
&& self.end_state == other.end_state
&& self.malformed == other.malformed
}
}
impl Eq for AreaIndex {}
impl AreaIndex {
pub fn new(area: &Area, image_sectors: u64, options: IndexOptions) -> Result<Self, Error> {
if !(1..=MAX_INTERVAL).contains(&options.interval) {
return Err(Error::InvalidArgument("seek index interval must be 1 to 65536"));
}
let (start, end) = audio_sector_range(area, image_sectors);
Ok(AreaIndex {
key: AreaKey::new(area, image_sectors),
start,
end,
interval: options.interval,
inline_budget: options.inline_budget,
checkpoints: Vec::new(),
stored: Stored::default(),
end_state: None,
malformed: Vec::new(),
image_id: None,
claims: Vec::new(),
provisional: std::collections::BTreeMap::new(),
events: Vec::new(),
samples: Vec::new(),
hint_spacing: options.hint_spacing,
max_hints: options.max_hints.min(MAX_HINTS),
fingerprint: None,
fingerprint_checked: false,
confirmed: Vec::new(),
})
}
pub fn options(&self) -> IndexOptions {
IndexOptions {
interval: self.interval,
inline_budget: self.inline_budget,
hint_spacing: self.hint_spacing,
max_hints: self.max_hints,
}
}
pub fn frontier(&self) -> u64 {
if self.end_state.is_some() {
self.end
} else {
self.checkpoint_lsn(self.checkpoints.len().saturating_sub(1))
}
}
pub fn is_complete(&self) -> bool {
self.end_state.is_some()
}
pub fn checkpoints(&self) -> usize {
self.checkpoints.len()
}
pub fn memory(&self) -> usize {
std::mem::size_of::<Self>()
+ self.checkpoints.capacity() * std::mem::size_of::<Checkpoint>()
+ self.stored.memory()
+ self.malformed.capacity() * std::mem::size_of::<u32>()
+ self.samples.capacity() * std::mem::size_of::<(u32, u32)>()
+ self.confirmed.capacity() * std::mem::size_of::<(u32, u32, u64)>()
}
pub fn without_checkpoints(&self) -> AreaIndex {
AreaIndex { samples: self.samples.clone(), confirmed: self.confirmed.clone(), ..self.empty_clone() }
}
fn empty_clone(&self) -> AreaIndex {
AreaIndex {
key: self.key,
start: self.start,
end: self.end,
interval: self.interval,
inline_budget: self.inline_budget,
checkpoints: Vec::new(),
stored: Stored::default(),
end_state: None,
malformed: Vec::new(),
image_id: self.image_id,
claims: Vec::new(),
provisional: std::collections::BTreeMap::new(),
events: Vec::new(),
samples: Vec::new(),
hint_spacing: self.hint_spacing,
max_hints: self.max_hints,
fingerprint: self.fingerprint,
fingerprint_checked: self.fingerprint_checked,
confirmed: Vec::new(),
}
}
pub fn confirmations(&self) -> usize {
self.confirmed.len()
}
fn keep_confirmation(&mut self, lsn: u64, u: u32, digest: u64) {
let Ok(lsn) = u32::try_from(lsn) else { return };
if !self.fingerprint_checked || self.max_hints == 0 {
return;
}
match self.confirmed.binary_search_by_key(&lsn, |c| c.0) {
Ok(i) if self.confirmed[i].2 == digest => self.confirmed[i].1 = self.confirmed[i].1.min(u),
Ok(i) => self.confirmed[i] = (lsn, u, digest),
Err(i) => self.confirmed.insert(i, (lsn, u, digest)),
}
if self.confirmed.len() > self.max_hints {
self.confirmed.remove(0);
}
}
pub(crate) fn confirmation(&self, lsn: u64, u: u32) -> Option<u64> {
if !self.fingerprint_checked {
return None;
}
let lsn = u32::try_from(lsn).ok()?;
let i = self.confirmed.binary_search_by_key(&lsn, |c| c.0).ok()?;
let (_, u_l, digest) = self.confirmed[i];
(u_l <= u).then_some(digest)
}
pub fn hints(&self) -> usize {
self.samples.len()
}
pub(crate) fn hint_recorder(&self) -> Option<Box<HintRecorder>> {
(self.hint_spacing > 0 && self.max_hints > 0).then(|| {
Box::new(HintRecorder {
spacing: self.hint_spacing,
last: None,
list: Vec::new(),
tail: None,
flushed: false,
})
})
}
pub(crate) fn add_hints(&mut self, list: Vec<(u32, u32)>) {
if list.is_empty() || self.max_hints == 0 {
return;
}
let (start, end) = (self.start, self.end);
let after = self.samples.last().map_or(0, |s| u64::from(s.0) + 1);
let sorted = list.windows(2).all(|w| w[0].0 < w[1].0);
let ahead = sorted && list.first().is_some_and(|s| u64::from(s.0) >= after);
self.samples.extend(list.into_iter().filter(|&(l, _)| (start..end).contains(&u64::from(l))));
if !ahead {
self.samples.sort_unstable_by_key(|s| s.0);
self.samples.dedup_by_key(|s| s.0);
}
if self.samples.len() > self.max_hints {
self.thin_hints(self.max_hints - self.max_hints / 4);
}
}
pub(crate) fn thin_hints(&mut self, most: usize) {
let excess = self.samples.len().saturating_sub(most);
if excess == 0 {
return;
}
let gap = |i: usize| match i.checked_sub(1).map(|p| self.samples[p].1) {
Some(p) if p < self.samples[i].1 => self.samples[i].1 - p,
_ => u32::MAX,
};
let mut order: Vec<(u32, usize)> = (0..self.samples.len()).map(|i| (gap(i), i)).collect();
order.sort_unstable();
let mut drop = vec![false; self.samples.len()];
for &(_, i) in order.iter().take(excess) {
drop[i] = true;
}
let mut i = 0;
self.samples.retain(|_| {
i += 1;
!drop[i - 1]
});
}
pub(crate) fn drop_hints(&mut self) {
self.samples = Vec::new();
}
pub(crate) fn hint(&self, first: u32, end: u32, playtime: u32) -> Option<(u64, u32, u64, bool)> {
let below =
|| self.samples.iter().enumerate().filter(|(_, s)| s.1 < first && first - s.1 <= HINT_REACH);
let (i, &(lsn, t)) = below()
.filter(|(_, s)| self.confirmation(u64::from(s.0), first).is_some())
.max_by_key(|(_, s)| (s.1, s.0))
.or_else(|| below().max_by_key(|(_, s)| (s.1, s.0)))?;
let lsn = u64::from(lsn);
let next = self.samples[i + 1..].iter().find(|s| s.1 >= end);
if let Some(&(l, _)) = next.filter(|s| s.1 - end <= HINT_REACH) {
return Some((lsn, t, u64::from(l) + 1, true));
}
let run = self.samples[i + 1..].iter().take_while(|s| s.1 > t && s.1 < end).last().copied();
let (from, from_t) = run.map_or((lsn, t), |(l, n)| (u64::from(l), n));
let average = (self.end - self.start, playtime.max(1));
let local = match run {
Some((l, n)) if n - t >= 3 => Some((u64::from(l) - lsn, n - t)),
_ => i
.checked_sub(1)
.map(|p| self.samples[p])
.filter(|&(pl, pt)| u64::from(pl) < lsn && pt < t)
.map(|(pl, pt)| (lsn - u64::from(pl), t - pt)),
};
let (s, f) = match local {
Some(l) if u128::from(l.0) * u128::from(average.1) > u128::from(average.0) * u128::from(l.1) => l,
_ => average,
};
let span = u128::from(end - from_t) * u128::from(s) / u128::from(f.max(1));
let span = u64::try_from(span + span / 4 + 4).unwrap_or(u64::MAX);
Some((lsn, t, from.saturating_add(span), false))
}
pub(crate) fn bind_fingerprint(&mut self, fingerprint: u64) -> Result<(), Error> {
match self.fingerprint {
Some(f) if f != fingerprint => {
Err(Error::InvalidArgument("seek index of another disc (TOC differs)"))
}
_ => {
self.fingerprint = Some(fingerprint);
self.fingerprint_checked = true;
Ok(())
}
}
}
pub fn extend<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());
if self.is_complete() {
self.verify(image)?;
return Ok(true);
}
let mut cursor = AreaCursor::resume(self, u32::MAX);
let next = self.checkpoint_lsn(self.checkpoints.len());
let stop = self.frontier().saturating_add(max_sectors).max(next.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?;
self.verify(image)?;
Ok(self.is_complete())
}
pub(crate) fn key(&self) -> AreaKey {
self.key
}
pub(crate) fn check_key(&self, area: &Area, image_sectors: u64) -> Result<(), Error> {
if self.key != AreaKey::new(area, image_sectors) {
return Err(Error::InvalidArgument("seek index of another area or image"));
}
Ok(())
}
fn checkpoint_lsn(&self, j: usize) -> u64 {
self.start + j as u64 * u64::from(self.interval)
}
fn boundaries(&self) -> usize {
(self.end - self.start).div_ceil(u64::from(self.interval)) as usize
}
pub(crate) fn plan(&self, first: u32) -> Plan<'_> {
if let Some(end) = self.end_state.filter(|e| first >= e.next_acceptable) {
return Plan::End(end);
}
let j = self.checkpoints.partition_point(|c| c.next_acceptable <= first);
let Some(j) = j.checked_sub(1) else { return Plan::Start };
let checkpoint = self.checkpoints[j];
let held = self.stored.get(j as u32);
Plan::At { lsn: self.checkpoint_lsn(j), checkpoint, held }
}
pub(crate) fn plan_at(&self, j: usize) -> Plan<'_> {
let checkpoint = self.checkpoints[j];
Plan::At { lsn: self.checkpoint_lsn(j), checkpoint, held: self.stored.get(j as u32) }
}
pub(crate) fn checkpoint_before(&self, lsn: u64) -> Option<usize> {
let j = ((lsn.checked_sub(self.start)?) / u64::from(self.interval)) as usize;
(!self.checkpoints.is_empty()).then(|| j.min(self.checkpoints.len() - 1))
}
pub(crate) fn malformed_below(&self, lsn: u64) -> impl Iterator<Item = u32> + '_ {
self.malformed.iter().copied().take_while(move |&m| u64::from(m) < lsn)
}
pub(crate) fn recorder(&self, from: u64) -> Option<Box<Recorder>> {
if self.end_state.is_some() {
return None;
}
let first = self.checkpoints.len();
Some(Box::new(Recorder {
key: self.key,
interval: self.interval,
first: first as u32,
next: self.checkpoint_lsn(first),
from,
budget: self.inline_budget,
checkpoints: Vec::new(),
stored: Stored::default(),
end_state: None,
kept: false,
}))
}
pub fn absorb(&mut self, cursor: &mut impl crate::audio::SeekCursor) -> Result<(), Error> {
let cursor = crate::audio::sealed::Sealed::area_cursor_mut(cursor);
match self.take_from(cursor) {
Ok(()) => {
Self::drain(cursor);
self.take_provisional(cursor);
Ok(())
}
Err(e) => {
if self.of_another_image(cursor) {
cursor.stop_recording();
}
Err(e)
}
}
}
fn of_another_image(&self, cursor: &AreaCursor) -> bool {
matches!((self.image_id, cursor.image_id()), (Some(a), Some(b)) if a != b)
}
pub(crate) fn forget_image(&mut self) {
self.image_id = None;
}
pub(crate) fn take_from(&mut self, cursor: &AreaCursor) -> Result<(), Error> {
let Some(r) = cursor.recorder() else { return Ok(()) };
if self.of_another_image(cursor) {
return Err(Error::InvalidArgument("cursor of another image than the seek index's"));
}
if r.key != self.key || r.interval != self.interval {
return Err(Error::InvalidArgument("cursor of another area, image size or seek interval"));
}
if r.from > self.frontier() || r.first as usize > self.checkpoints.len() {
return Err(Error::InvalidArgument("cursor's checkpoints do not join the seek index"));
}
let have = self.checkpoints.len();
for (i, c) in r.checkpoints.iter().enumerate() {
let j = r.first as usize + i;
if j < have && self.checkpoints[j].next_acceptable != c.next_acceptable
|| j < have && self.checkpoints[j].malformed_before != c.malformed_before
{
return Err(Error::InvalidArgument("cursor's checkpoints differ from the seek index"));
}
}
if matches!((self.end_state, r.end_state), (Some(a), Some(b)) if a != b) {
return Err(Error::InvalidArgument("cursor's end state differs from the seek index"));
}
let old_frontier = self.frontier();
let skip = have - r.first as usize;
for (i, c) in r.checkpoints.iter().enumerate().skip(skip) {
let j = r.first + i as u32;
let start = self.checkpoint_lsn(j as usize) - u64::from(c.back);
self.stored.take(&r.stored, j, start, self.inline_budget);
self.checkpoints.push(*c);
}
if r.end_state.is_some() && self.checkpoints.len() == self.boundaries() {
self.end_state = r.end_state;
}
let frontier = self.frontier();
if frontier > old_frontier && self.malformed.len() < MAX_MALFORMED_WARNINGS {
self.malformed = cursor
.warnings()
.iter()
.filter_map(|w| w.lsn)
.take_while(|&m| u64::from(m) < frontier)
.take(MAX_MALFORMED_WARNINGS)
.collect();
}
if self.image_id.is_none() {
self.image_id = cursor.image_id();
}
self.prune_provisional();
Ok(())
}
}
impl AreaIndex {
pub(crate) fn absorb_drain(&mut self, cursor: &mut AreaCursor) {
if self.take_from(cursor).is_err() {
cursor.stop_recording();
return;
}
Self::drain(cursor);
self.take_provisional(cursor);
}
pub(crate) fn drain(cursor: &mut AreaCursor) {
if let Some(r) = cursor.recorder_mut() {
if r.end_state.is_some() {
cursor.stop_recording();
} else {
r.first += r.checkpoints.len() as u32;
r.checkpoints.clear();
r.stored = Stored::default();
}
}
}
pub(crate) fn plan_lsn(&self, first: u32) -> Option<u64> {
match self.plan(first) {
Plan::Start => Some(self.start),
Plan::At { lsn, .. } => Some(lsn),
Plan::End(_) => None,
}
}
pub(crate) fn interval(&self) -> u32 {
self.interval
}
}
impl AreaIndex {
pub fn pending_claims(&self) -> usize {
self.claims.len()
}
pub fn take_events(&mut self) -> Vec<SeekEvent> {
std::mem::take(&mut self.events)
}
pub(crate) fn take_provisional(&mut self, cursor: &mut AreaCursor) {
match (self.image_id, cursor.image_id()) {
(Some(id), Some(c)) if c != id => return,
(None, Some(c)) if cursor.has_news() => self.image_id = Some(c),
_ => {}
}
if let Some(claim) = cursor.unregistered_claim() {
if self.claims.len() >= MAX_CLAIMS {
let old = self.claims.remove(0);
if old.settle(Verdict::Unverified) {
queue_events(&mut self.events, [old.event()]);
}
}
self.claims.push(claim);
}
if cursor.hints_stale() {
self.drop_hints();
}
self.add_hints(cursor.take_hints());
let frontier = self.frontier();
let most = self.boundaries();
for (lsn, p) in cursor.take_provisional_checkpoints() {
if lsn > frontier && self.provisional.len() < most {
self.provisional.insert(lsn, p);
}
}
}
pub(crate) fn cap_claims(&mut self) {
while self.claims.len() > MAX_CLAIMS {
let old = self.claims.remove(0);
if old.settle(Verdict::Unverified) {
queue_events(&mut self.events, [old.event()]);
}
}
}
fn prune_provisional(&mut self) {
let frontier = self.frontier();
self.provisional.retain(|&lsn, _| lsn > frontier);
}
pub(crate) fn plan_provisional(&self, u: u32) -> Option<(u64, Provisional)> {
let mut best = None;
let mut prev: Option<u64> = None;
for (&lsn, &p) in &self.provisional {
if prev.is_some_and(|q| q + u64::from(self.interval) != lsn) {
best = None;
}
prev = Some(lsn);
if p.seen > u {
return best;
}
if p.under.is_none_or(|n| n < u) {
best = Some((lsn, p));
}
}
None
}
pub fn verify<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Result<usize, 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 frontier = self.frontier();
let mut settled = 0;
let mut i = 0;
while i < self.claims.len() {
let claim = std::sync::Arc::clone(&self.claims[i]);
let lsn = claim.lsn();
if claim.verdict().is_some() {
self.claims.remove(i);
continue;
}
if lsn == 0 || lsn > frontier || lsn >= self.end {
i += 1;
continue;
}
let foreign = claim.image().is_some_and(|id| id != image.id());
let verdict = match if foreign { None } else { AreaCursor::state_at(self, lsn, image)? } {
None => Verdict::Unverified,
Some((a, held, _)) => {
let u = claim.first;
if a <= u && held.is_none_or(|g| g < u) {
if self.fingerprint_checked && lsn < self.end {
let d = digest(&crate::audio::read_sector(image, lsn)?);
self.keep_confirmation(lsn, u, d);
}
Verdict::Confirmed
} else {
Verdict::Refuted { exact_from: a.max(held.map_or(0, |g| g.saturating_add(1))) }
}
}
};
self.claims.remove(i);
if claim.settle(verdict) {
settled += 1;
let event = claim.event();
match event.speculation {
Speculation::Refuted { first, last_returned, exact_from, .. } => sb_log!(
image.log(),
Warn,
"area {}: provisional reading from LSN {lsn} for frames {first}.. possibly different \
from the specification below frame {exact_from} (4.2 item 8; returned up to {:?})",
claim.slot,
last_returned
),
_ => sb_log!(
image.log(),
Debug,
"area {}: provisional reading from LSN {lsn}: {:?}",
claim.slot,
event.speculation
),
}
queue_events(&mut self.events, [event]);
}
}
Ok(settled)
}
}
#[derive(Debug, Default)]
pub(crate) struct SeekIndexes {
indexes: [std::sync::RwLock<Option<AreaIndex>>; 2],
events: [std::sync::Mutex<Vec<SeekEvent>>; 2],
}
impl SeekIndexes {
fn at(slot: crate::Slot) -> usize {
match slot {
crate::Slot::TwoChannel => 0,
crate::Slot::Multichannel => 1,
}
}
pub(crate) fn read<T>(&self, slot: crate::Slot, f: impl FnOnce(Option<&AreaIndex>) -> T) -> T {
let index = self.indexes[Self::at(slot)].read().unwrap_or_else(std::sync::PoisonError::into_inner);
f(index.as_ref())
}
pub(crate) fn write<T>(&self, slot: crate::Slot, f: impl FnOnce(&mut Option<AreaIndex>) -> T) -> T {
let mut index =
self.indexes[Self::at(slot)].write().unwrap_or_else(std::sync::PoisonError::into_inner);
f(&mut index)
}
#[inline]
pub(crate) fn absorb(&self, cursor: &mut AreaCursor, image_id: u64) {
let kept = cursor.recorder().is_none_or(|r| r.kept);
if kept && cursor.has_news() {
if cursor.image_id().is_some_and(|id| id != image_id) {
cursor.stop_recording();
return;
}
let events = self.write(cursor.slot(), |index| match index {
Some(index) => {
index.absorb_drain(cursor);
index.take_events()
}
None => {
cursor.stop_recording();
Vec::new()
}
});
self.push_events(cursor.slot(), events);
}
}
pub(crate) fn push_events(&self, slot: crate::Slot, events: Vec<SeekEvent>) {
if !events.is_empty() {
let mut queue =
self.events[Self::at(slot)].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
queue_events(&mut queue, events);
}
}
pub(crate) fn take_events(&self, slot: crate::Slot) -> Vec<SeekEvent> {
let mut queue = self.events[Self::at(slot)].lock().unwrap_or_else(std::sync::PoisonError::into_inner);
std::mem::take(&mut *queue)
}
}
#[derive(Clone, Debug)]
pub(crate) struct Recorder {
key: AreaKey,
interval: u32,
first: u32,
next: u64,
from: u64,
budget: usize,
checkpoints: Vec<Checkpoint>,
stored: Stored,
end_state: Option<EndState>,
pub(crate) kept: bool,
}
impl Recorder {
pub(crate) fn has_news(&self) -> bool {
!self.checkpoints.is_empty() || self.end_state.is_some()
}
#[inline]
pub(crate) fn due(&self, lsn: u64) -> bool {
lsn == self.next
}
pub(crate) fn record(
&mut self,
lsn: u64,
next_acceptable: u32,
malformed_before: u64,
assembling: Option<Assembling<'_>>,
sector: &[u8; SECTOR_SIZE],
) {
let at = self.first + self.checkpoints.len() as u32;
let mut back = 0;
if let Some(a) = assembling {
back = u32::try_from(lsn - a.start_lsn).unwrap_or(u32::MAX).max(1);
if u64::from(back) > REPLAY_SECTORS {
self.stored.add(at, a.start_lsn, (a.number, a.kind, a.remaining), a.data, self.budget);
}
}
self.checkpoints.push(Checkpoint { next_acceptable, back, malformed_before, digest: digest(sector) });
self.next += u64::from(self.interval);
}
pub(crate) fn finish(&mut self, next_acceptable: u32, malformed: u64) {
self.end_state = Some(EndState { next_acceptable, malformed });
}
}
pub(crate) fn toc_fingerprint(toc: &crate::Toc, slot: crate::Slot) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut put = |bytes: &[u8]| {
for &b in bytes {
h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3);
}
};
put(&toc.sectors.to_le_bytes());
put(&[match toc.sector_format {
crate::SectorFormat::Plain => 0,
crate::SectorFormat::Raw2054 => 1,
crate::SectorFormat::Raw2064 => 2,
}]);
let m = &toc.master;
put(&[m.version.major, m.version.minor]);
put(&m.album_set_size.to_le_bytes());
put(&m.album_sequence_number.to_le_bytes());
for stored in [&m.album_catalog_number_stored, &m.disc_catalog_number_stored] {
put(&(stored.len() as u32).to_le_bytes());
put(stored);
}
for g in m.album_genres.iter().chain(&m.disc_genres) {
put(&[g.category, g.index]);
}
for p in [m.two_channel, m.multichannel] {
put(&p.toc1_lsn.to_le_bytes());
put(&p.toc2_lsn.to_le_bytes());
put(&p.toc_sectors.to_le_bytes());
}
put(&[m.disc_flags]);
put(&m.date.year.to_le_bytes());
put(&[m.date.month, m.date.day]);
if let Some(a) = toc.area(slot) {
put(&[a.version.major, a.version.minor]);
put(&a.max_byte_rate.to_le_bytes());
put(&[
a.sample_frequency_code,
a.frame_format,
a.channel_count,
a.area_config,
a.max_available_channels,
a.area_mute_flags,
a.track_attribute,
a.playtime.minutes,
a.playtime.seconds,
a.playtime.frames,
a.track_offset,
]);
put(&a.audio_start_lsn.to_le_bytes());
put(&a.audio_end_lsn.to_le_bytes());
put(&(a.tracks.len() as u32).to_le_bytes());
for t in &a.tracks {
put(&[t.number, t.start_flags, t.duration_flags]);
put(&t.start_lsn.to_le_bytes());
put(&t.length_sectors.to_le_bytes());
put(&t.start_frame.to_le_bytes());
put(&t.duration_frames.to_le_bytes());
let isrc = t.isrc.as_deref().unwrap_or("");
put(&(isrc.len() as u32).to_le_bytes());
put(isrc.as_bytes());
}
}
h
}
pub(crate) fn layout_suspect(toc: &crate::Toc, slot: crate::Slot) -> bool {
let Some(a) = toc.area(slot) else { return false };
let (s, e) = (u64::from(a.audio_start_lsn), u64::from(a.audio_end_lsn));
if e >= toc.sectors {
return true;
}
let overlaps = |from: u64, to: u64| from <= e && s <= to && from <= to;
let other = match slot {
crate::Slot::TwoChannel => toc.master.multichannel,
crate::Slot::Multichannel => toc.master.two_channel,
};
if other.is_used() {
let len = u64::from(other.toc_sectors);
for t in [other.toc1_lsn, other.toc2_lsn].into_iter().filter(|&t| t != 0) {
if overlaps(u64::from(t), u64::from(t) + len - 1) {
return true;
}
}
}
toc.areas
.iter()
.filter(|o| o.slot != slot)
.any(|o| overlaps(u64::from(o.audio_start_lsn), u64::from(o.audio_end_lsn)))
}
#[cfg(test)]
mod tests {
use super::*;
fn index(next: &[u32], end: Option<u32>) -> AreaIndex {
AreaIndex {
key: AreaKey::new(&crate::audio::tests_support::area(1).1, 200),
start: 100,
end: 200,
interval: 10,
inline_budget: 0,
checkpoints: next
.iter()
.map(|&a| Checkpoint { next_acceptable: a, back: 0, malformed_before: 0, digest: 0 })
.collect(),
stored: Stored::default(),
end_state: end.map(|a| EndState { next_acceptable: a, malformed: 0 }),
malformed: Vec::new(),
image_id: None,
claims: Vec::new(),
provisional: std::collections::BTreeMap::new(),
events: Vec::new(),
samples: Vec::new(),
hint_spacing: DEFAULT_HINT_SPACING,
max_hints: DEFAULT_MAX_HINTS,
fingerprint: None,
fingerprint_checked: false,
confirmed: Vec::new(),
}
}
fn at(p: Plan<'_>) -> Option<u64> {
match p {
Plan::At { lsn, .. } => Some(lsn),
Plan::Start | Plan::End(_) => None,
}
}
#[test]
fn plan_takes_the_last_checkpoint_with_a_at_most_first() {
let ix = index(&[0, 3, 9, 1_166_881, 1_166_881], None);
assert_eq!(at(ix.plan(0)), Some(100));
assert_eq!(at(ix.plan(2)), Some(100));
assert_eq!(at(ix.plan(3)), Some(110));
assert_eq!(at(ix.plan(8)), Some(110));
assert_eq!(at(ix.plan(9)), Some(120));
assert_eq!(at(ix.plan(1_166_880)), Some(120));
assert_eq!(at(ix.plan(1_166_881)), Some(140));
assert!(matches!(index(&[], None).plan(5), Plan::Start));
let done = index(&[0, 3], Some(7));
assert_eq!(at(done.plan(6)), Some(110));
assert!(matches!(done.plan(7), Plan::End(EndState { next_acceptable: 7, .. })));
assert_eq!(done.frontier(), 200);
assert_eq!(ix.frontier(), 140);
assert_eq!(index(&[], None).frontier(), 100);
}
#[test]
fn provisional_starts_stay_within_one_reading() {
let mut ix = index(&[], None);
let p = |seen| Provisional { back: 0, digest: 0, seen, under: None };
for (lsn, seen) in [(110, 10), (120, 20), (160, 50), (170, 60)] {
ix.provisional.insert(lsn, p(seen));
}
assert_eq!(ix.plan_provisional(15).map(|x| x.0), Some(110));
assert_eq!(ix.plan_provisional(35), None, "between the readings");
assert_eq!(ix.plan_provisional(55).map(|x| x.0), Some(160));
}
#[test]
fn options_are_checked() {
let (_, area, _) = crate::audio::tests_support::area(4);
for k in [0, MAX_INTERVAL + 1] {
let e = AreaIndex::new(&area, 4, IndexOptions::new().with_interval(k)).unwrap_err();
assert!(matches!(e, Error::InvalidArgument(_)));
}
let ix = AreaIndex::new(&area, 4, IndexOptions::new().with_interval(MAX_INTERVAL)).unwrap();
assert_eq!(ix.options().interval, MAX_INTERVAL);
assert_eq!((ix.frontier(), ix.is_complete(), ix.checkpoints()), (0, false, 0));
assert!(ix.memory() >= std::mem::size_of::<AreaIndex>());
}
#[test]
fn bracket_takes_the_tightest_knots_inside() {
let knots = [(150, 10), (200, 20), (300, 30), (900, 5), (50, 1)];
assert_eq!(bracket((100, 0), (1000, 100), &knots, 25), ((200, 20), (300, 30)));
assert_eq!(bracket((100, 0), (1000, 100), &knots, 35), ((300, 30), (1000, 100)));
assert_eq!(bracket((100, 0), (1000, 100), &knots, 7), ((900, 5), (1000, 100)));
assert_eq!(bracket((100, 0), (1000, 100), &knots, 4), ((100, 0), (900, 5)));
assert_eq!(bracket((250, 24), (280, 28), &knots, 25), ((250, 24), (280, 28)));
assert_eq!(bracket((100, 0), (1000, 100), &[], 7), ((100, 0), (1000, 100)));
}
#[test]
fn hints_thin_by_gap() {
let mut ix = index(&[], None);
ix.add_hints(vec![(110, 10), (111, 11), (112, 12), (150, 500), (151, 508), (190, 900)]);
ix.thin_hints(4);
assert_eq!(ix.samples.len(), 4, "{:?}", ix.samples);
assert!(
ix.samples.contains(&(110, 10))
&& ix.samples.contains(&(150, 500))
&& ix.samples.contains(&(190, 900))
);
assert_eq!(ix.hint(505, 520, 1000).map(|h| h.0), Some(150));
assert_eq!(ix.hint(700, 710, 1000), None, "beyond the reach");
}
#[test]
fn digest_is_fnv1a() {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for _ in 0..SECTOR_SIZE {
h = h.wrapping_mul(0x0100_0000_01b3);
}
assert_eq!(digest(&[0; SECTOR_SIZE]), h);
assert_ne!(digest(&[0; SECTOR_SIZE]), digest(&[1; SECTOR_SIZE]));
}
}