use std::collections::VecDeque;
use std::io::{Read, Seek};
use crate::control::Progress;
use crate::dst::{DstDecoder, DstError};
use crate::error::{Error, Slot, Warning, WarningCode};
use crate::image::{Image, ReadOutcome, SECTOR_SIZE};
use crate::log::{Level, Log, sb_log};
use crate::seek::{
AreaIndex, Assembling, Claim, DamageRecorder, DamageStart, HintRecorder, Plan, Provisional,
ProvisionalRecorder, Recorder, ResumedFrom, SeekIndexes, SeekPolicy, Speculate, Speculation, digest,
first_record, locate,
};
use crate::toc::{Area, Track};
pub const FRAME_BYTES_PER_CHANNEL: usize = 4704;
pub const MAX_FRAME_BYTES: usize = 65_536;
pub const MISSING_FILL: u8 = 0x69;
pub const INVALID_FILL: u8 = 0x55;
pub const MAX_CHANNELS: u8 = 6;
pub const MAX_MALFORMED_WARNINGS: usize = 4096;
pub const MAX_PROBLEM_LINES: usize = MAX_MALFORMED_WARNINGS;
#[derive(Clone, Copy, Debug, Default)]
struct LineCap(usize);
impl LineCap {
#[inline]
fn admit(&mut self, log: &Log, level: Level, slot: &str, what: &str) -> bool {
if !log.enabled(level) {
return false;
}
self.0 = self.0.saturating_add(1);
if self.0 == MAX_PROBLEM_LINES + 1 {
log.write(
level,
format_args!(
"area {slot}: further {what} lines suppressed (at most {MAX_PROBLEM_LINES} per cursor)"
),
);
}
self.0 <= MAX_PROBLEM_LINES
}
}
#[derive(Clone, Copy, Debug)]
enum Malformed {
Overrun { p: usize, k: usize, len: usize, pos: usize },
NoRecord { p: usize, f: usize },
Oversized { number: u32 },
}
impl std::fmt::Display for Malformed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Malformed::Overrun { p, k, len, pos } => {
write!(f, "packet {p} of {k} ({len} bytes at {pos}) overruns the sector")
}
Malformed::NoRecord { p, f: records } => {
write!(f, "frame start in packet {p} without a frame record ({records} records)")
}
Malformed::Oversized { number } => {
write!(f, "frame {number} exceeds {MAX_FRAME_BYTES} bytes and is discarded")
}
}
}
}
#[doc(hidden)]
pub const MAX_PARALLEL_BATCH: usize = 512;
#[doc(hidden)]
pub const PARALLEL_FRAMES_PER_THREAD: usize = 16;
#[cfg(feature = "parallel")]
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub enum DecodeOn {
#[default]
CurrentPool,
Pool(std::sync::Arc<rayon::ThreadPool>),
CallingThread,
}
pub const FRAMES_PER_SECTOR: u64 = 7;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FrameKind {
Dst,
Dsd,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AreaFrame {
pub number: u32,
pub kind: FrameKind,
pub data: Vec<u8>,
pub lost_from: Option<u32>,
}
#[derive(Debug)]
struct Assembly {
number: u32,
kind: FrameKind,
data: Vec<u8>,
remaining: i32,
start_lsn: u64,
}
#[derive(Clone, Copy)]
struct At<'a> {
log: &'a Log,
slot: Option<Slot>,
lsn: u64,
}
impl At<'_> {
fn slot(&self) -> &'static str {
self.slot.map_or("?", Slot::name)
}
}
#[derive(Debug)]
pub struct Demuxer {
channels: u8,
assembling: Option<Assembly>,
next_acceptable: u32,
ready: VecDeque<AreaFrame>,
malformed: u64,
slot: Option<Slot>,
reason: Option<Malformed>,
discarded_lines: LineCap,
seen: u32,
lost_from: Option<u32>,
}
impl Demuxer {
pub fn new(channels: u8) -> Self {
Demuxer {
channels,
assembling: None,
next_acceptable: 0,
ready: VecDeque::new(),
malformed: 0,
slot: None,
reason: None,
discarded_lines: LineCap::default(),
seen: 0,
lost_from: None,
}
}
pub fn push_unreadable(&mut self) {
self.push_unreadable_at(self.at(&Log::none(), 0));
}
fn push_unreadable_at(&mut self, at: At<'_>) {
self.reason = None;
let complete = self.assembling.as_ref().is_some_and(|a| self.is_complete(a));
if complete {
self.deliver_if_complete(at);
} else if let Some(a) = self.assembling.take() {
sb_log!(
at.log,
Debug,
"area {} frame {} (from LSN {}): lost, runs into unreadable LSN {}",
at.slot(),
a.number,
a.start_lsn,
at.lsn
);
}
self.lost_from.get_or_insert(self.next_acceptable);
}
pub fn lost_from(&self) -> Option<u32> {
self.lost_from
}
fn is_complete(&self, a: &Assembly) -> bool {
!a.data.is_empty()
&& match a.kind {
FrameKind::Dst => a.remaining == 0,
FrameKind::Dsd => a.data.len() == usize::from(self.channels) * FRAME_BYTES_PER_CHANNEL,
}
}
fn at<'a>(&self, log: &'a Log, lsn: u64) -> At<'a> {
At { log, slot: self.slot, lsn }
}
pub fn malformed_sectors(&self) -> u64 {
self.malformed
}
pub fn pop(&mut self) -> Option<AreaFrame> {
self.ready.pop_front()
}
pub fn push_sector(&mut self, sector: &[u8; SECTOR_SIZE]) -> bool {
self.push_sector_at(sector, self.at(&Log::none(), 0))
}
fn push_sector_at(&mut self, sector: &[u8; SECTOR_SIZE], at: At<'_>) -> bool {
let header = sector[0];
let dst = header & 1 != 0;
let f = usize::from((header >> 2) & 7);
let k = usize::from(header >> 5);
let record = if dst { 4 } else { 3 };
let h = 1 + 2 * k + f * record;
let byte = |i: usize| sector.get(i).copied().unwrap_or(0);
self.reason = None;
let mut malformed = false;
let mut x = 0usize;
let mut pos = h;
for p in 0..k {
let w = u16::from_be_bytes([byte(1 + 2 * p), byte(2 + 2 * p)]);
let start = w & 0x8000 != 0;
let packet_type = (w >> 11) & 7;
let len = usize::from(w & 0x07FF);
let Some(payload) = sector.get(pos..pos + len) else {
self.reason.get_or_insert(Malformed::Overrun { p, k, len, pos });
malformed = true;
break;
};
if packet_type == 2 {
if start {
self.deliver_if_complete(at);
if x < f {
let r = 1 + 2 * k + x * record;
let number =
(u32::from(byte(r)) * 60 + u32::from(byte(r + 1))) * 75 + u32::from(byte(r + 2));
let remaining = if dst { i32::from((byte(r + 3) >> 2) & 0x1F) } else { 0 };
let kind = if dst { FrameKind::Dst } else { FrameKind::Dsd };
let data = match kind {
FrameKind::Dsd => Vec::with_capacity(
(usize::from(self.channels) * FRAME_BYTES_PER_CHANNEL).min(MAX_FRAME_BYTES),
),
FrameKind::Dst => Vec::new(),
};
self.assembling = Some(Assembly { number, kind, data, remaining, start_lsn: at.lsn });
x += 1;
} else {
self.reason.get_or_insert(Malformed::NoRecord { p, f });
malformed = true;
}
}
if let Some(a) = &mut self.assembling {
if a.data.len() + len > MAX_FRAME_BYTES {
if self.discarded_lines.admit(at.log, Level::Warn, at.slot(), "discarded-frame") {
sb_log!(
at.log,
Warn,
"area {} frame {} (from LSN {}): discarded at LSN {}, more than {MAX_FRAME_BYTES} \
bytes (4.4.3)",
at.slot(),
a.number,
a.start_lsn,
at.lsn
);
}
self.reason.get_or_insert(Malformed::Oversized { number: a.number });
self.assembling = None;
malformed = true;
} else {
a.data.extend_from_slice(payload);
a.remaining = a.remaining.saturating_sub(1);
}
}
}
pos += len;
}
if malformed {
self.malformed += 1;
}
malformed
}
pub fn finish(&mut self) {
self.finish_at(self.at(&Log::none(), 0));
}
fn finish_at(&mut self, at: At<'_>) {
self.deliver_if_complete(at);
}
fn deliver_if_complete(&mut self, at: At<'_>) {
let Some(a) = self.assembling.take() else { return };
let complete = self.is_complete(&a);
if complete {
self.seen = self.seen.max(a.number.saturating_add(1));
}
if complete && a.number >= self.next_acceptable {
let (start_lsn, len) = (a.start_lsn, a.data.len());
self.next_acceptable = a.number + 1;
let lost_from = self.lost_from.take().filter(|&l| l < a.number);
self.ready.push_back(AreaFrame { number: a.number, kind: a.kind, data: a.data, lost_from });
sb_log!(
at.log,
Trace,
"area {} frame {} (from LSN {start_lsn}): accepted, {:?}, {len} bytes",
at.slot(),
a.number,
a.kind
);
return;
}
if !self.discarded_lines.admit(at.log, Level::Warn, at.slot(), "discarded-frame") {
return;
}
if !complete {
sb_log!(
at.log,
Warn,
"area {} frame {} (from LSN {}): discarded, incomplete ({:?}, {} bytes{}; 4.4.2)",
at.slot(),
a.number,
a.start_lsn,
a.kind,
a.data.len(),
match a.kind {
FrameKind::Dst if a.remaining != 0 => ", sector count does not match",
_ => "",
}
);
} else {
sb_log!(
at.log,
Warn,
"area {} frame {} (from LSN {}): discarded, not after the last accepted frame {} (4.5)",
at.slot(),
a.number,
a.start_lsn,
self.next_acceptable.saturating_sub(1)
);
}
}
}
#[derive(Debug)]
pub struct AreaCursor {
demux: Demuxer,
image_id: Option<u64>,
slot: Slot,
warnings: Vec<Warning>,
next_lsn: u64,
end_lsn: u64,
buf: Vec<u8>,
buf_lsn: u64,
buf_sectors: u64,
finished: bool,
malformed_lines: LineCap,
recorder: Option<Box<Recorder>>,
replay: Option<Replay>,
resumed: ResumedFrom,
stop_lsn: u64,
verify: Option<(u64, u64)>,
key: AreaKey,
before_read: Option<Box<(u64, Vec<Warning>)>>,
speculate: Option<Speculate>,
claim: Option<std::sync::Arc<Claim>>,
claim_registered: bool,
provisional: Option<Box<ProvisionalRecorder>>,
read_to: u64,
read_then: u64,
suspect: Option<crate::seek::Suspect>,
hints: Option<Box<HintRecorder>>,
hints_stale: bool,
sectors_read: u64,
progress_end: u64,
progress: Option<Progress>,
buf_bad: Vec<(u64, u64)>,
damaged: Option<u64>,
for_index: bool,
unreadable_lines: LineCap,
damage: Option<Box<DamageRecorder>>,
damage_start: Option<Box<DamageStart>>,
}
#[derive(Clone, Copy, Debug)]
struct Replay {
until: u64,
next_acceptable: u32,
malformed: u64,
lost_from: Option<u32>,
}
const READ_CHUNK: u64 = 32;
fn held(buf: &[u8], at: usize) -> &[u8; SECTOR_SIZE] {
static ZERO: [u8; SECTOR_SIZE] = [0; SECTOR_SIZE];
buf.get(at..).and_then(<[u8]>::first_chunk).unwrap_or(&ZERO)
}
impl AreaCursor {
pub fn new(area: &Area, image_sectors: u64) -> Self {
Self::with_key(AreaKey::new(area, image_sectors))
}
fn with_key(key: AreaKey) -> Self {
let (start, end) = key.audio_sector_range();
let mut demux = Demuxer::new(key.channels);
demux.slot = Some(key.slot);
AreaCursor {
demux,
image_id: None,
slot: key.slot,
warnings: Vec::new(),
next_lsn: start,
end_lsn: end,
buf: Vec::new(),
buf_lsn: 0,
buf_sectors: 0,
finished: false,
malformed_lines: LineCap::default(),
recorder: None,
replay: None,
resumed: ResumedFrom::Start,
stop_lsn: u64::MAX,
verify: None,
key,
before_read: None,
speculate: None,
claim: None,
claim_registered: false,
provisional: None,
read_to: 0,
read_then: 0,
suspect: None,
hints: None,
hints_stale: false,
sectors_read: 0,
progress_end: end,
progress: None,
buf_bad: Vec::new(),
damaged: None,
for_index: false,
unreadable_lines: LineCap::default(),
damage: None,
damage_start: None,
}
}
#[inline]
fn is_bad(&self, lsn: u64) -> bool {
!self.buf_bad.is_empty() && self.buf_bad.iter().any(|&(s, e)| (s..e).contains(&lsn))
}
pub(crate) fn damaged(&self) -> Option<u64> {
self.damaged
}
pub(crate) fn for_index(&mut self) {
self.for_index = true;
(self.damage, self.damage_start) = (None, None);
}
fn restart_unindexed(&mut self, log: &Log, lsn: u64) {
let (image_id, stop, counts) = (self.image_id, self.stop_lsn, self.take_progress());
let (hints, stale) = (self.hints.take(), self.hints_stale);
let checkpoint = match self.resumed {
ResumedFrom::Checkpoint { lsn, .. } => lsn,
_ => self.end_lsn,
};
let mut damage = self.damage.take();
*self = Self::with_key(self.key);
self.image_id = image_id;
self.keep_progress(counts);
(self.hints, self.hints_stale) = (hints, stale);
if let Some(d) = damage.as_deref_mut() {
d.restart();
}
self.damage = damage;
if stop != u64::MAX {
self.stop_lsn = self.next_lsn;
}
sb_log!(
log,
Info,
"area {}: unreadable sector LSN {lsn} at or before the seek index's checkpoint at LSN {checkpoint}: \
scanning from LSN {}",
self.slot,
self.next_lsn
);
}
fn process_unreadable(&mut self, log: &Log, lsn: u64) {
if self.damaged.is_none() {
self.damaged = Some(lsn);
if let Some(r) = self.recorder.as_deref_mut() {
r.halt();
}
if let Some(p) = self.provisional.as_deref_mut() {
p.halt();
}
}
if let Some(d) = self.damage.as_deref_mut() {
d.unreadable(lsn);
}
if self.unreadable_lines.admit(log, Level::Warn, self.slot.name(), "unreadable-sector") {
sb_log!(log, Warn, "area {} audio sector LSN {lsn}: unreadable; its frames are lost", self.slot);
}
let at = self.demux.at(log, lsn);
self.demux.push_unreadable_at(at);
}
pub fn progress(&mut self) -> Progress {
let read = self.sectors_read;
let expected = if self.finished { read } else { self.expected(self.next_lsn) };
self.progress
.get_or_insert_with(|| {
let p = Progress::default();
p.set(read, expected);
p
})
.clone()
}
fn expected(&self, next: u64) -> u64 {
self.sectors_read + self.progress_end.saturating_sub(next)
}
#[inline]
fn count_read(&mut self, n: u64, next: u64) {
self.sectors_read += n;
if let Some(p) = &self.progress {
p.set(self.sectors_read, self.expected(next));
}
}
pub(crate) fn progress_done(&self) {
if let Some(p) = &self.progress {
p.set(self.sectors_read, self.sectors_read);
}
}
pub(crate) fn set_progress_end(&mut self, lsn: u64) {
self.progress_end = lsn.min(self.end_lsn);
if let Some(sp) = self.speculate.as_mut() {
sp.exact.set_progress_end(lsn);
}
}
pub(crate) fn restart_progress(&mut self) {
self.sectors_read = 0;
self.progress = None;
}
fn keep_progress(&mut self, from: (u64, u64, Option<Progress>)) {
(self.sectors_read, self.progress_end, self.progress) = from;
}
fn take_progress(&mut self) -> (u64, u64, Option<Progress>) {
(self.sectors_read, self.progress_end, self.progress.take())
}
pub(crate) fn speculative(
exact: AreaCursor,
(first, end): (u32, u32),
(playtime, knots): (u32, Vec<(u64, u32)>),
(interval, hint, track_start): (u32, Option<crate::seek::Hint>, Option<u64>),
options: crate::seek::SpeculativeOptions,
) -> Self {
let from = match exact.resumed {
ResumedFrom::Checkpoint { lsn, .. } => lsn,
_ => exact.next_lsn,
};
let mut cursor = Self::with_key(exact.key);
cursor.next_lsn = from;
cursor.resumed = ResumedFrom::Speculative { lsn: 0, probes: 0 };
cursor.claim = Some(Claim::new(cursor.slot, first));
cursor.speculate = Some(Speculate {
first,
end,
playtime,
interval,
options,
knots,
exact: Box::new(exact),
from,
hint,
track_start,
});
cursor
}
fn begin<R: Read + Seek>(&mut self, image: &mut Image<R>, mut sp: Speculate) -> Result<(), Error> {
let (start, _) = self.key.audio_sector_range();
if let Some((l, t, to, confirmed)) = sp.hint {
self.read_to = to;
if let Some(ts) = sp.track_start.take() {
let sector = match self.sector(image, ts) {
Err(Error::Cancelled) => {
sp.track_start = Some(ts);
self.speculate = Some(sp);
return Err(Error::Cancelled);
}
r => r?,
};
if first_record(§or).is_some_and(|r| r <= sp.first) {
self.start_provisional(start, (ts, 0), &sp);
return Ok(());
}
}
let sector = match self.sector(image, l) {
Err(Error::Cancelled) => {
self.speculate = Some(sp);
return Err(Error::Cancelled);
}
r => r?,
};
if self.is_bad(l) || image.is_unreadable(l) {
sb_log!(image.log(), Debug, "area {}: seek hint at LSN {l} unreadable: searching", self.slot);
self.read_to = 0;
sp.hint = None;
} else if first_record(§or) == Some(t) && t < sp.first {
self.start_provisional(start, (l, 0), &sp);
let marked = image.unreadable_sectors().first_in(start, l).is_some();
if !marked && confirmed.is_some_and(|d| d == digest(§or)) {
if let Some(claim) = &self.claim {
claim.confirm_saved();
}
sb_log!(
image.log(),
Debug,
"area {}: provisional reading from LSN {l} confirmed from saved state (4.2 item 9)",
self.slot
);
}
return Ok(());
} else {
sb_log!(
image.log(),
Warn,
"area {}: seek hint at LSN {l} (frame {t}) does not match the image (first record {:?}): \
hints dropped, searching",
self.slot,
first_record(§or)
);
self.hints_stale = true;
self.read_to = 0;
sp.hint = None;
}
}
let range = (sp.from, self.end_lsn);
let located = locate(image, range, (sp.first, sp.playtime), &sp.knots, &sp.options, &mut |n| {
self.count_read(n, sp.from)
});
let located = match located {
Err(Error::Cancelled) => {
self.speculate = Some(sp);
return Err(Error::Cancelled);
}
r => r?,
};
let (l, probes) = (located.lsn, located.reads);
let exact_instead = located.decreasing && sp.options.exact_when_suspect;
if l <= sp.from || exact_instead {
let (image_id, counts, stale) = (self.image_id, self.take_progress(), self.hints_stale);
*self = *sp.exact;
self.image_id = image_id;
self.hints_stale = stale;
self.keep_progress(counts);
sb_log!(
image.log(),
Debug,
"area {}: no provisional start past LSN {} for frame {} ({probes} reads): exact",
self.slot,
sp.from,
sp.first
);
return Ok(());
}
self.start_provisional(start, (l, probes), &sp);
if located.decreasing && self.suspect.is_none() {
self.suspect = Some(crate::seek::Suspect::FrameNumbersDecrease);
}
if let Some((at, bytes, bad)) = located.chunk {
self.buf_sectors = (bytes.len() / SECTOR_SIZE) as u64;
self.buf_lsn = at;
self.buf = bytes;
self.buf_bad = bad;
}
let (sectors, frames) = located.density;
let span =
u128::from(sp.end.saturating_sub(located.frame)) * u128::from(sectors) / u128::from(frames);
let span = u64::try_from(span + span / 4 + 4).unwrap_or(u64::MAX);
let through_first =
u128::from(sp.first + 1 - located.frame) * u128::from(sectors) / u128::from(frames);
let through_first = u64::try_from(through_first + through_first / 4 + 4).unwrap_or(u64::MAX);
let from = if self.buf_sectors > 0 { (self.buf_lsn + self.buf_sectors).max(l) } else { l };
let left = crate::seek::FIRST_FRAME_BUDGET.saturating_sub(located.used);
let need = (l + through_first).saturating_sub(from);
let range = l.saturating_add(span).saturating_sub(from);
self.read_to = from + need.max(range).min(left);
self.read_then = l.saturating_add(span);
Ok(())
}
fn start_provisional(&mut self, start: u64, (l, probes): (u64, u32), sp: &Speculate) {
self.next_lsn = l;
self.demux.next_acceptable = sp.first;
self.resumed = ResumedFrom::Speculative { lsn: l, probes };
if let Some(claim) = &self.claim {
claim.set_lsn(l);
}
self.provisional = Some(ProvisionalRecorder::new(start, l, sp.interval));
if sp.options.layout_suspect {
self.suspect = Some(crate::seek::Suspect::AreaLayout);
}
}
pub fn suspect(&self) -> Option<crate::seek::Suspect> {
self.suspect.filter(|_| self.claim.as_ref().is_some_and(|c| c.lsn() > 0))
}
pub(crate) fn take_hints(&mut self) -> Vec<(u32, u32)> {
self.hints.as_mut().map(|h| h.take()).unwrap_or_default()
}
pub(crate) fn flush_hints(&mut self) {
if let Some(h) = self.hints.as_deref_mut() {
h.flush();
}
}
pub(crate) fn hints_stale(&mut self) -> bool {
std::mem::take(&mut self.hints_stale)
}
pub(crate) fn record_hints(&mut self, recorder: Option<Box<HintRecorder>>) {
if let Some(sp) = self.speculate.as_mut() {
sp.exact.hints = recorder.as_ref().map(|r| Box::new(HintRecorder::clone(r)));
}
self.hints = recorder;
}
pub(crate) fn size_first_read(&mut self, lsn: u64) {
self.read_to = lsn;
}
pub(crate) fn provisional_at(
exact: &AreaCursor,
(lsn, p): (u64, Provisional),
first: u32,
interval: u32,
) -> Self {
let mut cursor = Self::with_key(exact.key);
let (start, _) = cursor.key.audio_sector_range();
let from = lsn - u64::from(p.back);
cursor.next_lsn = from;
cursor.demux.next_acceptable = first;
if from < lsn {
cursor.replay =
Some(Replay { until: lsn, next_acceptable: first, malformed: 0, lost_from: None });
}
cursor.verify = Some((lsn, p.digest));
cursor.resumed = ResumedFrom::Speculative { lsn, probes: 0 };
let claim = Claim::new(cursor.slot, first);
claim.set_lsn(lsn);
cursor.claim = Some(claim);
cursor.provisional = Some(ProvisionalRecorder::new(start, lsn, interval));
cursor
}
pub(crate) fn state_at<R: Read + Seek>(
index: &AreaIndex,
lsn: u64,
image: &mut Image<R>,
) -> Result<Option<(u32, Option<u32>, u64)>, Error> {
let mut cursor = Self::with_key(index.key());
if let Some(j) = index.checkpoint_before(lsn) {
cursor.resume_at(index, index.plan_at(j));
}
cursor.recorder = None;
cursor.for_index();
cursor.scan_to(image, lsn)?;
if let ResumedFrom::Discarded { .. } = cursor.resumed {
return Ok(None);
}
if cursor.damaged.is_some() {
return Ok(None);
}
if let Some((at, want)) = cursor.verify {
if at < cursor.end_lsn {
let sector = cursor.sector(image, at)?;
if cursor.is_bad(at) || image.is_unreadable(at) || digest(§or) != want {
return Ok(None);
}
}
}
let d = &cursor.demux;
Ok(Some((d.next_acceptable, d.assembling.as_ref().map(|a| a.number), d.malformed)))
}
pub fn speculation(&self) -> Speculation {
self.claim.as_ref().map_or(Speculation::Exact, |c| c.speculation())
}
pub fn claim(&self) -> Option<u64> {
self.claim.as_ref().map(|c| c.id)
}
pub fn claim_lsn(&self) -> Option<u64> {
self.claim.as_ref().map(|c| c.lsn()).filter(|&l| l > 0)
}
pub(crate) fn unregistered_claim(&mut self) -> Option<std::sync::Arc<Claim>> {
let claim = self.claim.as_ref().filter(|c| !self.claim_registered && c.lsn() > 0)?;
let claim = std::sync::Arc::clone(claim);
self.claim_registered = true;
Some(claim)
}
pub(crate) fn take_provisional_checkpoints(&mut self) -> Vec<(u64, Provisional)> {
self.provisional.as_mut().map(|p| std::mem::take(&mut p.list)).unwrap_or_default()
}
#[inline]
pub(crate) fn has_news(&self) -> bool {
self.recorder.as_deref().is_some_and(Recorder::has_news)
|| self.damage.as_deref().is_some_and(DamageRecorder::has_news)
|| (!self.claim_registered && self.claim.as_ref().is_some_and(|c| c.lsn() > 0))
|| self.provisional.as_ref().is_some_and(|p| !p.list.is_empty())
|| self.hints_stale
|| self.hints.as_deref().is_some_and(HintRecorder::has_news)
}
pub(crate) fn resume(index: &AreaIndex, first: u32) -> Self {
let mut cursor = Self::with_key(index.key());
let slot = cursor.slot;
let warn = |lsn: u32| Warning {
code: WarningCode::AudioSectorMalformed,
slot: Some(slot),
track: None,
lsn: Some(lsn),
};
match index.plan(first) {
Plan::Start => cursor.recorder = index.recorder(cursor.next_lsn),
Plan::End(end) => {
cursor.next_lsn = cursor.end_lsn;
cursor.finished = true;
cursor.demux.next_acceptable = end.next_acceptable;
cursor.demux.malformed = end.malformed;
cursor.warnings = index.malformed_below(cursor.end_lsn).map(warn).collect();
cursor.resumed = ResumedFrom::End;
}
plan @ Plan::At { .. } => cursor.resume_at(index, plan),
}
cursor.damage_start = index.damage_start(first).map(Box::new);
cursor.damage = Some(index.damage_recorder());
cursor
}
pub(crate) fn damage_start_lsn(&self) -> Option<(u64, u64)> {
self.damage_start.as_ref().map(|d| (d.at.lsn, d.at.lsn - u64::from(d.at.checkpoint.back)))
}
pub(crate) fn size_damage_read(&mut self, lsn: u64) {
if let Some(d) = self.damage_start.as_deref_mut() {
d.read_to = lsn;
}
}
fn resume_damaged(&mut self, log: &Log, d: &DamageStart) {
let (image_id, counts) = (self.image_id, self.take_progress());
let (hints, stale) = (self.hints.take(), self.hints_stale);
let mut damage = self.damage.take();
*self = Self::with_key(self.key);
self.image_id = image_id;
self.keep_progress(counts);
(self.hints, self.hints_stale) = (hints, stale);
if let Some(r) = damage.as_deref_mut() {
r.resume(d);
}
self.damage = damage;
self.damaged = d.runs.first().map(|r| r.0);
let slot = self.slot;
self.warnings = d
.malformed
.iter()
.map(|&lsn| Warning {
code: WarningCode::AudioSectorMalformed,
slot: Some(slot),
track: None,
lsn: Some(lsn),
})
.collect();
let (lsn, c) = (d.at.lsn, d.at.checkpoint);
let replay_from = lsn - u64::from(c.back);
self.demux.next_acceptable = c.next_acceptable;
self.demux.malformed = c.malformed_before;
if replay_from < lsn {
self.replay = Some(Replay {
until: lsn,
next_acceptable: c.next_acceptable,
malformed: c.malformed_before,
lost_from: d.at.lost_from,
});
} else {
self.demux.lost_from = d.at.lost_from;
}
self.next_lsn = replay_from;
self.read_to = d.read_to;
self.verify = Some((lsn, c.digest));
self.resumed = ResumedFrom::Checkpoint { lsn, replay_from };
sb_log!(
log,
Info,
"area {}: unreadable sectors before LSN {lsn}: resuming at the state a scan meeting them had there \
(next acceptable {}, lost from {:?})",
self.slot,
c.next_acceptable,
d.at.lost_from
);
}
fn resume_at(&mut self, index: &AreaIndex, plan: Plan<'_>) {
let slot = self.slot;
let warn = |lsn: u32| Warning {
code: WarningCode::AudioSectorMalformed,
slot: Some(slot),
track: None,
lsn: Some(lsn),
};
let Plan::At { lsn, checkpoint, held } = plan else { return };
self.warnings = index.malformed_below(lsn).map(warn).collect();
let replay_from = match held {
Some((h, bytes)) => {
self.demux.assembling = Some(Assembly {
number: h.number,
kind: h.kind,
data: bytes.to_vec(),
remaining: h.remaining,
start_lsn: lsn - u64::from(checkpoint.back),
});
lsn
}
None => lsn - u64::from(checkpoint.back),
};
self.demux.next_acceptable = checkpoint.next_acceptable;
self.demux.malformed = checkpoint.malformed_before;
if replay_from < lsn {
self.replay = Some(Replay {
until: lsn,
next_acceptable: checkpoint.next_acceptable,
malformed: checkpoint.malformed_before,
lost_from: None,
});
}
self.next_lsn = replay_from;
self.verify = Some((lsn, checkpoint.digest));
self.recorder = index.recorder(lsn);
self.resumed = ResumedFrom::Checkpoint { lsn, replay_from };
}
fn discard_index(&mut self, log: &Log, lsn: u64) {
let (image_id, stop, counts) = (self.image_id, self.stop_lsn, self.take_progress());
*self = Self::with_key(self.key);
self.image_id = image_id;
self.keep_progress(counts);
self.resumed = ResumedFrom::Discarded { lsn };
if stop != u64::MAX {
self.stop_lsn = self.next_lsn;
}
sb_log!(
log,
Warn,
"area {}: seek index does not match the image at LSN {lsn}, discarded; scanning from LSN {}",
self.slot,
self.next_lsn
);
}
pub fn resumed_from(&self) -> ResumedFrom {
self.resumed
}
pub fn lost_from(&self) -> Option<u32> {
self.demux.lost_from()
}
pub(crate) fn scan_to<R: Read + Seek>(&mut self, image: &mut Image<R>, stop: u64) -> Result<bool, Error> {
self.stop_lsn = stop;
let result = loop {
match self.next_frame(image) {
Some(Ok(_)) => {}
Some(Err(e)) => break Err(e),
None => break Ok(self.finished),
}
};
self.stop_lsn = u64::MAX;
result
}
pub(crate) fn recorder(&self) -> Option<&Recorder> {
self.recorder.as_deref()
}
pub(crate) fn recorder_mut(&mut self) -> Option<&mut Recorder> {
self.recorder.as_deref_mut()
}
pub(crate) fn keep_for_disc(&mut self) {
if let Some(r) = self.recorder.as_deref_mut() {
r.kept = true;
}
if let Some(d) = self.damage.as_deref_mut() {
d.kept = true;
}
if let Some(sp) = self.speculate.as_mut() {
sp.exact.keep_for_disc();
}
}
pub(crate) fn stop_recording(&mut self) {
self.recorder = None;
self.damage = None;
}
pub(crate) fn damage_recorder(&self) -> Option<&DamageRecorder> {
self.damage.as_deref()
}
pub(crate) fn damage_recorder_mut(&mut self) -> Option<&mut DamageRecorder> {
self.damage.as_deref_mut()
}
pub(crate) fn carry_counts(&mut self, from: &AreaCursor) {
self.before_read = Some(Box::new((from.malformed_sectors(), from.warnings().to_vec())));
}
pub(crate) fn image_id(&self) -> Option<u64> {
self.image_id
}
pub(crate) fn slot(&self) -> Slot {
self.slot
}
pub(crate) fn scan_lsn(&self) -> u64 {
self.next_lsn
}
pub fn malformed_sectors(&self) -> u64 {
match (&self.image_id, &self.before_read) {
(Some(_), _) => self.demux.malformed_sectors(),
(None, Some(b)) => b.0,
(None, None) => 0,
}
}
pub fn warnings(&self) -> &[Warning] {
match (&self.image_id, &self.before_read) {
(Some(_), _) => &self.warnings,
(None, Some(b)) => &b.1,
(None, None) => &[],
}
}
fn sector<R: Read + Seek>(&mut self, image: &mut Image<R>, lsn: u64) -> Result<[u8; SECTOR_SIZE], Error> {
let at = self.load(image, lsn)?;
Ok(*held(&self.buf, at))
}
fn load<R: Read + Seek>(&mut self, image: &mut Image<R>, lsn: u64) -> Result<usize, Error> {
if !(self.buf_lsn..self.buf_lsn + self.buf_sectors).contains(&lsn) {
let sized = self.read_to.saturating_sub(lsn);
let then = self.read_then.saturating_sub(lsn);
let n = if sized > 0 { sized } else { READ_CHUNK.max(then) }
.min(crate::seek::MAX_READ_SECTORS)
.min(self.end_lsn - lsn);
image.check_cancel()?;
self.buf.resize(n as usize * SECTOR_SIZE, 0);
if image.read_audio(lsn, &mut self.buf, &mut self.buf_bad)? == ReadOutcome::OutOfRange {
sb_log!(
image.log(),
Error,
"area {}: audio sectors from LSN {lsn} outside the image",
self.slot
);
return Err(Error::InvalidArgument("audio sectors outside the image"));
}
self.count_read(n, lsn + n);
self.buf_lsn = lsn;
self.buf_sectors = n;
}
Ok((lsn - self.buf_lsn) as usize * SECTOR_SIZE)
}
pub fn next_frame<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<AreaFrame, Error>> {
match self.image_id {
None => {
self.image_id = Some(image.id());
if let Some(claim) = &self.claim {
claim.set_image(image.id());
}
if let Some(sp) = self.speculate.take() {
if let Err(e) = self.begin(image, sp) {
if let Error::Cancelled = e {
self.image_id = None;
} else {
self.finished = true;
}
return Some(Err(e));
}
}
let (start, end) = self.key.audio_sector_range();
let upto = match self.resumed {
ResumedFrom::Checkpoint { lsn, .. } => Some(lsn.saturating_add(1)),
ResumedFrom::End => Some(end),
_ => None,
};
let marked = upto.and_then(|upto| image.unreadable_sectors().first_in(start, upto));
let from = upto.map_or(start, |u| u - 1);
let damage = self.damage_start.take().filter(|d| {
(marked.is_some() || d.at.lsn > from)
&& d.fits(&image.unreadable_sectors().runs_in(start, d.at.lsn + 1))
});
if let Some(d) = damage {
self.resume_damaged(image.log(), &d);
} else if let Some(bad) = marked.filter(|_| !self.for_index) {
self.restart_unindexed(image.log(), bad);
}
match self.resumed {
ResumedFrom::Start => sb_log!(
image.log(),
Debug,
"area {}: scanning audio sectors LSN {}..{}",
self.slot,
self.next_lsn,
self.end_lsn
),
ResumedFrom::Checkpoint { lsn, replay_from } => sb_log!(
image.log(),
Debug,
"area {}: resuming at LSN {lsn} from seek index (next acceptable {}, replay from LSN \
{replay_from}), scanning to LSN {}",
self.slot,
self.replay.map_or(self.demux.next_acceptable, |r| r.next_acceptable),
self.end_lsn
),
ResumedFrom::End => sb_log!(
image.log(),
Debug,
"area {}: seek index: no frame accepted at or after the range, nothing to read",
self.slot
),
ResumedFrom::Speculative { lsn, probes } => sb_log!(
image.log(),
Info,
"area {}: provisional reading from LSN {lsn} for frames {}.. ({probes} reads to choose it; \
4.2 item 8): positions provisional, counts from LSN {lsn}",
self.slot,
self.demux.next_acceptable
),
ResumedFrom::Discarded { .. } => {}
}
}
Some(id) if id != image.id() => {
return Some(Err(Error::InvalidArgument("audio cursor used with another image")));
}
Some(_) => {}
}
loop {
if let Some(f) = self.demux.pop() {
return Some(Ok(f));
}
if self.finished {
return None;
}
if let Some(r) = self.replay.filter(|r| self.next_lsn >= r.until) {
self.demux.ready.clear();
self.demux.next_acceptable = r.next_acceptable;
self.demux.malformed = r.malformed;
self.demux.lost_from = r.lost_from;
self.replay = None;
}
if self.next_lsn >= self.stop_lsn && self.replay.is_none() && self.next_lsn < self.end_lsn {
return None;
}
if self.next_lsn < self.end_lsn {
let lsn = self.next_lsn;
self.next_lsn += 1;
match self.load(image, lsn) {
Ok(_) if self.is_bad(lsn) || image.is_unreadable(lsn) => {
let replaying = self.replay.is_some_and(|r| lsn < r.until);
let verifying = self.verify.is_some_and(|(at, _)| at == lsn);
if (replaying || verifying) && !self.for_index {
self.restart_unindexed(image.log(), lsn);
continue;
}
if verifying {
self.verify = None;
}
self.process_unreadable(image.log(), lsn);
}
Ok(at) => {
let s = held(&self.buf, at);
if let Some(r) = self.replay {
if lsn < r.until {
let malformed = self.demux.malformed;
self.demux.push_sector_at(s, self.demux.at(&Log::none(), lsn));
self.demux.malformed = malformed;
self.demux.ready.clear();
continue;
}
}
if let Some((at, want)) = self.verify.filter(|&(at, _)| at == lsn) {
self.verify = None;
if digest(s) != want {
self.discard_index(image.log(), at);
continue;
}
}
if let Some(h) = self.hints.as_deref_mut() {
h.see(lsn, s);
}
if let Some(pr) = self.provisional.as_deref_mut().filter(|p| p.due(lsn)) {
let under = self.demux.assembling.as_ref().map(|a| (lsn - a.start_lsn, a.number));
pr.record(lsn, under, self.demux.seen, s);
}
if let Some(rec) = self.recorder.as_deref_mut().filter(|r| r.due(lsn)) {
let d = &self.demux;
let assembling = d.assembling.as_ref().map(|a| Assembling {
start_lsn: a.start_lsn,
number: a.number,
kind: a.kind,
remaining: a.remaining,
data: &a.data,
});
rec.record(lsn, d.next_acceptable, d.malformed, assembling, s);
}
if let Some(rec) = self.damage.as_deref_mut().filter(|r| r.due(lsn)) {
let d = &self.demux;
let back = d
.assembling
.as_ref()
.map_or(0, |a| u32::try_from(lsn - a.start_lsn).unwrap_or(u32::MAX).max(1));
rec.record(lsn, (d.next_acceptable, back, d.malformed), d.lost_from, s);
}
let at = self.demux.at(image.log(), lsn);
let malformed = self.demux.push_sector_at(s, at);
if let Some(reason) = self.demux.reason.filter(|_| malformed) {
let code = WarningCode::AudioSectorMalformed.code();
let log = image.log();
if self.malformed_lines.admit(log, Level::Warn, self.slot.name(), code) {
sb_log!(
log,
Warn,
"area {} audio sector LSN {lsn}: {code}: {reason}",
self.slot
);
}
}
if malformed && self.warnings.len() < MAX_MALFORMED_WARNINGS {
let lsn = u32::try_from(lsn).ok();
self.warnings.push(Warning {
code: WarningCode::AudioSectorMalformed,
slot: Some(self.slot),
track: None,
lsn,
});
}
}
Err(Error::Cancelled) => {
self.next_lsn = lsn;
return Some(Err(Error::Cancelled));
}
Err(e) => {
self.finished = true;
return Some(Err(e));
}
}
} else {
self.demux.finish_at(self.demux.at(image.log(), self.end_lsn));
self.finished = true;
self.progress_done();
if let Some(rec) = self.recorder.as_deref_mut() {
rec.finish(self.demux.next_acceptable, self.demux.malformed);
}
sb_log!(
image.log(),
Debug,
"area {}: scan ended at LSN {}, {} malformed sectors",
self.slot,
self.end_lsn,
self.demux.malformed_sectors()
);
}
}
}
}
pub(crate) fn read_sector<R: Read + Seek>(
image: &mut Image<R>,
lsn: u64,
) -> Result<[u8; SECTOR_SIZE], Error> {
let mut out = [0u8; SECTOR_SIZE];
image.check_cancel()?;
let mut bad = Vec::new();
if image.read_audio(lsn, &mut out, &mut bad)? == ReadOutcome::OutOfRange {
return Err(Error::InvalidArgument("audio sectors outside the image"));
}
if !bad.is_empty() {
return Err(Error::SectorUnreadable { lsn });
}
Ok(out)
}
#[derive(Debug)]
pub struct AreaFrames<'a, R> {
image: &'a mut Image<R>,
cursor: AreaCursor,
}
impl<'a, R: Read + Seek> AreaFrames<'a, R> {
pub(crate) fn new(image: &'a mut Image<R>, area: &Area) -> Self {
let cursor = AreaCursor::new(area, image.sector_count());
AreaFrames { image, cursor }
}
pub(crate) fn with_cursor(image: &'a mut Image<R>, cursor: AreaCursor) -> Self {
AreaFrames { image, cursor }
}
pub fn malformed_sectors(&self) -> u64 {
self.cursor.malformed_sectors()
}
pub fn warnings(&self) -> &[Warning] {
self.cursor.warnings()
}
pub fn progress(&mut self) -> Progress {
self.cursor.progress()
}
pub fn lost_from(&self) -> Option<u32> {
self.cursor.lost_from()
}
}
impl<R: Read + Seek> Iterator for AreaFrames<'_, R> {
type Item = Result<AreaFrame, Error>;
fn next(&mut self) -> Option<Self::Item> {
self.cursor.next_frame(self.image)
}
}
pub fn audio_sector_range(area: &Area, n: u64) -> (u64, u64) {
let start = u64::from(area.audio_start_lsn);
let end = (u64::from(area.audio_end_lsn) + 1).min(n);
(start, end.max(start))
}
pub fn check_track(area: &Area, track: &Track, image_sectors: u64) -> Result<(), Error> {
check_channels(area)?;
if track.duration_frames == 0 {
return Err(Error::TrackEmpty);
}
check_capacity(area, track.end_frame(), image_sectors)
}
pub fn check_range(area: &Area, first: u32, end: u32, image_sectors: u64) -> Result<(), Error> {
check_channels(area)?;
let playtime = area.playtime_frames();
if first > end || end > playtime {
return Err(Error::FrameRangeInvalid { first, end, playtime });
}
if first == end {
return Err(Error::TrackEmpty);
}
check_capacity(area, end, image_sectors)
}
pub(crate) fn check_channels(area: &Area) -> Result<(), Error> {
if !(1..=MAX_CHANNELS).contains(&area.channel_count) {
return Err(Error::ChannelCountUnsupported { channels: area.channel_count });
}
Ok(())
}
fn check_capacity(area: &Area, end_frame: u32, image_sectors: u64) -> Result<(), Error> {
let (start, end) = audio_sector_range(area, image_sectors);
let capacity = (end - start).saturating_mul(FRAMES_PER_SECTOR);
if u64::from(end_frame) > capacity {
return Err(Error::TrackExceedsCapacity { end_frame, capacity });
}
Ok(())
}
const PACKET_BYTES_PER_SECTOR: u64 = SECTOR_SIZE as u64 - 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AreaCapacity {
pub audio_sectors: u64,
pub playtime_frames: u32,
pub max_track_end: u32,
pub capacity: u64,
pub plain_frame_bound: Option<u64>,
}
impl AreaCapacity {
pub fn frames_per_sector(&self) -> f64 {
if self.audio_sectors == 0 {
return f64::INFINITY;
}
let claimed = self.playtime_frames.max(self.max_track_end);
f64::from(claimed) / self.audio_sectors as f64
}
}
pub fn area_capacity(area: &Area, image_sectors: u64) -> AreaCapacity {
let (start, end) = audio_sector_range(area, image_sectors);
let n = end - start;
let plain_frame_bound = (1..=MAX_CHANNELS).contains(&area.channel_count).then(|| {
let frame = u64::from(area.channel_count) * FRAME_BYTES_PER_CHANNEL as u64;
n.saturating_mul(PACKET_BYTES_PER_SECTOR) / frame
});
AreaCapacity {
audio_sectors: n,
playtime_frames: area.playtime_frames(),
max_track_end: area.tracks.iter().map(Track::end_frame).max().unwrap_or(0),
capacity: n.saturating_mul(FRAMES_PER_SECTOR),
plain_frame_bound,
}
}
pub fn track_range_with_pause(area: &Area, number: u32) -> Option<(u32, u32)> {
let track = area.track(number)?;
let first = if number == 1 { 0 } else { track.start_frame };
let next =
number.checked_add(1).and_then(|n| area.track(n)).map_or(area.playtime_frames(), |t| t.start_frame);
Some((first, next.max(track.end_frame())))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FrameSpan {
Track(u32),
Range(u32, u32),
}
#[derive(Clone, Copy, Debug, Default)]
pub struct CursorOptions<'a> {
index: Option<&'a AreaIndex>,
policy: Option<SeekPolicy>,
}
impl<'a> CursorOptions<'a> {
pub fn new() -> Self {
Self::default()
}
pub fn with_index(mut self, index: &'a AreaIndex) -> Self {
self.index = Some(index);
self
}
pub fn with_policy(mut self, policy: SeekPolicy) -> Self {
self.policy = Some(policy);
self
}
pub(crate) fn index(&self) -> Option<&'a AreaIndex> {
self.index
}
pub(crate) fn policy(&self) -> Option<SeekPolicy> {
self.policy
}
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Opening {
Continues,
FromIndex,
Fresh,
}
#[derive(Clone, Copy, Debug)]
pub struct Continuation<'a> {
area: &'a Area,
first: u32,
end: u32,
image_sectors: u64,
image_id: Option<u64>,
log: &'a Log,
track: Option<u32>,
seek: &'a SeekIndexes,
policy: SeekPolicy,
}
impl<'a> Continuation<'a> {
pub(crate) fn new(
area: &'a Area,
(first, end): (u32, u32),
(image_sectors, image_id): (u64, Option<u64>),
log: &'a Log,
track: Option<u32>,
(seek, policy): (&'a SeekIndexes, SeekPolicy),
) -> Self {
Continuation { area, first, end, image_sectors, image_id, log, track, seek, policy }
}
fn with_index<T>(&self, f: impl FnOnce(Option<&AreaIndex>) -> T) -> T {
self.seek.read(self.area.slot, |index| f(index.filter(|i| self.check_index(i).is_ok())))
}
fn log_how(&self, what: &str, opening: Opening) {
if self.log.enabled(Level::Info) {
let how = match opening {
Opening::Continues => "continuing the earlier scan",
Opening::FromIndex => "from the seek index",
Opening::Fresh => "new scan of the area",
};
log_open(self.log, self.area, self.track, (self.first, self.end), what, how);
}
}
fn absorb(&self, cursor: &mut AreaCursor) {
if let Some(id) = self.image_id {
self.seek.absorb(cursor, id);
}
}
fn absorb_into(&self, cursor: &mut AreaCursor, index: &mut AreaIndex) {
let other_image = matches!((cursor.image_id(), self.image_id), (Some(a), Some(b)) if a != b);
if !other_image && index.take_from(cursor).is_ok() {
AreaIndex::drain(cursor);
}
}
pub fn range(&self) -> (u32, u32) {
(self.first, self.end)
}
pub fn audio(self, prev: TrackAudioCursor) -> TrackAudioCursor {
let opening = self.log_audio(&prev);
self.audio_as(prev, opening)
}
#[doc(hidden)]
pub fn log_audio(&self, prev: &TrackAudioCursor) -> Opening {
let opening = self.with_index(|index| {
prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index)
});
self.log_how("decoded audio", opening);
opening
}
#[doc(hidden)]
pub fn audio_unlogged(self, prev: TrackAudioCursor) -> TrackAudioCursor {
let opening = self.with_index(|index| {
prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index)
});
self.audio_as(prev, opening)
}
#[doc(hidden)]
pub fn audio_as(self, mut prev: TrackAudioCursor, opening: Opening) -> TrackAudioCursor {
self.absorb(&mut prev.frames.area);
self.with_index(|index| {
let mut next = prev.open_as(
self.area,
(self.first, self.end),
(self.image_sectors, self.image_id),
index,
(opening, self.policy),
);
if opening != Opening::Continues && index.is_some() {
next.frames.area.keep_for_disc();
}
next
})
}
pub fn frames(self, prev: TrackCursor) -> TrackCursor {
let opening = self.log_frames(&prev);
self.frames_as(prev, opening)
}
#[doc(hidden)]
pub fn log_frames(&self, prev: &TrackCursor) -> Opening {
let opening = self.with_index(|index| {
prev.opening(self.area, self.first, self.image_sectors, self.image_id, index)
});
self.log_how("frames", opening);
opening
}
#[doc(hidden)]
pub fn frames_unlogged(self, prev: TrackCursor) -> TrackCursor {
let opening = self.with_index(|index| {
prev.opening(self.area, self.first, self.image_sectors, self.image_id, index)
});
self.frames_as(prev, opening)
}
#[doc(hidden)]
pub fn frames_as(self, mut prev: TrackCursor, opening: Opening) -> TrackCursor {
self.absorb(&mut prev.area);
self.with_index(|index| {
let mut next = prev.open_as(
self.area,
(self.first, self.end),
(self.image_sectors, self.image_id),
index,
(opening, self.policy),
);
if opening != Opening::Continues && index.is_some() {
next.area.keep_for_disc();
}
next
})
}
#[doc(hidden)]
pub fn check_index(&self, index: &AreaIndex) -> Result<(), Error> {
index.check_key(self.area, self.image_sectors)
}
#[doc(hidden)]
pub fn log_audio_indexed(&self, prev: &TrackAudioCursor, index: &AreaIndex) -> Opening {
let index = Some(index).filter(|i| self.check_index(i).is_ok());
let opening = prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index);
self.log_how("decoded audio", opening);
opening
}
#[doc(hidden)]
pub fn audio_indexed_unlogged(self, prev: TrackAudioCursor, index: &mut AreaIndex) -> TrackAudioCursor {
let opening = {
let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
prev.opening(self.area, self.first, (self.image_sectors, self.image_id), index)
};
self.audio_indexed_as(prev, index, opening)
}
#[doc(hidden)]
pub fn audio_indexed_as(
self,
mut prev: TrackAudioCursor,
index: &mut AreaIndex,
opening: Opening,
) -> TrackAudioCursor {
self.absorb_into(&mut prev.frames.area, index);
let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
prev.open_as(
self.area,
(self.first, self.end),
(self.image_sectors, self.image_id),
index,
(opening, self.policy),
)
}
#[doc(hidden)]
pub fn log_frames_indexed(&self, prev: &TrackCursor, index: &AreaIndex) -> Opening {
let index = Some(index).filter(|i| self.check_index(i).is_ok());
let opening = prev.opening(self.area, self.first, self.image_sectors, self.image_id, index);
self.log_how("frames", opening);
opening
}
#[doc(hidden)]
pub fn frames_indexed_unlogged(self, prev: TrackCursor, index: &mut AreaIndex) -> TrackCursor {
let opening = {
let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
prev.opening(self.area, self.first, self.image_sectors, self.image_id, index)
};
self.frames_indexed_as(prev, index, opening)
}
#[doc(hidden)]
pub fn frames_indexed_as(
self,
mut prev: TrackCursor,
index: &mut AreaIndex,
opening: Opening,
) -> TrackCursor {
self.absorb_into(&mut prev.area, index);
let index = Some(&*index).filter(|i| self.check_index(i).is_ok());
prev.open_as(
self.area,
(self.first, self.end),
(self.image_sectors, self.image_id),
index,
(opening, self.policy),
)
}
#[doc(hidden)]
pub fn log_fresh_frames(&self) {
self.log_how("frames", Opening::Fresh);
}
#[doc(hidden)]
pub fn fresh_frames(self) -> TrackCursor {
self.seek.read(self.area.slot, |index| {
let index = index.filter(|i| i.check_key(self.area, self.image_sectors).is_ok());
let range = (self.first, self.end);
let mut c = TrackCursor::start_with(self.area, range, self.image_sectors, index, self.policy);
if index.is_some() {
c.area.keep_for_disc();
}
c
})
}
}
pub(crate) fn log_open(
log: &Log,
area: &Area,
track: Option<u32>,
(first, end): (u32, u32),
what: &str,
how: &str,
) {
let slot = area.slot;
let c = area.channel_count;
match track {
Some(n) => {
sb_log!(log, Info, "area {slot} track {n}: frames {first}..{end} ({c} channels), {what}, {how}")
}
None => sb_log!(log, Info, "area {slot} range: frames {first}..{end} ({c} channels), {what}, {how}"),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FrameContent {
Dsd(Vec<u8>),
Dst(Vec<u8>),
Missing,
}
impl FrameContent {
pub fn dst_equivalent(&self, channels: u8) -> Result<std::borrow::Cow<'_, [u8]>, Error> {
if !(1..=MAX_CHANNELS).contains(&channels) {
return Err(Error::InvalidArgument("channel count must be 1 to 6"));
}
Ok(self.equivalent_checked(channels))
}
fn equivalent_checked(&self, channels: u8) -> std::borrow::Cow<'_, [u8]> {
let plain = |bytes: &[u8]| {
let mut v = Vec::with_capacity(1 + bytes.len());
v.push(0x00);
v.extend_from_slice(bytes);
v
};
match self {
FrameContent::Dst(bytes) => std::borrow::Cow::Borrowed(bytes),
FrameContent::Dsd(bytes) => std::borrow::Cow::Owned(plain(bytes)),
FrameContent::Missing => {
let fill = fill_frame(channels, MISSING_FILL);
std::borrow::Cow::Owned(plain(&fill))
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct TrackFrame {
pub number: u32,
pub content: FrameContent,
lost: bool,
}
impl TrackFrame {
pub fn new(number: u32, content: FrameContent) -> Self {
TrackFrame { number, content, lost: false }
}
pub fn lost(number: u32) -> Self {
TrackFrame { number, content: FrameContent::Missing, lost: true }
}
pub fn is_lost(&self) -> bool {
self.lost
}
}
#[derive(Debug)]
pub struct TrackCursor {
area: AreaCursor,
area_key: AreaKey,
next: u32,
end: u32,
channels: u8,
peeked: Option<AreaFrame>,
exhausted: bool,
failed: bool,
missing: u64,
lost: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AreaKey {
pub(crate) slot: Slot,
pub(crate) start: u32,
pub(crate) end: u32,
pub(crate) channels: u8,
pub(crate) image_sectors: u64,
}
impl AreaKey {
pub(crate) fn audio_sector_range(&self) -> (u64, u64) {
let start = u64::from(self.start);
let end = (u64::from(self.end) + 1).min(self.image_sectors);
(start, end.max(start))
}
pub(crate) fn new(area: &Area, image_sectors: u64) -> Self {
AreaKey {
slot: area.slot,
start: area.audio_start_lsn,
end: area.audio_end_lsn,
channels: area.channel_count,
image_sectors,
}
}
}
impl TrackCursor {
pub fn new(area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
check_track(area, track, image_sectors)?;
Ok(Self::start(area, track.start_frame, track.end_frame(), image_sectors))
}
pub fn open_range(
area: &Area,
first: u32,
end: u32,
image_sectors: u64,
options: CursorOptions<'_>,
) -> Result<Self, Error> {
check_range(area, first, end, image_sectors)?;
let index = options.index();
if let Some(index) = index {
index.check_key(area, image_sectors)?;
}
Ok(match (index, options.policy().unwrap_or_default()) {
(None, SeekPolicy::Exact) => Self::start(area, first, end, image_sectors),
(Some(index), SeekPolicy::Exact) => Self::start_indexed(area, first, end, image_sectors, index),
(index, policy) => Self::start_with(area, (first, end), image_sectors, index, policy),
})
}
pub(crate) fn start_indexed(
area: &Area,
first: u32,
end: u32,
image_sectors: u64,
index: &AreaIndex,
) -> Self {
let mut cursor = TrackCursor {
area: AreaCursor::resume(index, first),
..Self::start(area, first, end, image_sectors)
}
.estimated(area);
let (s0, s1) = audio_sector_range(area, image_sectors);
let hinted = index.hint(first, end, area.playtime_frames()).filter(|h| h.3).map(|h| h.2);
let sized = |lsn: u64, replay_from: u64| {
let to = hinted.filter(|&to| to > lsn).unwrap_or_else(|| {
let frames = u128::from(end - first);
let span = frames * u128::from(s1 - s0) / u128::from(area.playtime_frames().max(1));
let span = u64::try_from(span + span / 4 + 4).unwrap_or(u64::MAX);
lsn.saturating_add(u64::from(index.interval())).saturating_add(span)
});
let most = lsn + u64::from(index.interval()) + 64;
to.min(most).min(replay_from + crate::seek::MAX_READ_SECTORS)
};
if let ResumedFrom::Checkpoint { lsn, replay_from } = cursor.area.resumed {
cursor.area.size_first_read(sized(lsn, replay_from));
}
if let Some((lsn, replay_from)) = cursor.area.damage_start_lsn() {
cursor.area.size_damage_read(sized(lsn, replay_from));
}
cursor.area.record_hints(index.hint_recorder());
cursor
}
fn estimated(mut self, area: &Area) -> Self {
let (start, stop) = audio_sector_range(area, self.area_key.image_sectors);
let playtime = area.playtime_frames();
let lsn = if playtime == 0 || self.end >= playtime {
stop
} else {
start + (u128::from(stop - start) * u128::from(self.end) / u128::from(playtime)) as u64
};
self.area.set_progress_end(lsn);
self
}
pub fn progress(&mut self) -> Progress {
self.area.progress()
}
pub(crate) fn start_with(
area: &Area,
(first, end): (u32, u32),
image_sectors: u64,
index: Option<&AreaIndex>,
policy: SeekPolicy,
) -> Self {
let exact = match index {
Some(index) => Self::start_indexed(area, first, end, image_sectors, index),
None => Self::start(area, first, end, image_sectors),
};
let interval = index.map_or(crate::seek::DEFAULT_INTERVAL, AreaIndex::interval);
let mut cursor = exact.speculate(area, (first, end), (interval, index), policy).estimated(area);
cursor.area.record_hints(index.and_then(AreaIndex::hint_recorder));
cursor
}
fn speculate(
self,
area: &Area,
(first, end): (u32, u32),
(interval, provisional): (u32, Option<&AreaIndex>),
policy: SeekPolicy,
) -> Self {
let SeekPolicy::Speculative(mut options) = policy else { return self };
options.layout_suspect |= u64::from(area.audio_end_lsn) >= self.area_key.image_sectors;
if options.layout_suspect && options.exact_when_suspect {
return self;
}
let from = match self.area.resumed {
ResumedFrom::Checkpoint { lsn, .. } => lsn,
ResumedFrom::Start => self.area.next_lsn,
_ => return self,
};
let (start, stop) = audio_sector_range(area, self.area_key.image_sectors);
let playtime = area.playtime_frames();
if playtime == 0 {
return self;
}
let estimate = start + (u128::from(stop - start) * u128::from(first) / u128::from(playtime)) as u64;
if estimate <= from.saturating_add(options.min_gap_sectors) {
return self;
}
let hint = provisional
.and_then(|i| i.hint(first, end, playtime))
.filter(|h| h.0 > from)
.map(|(lsn, t, to, _)| (lsn, t, to, provisional.and_then(|i| i.confirmation(lsn, first))));
if let Some(p) = provisional
.and_then(|i| i.plan_provisional(first))
.filter(|&(lsn, _)| lsn > from && hint.is_none())
{
let mut area_cursor = AreaCursor::provisional_at(&self.area, p, first, interval);
if options.layout_suspect {
area_cursor.suspect = Some(crate::seek::Suspect::AreaLayout);
}
return TrackCursor { area: area_cursor, ..self };
}
let track_start = hint.filter(|h| h.3.is_none()).and_then(|(lsn, _, to, _)| {
area.tracks
.iter()
.filter(|t| t.start_frame == first)
.map(|t| u64::from(t.start_lsn))
.filter(|&l| l > lsn && l < to && (start..stop).contains(&l))
.max()
});
let knots = area
.tracks
.iter()
.map(|t| (u64::from(t.start_lsn), t.start_frame))
.filter(|&(l, _)| (start..stop).contains(&l))
.collect();
let area_cursor = AreaCursor::speculative(
self.area,
(first, self.end),
(playtime, knots),
(interval, hint, track_start),
options,
);
TrackCursor { area: area_cursor, ..self }
}
pub fn slot(&self) -> Slot {
self.area_key.slot
}
pub fn speculation(&self) -> Speculation {
self.area.speculation()
}
pub fn suspect(&self) -> Option<crate::Suspect> {
self.area.suspect()
}
pub fn claim_lsn(&self) -> Option<u64> {
self.area.claim_lsn()
}
pub fn claim(&self) -> Option<u64> {
self.area.claim()
}
pub fn resumed_from(&self) -> ResumedFrom {
self.area.resumed_from()
}
pub(crate) fn area_mut(&mut self) -> &mut AreaCursor {
&mut self.area
}
pub(crate) fn start(area: &Area, first: u32, end: u32, image_sectors: u64) -> Self {
let cursor = TrackCursor {
area: AreaCursor::new(area, image_sectors),
area_key: AreaKey::new(area, image_sectors),
next: first,
end,
channels: area.channel_count,
peeked: None,
exhausted: false,
failed: false,
missing: 0,
lost: 0,
};
cursor.estimated(area)
}
pub fn continue_to(self, area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
check_track(area, track, image_sectors)?;
Ok(self.continue_in(area, track.start_frame, track.end_frame(), (image_sectors, None), None))
}
pub fn continue_to_range(
self,
area: &Area,
first: u32,
end: u32,
image_sectors: u64,
) -> Result<Self, Error> {
check_range(area, first, end, image_sectors)?;
Ok(self.continue_in(area, first, end, (image_sectors, None), None))
}
pub(crate) fn continue_in(
self,
area: &Area,
first: u32,
end: u32,
(image_sectors, image_id): (u64, Option<u64>),
index: Option<&AreaIndex>,
) -> Self {
let opening = self.opening(area, first, image_sectors, image_id, index);
self.open_as(area, (first, end), (image_sectors, image_id), index, (opening, SeekPolicy::Exact))
}
pub(crate) fn opening(
&self,
area: &Area,
first: u32,
image_sectors: u64,
image_id: Option<u64>,
index: Option<&AreaIndex>,
) -> Opening {
if self.reuses(area, first, image_sectors, image_id, index) {
Opening::Continues
} else if index.is_some() {
Opening::FromIndex
} else {
Opening::Fresh
}
}
pub(crate) fn open_as(
self,
area: &Area,
(first, end): (u32, u32),
(image_sectors, image_id): (u64, Option<u64>),
index: Option<&AreaIndex>,
(opening, policy): (Opening, SeekPolicy),
) -> Self {
let reusable = self.reusable(area, first, image_sectors, image_id);
match (opening, index) {
(Opening::Continues, _) if reusable => {
let mut next = TrackCursor { next: first, end, missing: 0, lost: 0, ..self };
next.area.restart_progress();
next.estimated(area)
}
(Opening::Continues | Opening::FromIndex, Some(index)) => {
let mut next = Self::start_with(area, (first, end), image_sectors, Some(index), policy);
if reusable
&& next.area.speculation() == Speculation::Exact
&& self.area.speculation() == Speculation::Exact
{
next.area.carry_counts(&self.area);
}
next
}
_ => Self::start_with(area, (first, end), image_sectors, None, policy),
}
}
fn reuses(
&self,
area: &Area,
first: u32,
image_sectors: u64,
image_id: Option<u64>,
index: Option<&AreaIndex>,
) -> bool {
self.reusable(area, first, image_sectors, image_id)
&& (self.area.damaged().is_some() || index.is_none_or(|index| {
let ahead = 2 * u64::from(index.interval());
index.plan_lsn(first).is_some_and(|lsn| lsn <= self.area.scan_lsn().saturating_add(ahead))
}))
}
fn reusable(&self, area: &Area, first: u32, image_sectors: u64, image_id: Option<u64>) -> bool {
let other_image = matches!((self.area.image_id, image_id), (Some(a), Some(b)) if a != b);
!(self.failed
|| other_image
|| self.area_key != AreaKey::new(area, image_sectors)
|| first < self.next)
}
pub fn channels(&self) -> u8 {
self.channels
}
pub fn dst_equivalent<'c>(&self, content: &'c FrameContent) -> std::borrow::Cow<'c, [u8]> {
content.equivalent_checked(self.channels)
}
pub fn missing_frames(&self) -> u64 {
self.missing
}
pub fn lost_frames(&self) -> u64 {
self.lost
}
pub fn range(&self) -> (u32, u32) {
(self.next, self.end)
}
pub fn malformed_sectors(&self) -> u64 {
self.area.malformed_sectors()
}
pub fn warnings(&self) -> &[Warning] {
self.area.warnings()
}
pub fn next_frame<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<TrackFrame, Error>> {
if self.next >= self.end {
return None;
}
if let Err(e) = image.check_cancel() {
return Some(Err(e));
}
let t = self.next;
while !self.exhausted && self.peeked.as_ref().is_none_or(|f| f.number < t) {
match self.area.next_frame(image) {
Some(Ok(f)) => self.peeked = Some(f),
Some(Err(Error::Cancelled)) => return Some(Err(Error::Cancelled)),
Some(Err(e)) => {
self.next = self.end;
self.failed = true;
return Some(Err(e));
}
None => {
self.peeked = None;
self.exhausted = true;
}
}
}
self.next += 1;
if self.next >= self.end {
self.area.progress_done();
self.area.flush_hints();
}
if let Some(claim) = &self.area.claim {
claim.returned(t);
}
let content = match self.peeked.take_if(|f| f.number == t) {
Some(f) => match f.kind {
FrameKind::Dsd => FrameContent::Dsd(f.data),
FrameKind::Dst => FrameContent::Dst(f.data),
},
None => {
let from = match &self.peeked {
Some(f) => f.lost_from,
None => self.area.demux.lost_from(),
};
if from.is_some_and(|from| from <= t) {
self.lost += 1;
return Some(Ok(TrackFrame::lost(t)));
}
self.missing += 1;
FrameContent::Missing
}
};
Some(Ok(TrackFrame { number: t, content, lost: false }))
}
}
#[derive(Debug)]
pub struct TrackFrames<'a, R> {
image: &'a mut Image<R>,
cursor: TrackCursor,
seek: Option<&'a SeekIndexes>,
}
impl<'a, R: Read + Seek> TrackFrames<'a, R> {
pub(crate) fn with_cursor(
image: &'a mut Image<R>,
cursor: TrackCursor,
seek: Option<&'a SeekIndexes>,
) -> Self {
TrackFrames { image, cursor, seek }
}
pub fn into_cursor(self) -> TrackCursor {
self.cursor
}
pub fn channels(&self) -> u8 {
self.cursor.channels()
}
pub fn missing_frames(&self) -> u64 {
self.cursor.missing_frames()
}
pub fn lost_frames(&self) -> u64 {
self.cursor.lost_frames()
}
pub fn dst_equivalent<'c>(&self, content: &'c FrameContent) -> std::borrow::Cow<'c, [u8]> {
self.cursor.dst_equivalent(content)
}
pub fn range(&self) -> (u32, u32) {
self.cursor.range()
}
pub fn malformed_sectors(&self) -> u64 {
self.cursor.malformed_sectors()
}
pub fn warnings(&self) -> &[Warning] {
self.cursor.warnings()
}
pub fn speculation(&self) -> Speculation {
self.cursor.speculation()
}
pub fn suspect(&self) -> Option<crate::Suspect> {
self.cursor.suspect()
}
pub fn claim_lsn(&self) -> Option<u64> {
self.cursor.claim_lsn()
}
pub fn claim(&self) -> Option<u64> {
self.cursor.claim()
}
pub fn progress(&mut self) -> Progress {
self.cursor.progress()
}
}
impl<R: Read + Seek> Iterator for TrackFrames<'_, R> {
type Item = Result<TrackFrame, Error>;
fn next(&mut self) -> Option<Self::Item> {
let frame = self.cursor.next_frame(self.image);
if let Some(seek) = self.seek {
seek.absorb(&mut self.cursor.area, self.image.id());
}
frame
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FrameStatus {
Dsd,
Decoded,
Missing,
Invalid(DstError),
Lost,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioFrame {
pub number: u32,
pub status: FrameStatus,
pub data: Vec<u8>,
}
pub fn decode_frame(decoder: &mut DstDecoder, frame: TrackFrame, channels: u8) -> Result<AudioFrame, Error> {
if !(1..=MAX_CHANNELS).contains(&channels) {
return Err(Error::InvalidArgument("channel count must be 1 to 6"));
}
if let FrameContent::Dsd(data) = &frame.content {
if data.len() != usize::from(channels) * FRAME_BYTES_PER_CHANNEL {
return Err(Error::InvalidArgument("a plain DSD frame must be channels x 4704 bytes"));
}
}
Ok(decode_checked(decoder, frame, channels))
}
fn decode_checked(decoder: &mut DstDecoder, frame: TrackFrame, channels: u8) -> AudioFrame {
let (status, data) = match frame.content {
FrameContent::Dsd(data) => (FrameStatus::Dsd, data),
FrameContent::Missing if frame.lost => (FrameStatus::Lost, fill_frame(channels, MISSING_FILL)),
FrameContent::Missing => (FrameStatus::Missing, fill_frame(channels, MISSING_FILL)),
FrameContent::Dst(bytes) => {
let mut out = vec![0u8; usize::from(channels) * FRAME_BYTES_PER_CHANNEL];
match decoder.decode(&bytes, channels, &mut out) {
Ok(()) => (FrameStatus::Decoded, out),
Err(e) => {
debug_assert_ne!(
e,
DstError::InvalidArguments,
"decoder arguments checked by check_track"
);
out.fill(INVALID_FILL);
(FrameStatus::Invalid(e), out)
}
}
}
};
AudioFrame { number: frame.number, status, data }
}
fn decode_dst_run(
decoder: &mut DstDecoder,
frames: Vec<TrackFrame>,
channels: u8,
log: &Log,
) -> Vec<AudioFrame> {
if let (Some(first), Some(last)) = (frames.first(), frames.last()) {
sb_log!(
log,
Trace,
"decoding DST frames {}..={} on thread {:?}",
first.number,
last.number,
std::thread::current().id()
);
}
let size = usize::from(channels) * FRAME_BYTES_PER_CHANNEL;
let mut outs = vec![vec![0u8; size]; frames.len()];
let results = {
let bytes: Vec<&[u8]> = frames
.iter()
.map(|f| match &f.content {
FrameContent::Dst(b) => b.as_slice(),
_ => &[],
})
.collect();
let mut slices: Vec<&mut [u8]> = outs.iter_mut().map(Vec::as_mut_slice).collect();
decoder.decode_many(&bytes, channels, &mut slices)
};
frames
.into_iter()
.zip(outs)
.zip(results)
.map(|((frame, mut out), result)| {
let status = match result {
Ok(()) => FrameStatus::Decoded,
Err(e) => {
debug_assert_ne!(
e,
DstError::InvalidArguments,
"decoder arguments checked by check_track"
);
out.fill(INVALID_FILL);
FrameStatus::Invalid(e)
}
};
AudioFrame { number: frame.number, status, data: out }
})
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Stored {
Dst(Vec<u8>),
Dsd,
Missing,
}
impl Stored {
pub fn content(&self, frame: &AudioFrame) -> FrameContent {
match self {
Stored::Dst(bytes) => FrameContent::Dst(bytes.clone()),
Stored::Dsd => FrameContent::Dsd(frame.data.clone()),
Stored::Missing => FrameContent::Missing,
}
}
pub fn bytes<'a>(&'a self, frame: &'a AudioFrame) -> &'a [u8] {
match self {
Stored::Dst(bytes) => bytes,
Stored::Dsd => &frame.data,
Stored::Missing => &[],
}
}
}
#[derive(Debug)]
pub struct TrackAudioCursor {
frames: TrackCursor,
#[cfg(feature = "parallel")]
decode_on: DecodeOn,
dst_lanes: Option<usize>,
decoder: DstDecoder,
ahead: VecDeque<Pending>,
ready: VecDeque<AudioFrame>,
pending_error: Option<Error>,
stored: Option<VecDeque<Stored>>,
missing: u64,
invalid: u64,
lost: u64,
missing_lines: LineCap,
invalid_lines: LineCap,
lost_lines: LineCap,
}
#[derive(Debug)]
enum Pending {
Here(TrackFrame),
#[cfg(feature = "parallel")]
Pool(std::sync::Arc<pool::Job>, usize),
}
impl TrackAudioCursor {
pub fn new(area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
Ok(Self::from_frames(TrackCursor::new(area, track, image_sectors)?))
}
pub fn open_range(
area: &Area,
first: u32,
end: u32,
image_sectors: u64,
options: CursorOptions<'_>,
) -> Result<Self, Error> {
Ok(Self::from_frames(TrackCursor::open_range(area, first, end, image_sectors, options)?))
}
pub fn resumed_from(&self) -> ResumedFrom {
self.frames.resumed_from()
}
pub fn slot(&self) -> Slot {
self.frames.slot()
}
pub fn speculation(&self) -> Speculation {
self.frames.speculation()
}
pub fn suspect(&self) -> Option<crate::Suspect> {
self.frames.suspect()
}
pub fn claim_lsn(&self) -> Option<u64> {
self.frames.claim_lsn()
}
pub fn claim(&self) -> Option<u64> {
self.frames.claim()
}
pub fn continue_to(self, area: &Area, track: &Track, image_sectors: u64) -> Result<Self, Error> {
check_track(area, track, image_sectors)?;
Ok(self.continue_in(area, track.start_frame, track.end_frame(), (image_sectors, None), None))
}
pub fn continue_to_range(
self,
area: &Area,
first: u32,
end: u32,
image_sectors: u64,
) -> Result<Self, Error> {
check_range(area, first, end, image_sectors)?;
Ok(self.continue_in(area, first, end, (image_sectors, None), None))
}
pub(crate) fn continue_in(
self,
area: &Area,
first: u32,
end: u32,
image: (u64, Option<u64>),
index: Option<&AreaIndex>,
) -> Self {
let opening = self.opening(area, first, image, index);
self.open_as(area, (first, end), image, index, (opening, SeekPolicy::Exact))
}
pub(crate) fn opening(
&self,
area: &Area,
first: u32,
(image_sectors, image_id): (u64, Option<u64>),
index: Option<&AreaIndex>,
) -> Opening {
match self.pending_error {
Some(_) if index.is_some() => Opening::FromIndex,
Some(_) => Opening::Fresh,
None => self.frames.opening(area, first, image_sectors, image_id, index),
}
}
pub(crate) fn open_as(
self,
area: &Area,
range: (u32, u32),
image: (u64, Option<u64>),
index: Option<&AreaIndex>,
opening: (Opening, SeekPolicy),
) -> Self {
let mut frames = self.frames;
if self.pending_error.is_some() {
frames.failed = true;
}
let mut next = Self::from_frames(frames.open_as(area, range, image, index, opening));
#[cfg(feature = "parallel")]
{
next.decode_on = self.decode_on;
}
next.dst_lanes = self.dst_lanes;
next.stored = self.stored.map(|_| VecDeque::new());
next
}
pub(crate) fn from_frames(frames: TrackCursor) -> Self {
TrackAudioCursor {
frames,
#[cfg(feature = "parallel")]
decode_on: DecodeOn::default(),
dst_lanes: None,
decoder: DstDecoder::new(),
ahead: VecDeque::new(),
ready: VecDeque::new(),
pending_error: None,
stored: None,
missing: 0,
invalid: 0,
lost: 0,
missing_lines: LineCap::default(),
invalid_lines: LineCap::default(),
lost_lines: LineCap::default(),
}
}
pub fn channels(&self) -> u8 {
self.frames.channels()
}
pub fn missing_frames(&self) -> u64 {
self.missing
}
pub fn invalid_dst_frames(&self) -> u64 {
self.invalid
}
pub fn lost_frames(&self) -> u64 {
self.lost
}
pub fn malformed_sectors(&self) -> u64 {
self.frames.malformed_sectors()
}
pub fn warnings(&self) -> &[Warning] {
self.frames.warnings()
}
pub fn progress(&mut self) -> Progress {
self.frames.progress()
}
#[cfg(feature = "parallel")]
pub fn decode_on(&self) -> &DecodeOn {
&self.decode_on
}
#[cfg(feature = "parallel")]
pub fn set_decode_on(&mut self, on: DecodeOn) {
self.decode_on = on;
}
pub fn with_dst_lanes(mut self, lanes: usize) -> Result<Self, Error> {
if !(1..=crate::dst::MAX_LANES).contains(&lanes) {
return Err(Error::DstLanesInvalid { lanes });
}
self.dst_lanes = Some(lanes);
Ok(self)
}
pub fn dst_lanes(&self) -> Option<usize> {
self.dst_lanes
}
fn group(&self, channels: u8) -> usize {
self.dst_lanes.unwrap_or_else(|| crate::dst::lanes(channels))
}
fn window(&self, channels: u8) -> usize {
let group = self.group(channels);
#[cfg(feature = "parallel")]
{
let threads = match &self.decode_on {
DecodeOn::CurrentPool => rayon::current_num_threads(),
DecodeOn::Pool(pool) => pool.current_num_threads(),
DecodeOn::CallingThread => 1,
};
match threads {
0 | 1 => group,
n => (PARALLEL_FRAMES_PER_THREAD * n).min(MAX_PARALLEL_BATCH),
}
}
#[cfg(not(feature = "parallel"))]
{
group
}
}
fn fill<R: Read + Seek>(&mut self, image: &mut Image<R>) -> bool {
let channels = self.channels();
let window = self.window(channels);
let group = self.group(channels);
let held = self.ahead.len() + self.ready.len();
if self.pending_error.is_some() || (held > 0 && held + group > window) {
return false;
}
let mut room = (window - held) / group * group;
#[cfg(feature = "parallel")]
let mut batch: Vec<TrackFrame> = Vec::with_capacity(group);
let mut cancelled = false;
while self.pending_error.is_none() && room > 0 {
let next = self.frames.next_frame(image);
if let (Some(stored), Some(Ok(f))) = (self.stored.as_mut(), &next) {
stored.push_back(match &f.content {
FrameContent::Dst(bytes) => Stored::Dst(bytes.clone()),
FrameContent::Dsd(_) => Stored::Dsd,
FrameContent::Missing => Stored::Missing,
});
}
match next {
#[cfg(feature = "parallel")]
Some(Ok(f @ TrackFrame { content: FrameContent::Dst(_), .. })) if window > group => {
batch.push(f);
if batch.len() == group {
self.spawn_batch(&mut batch, channels, image.log());
}
}
Some(Ok(f)) => {
#[cfg(feature = "parallel")]
self.spawn_batch(&mut batch, channels, image.log());
self.ahead.push_back(Pending::Here(f));
}
Some(Err(Error::Cancelled)) => {
cancelled = true;
break;
}
Some(Err(e)) => {
#[cfg(feature = "parallel")]
self.spawn_batch(&mut batch, channels, image.log());
self.pending_error = Some(e);
}
None => break,
}
room -= 1;
}
#[cfg(feature = "parallel")]
self.spawn_batch(&mut batch, channels, image.log());
debug_assert!(self.stored_in_step(), "stored content out of step after fill");
cancelled
}
#[cfg(feature = "parallel")]
fn spawn_batch(&mut self, batch: &mut Vec<TrackFrame>, channels: u8, log: &Log) {
if batch.is_empty() {
return;
}
let n = batch.len();
let pool = match &self.decode_on {
DecodeOn::Pool(pool) => Some(&**pool),
DecodeOn::CurrentPool | DecodeOn::CallingThread => None,
};
let job = pool::Job::spawn(std::mem::take(batch), channels, log.clone(), pool);
self.ahead.extend((0..n).map(|i| Pending::Pool(std::sync::Arc::clone(&job), i)));
}
pub fn next_frame<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<AudioFrame, Error>> {
let frame = self.next_decoded(image);
if let (Some(Ok(_)), Some(stored)) = (&frame, self.stored.as_mut()) {
let popped = stored.pop_front();
debug_assert!(popped.is_some() && self.stored_in_step(), "stored content out of step");
}
frame
}
fn stored_in_step(&self) -> bool {
self.stored.as_ref().is_none_or(|s| s.len() == self.ready.len() + self.ahead.len())
}
pub fn keep_stored(&mut self) -> Result<(), Error> {
if self.stored.is_some() {
return Ok(());
}
if !(self.ready.is_empty() && self.ahead.is_empty()) {
return Err(Error::InvalidArgument("stored content is kept only from before the first read"));
}
self.stored = Some(VecDeque::new());
Ok(())
}
pub fn keeps_stored(&self) -> bool {
self.stored.is_some()
}
pub fn next_frame_with_stored<R: Read + Seek>(
&mut self,
image: &mut Image<R>,
) -> Option<Result<(AudioFrame, Stored), Error>> {
if self.stored.is_none() {
return Some(Err(Error::InvalidArgument("the cursor does not keep stored content")));
}
let frame = match self.next_decoded(image)? {
Ok(f) => f,
Err(e) => return Some(Err(e)),
};
let popped = self.stored.as_mut().and_then(VecDeque::pop_front);
debug_assert!(popped.is_some() && self.stored_in_step(), "stored content out of step");
Some(match popped {
Some(stored) => Ok((frame, stored)),
None => Err(Error::Io(std::io::Error::other("internal error: stored content out of step"))),
})
}
pub fn dst_equivalent<'c>(&self, content: &'c FrameContent) -> std::borrow::Cow<'c, [u8]> {
self.frames.dst_equivalent(content)
}
fn next_decoded<R: Read + Seek>(&mut self, image: &mut Image<R>) -> Option<Result<AudioFrame, Error>> {
if let Err(e) = image.check_cancel() {
return Some(Err(e));
}
let mut frame = if let Some(f) = self.ready.pop_front() {
f
} else {
if self.fill(image) {
return Some(Err(Error::Cancelled));
}
match self.ahead.pop_front() {
Some(Pending::Here(f)) => {
let channels = self.channels();
if matches!(f.content, FrameContent::Dst(_)) {
let mut run = vec![f];
let group = self.group(channels);
while run.len() < group {
match self.ahead.front() {
Some(Pending::Here(TrackFrame { content: FrameContent::Dst(_), .. })) => {
if let Some(Pending::Here(g)) = self.ahead.pop_front() {
run.push(g);
}
}
_ => break,
}
}
let mut decoded =
decode_dst_run(&mut self.decoder, run, channels, image.log()).into_iter();
let first = decoded.next()?;
self.ready.extend(decoded);
first
} else {
decode_checked(&mut self.decoder, f, channels)
}
}
#[cfg(feature = "parallel")]
Some(Pending::Pool(job, i)) => job.wait(i),
None => return self.pending_error.take().map(Err),
}
};
let log = image.log();
let level = match frame.status {
FrameStatus::Missing | FrameStatus::Invalid(_) | FrameStatus::Lost => Level::Warn,
FrameStatus::Dsd | FrameStatus::Decoded => Level::Trace,
};
if log.enabled(level) {
let (number, status, slot) = (frame.number, frame.status, self.frames.area.slot);
self.ready.push_front(frame);
match status {
FrameStatus::Missing => {
if self.missing_lines.admit(log, level, slot.name(), "missing-frame") {
sb_log!(log, Warn, "area {slot} frame {number}: missing, filled with 0x69 (4.6)");
}
}
FrameStatus::Invalid(e) => {
if self.invalid_lines.admit(log, level, slot.name(), "invalid-DST-frame") {
sb_log!(
log,
Warn,
"area {slot} frame {number}: invalid DST frame ({e}, rule {} of 5.6), filled with 0x55 \
(4.6)",
e.rule()
);
}
}
FrameStatus::Lost => {
if self.lost_lines.admit(log, level, slot.name(), "lost-frame") {
sb_log!(
log,
Warn,
"area {slot} frame {number}: lost to unreadable sectors, filled with 0x69"
);
}
}
FrameStatus::Dsd | FrameStatus::Decoded => {
sb_log!(log, Trace, "area {slot} frame {number}: {status:?}");
}
}
frame = self.ready.pop_front()?;
}
match frame.status {
FrameStatus::Missing => self.missing += 1,
FrameStatus::Invalid(_) => self.invalid += 1,
FrameStatus::Lost => self.lost += 1,
FrameStatus::Dsd | FrameStatus::Decoded => {}
}
Some(Ok(frame))
}
}
pub trait SeekCursor: sealed::Sealed {}
pub(crate) mod sealed {
pub trait Sealed {
fn area_cursor_mut(&mut self) -> &mut super::AreaCursor;
}
}
impl SeekCursor for AreaCursor {}
impl SeekCursor for TrackCursor {}
impl SeekCursor for TrackAudioCursor {}
impl sealed::Sealed for AreaCursor {
fn area_cursor_mut(&mut self) -> &mut AreaCursor {
self
}
}
impl sealed::Sealed for TrackCursor {
fn area_cursor_mut(&mut self) -> &mut AreaCursor {
&mut self.area
}
}
impl sealed::Sealed for TrackAudioCursor {
fn area_cursor_mut(&mut self) -> &mut AreaCursor {
&mut self.frames.area
}
}
#[cfg(feature = "parallel")]
mod pool {
use std::any::Any;
use std::cell::RefCell;
use std::panic::AssertUnwindSafe;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use super::{AudioFrame, TrackFrame, decode_dst_run};
use crate::dst::DstDecoder;
use crate::log::{Log, sb_log};
thread_local! {
static DECODER: RefCell<DstDecoder> = RefCell::new(DstDecoder::new());
}
#[derive(Debug, Default)]
pub(super) struct Job {
state: Mutex<State>,
done: Condvar,
}
type Panic = Option<Box<dyn Any + Send>>;
#[derive(Debug, Default)]
struct State {
result: Option<Result<Vec<Option<AudioFrame>>, Panic>>,
waiting: bool,
}
impl Job {
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) fn spawn(
frames: Vec<TrackFrame>,
channels: u8,
log: Log,
pool: Option<&rayon::ThreadPool>,
) -> Arc<Job> {
let job = Arc::new(Job::default());
let out = Arc::clone(&job);
let work = move || {
if Arc::strong_count(&out) == 1 {
return;
}
let range = (frames.first().map(|f| f.number), frames.last().map(|f| f.number));
let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
DECODER.with(|d| match d.try_borrow_mut() {
Ok(mut d) => decode_dst_run(&mut d, frames, channels, &log),
Err(_) => decode_dst_run(&mut DstDecoder::new(), frames, channels, &log),
})
}));
if result.is_err() {
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
sb_log!(
&log,
Error,
"panic while decoding DST frames {:?}..={:?} on a pool thread; resumed on the caller",
range.0,
range.1
);
}));
DECODER.with(|d| {
if let Ok(mut d) = d.try_borrow_mut() {
*d = DstDecoder::new();
}
});
}
let result = result.map(|v| v.into_iter().map(Some).collect()).map_err(Some);
let mut state = out.lock();
state.result = Some(result);
if state.waiting {
out.done.notify_one();
}
};
match pool {
Some(pool) => pool.spawn(work),
None => rayon::spawn(work),
}
job
}
pub(super) fn wait(&self, i: usize) -> AudioFrame {
loop {
if let Some(f) = Self::take(&mut self.lock(), i) {
return f;
}
if rayon::yield_now() != Some(rayon::Yield::Executed) {
let mut state = self.lock();
state.waiting = true;
loop {
if let Some(f) = Self::take(&mut state, i) {
return f;
}
state = self.done.wait(state).unwrap_or_else(PoisonError::into_inner);
}
}
}
}
fn take(state: &mut State, i: usize) -> Option<AudioFrame> {
match state.result.as_mut()? {
Ok(frames) => frames.get_mut(i).and_then(Option::take),
Err(panic) => std::panic::resume_unwind(
panic.take().unwrap_or_else(|| Box::new("a group of DST frames panicked while decoding")),
),
}
}
}
}
#[derive(Debug)]
pub struct TrackAudio<'a, R> {
image: &'a mut Image<R>,
cursor: TrackAudioCursor,
seek: Option<&'a SeekIndexes>,
}
impl<'a, R: Read + Seek> TrackAudio<'a, R> {
pub(crate) fn with_cursor(
image: &'a mut Image<R>,
cursor: TrackAudioCursor,
seek: Option<&'a SeekIndexes>,
) -> Self {
TrackAudio { image, cursor, seek }
}
pub fn into_cursor(self) -> TrackAudioCursor {
self.cursor
}
pub fn channels(&self) -> u8 {
self.cursor.channels()
}
pub fn missing_frames(&self) -> u64 {
self.cursor.missing_frames()
}
pub fn invalid_dst_frames(&self) -> u64 {
self.cursor.invalid_dst_frames()
}
pub fn lost_frames(&self) -> u64 {
self.cursor.lost_frames()
}
pub fn malformed_sectors(&self) -> u64 {
self.cursor.malformed_sectors()
}
pub fn warnings(&self) -> &[Warning] {
self.cursor.warnings()
}
pub fn speculation(&self) -> Speculation {
self.cursor.speculation()
}
pub fn suspect(&self) -> Option<crate::Suspect> {
self.cursor.suspect()
}
pub fn claim_lsn(&self) -> Option<u64> {
self.cursor.claim_lsn()
}
pub fn claim(&self) -> Option<u64> {
self.cursor.claim()
}
pub fn progress(&mut self) -> Progress {
self.cursor.progress()
}
}
impl<R: Read + Seek> TrackAudio<'_, R> {
pub fn keep_stored(&mut self) -> Result<(), Error> {
self.cursor.keep_stored()
}
pub fn next_with_stored(&mut self) -> Option<Result<(AudioFrame, Stored), Error>> {
let frame = self.cursor.next_frame_with_stored(self.image);
if let Some(seek) = self.seek {
seek.absorb(&mut self.cursor.frames.area, self.image.id());
}
frame
}
}
impl<R: Read + Seek> Iterator for TrackAudio<'_, R> {
type Item = Result<AudioFrame, Error>;
fn next(&mut self) -> Option<Self::Item> {
let frame = self.cursor.next_frame(self.image);
if let Some(seek) = self.seek {
seek.absorb(&mut self.cursor.frames.area, self.image.id());
}
frame
}
}
pub fn fill_frame(channels: u8, value: u8) -> Vec<u8> {
vec![value; usize::from(channels) * FRAME_BYTES_PER_CHANNEL]
}
pub fn deinterleave(frame: &[u8], channels: u8, channel: u8, out: &mut [u8]) -> Result<(), Error> {
let c = usize::from(channels);
if c == 0
|| channel >= channels
|| frame.len() != c * FRAME_BYTES_PER_CHANNEL
|| out.len() != FRAME_BYTES_PER_CHANNEL
{
return Err(Error::InvalidArgument("frame, channel or output size mismatch"));
}
for (o, chunk) in out.iter_mut().zip(frame.chunks_exact(c)) {
*o = chunk.get(usize::from(channel)).copied().unwrap_or(0);
}
Ok(())
}
pub(crate) fn find_track(areas: &[Area], slot: Slot, number: u32) -> Result<(&Area, &Track), Error> {
let area = areas.iter().find(|a| a.slot == slot).ok_or(Error::NoSuchArea(slot))?;
let track = area.track(number).ok_or(Error::NoSuchTrack { slot, track: number })?;
Ok((area, track))
}
#[cfg(test)]
pub(crate) mod tests_support {
pub(crate) fn area(sectors: u32) -> (crate::Image<std::io::Cursor<Vec<u8>>>, crate::Area, crate::Track) {
super::tests::malformed_area(sectors, sectors)
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::toc::Timecode;
fn sector(header: u8, packets: &[(bool, u8, u16)], records: &[[u8; 4]], dst: bool) -> [u8; 2048] {
let mut s = [0u8; 2048];
s[0] = header;
let mut at = 1;
for &(start, ty, len) in packets {
let w = (u16::from(start) << 15) | (u16::from(ty) << 11) | len;
s[at..at + 2].copy_from_slice(&w.to_be_bytes());
at += 2;
}
for r in records {
let n = if dst { 4 } else { 3 };
s[at..at + n].copy_from_slice(&r[..n]);
at += n;
}
s
}
#[test]
fn dst_frame_across_two_sectors() {
let mut d = Demuxer::new(2);
let s1 = sector(1 | (1 << 2) | (1 << 5), &[(true, 2, 100)], &[[0, 0, 5, 2 << 2]], true);
let s2 = sector(1 | (1 << 5), &[(false, 2, 50)], &[], true);
assert!(!d.push_sector(&s1));
assert!(!d.push_sector(&s2));
assert!(d.pop().is_none());
d.finish();
let f = d.pop().unwrap();
assert_eq!((f.number, f.kind, f.data.len()), (5, FrameKind::Dst, 150));
}
#[test]
fn overrun_and_backwards_timecodes() {
let mut d = Demuxer::new(2);
let over =
sector(1 | (1 << 2) | (2 << 5), &[(true, 2, 2000), (false, 2, 100)], &[[0, 0, 1, 1 << 2]], true);
assert!(d.push_sector(&over));
d.finish();
assert_eq!(d.pop().map(|f| f.number), Some(1));
let mut d = Demuxer::new(2);
let a = sector(1 | (1 << 2) | (1 << 5), &[(true, 2, 10)], &[[0, 0, 9, 1 << 2]], true);
let b = sector(1 | (1 << 2) | (1 << 5), &[(true, 2, 10)], &[[0, 0, 3, 1 << 2]], true);
d.push_sector(&a);
d.push_sector(&b);
d.finish();
assert_eq!(d.pop().map(|f| f.number), Some(9));
assert!(d.pop().is_none());
}
#[test]
fn start_without_record_is_malformed() {
let mut d = Demuxer::new(2);
let s = sector(1 << 5, &[(true, 2, 10)], &[], false);
assert!(d.push_sector(&s));
d.finish();
assert!(d.pop().is_none());
}
#[cfg(feature = "parallel")]
#[test]
#[cfg_attr(miri, ignore = "starts 67 threads")]
fn parallel_window_is_capped() {
let (_, area, track) = malformed_area(1, 1);
let mut cursor = TrackAudioCursor::new(&area, &track, 1).unwrap();
let pool = |n| std::sync::Arc::new(rayon::ThreadPoolBuilder::new().num_threads(n).build().unwrap());
let (wide, narrow, single) = (pool(64), pool(2), pool(1));
wide.install(|| assert_eq!(cursor.window(2), MAX_PARALLEL_BATCH));
narrow.install(|| assert_eq!(cursor.window(2), 2 * PARALLEL_FRAMES_PER_THREAD));
single.install(|| assert_eq!(cursor.window(2), crate::dst::lanes(2)));
cursor.set_decode_on(DecodeOn::Pool(std::sync::Arc::clone(&narrow)));
wide.install(|| assert_eq!(cursor.window(2), 2 * PARALLEL_FRAMES_PER_THREAD));
assert_eq!(cursor.window(2), 2 * PARALLEL_FRAMES_PER_THREAD);
cursor.set_decode_on(DecodeOn::Pool(single));
wide.install(|| assert_eq!(cursor.window(2), crate::dst::lanes(2)));
cursor.set_decode_on(DecodeOn::CallingThread);
wide.install(|| assert_eq!(cursor.window(2), crate::dst::lanes(2)));
let next = cursor.continue_to(&area, &track, 1).unwrap();
assert!(matches!(next.decode_on(), DecodeOn::CallingThread));
let bound = MAX_PARALLEL_BATCH * (MAX_FRAME_BYTES + 6 * FRAME_BYTES_PER_CHANNEL);
assert!(bound <= 48_100_000, "{bound}");
}
pub(crate) fn malformed_area(
sectors: u32,
frames: u32,
) -> (Image<std::io::Cursor<Vec<u8>>>, Area, Track) {
area_of(sectors, frames, |_, s| s[..3].copy_from_slice(&[1 << 5, 0x17, 0xFF]))
}
fn incomplete_frames_area(sectors: u32, frames: u32) -> (Image<std::io::Cursor<Vec<u8>>>, Area, Track) {
area_of(sectors, frames, |i, s| {
let (m, sec, f) = ((i / 4500) as u8, (i / 75 % 60) as u8, (i % 75) as u8);
s[..6].copy_from_slice(&[(1 << 5) | (1 << 2), 0x90, 10, m, sec, f]);
})
}
fn area_of(
sectors: u32,
frames: u32,
fill: impl Fn(usize, &mut [u8]),
) -> (Image<std::io::Cursor<Vec<u8>>>, Area, Track) {
use crate::toc::{AreaKind, AreaText, Timecode, TrackText, Version};
let mut bytes = vec![0u8; sectors as usize * SECTOR_SIZE];
for (i, s) in bytes.chunks_exact_mut(SECTOR_SIZE).enumerate() {
fill(i, s);
}
let image = Image::options()
.with_format(crate::SectorFormat::Plain)
.open(std::io::Cursor::new(bytes))
.unwrap();
let playtime = Timecode {
minutes: (frames / 4500) as u8,
seconds: (frames / 75 % 60) as u8,
frames: (frames % 75) as u8,
};
let track = Track {
number: 1,
start_lsn: 0,
length_sectors: sectors,
start_frame: 0,
duration_frames: frames,
start_flags: 0,
duration_flags: 0,
isrc: None,
genre: None,
text: TrackText::default(),
};
let area = Area {
slot: Slot::TwoChannel,
kind: AreaKind::TwoChannel,
version: Version { major: 1, minor: 20 },
toc_lsn: 0,
toc_sectors: 0,
max_byte_rate: 0,
sample_frequency_code: 4,
frame_format: 0,
channel_count: 2,
area_config: 0,
max_available_channels: 2,
area_mute_flags: 0,
track_attribute: 0,
playtime,
track_offset: 0,
audio_start_lsn: 0,
audio_end_lsn: sectors - 1,
text_channel_count: 0,
locales: Vec::new(),
text_charset: 0,
text: AreaText::default(),
tracks: vec![track.clone()],
};
(image, area, track)
}
type Lines = std::sync::Arc<std::sync::Mutex<Vec<String>>>;
fn recorder(level: Level) -> (Log, Lines) {
let lines = Lines::default();
let sink = std::sync::Arc::clone(&lines);
(Log::new(level, move |_, m| sink.lock().unwrap().push(m.to_string())), lines)
}
#[test]
#[cfg_attr(miri, ignore = "decodes thousands of frames")]
fn problem_lines_are_capped() {
let n = MAX_PROBLEM_LINES + 100;
let (mut image, area, track) = malformed_area(n as u32, n as u32);
let (log, lines) = recorder(Level::Warn);
image.set_log(log);
let mut cursor = TrackAudioCursor::new(&area, &track, image.sector_count()).unwrap();
let mut frames = 0;
while let Some(f) = cursor.next_frame(&mut image) {
assert_eq!(f.unwrap().status, FrameStatus::Missing);
frames += 1;
}
assert_eq!((frames, cursor.missing_frames()), (n, n as u64));
assert_eq!(cursor.malformed_sectors(), n as u64);
let lines = lines.lock().unwrap();
let malformed: Vec<_> = lines.iter().filter(|m| m.contains(": audio-sector-malformed: ")).collect();
let missing = lines.iter().filter(|m| m.contains(": missing, filled")).count();
assert_eq!((malformed.len(), missing), (MAX_PROBLEM_LINES, MAX_PROBLEM_LINES));
let listed: Vec<_> = cursor
.warnings()
.iter()
.map(|w| {
format!(
"area 2ch audio sector LSN {}: audio-sector-malformed: packet 0 of 1 (2047 bytes at 3) overruns the sector",
w.lsn.unwrap()
)
})
.collect();
assert_eq!(malformed.into_iter().cloned().collect::<Vec<_>>(), listed);
for what in ["audio-sector-malformed", "missing-frame"] {
let suppressed =
format!("area 2ch: further {what} lines suppressed (at most {MAX_PROBLEM_LINES} per cursor)");
assert_eq!(lines.iter().filter(|m| **m == suppressed).count(), 1, "{what}");
}
let (mut image, area, track) = incomplete_frames_area(n as u32, n as u32);
let (log, lines) = recorder(Level::Warn);
image.set_log(log);
let mut cursor = TrackAudioCursor::new(&area, &track, image.sector_count()).unwrap();
while let Some(f) = cursor.next_frame(&mut image) {
assert_eq!(f.unwrap().status, FrameStatus::Missing);
}
assert_eq!(cursor.malformed_sectors(), 0);
let lines = lines.lock().unwrap();
let discarded: Vec<_> =
lines.iter().filter(|m| m.contains(": discarded, incomplete (Dsd, 10 bytes")).collect();
assert_eq!(discarded.len(), MAX_PROBLEM_LINES);
assert_eq!(
discarded[0],
"area 2ch frame 0 (from LSN 0): discarded, incomplete (Dsd, 10 bytes; 4.4.2)"
);
let suppressed = format!(
"area 2ch: further discarded-frame lines suppressed (at most {MAX_PROBLEM_LINES} per cursor)"
);
assert_eq!(lines.iter().filter(|m| **m == suppressed).count(), 1);
let at = lines.iter().position(|m| *m == suppressed).unwrap();
assert!(lines[..at].iter().filter(|m| m.contains(": discarded,")).count() == MAX_PROBLEM_LINES);
}
#[test]
fn a_frame_survives_a_sink_that_panics() {
let (mut image, area, track) = malformed_area(1, 3);
let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = std::sync::Arc::clone(&calls);
image.set_log(Log::new(Level::Warn, move |_, m| {
if m.to_string().contains("frame 1: missing")
&& counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0
{
panic!("sink");
}
}));
let mut cursor = TrackAudioCursor::new(&area, &track, image.sector_count()).unwrap();
assert_eq!(cursor.next_frame(&mut image).unwrap().unwrap().number, 0);
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cursor.next_frame(&mut image)));
assert!(caught.is_err());
assert_eq!(cursor.missing_frames(), 1, "the frame whose line panicked is not counted");
let numbers: Vec<_> =
std::iter::from_fn(|| cursor.next_frame(&mut image)).map(|f| f.unwrap().number).collect();
assert_eq!(numbers, [1, 2]);
assert_eq!(cursor.missing_frames(), 3);
}
#[test]
fn decode_frame_rejects_bad_arguments() {
let mut d = DstDecoder::new();
let missing = || TrackFrame::new(0, FrameContent::Missing);
for channels in [0, 7, 255] {
assert!(matches!(decode_frame(&mut d, missing(), channels), Err(Error::InvalidArgument(_))));
}
let short = TrackFrame::new(0, FrameContent::Dsd(vec![0; 10]));
assert!(matches!(decode_frame(&mut d, short, 2), Err(Error::InvalidArgument(_))));
let ok = decode_frame(&mut d, missing(), 2).unwrap();
assert_eq!((ok.status, ok.data.len()), (FrameStatus::Missing, 2 * 4704));
}
#[test]
fn dst_equivalents() {
let missing = FrameContent::Missing.dst_equivalent(3).unwrap();
assert_eq!(missing.len(), 1 + 3 * FRAME_BYTES_PER_CHANNEL);
assert_eq!(missing[0], 0);
assert!(missing[1..].iter().all(|&b| b == MISSING_FILL));
let plain = FrameContent::Dsd(vec![7; FRAME_BYTES_PER_CHANNEL]);
let plain = plain.dst_equivalent(1).unwrap();
assert_eq!((plain.len(), plain[0], plain[1]), (1 + FRAME_BYTES_PER_CHANNEL, 0, 7));
let dst = FrameContent::Dst(vec![1, 2, 3]);
assert_eq!(&*dst.dst_equivalent(6).unwrap(), &[1, 2, 3]);
for channels in [0, 7, 255] {
assert!(matches!(FrameContent::Missing.dst_equivalent(channels), Err(Error::InvalidArgument(_))));
}
}
#[test]
fn deinterleave_channel() {
let frame: Vec<u8> = (0..2 * 4704).map(|i| (i % 2) as u8).collect();
let mut out = vec![9u8; 4704];
deinterleave(&frame, 2, 1, &mut out).unwrap();
assert!(out.iter().all(|&b| b == 1));
assert!(deinterleave(&frame, 2, 2, &mut out).is_err());
}
fn capacity_area(
channels: u8,
(start, end): (u32, u32),
playtime: Timecode,
tracks: &[(u32, u32)],
) -> Area {
let (_, mut area, track) = area_of(1, 1, |_, _| {});
area.channel_count = channels;
area.audio_start_lsn = start;
area.audio_end_lsn = end;
area.playtime = playtime;
area.tracks = tracks
.iter()
.map(|&(s, d)| Track { start_frame: s, duration_frames: d, ..track.clone() })
.collect();
area
}
fn tc(frames: u32) -> Timecode {
Timecode {
minutes: (frames / 4500) as u8,
seconds: (frames / 75 % 60) as u8,
frames: (frames % 75) as u8,
}
}
#[test]
fn area_capacity_of_synthetic_areas() {
let area = capacity_area(2, (100, 199), tc(50), &[(0, 20), (20, 40)]);
let c = area_capacity(&area, 1000);
assert_eq!((c.audio_sectors, c.playtime_frames, c.max_track_end, c.capacity), (100, 50, 60, 700));
assert_eq!(c.plain_frame_bound, Some(21));
assert_eq!(c.frames_per_sector(), 0.6);
let c = area_capacity(&area, 150);
assert_eq!((c.audio_sectors, c.capacity, c.plain_frame_bound), (50, 350, Some(10)));
assert_eq!(c.frames_per_sector(), 1.2);
for (channels, bound) in [(1, 4090), (2, 2045), (3, 1363), (4, 1022), (5, 818), (6, 681)] {
let area = capacity_area(channels, (0, 9407), tc(0), &[]);
let c = area_capacity(&area, 9408);
assert_eq!(c.plain_frame_bound, Some(bound), "{channels} channels");
assert_eq!((c.max_track_end, c.frames_per_sector()), (0, 0.0));
}
for (channels, per_sector, measured) in
[(2, 0.2174, 0.2172), (5, 0.0869, 0.0869), (6, 0.0725, 0.0724)]
{
let area = capacity_area(channels, (0, 999_999), tc(0), &[]);
let bound = area_capacity(&area, 1_000_000).plain_frame_bound.unwrap();
let bound = bound as f64 / 1e6;
assert!((bound - per_sector).abs() < 5e-5, "{channels} channels: {bound}");
assert!(measured <= bound, "{channels} channels: {bound}");
}
}
#[test]
fn area_capacity_of_hostile_areas() {
for (range, playtime, tracks) in
[((500, 600), 75, &[(0, 75)][..]), ((500, 600), 0, &[]), ((300, 200), 10, &[(0, 10)])]
{
let c = area_capacity(&capacity_area(2, range, tc(playtime), tracks), 400);
assert_eq!((c.audio_sectors, c.capacity, c.plain_frame_bound), (0, 0, Some(0)));
assert_eq!(c.frames_per_sector(), f64::INFINITY);
assert!(c.frames_per_sector() > 1e300);
}
for channels in [0, 7, 8, 255] {
let c = area_capacity(&capacity_area(channels, (0, 9), tc(5), &[(0, 5)]), 10);
assert_eq!((c.audio_sectors, c.capacity, c.plain_frame_bound), (10, 70, None));
assert_eq!(c.frames_per_sector(), 0.5);
}
let largest = Timecode { minutes: 255, seconds: 255, frames: 255 };
let area = capacity_area(1, (0, u32::MAX), largest, &[(u32::MAX - 1, u32::MAX), (5, 1)]);
let c = area_capacity(&area, u64::MAX);
let n = 1u64 << 32;
assert_eq!((c.audio_sectors, c.capacity, c.max_track_end), (n, 7 * n, u32::MAX));
assert_eq!(c.playtime_frames, largest.frame_number());
assert_eq!(c.plain_frame_bound, Some(n * 2045 / 4704));
assert_eq!(c.frames_per_sector(), f64::from(u32::MAX) / n as f64);
assert!(c.frames_per_sector() < 1.0);
}
}