use std::io::{Read, Seek};
use std::sync::Arc;
use crate::audio::{
self, AreaCursor, AreaFrames, Continuation, TrackAudio, TrackAudioCursor, TrackCursor, TrackFrames,
};
use crate::control::CancelToken;
use crate::error::{Error, Slot, Warning};
use crate::image::{Image, SectorFormat};
use crate::log::{Log, sb_log};
use crate::read_at::{ReadAt, ReadAtReader};
use crate::seek::{AreaIndex, IndexOptions, SeekIndexes, SeekPolicy, Speculation};
use crate::toc::{self, Timecode, Toc, TocDigests, TocStored};
#[derive(Debug)]
pub struct Disc<R> {
image: Image<R>,
shared: Arc<DiscShared>,
policy: [SeekPolicy; 2],
}
#[derive(Debug)]
struct DiscShared {
toc: Toc,
warnings: Vec<Warning>,
digests: TocDigests,
stored: TocStored,
seek: SeekIndexes,
}
impl<R: Read + Seek> Disc<R> {
pub fn open(reader: R) -> Result<Self, Error> {
Self::from_image(Image::open(reader)?)
}
pub fn open_with_log(reader: R, log: Log) -> Result<Self, Error> {
Self::from_image(Image::open_with_log(reader, log)?)
}
pub fn open_with_format(reader: R, format: SectorFormat) -> Result<Self, Error> {
Self::from_image(Image::with_format(reader, format)?)
}
pub fn open_with_format_and_log(reader: R, format: SectorFormat, log: Log) -> Result<Self, Error> {
Self::from_image(Image::with_format_and_log(reader, format, log)?)
}
pub fn from_image(mut image: Image<R>) -> Result<Self, Error> {
let (toc, warnings, digests, stored) = toc::read_toc(&mut image)?;
image.release_buffer();
Ok(Disc {
image,
shared: Arc::new(DiscShared { toc, warnings, digests, stored, seek: SeekIndexes::default() }),
policy: [SeekPolicy::Exact; 2],
})
}
pub fn share<R2: Read + Seek>(&self, reader: R2) -> Result<Disc<R2>, Error> {
self.share_with_log(reader, self.log().clone())
}
pub fn share_with_log<R2: Read + Seek>(&self, reader: R2, log: Log) -> Result<Disc<R2>, Error> {
let mut image = self.image.share(reader, log)?;
if TocDigests::of(&mut image, &self.shared.toc)?.as_ref() != Some(&self.shared.digests) {
sb_log!(image.log(), Info, "shared reader refused: its TOC sectors differ from the image's");
return Err(Error::InvalidArgument("shared reader of another image"));
}
sb_log!(image.log(), Debug, "shared reader checked: same length and TOC sectors");
image.release_buffer();
Ok(Disc { image, shared: Arc::clone(&self.shared), policy: self.policy })
}
pub fn toc(&self) -> &Toc {
&self.shared.toc
}
#[cfg(feature = "output")]
pub(crate) fn toc_digests(&self) -> &TocDigests {
&self.shared.digests
}
pub fn log(&self) -> &Log {
self.image.log()
}
pub fn set_log(&mut self, log: Log) {
self.image.set_log(log);
}
pub fn cancel_token(&self) -> CancelToken {
self.image.cancel_token()
}
pub fn track_timecodes_stored(&self, slot: Slot, number: u32) -> Result<(Timecode, Timecode), Error> {
self.find_track(slot, number)?;
self.shared.stored.track_timecodes(slot, number).ok_or(Error::NoSuchTrack { slot, track: number })
}
pub fn warnings(&self) -> &[Warning] {
&self.shared.warnings
}
pub fn enable_seek_index(&mut self, slot: Slot, options: IndexOptions) -> Result<(), Error> {
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
let mut index = AreaIndex::new(area, self.image.sector_count(), options)?;
index.bind_fingerprint(crate::seek::toc_fingerprint(&self.shared.toc, slot))?;
sb_log!(self.log(), Debug, "area {slot}: seek index enabled, interval {} sectors", options.interval);
self.shared.seek.write(slot, |kept| *kept = Some(index));
Ok(())
}
pub fn set_seek_index(&mut self, slot: Slot, mut index: AreaIndex) -> Result<(), Error> {
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
index.check_key(area, self.image.sector_count())?;
index.bind_fingerprint(crate::seek::toc_fingerprint(&self.shared.toc, slot))?;
index.forget_image();
sb_log!(
self.log(),
Debug,
"area {slot}: seek index set, frontier LSN {}{}",
index.frontier(),
if index.is_complete() { ", complete" } else { "" }
);
self.shared.seek.write(slot, |kept| *kept = Some(index));
Ok(())
}
pub fn set_seek_policy(&mut self, slot: Slot, policy: SeekPolicy) -> Result<(), Error> {
self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
sb_log!(self.log(), Debug, "area {slot}: seek policy {policy:?}");
self.policy[slot_index(slot)] = policy;
Ok(())
}
pub fn seek_policy(&self, slot: Slot) -> SeekPolicy {
self.policy[slot_index(slot)]
}
fn cursor_policy(&self, slot: Slot) -> SeekPolicy {
match self.seek_policy(slot) {
SeekPolicy::Speculative(mut options) => {
options.layout_suspect = crate::seek::layout_suspect(&self.shared.toc, slot);
SeekPolicy::Speculative(options)
}
exact => exact,
}
}
pub fn take_seek_index(&mut self, slot: Slot) -> Option<AreaIndex> {
self.shared.seek.write(slot, Option::take)
}
pub fn seek_index(&self, slot: Slot) -> Option<AreaIndex> {
self.shared.seek.read(slot, |kept| kept.cloned())
}
pub fn extend_seek_index(&mut self, slot: Slot, max_sectors: u64) -> Result<bool, Error> {
let Some(mut index) = self.seek_index(slot) else {
return Err(Error::InvalidArgument("no seek index kept for the area"));
};
let result = index.extend(&mut self.image, max_sectors);
self.shared.seek.push_events(slot, index.take_events());
let merged = self.shared.seek.write(slot, |kept| match kept {
Some(kept) => kept.merge(&index).map(|()| kept.is_complete()),
None => Ok(false),
});
match (result, merged) {
(Err(e), _) | (Ok(_), Err(e)) => Err(e),
(Ok(_), Ok(complete)) => Ok(complete),
}
}
pub fn verify_speculation(&mut self, slot: Slot, max_sectors: u64) -> Result<bool, Error> {
let complete = self.extend_seek_index(slot, max_sectors)?;
let unchecked = |kept: Option<&AreaIndex>| kept.is_some_and(AreaIndex::has_reached_claims);
Ok(complete && !self.shared.seek.read(slot, unchecked))
}
pub fn take_seek_events(&self, slot: Slot) -> Vec<crate::seek::SeekEvent> {
self.shared.seek.take_events(slot)
}
pub fn absorb_seek_checkpoints(&self, cursor: &mut impl crate::audio::SeekCursor) {
self.shared.seek.absorb(crate::audio::sealed::Sealed::area_cursor_mut(cursor), self.image.id());
}
pub fn area_frames(&mut self, slot: Slot) -> Result<AreaFrames<'_, R>, Error> {
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
Ok(AreaFrames::new(&mut self.image, area))
}
pub fn stored_frame_list(&mut self, slot: Slot) -> Result<AreaFrames<'_, R>, Error> {
let cursor = self.stored_frame_list_cursor(slot)?;
Ok(AreaFrames::with_cursor(&mut self.image, cursor))
}
pub fn stored_frame_list_cursor(&self, slot: Slot) -> Result<AreaCursor, Error> {
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
audio::check_channels(area)
.inspect_err(|e| sb_log!(self.log(), Info, "area {slot} stored frame list: {e}"))?;
sb_log!(
self.log(),
Info,
"area {slot} stored frame list ({} channels), new scan of the area",
area.channel_count
);
Ok(AreaCursor::new(area, self.image.sector_count()))
}
pub fn check_track(&self, slot: Slot, number: u32) -> Result<(), Error> {
let (area, track) = self.find_track(slot, number)?;
audio::check_track(area, track, self.image.sector_count())
.inspect_err(|e| sb_log!(self.log(), Info, "area {slot} track {number}: no audio: {e}"))
}
fn find_track(&self, slot: Slot, number: u32) -> Result<(&crate::Area, &crate::Track), Error> {
audio::find_track(&self.shared.toc.areas, slot, number)
.inspect_err(|e| sb_log!(self.log(), Info, "area {slot} track {number}: {e}"))
}
fn frames_cursor(
&self,
area: &crate::Area,
(first, end): (u32, u32),
track: Option<u32>,
what: &str,
) -> TrackCursor {
let n = self.image.sector_count();
let policy = self.cursor_policy(area.slot);
let (cursor, how) = self.shared.seek.read(area.slot, |index| {
let mut cursor = TrackCursor::start_with(area, (first, end), n, index, policy);
if index.is_some() {
cursor.area_mut().keep_for_disc();
}
let how = match (cursor.speculation(), index) {
(Speculation::Exact, Some(_)) => "from the seek index",
(Speculation::Exact, None) => "new scan of the area",
_ => "provisional start allowed (4.2 item 8)",
};
(cursor, how)
});
audio::log_open(self.log(), area, track, (first, end), what, how);
cursor
}
pub fn track_frames(&mut self, slot: Slot, number: u32) -> Result<TrackFrames<'_, R>, Error> {
let cursor = self.track_frames_cursor(slot, number)?;
Ok(TrackFrames::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
}
pub fn track_frames_cursor(&self, slot: Slot, number: u32) -> Result<TrackCursor, Error> {
self.check_track(slot, number)?;
let (area, track) = audio::find_track(&self.shared.toc.areas, slot, number)?;
Ok(self.frames_cursor(area, (track.start_frame, track.end_frame()), Some(number), "frames"))
}
pub fn range_frames(&mut self, slot: Slot, first: u32, end: u32) -> Result<TrackFrames<'_, R>, Error> {
let cursor = self.range_frames_cursor(slot, first, end)?;
Ok(TrackFrames::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
}
pub fn range_frames_cursor(&self, slot: Slot, first: u32, end: u32) -> Result<TrackCursor, Error> {
self.check_range(slot, first, end)?;
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
Ok(self.frames_cursor(area, (first, end), None, "frames"))
}
pub fn continue_track_frames(
&self,
prev: TrackCursor,
slot: Slot,
number: u32,
) -> Result<TrackCursor, Error> {
Ok(self.track_continuation(slot, number)?.frames(prev))
}
pub fn continue_range_frames(
&self,
prev: TrackCursor,
slot: Slot,
first: u32,
end: u32,
) -> Result<TrackCursor, Error> {
Ok(self.range_continuation(slot, first, end)?.frames(prev))
}
pub fn read_frames(&mut self, cursor: TrackCursor) -> TrackFrames<'_, R> {
TrackFrames::with_cursor(&mut self.image, cursor, Some(&self.shared.seek))
}
pub fn track_audio(&mut self, slot: Slot, number: u32) -> Result<TrackAudio<'_, R>, Error> {
let cursor = self.track_audio_cursor(slot, number)?;
Ok(TrackAudio::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
}
pub fn check_range(&self, slot: Slot, first: u32, end: u32) -> Result<(), Error> {
self.shared
.toc
.area(slot)
.ok_or(Error::NoSuchArea(slot))
.and_then(|area| audio::check_range(area, first, end, self.image.sector_count()))
.inspect_err(|e| {
sb_log!(self.log(), Info, "area {slot} range: frames {first}..{end}: no audio: {e}")
})
}
pub fn range_audio(&mut self, slot: Slot, first: u32, end: u32) -> Result<TrackAudio<'_, R>, Error> {
let cursor = self.range_audio_cursor(slot, first, end)?;
Ok(TrackAudio::with_cursor(&mut self.image, cursor, Some(&self.shared.seek)))
}
pub fn range_audio_cursor(&self, slot: Slot, first: u32, end: u32) -> Result<TrackAudioCursor, Error> {
self.check_range(slot, first, end)?;
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
Ok(TrackAudioCursor::from_frames(self.frames_cursor(area, (first, end), None, "decoded audio")))
}
pub fn range_audio_cursor_indexed(
&self,
slot: Slot,
first: u32,
end: u32,
index: &AreaIndex,
) -> Result<TrackAudioCursor, Error> {
Ok(TrackAudioCursor::from_frames(self.indexed_cursor(slot, (first, end), index, "decoded audio")?))
}
pub fn range_frames_cursor_indexed(
&self,
slot: Slot,
first: u32,
end: u32,
index: &AreaIndex,
) -> Result<TrackCursor, Error> {
self.indexed_cursor(slot, (first, end), index, "frames")
}
fn indexed_cursor(
&self,
slot: Slot,
(first, end): (u32, u32),
index: &AreaIndex,
what: &str,
) -> Result<TrackCursor, Error> {
self.check_range(slot, first, end)?;
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
let n = self.image.sector_count();
index
.check_key(area, n)
.inspect_err(|e| sb_log!(self.log(), Info, "area {slot} range: frames {first}..{end}: {e}"))?;
audio::log_open(self.log(), area, None, (first, end), what, "from the seek index");
Ok(TrackCursor::start_with(area, (first, end), n, Some(index), self.cursor_policy(slot)))
}
pub fn continue_range_audio(
&self,
prev: TrackAudioCursor,
slot: Slot,
first: u32,
end: u32,
) -> Result<TrackAudioCursor, Error> {
Ok(self.range_continuation(slot, first, end)?.audio(prev))
}
pub fn track_audio_cursor(&self, slot: Slot, number: u32) -> Result<TrackAudioCursor, Error> {
self.check_track(slot, number)?;
let (area, track) = audio::find_track(&self.shared.toc.areas, slot, number)?;
let range = (track.start_frame, track.end_frame());
Ok(TrackAudioCursor::from_frames(self.frames_cursor(area, range, Some(number), "decoded audio")))
}
pub fn continue_track_audio(
&self,
prev: TrackAudioCursor,
slot: Slot,
number: u32,
) -> Result<TrackAudioCursor, Error> {
Ok(self.track_continuation(slot, number)?.audio(prev))
}
pub fn track_continuation(&self, slot: Slot, number: u32) -> Result<Continuation<'_>, Error> {
self.check_track(slot, number)?;
let (area, track) = audio::find_track(&self.shared.toc.areas, slot, number)?;
let n = self.image.sector_count();
let range = (track.start_frame, track.end_frame());
Ok(Continuation::new(
area,
range,
(n, Some(self.image.id())),
self.log(),
Some(number),
(&self.shared.seek, self.cursor_policy(area.slot)),
))
}
pub fn range_continuation(&self, slot: Slot, first: u32, end: u32) -> Result<Continuation<'_>, Error> {
self.check_range(slot, first, end)?;
let area = self.shared.toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
let n = self.image.sector_count();
Ok(Continuation::new(
area,
(first, end),
(n, Some(self.image.id())),
self.log(),
None,
(&self.shared.seek, self.cursor_policy(area.slot)),
))
}
pub fn track_range_with_pause(&self, slot: Slot, number: u32) -> Result<(u32, u32), Error> {
let (area, _) = self.find_track(slot, number)?;
audio::track_range_with_pause(area, number)
.ok_or(Error::NoSuchTrack { slot, track: number })
.inspect_err(|e| sb_log!(self.log(), Info, "area {slot} track {number}: {e}"))
}
pub fn read_track_audio(&mut self, cursor: TrackAudioCursor) -> TrackAudio<'_, R> {
TrackAudio::with_cursor(&mut self.image, cursor, Some(&self.shared.seek))
}
pub fn image_mut(&mut self) -> &mut Image<R> {
&mut self.image
}
pub fn into_inner(self) -> R {
self.image.into_inner()
}
}
impl<A: ReadAt + Clone> Clone for Disc<ReadAtReader<A>> {
fn clone(&self) -> Self {
Disc { image: self.image.clone(), shared: Arc::clone(&self.shared), policy: self.policy }
}
}
fn slot_index(slot: Slot) -> usize {
match slot {
Slot::TwoChannel => 0,
Slot::Multichannel => 1,
}
}
#[cfg(test)]
#[allow(clippy::duplicate_mod)]
#[path = "../tests/common/mod.rs"]
mod common;
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::common::{PFrame, S, Spec, TrackSpec, pack};
use super::*;
use crate::ReadAtReader;
use crate::audio::FRAME_BYTES_PER_CHANNEL;
fn plain_image() -> Vec<u8> {
let frames: Vec<PFrame> = (0..9)
.map(|number| PFrame {
number,
dst: false,
data: (0..2 * FRAME_BYTES_PER_CHANNEL).map(|i| (i as u32 * 7 + number * 13) as u8).collect(),
})
.collect();
let tracks = vec![TrackSpec { start: 0, duration: 4 }, TrackSpec { start: 4, duration: 5 }];
Spec { channels: 2, playtime: 9, tracks, audio: pack(&frames) }.build()
}
fn stored(plain: &[u8], format: SectorFormat) -> Vec<u8> {
let (p, d) = (format.stored_size() as usize, format.data_offset() as usize);
let mut out = vec![0u8; plain.len() / S * p];
for (i, sector) in plain.chunks_exact(S).enumerate() {
out[i * p + d..i * p + d + S].copy_from_slice(sector);
}
out
}
fn frames<R: Read + Seek>(disc: &mut Disc<R>) -> Vec<crate::AreaFrame> {
let count = if cfg!(miri) { 1 } else { usize::MAX };
disc.area_frames(Slot::TwoChannel).unwrap().take(count).map(Result::unwrap).collect()
}
#[test]
fn raw_disc_keeps_no_read_buffer_after_toc() {
let plain = plain_image();
let want = (!cfg!(miri)).then(|| frames(&mut Disc::open(Cursor::new(plain.as_slice())).unwrap()));
let formats: &[SectorFormat] = if cfg!(miri) {
&[SectorFormat::Raw2064]
} else {
&[SectorFormat::Raw2064, SectorFormat::Raw2054]
};
for &format in formats {
let bytes = stored(&plain, format);
let mut disc = Disc::open(Cursor::new(bytes.as_slice())).unwrap();
assert_eq!(disc.image.format(), format);
assert_eq!(disc.image.buffer_capacity(), 0);
let mut shared = disc.share(Cursor::new(bytes.as_slice())).unwrap();
assert_eq!(shared.image.buffer_capacity(), 0);
let mut source = Disc::open(ReadAtReader::new(bytes.as_slice())).unwrap();
let mut cloned = source.clone();
assert_eq!((source.image.buffer_capacity(), cloned.image.buffer_capacity()), (0, 0));
let first = frames(&mut disc);
assert!(!first.is_empty());
assert!(disc.image.buffer_capacity() > 0);
if let Some(want) = &want {
assert_eq!(&first, want);
assert_eq!(&frames(&mut disc), want);
assert_eq!(&frames(&mut shared), want);
assert_eq!(&frames(&mut source), want);
assert_eq!(&frames(&mut cloned), want);
}
}
}
}