mod dsdiff;
mod dsdiff_dst;
mod dsdiff_text;
mod dsf;
mod id3;
mod markers;
mod tags;
use std::borrow::Cow;
use std::collections::{BTreeSet, VecDeque};
use std::io::{Read, Seek};
use std::ops::Range;
use crate::audio::{
self, AudioFrame, FRAME_BYTES_PER_CHANNEL, FrameContent, TrackAudio, TrackFrame, TrackFrames,
};
use crate::disc::Disc;
use crate::dispatch::{self, Isa};
use crate::dst::DstDecoder;
use crate::error::{Error, Slot};
use crate::toc::{Area, Toc, TocDigests, Track};
pub use dsdiff::{CallerChunk, DsdiffDeparture, LocalChunk, PropertyChunk};
pub use dsdiff_dst::{DstIndexOffset, DstLengths, InvalidDst};
pub use dsdiff_text::{Comment, CommentKind};
pub use dsf::{DsfBitsPerSample, DsfChainFile, plan_dsf_chain};
pub use id3::{AlbumArtistFrame, ArrangerFrame, DateFrame, Id3Encoding, Id3Options, MAX_TAG_BYTES};
pub use markers::{InfoChunk, Marker, MarkerKind, MarkerText, Markers};
pub use tags::{ArtistTitleSource, GenreSources, TagItem, TagSet, TextSource};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Format {
Dsf,
DsdiffDsd,
DsdiffDst,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SourceTrack {
Auto,
None,
Track(u8),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Tags {
FromToc,
Set(TagSet),
Raw(Vec<u8>),
None,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OutputOptions {
pub dsf_bits_per_sample: DsfBitsPerSample,
pub dsf_unspecified_channel_type: Option<u32>,
pub dsdiff_property_order: [PropertyChunk; 5],
pub dsdiff_unspecified_channel_numbers: Option<Vec<u16>>,
pub dsdiff_unspecified_loudspeaker_configuration: bool,
pub dsdiff_loudspeaker_configuration: bool,
pub dsdiff_absolute_start: Option<u32>,
pub dsdiff_local_order: Vec<LocalChunk>,
pub dsdiff_dst_crc: bool,
pub dsdiff_dst_index: bool,
pub dsdiff_dst_index_offset: DstIndexOffset,
pub source_track: SourceTrack,
pub dsdiff_edited_master: bool,
pub dsdiff_edited_master_info: bool,
pub dsdiff_edited_master_id: String,
pub dsdiff_markers: Markers,
pub dsdiff_source_track_markers: bool,
pub dsdiff_clipped_program: bool,
pub dsdiff_text_pad_counted: bool,
pub tags: Tags,
pub text_source: TextSource,
pub genres: GenreSources,
pub id3: Id3Options,
pub dsdiff_artist_title: Option<bool>,
pub dsdiff_info_order: [InfoChunk; 4],
pub dsdiff_marker_text: MarkerText,
pub dsdiff_comments: Vec<Comment>,
pub dsdiff_text_replacement: Option<u8>,
pub dsdiff_empty_text: bool,
pub dsdiff_caller_chunks: Vec<CallerChunk>,
pub dsdiff_edited_master_id_written: bool,
pub dsdiff_artist_title_source: ArtistTitleSource,
pub dsdiff_empty_info: bool,
pub dsdiff_departures: BTreeSet<DsdiffDeparture>,
pub dsf_chain_first: Option<u32>,
pub dsf_chain_end: Option<u32>,
}
impl Default for OutputOptions {
fn default() -> Self {
OutputOptions {
dsf_bits_per_sample: DsfBitsPerSample::One,
dsf_unspecified_channel_type: None,
dsdiff_property_order: PropertyChunk::TABLE_ORDER,
dsdiff_unspecified_channel_numbers: None,
dsdiff_unspecified_loudspeaker_configuration: false,
dsdiff_loudspeaker_configuration: true,
dsdiff_absolute_start: None,
dsdiff_local_order: LocalChunk::DEFAULT_ORDER.to_vec(),
dsdiff_dst_crc: false,
dsdiff_dst_index: true,
dsdiff_dst_index_offset: DstIndexOffset::ChunkHeader,
source_track: SourceTrack::Auto,
dsdiff_edited_master: false,
dsdiff_edited_master_info: false,
dsdiff_edited_master_id: String::new(),
dsdiff_markers: Markers::FromToc,
dsdiff_source_track_markers: false,
dsdiff_clipped_program: false,
dsdiff_text_pad_counted: false,
tags: Tags::FromToc,
text_source: TextSource::DiscThenAlbum,
genres: GenreSources::default(),
id3: Id3Options::default(),
dsdiff_artist_title: None,
dsdiff_info_order: InfoChunk::TABLE_ORDER,
dsdiff_marker_text: MarkerText::Empty,
dsdiff_comments: Vec::new(),
dsdiff_text_replacement: Some(b'?'),
dsdiff_empty_text: false,
dsdiff_caller_chunks: Vec::new(),
dsdiff_edited_master_id_written: true,
dsdiff_artist_title_source: ArtistTitleSource::Album,
dsdiff_empty_info: true,
dsdiff_departures: BTreeSet::new(),
dsf_chain_first: None,
dsf_chain_end: None,
}
}
}
impl OutputOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_dsf_bits_per_sample(self, bits: DsfBitsPerSample) -> Self {
OutputOptions { dsf_bits_per_sample: bits, ..self }
}
pub fn with_dsf_unspecified_channel_type(self, channel_type: Option<u32>) -> Self {
OutputOptions { dsf_unspecified_channel_type: channel_type, ..self }
}
pub fn with_dsdiff_property_order(self, order: [PropertyChunk; 5]) -> Self {
OutputOptions { dsdiff_property_order: order, ..self }
}
pub fn with_dsdiff_unspecified_channel_numbers(self, numbers: Option<Vec<u16>>) -> Self {
OutputOptions { dsdiff_unspecified_channel_numbers: numbers, ..self }
}
pub fn with_dsdiff_unspecified_loudspeaker_configuration(self, write: bool) -> Self {
OutputOptions { dsdiff_unspecified_loudspeaker_configuration: write, ..self }
}
pub fn with_dsdiff_loudspeaker_configuration(self, write: bool) -> Self {
OutputOptions { dsdiff_loudspeaker_configuration: write, ..self }
}
pub fn with_dsdiff_absolute_start(self, frame: Option<u32>) -> Self {
OutputOptions { dsdiff_absolute_start: frame, ..self }
}
pub fn with_dsdiff_local_order(self, order: Vec<LocalChunk>) -> Self {
OutputOptions { dsdiff_local_order: order, ..self }
}
pub fn with_dsdiff_dst_crc(self, write: bool) -> Self {
OutputOptions { dsdiff_dst_crc: write, ..self }
}
pub fn with_dsdiff_dst_index(self, write: bool) -> Self {
OutputOptions { dsdiff_dst_index: write, ..self }
}
pub fn with_tags(self, tags: Tags) -> Self {
OutputOptions { tags, ..self }
}
pub fn with_text_source(self, source: TextSource) -> Self {
OutputOptions { text_source: source, ..self }
}
pub fn with_genres(self, genres: GenreSources) -> Self {
OutputOptions { genres, ..self }
}
pub fn with_id3(self, id3: Id3Options) -> Self {
OutputOptions { id3, ..self }
}
pub fn with_dsdiff_artist_title(self, write: Option<bool>) -> Self {
OutputOptions { dsdiff_artist_title: write, ..self }
}
pub fn with_dsdiff_info_order(self, order: [InfoChunk; 4]) -> Self {
OutputOptions { dsdiff_info_order: order, ..self }
}
pub fn with_dsdiff_marker_text(self, text: MarkerText) -> Self {
OutputOptions { dsdiff_marker_text: text, ..self }
}
pub fn with_dsdiff_comments(self, comments: Vec<Comment>) -> Self {
OutputOptions { dsdiff_comments: comments, ..self }
}
pub fn with_dsdiff_text_replacement(self, replacement: Option<u8>) -> Self {
OutputOptions { dsdiff_text_replacement: replacement, ..self }
}
pub fn with_dsdiff_empty_text(self, write: bool) -> Self {
OutputOptions { dsdiff_empty_text: write, ..self }
}
pub fn with_source_track(self, track: SourceTrack) -> Self {
OutputOptions { source_track: track, ..self }
}
pub fn with_dsdiff_edited_master(self, edited_master: bool) -> Self {
OutputOptions { dsdiff_edited_master: edited_master, ..self }
}
pub fn with_dsdiff_edited_master_info(self, write: bool) -> Self {
OutputOptions { dsdiff_edited_master_info: write, ..self }
}
pub fn with_dsdiff_edited_master_id(self, id: String) -> Self {
OutputOptions { dsdiff_edited_master_id: id, ..self }
}
pub fn with_dsdiff_markers(self, markers: Markers) -> Self {
OutputOptions { dsdiff_markers: markers, ..self }
}
pub fn with_dsdiff_source_track_markers(self, write: bool) -> Self {
OutputOptions { dsdiff_source_track_markers: write, ..self }
}
pub fn with_dsdiff_clipped_program(self, write: bool) -> Self {
OutputOptions { dsdiff_clipped_program: write, ..self }
}
pub fn with_dsdiff_text_pad_counted(self, counted: bool) -> Self {
OutputOptions { dsdiff_text_pad_counted: counted, ..self }
}
pub fn with_dsdiff_dst_index_offset(self, offset: DstIndexOffset) -> Self {
OutputOptions { dsdiff_dst_index_offset: offset, ..self }
}
pub fn with_dsdiff_caller_chunks(self, chunks: Vec<CallerChunk>) -> Self {
OutputOptions { dsdiff_caller_chunks: chunks, ..self }
}
pub fn with_dsdiff_edited_master_id_written(self, write: bool) -> Self {
OutputOptions { dsdiff_edited_master_id_written: write, ..self }
}
pub fn with_dsdiff_artist_title_source(self, source: ArtistTitleSource) -> Self {
OutputOptions { dsdiff_artist_title_source: source, ..self }
}
pub fn with_dsdiff_empty_info(self, write: bool) -> Self {
OutputOptions { dsdiff_empty_info: write, ..self }
}
pub fn with_dsdiff_departures(self, departures: impl IntoIterator<Item = DsdiffDeparture>) -> Self {
OutputOptions { dsdiff_departures: departures.into_iter().collect(), ..self }
}
pub(crate) fn departs(&self, d: DsdiffDeparture) -> bool {
self.dsdiff_departures.contains(&d)
}
pub fn with_dsf_chain(self, chain: Option<(u32, u32)>) -> Self {
OutputOptions { dsf_chain_first: chain.map(|c| c.0), dsf_chain_end: chain.map(|c| c.1), ..self }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RegionKind {
Header,
SoundData,
Trailer,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Region {
pub kind: RegionKind,
pub offset: u64,
pub len: u64,
}
#[derive(Clone, Debug)]
enum Part {
Bytes(Vec<u8>),
Dsf(dsf::DsfData),
Dsd(dsdiff::DsdData),
Dst(dsdiff_dst::DstData),
}
pub trait PositionSource {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error>;
fn dst_equivalent(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
let _ = t;
Err(Error::InvalidArgument("this source gives no DST equivalents"))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Input {
Content,
DstEquivalents,
DstEquivalentsAndContent,
}
#[derive(Clone, Debug)]
pub struct Layout {
format: Format,
slot: Slot,
first: u32,
end: u32,
channels: u8,
size: u64,
regions: Vec<Region>,
parts: Vec<Part>,
invalid: Option<InvalidDst>,
crc: bool,
image: Option<TocDigests>,
source: Option<u8>,
chain: Option<(u32, u32)>,
base: u32,
}
impl Layout {
pub fn new(
toc: &Toc,
slot: Slot,
first: u32,
end: u32,
format: Format,
options: &OutputOptions,
) -> Result<Layout, Error> {
let area = toc.area(slot).ok_or(Error::NoSuchArea(slot))?;
audio::check_range(area, first, end, toc.sectors)?;
if options.dsdiff_edited_master && format == Format::Dsf {
return Err(Error::InvalidArgument("an edited master is a DSDIFF file"));
}
let chain = match (options.dsf_chain_first, options.dsf_chain_end) {
(None, None) => None,
(Some(a1), Some(last)) => {
if format != Format::Dsf {
return Err(Error::InvalidArgument("a byte range of a chain is DSF only"));
}
if a1 > first || end > last {
return Err(Error::InvalidArgument("the range must be within its chain"));
}
if last > end && audio::check_range(area, end, last, toc.sectors).is_err() {
return Err(Error::InvalidArgument(
"the chain's ranges after this one are skipped or refused: it ends here",
));
}
Some((a1, last))
}
_ => return Err(Error::InvalidArgument("a chain needs both its first frame and its end")),
};
let mut layout = Layout {
format,
slot: area.slot,
first,
end,
channels: area.channel_count,
size: 0,
regions: Vec::new(),
parts: Vec::new(),
invalid: None,
crc: false,
image: None,
source: if options.dsdiff_edited_master {
None
} else {
source_track(area, first, end, options.source_track)?
},
chain,
base: first,
};
match format {
Format::Dsf => {
let tag = layout.tag(toc, area, options)?;
dsf::build(&mut layout, area, options, tag)?
}
Format::DsdiffDsd => dsdiff::build_dsd(&mut layout, toc, area, options)?,
Format::DsdiffDst => {
return Err(Error::InvalidArgument("a DST layout needs the frame lengths: Layout::new_dst"));
}
}
Ok(layout)
}
pub fn new_dst(toc: &Toc, lengths: &DstLengths, options: &OutputOptions) -> Result<Layout, Error> {
let area = toc.area(lengths.slot()).ok_or(Error::NoSuchArea(lengths.slot()))?;
let (first, end) = lengths.range();
audio::check_range(area, first, end, toc.sectors)?;
if options.dsf_chain_first.is_some() || options.dsf_chain_end.is_some() {
return Err(Error::InvalidArgument("a byte range of a chain is DSF only"));
}
let mut layout = Layout {
format: Format::DsdiffDst,
slot: area.slot,
first,
end,
channels: area.channel_count,
size: 0,
regions: Vec::new(),
parts: Vec::new(),
invalid: Some(lengths.invalid()),
crc: options.dsdiff_dst_crc,
image: None,
source: if options.dsdiff_edited_master {
None
} else {
source_track(area, first, end, options.source_track)?
},
chain: None,
base: first,
};
let data = dsdiff_dst::DstData::new(&layout, lengths, options)?;
dsdiff::assemble(&mut layout, toc, area, options, dsdiff::Sound::Dst(data))?;
Ok(layout)
}
fn push(&mut self, kind: RegionKind, len: u64, part: Part) {
self.regions.push(Region { kind, offset: self.size, len });
self.parts.push(part);
self.size += len;
}
pub fn size(&self) -> u64 {
self.size
}
pub fn format(&self) -> Format {
self.format
}
pub fn slot(&self) -> Slot {
self.slot
}
pub fn range(&self) -> (u32, u32) {
(self.first, self.end)
}
pub fn byte_range(&self) -> Option<(u64, u64)> {
self.parts.iter().find_map(|p| match p {
Part::Dsf(d) => Some(d.bytes()),
_ => None,
})
}
fn tag(&self, toc: &Toc, area: &Area, options: &OutputOptions) -> Result<Option<Vec<u8>>, Error> {
let source = self.source.and_then(|n| area.track(u32::from(n)));
match &options.tags {
Tags::None => Ok(None),
Tags::Raw(bytes) => id3::check_raw(bytes).map(|()| Some(bytes.clone())),
Tags::FromToc => id3::tag(&TagSet::from_toc(toc, area, source, options), &options.id3),
Tags::Set(set) => id3::tag(set, &options.id3),
}
}
pub fn source_track(&self) -> Option<u8> {
self.source
}
pub fn channels(&self) -> u8 {
self.channels
}
pub fn input(&self) -> Input {
match (self.invalid, self.crc) {
(None, _) => Input::Content,
(Some(_), false) => Input::DstEquivalents,
(Some(_), true) => Input::DstEquivalentsAndContent,
}
}
pub fn regions(&self) -> &[Region] {
&self.regions
}
pub fn memory(&self) -> usize {
let parts: usize = self
.parts
.iter()
.map(|p| match p {
Part::Bytes(b) => b.len(),
Part::Dst(d) => d.memory(),
Part::Dsf(_) | Part::Dsd(_) => 0,
})
.sum();
size_of::<Self>() + parts + self.regions.len() * (size_of::<Region>() + size_of::<Part>())
}
pub fn positions_for(&self, range: Range<u64>) -> Range<u32> {
let mut lo = u32::MAX;
let mut hi = 0;
for (region, part) in self.regions.iter().zip(&self.parts) {
let start = range.start.max(region.offset);
let end = range.end.min(region.offset + region.len);
if start >= end {
continue;
}
let p = match part {
Part::Bytes(_) => continue,
Part::Dsf(d) => d.positions(start - region.offset..end - region.offset),
Part::Dsd(d) => d.positions(start - region.offset..end - region.offset),
Part::Dst(d) => d.positions(start - region.offset..end - region.offset),
};
if !p.is_empty() {
lo = lo.min(p.start);
hi = hi.max(p.end);
}
}
if lo >= hi { self.first..self.first } else { self.base + lo..self.base + hi }
}
pub fn fill(&self, offset: u64, out: &mut [u8], source: &mut dyn PositionSource) -> Result<usize, Error> {
self.fill_with(Isa::detect(), offset, out, source)
}
pub(crate) fn fill_with(
&self,
isa: Isa,
offset: u64,
out: &mut [u8],
source: &mut dyn PositionSource,
) -> Result<usize, Error> {
dispatch::output_path(isa, Fill { layout: self, offset, out, source })
}
#[inline(always)]
fn fill_inner(
&self,
offset: u64,
out: &mut [u8],
source: &mut dyn PositionSource,
) -> Result<usize, Error> {
let len =
usize::try_from(self.size.saturating_sub(offset)).map_or(out.len(), |rest| rest.min(out.len()));
let out = &mut out[..len];
let mut source = Checked { inner: source, len: usize::from(self.channels) * FRAME_BYTES_PER_CHANNEL };
let mut done = 0;
for (region, part) in self.regions.iter().zip(&self.parts) {
if done == len {
break;
}
let at = offset + done as u64;
if at >= region.offset + region.len {
continue;
}
let rel = at - region.offset;
let n = usize::try_from(region.len - rel).map_or(len - done, |rest| rest.min(len - done));
let dst = &mut out[done..done + n];
match part {
Part::Bytes(b) => {
let rel = rel as usize; dst.copy_from_slice(&b[rel..rel + n]);
}
Part::Dsf(d) => d.fill(rel, dst, self.base, &mut source)?,
Part::Dsd(d) => d.fill(rel, dst, self.first, &mut source)?,
Part::Dst(d) => d.fill(rel, dst, self.first, &mut source)?,
}
done += n;
}
Ok(len)
}
pub fn read_at<R: Read + Seek>(
&self,
disc: &mut Disc<R>,
offset: u64,
out: &mut [u8],
) -> Result<usize, Error> {
self.read_at_with(Isa::detect(), disc, offset, out)
}
pub(crate) fn read_at_with<R: Read + Seek>(
&self,
isa: Isa,
disc: &mut Disc<R>,
offset: u64,
out: &mut [u8],
) -> Result<usize, Error> {
dispatch::output_path(isa, ReadAt { layout: self, disc, offset, out })
}
#[inline(always)]
fn read_at_inner<R: Read + Seek>(
&self,
disc: &mut Disc<R>,
offset: u64,
out: &mut [u8],
) -> Result<usize, Error> {
if self.image.as_ref().is_some_and(|d| d != disc.toc_digests()) {
return Err(Error::InvalidArgument("the layout is of another image"));
}
let area = disc.toc().area(self.slot).ok_or(Error::NoSuchArea(self.slot))?;
if area.channel_count != self.channels {
return Err(Error::InvalidArgument("the layout is of another area"));
}
let end = offset.saturating_add(out.len() as u64).min(self.size);
let positions = self.positions_for(offset..end);
if positions.is_empty() {
return self.fill_inner(offset, out, &mut NoPositions);
}
match self.invalid {
None => {
let frames = disc.range_audio(self.slot, positions.start, positions.end)?;
self.fill_inner(offset, out, &mut Window { frames, window: VecDeque::new() })
}
Some(invalid) => {
let frames = disc.range_frames(self.slot, positions.start, positions.end)?;
let mut source = StoredWindow {
frames,
window: VecDeque::new(),
decoder: DstDecoder::new(),
channels: self.channels,
invalid,
};
self.fill_inner(offset, out, &mut source)
}
}
}
}
impl<R: Read + Seek> Disc<R> {
pub fn output_layout(
&self,
slot: Slot,
first: u32,
end: u32,
format: Format,
options: &OutputOptions,
) -> Result<Layout, Error> {
let mut layout = Layout::new(self.toc(), slot, first, end, format, options)?;
layout.image = Some(self.toc_digests().clone());
Ok(layout)
}
pub fn plan_dsf_chain(
&self,
slot: Slot,
bounds: &[u32],
) -> Result<Vec<Result<DsfChainFile, Error>>, Error> {
plan_dsf_chain(self.toc(), slot, bounds)
}
pub fn output_layout_dst(&self, lengths: &DstLengths, options: &OutputOptions) -> Result<Layout, Error> {
let mut layout = Layout::new_dst(self.toc(), lengths, options)?;
layout.image = Some(self.toc_digests().clone());
Ok(layout)
}
}
struct Fill<'a, 'b> {
layout: &'a Layout,
offset: u64,
out: &'a mut [u8],
source: &'a mut (dyn PositionSource + 'b),
}
impl dispatch::Work for Fill<'_, '_> {
type Output = Result<usize, Error>;
#[inline(always)]
fn run(self) -> Self::Output {
self.layout.fill_inner(self.offset, self.out, self.source)
}
}
struct ReadAt<'a, R> {
layout: &'a Layout,
disc: &'a mut Disc<R>,
offset: u64,
out: &'a mut [u8],
}
impl<R: Read + Seek> crate::dispatch::Work for ReadAt<'_, R> {
type Output = Result<usize, Error>;
#[inline(always)]
fn run(self) -> Self::Output {
self.layout.read_at_inner(self.disc, self.offset, self.out)
}
}
fn source_track(area: &Area, first: u32, end: u32, choice: SourceTrack) -> Result<Option<u8>, Error> {
match choice {
SourceTrack::None => Ok(None),
SourceTrack::Track(n) => {
let t: &Track =
area.track(u32::from(n)).ok_or(Error::NoSuchTrack { slot: area.slot, track: n.into() })?;
if t.start_frame.max(first) < t.end_frame().min(end) {
Ok(Some(n))
} else {
Err(Error::InvalidArgument("the source track must overlap the range"))
}
}
SourceTrack::Auto if (first, end) == (0, area.playtime_frames()) => Ok(None),
SourceTrack::Auto => Ok(area
.tracks
.iter()
.find(|t| {
let with_pause = audio::track_range_with_pause(area, u32::from(t.number));
(t.start_frame, t.end_frame()) == (first, end) || with_pause == Some((first, end))
})
.map(|t| t.number)),
}
}
struct Checked<'a> {
inner: &'a mut dyn PositionSource,
len: usize,
}
impl Checked<'_> {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
let len = self.len;
let c = self.inner.content(t)?;
if c.len() != len {
return Err(Error::InvalidArgument("position content must be C x 4704 bytes"));
}
Ok(c)
}
fn dst_equivalent(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
self.inner.dst_equivalent(t)
}
}
struct NoPositions;
impl PositionSource for NoPositions {
fn content(&mut self, _t: u32) -> Result<Cow<'_, [u8]>, Error> {
Err(Error::InvalidArgument("no position is needed"))
}
}
const WINDOW: u32 = 4;
struct Window<'a, R> {
frames: TrackAudio<'a, R>,
window: VecDeque<AudioFrame>,
}
impl<R: Read + Seek> PositionSource for Window<'_, R> {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
while self.window.back().is_none_or(|f| f.number < t) {
let frame = self.frames.next().ok_or(Error::InvalidArgument("position past the range"))??;
self.window.push_back(frame);
}
while self.window.front().is_some_and(|f| f.number.saturating_add(WINDOW) < t) {
self.window.pop_front();
}
let front = self.window.front().map_or(t, |f| f.number);
let i = t.checked_sub(front).ok_or(Error::InvalidArgument("position no longer held"))?;
let frame = self.window.get(i as usize).ok_or(Error::InvalidArgument("position not held"))?;
Ok(Cow::Borrowed(&frame.data))
}
}
struct Stored {
frame: TrackFrame,
decoded: Option<AudioFrame>,
}
struct StoredWindow<'a, R> {
frames: TrackFrames<'a, R>,
window: VecDeque<Stored>,
decoder: DstDecoder,
channels: u8,
invalid: InvalidDst,
}
impl<R: Read + Seek> StoredWindow<'_, R> {
fn get(&mut self, t: u32, decode: bool) -> Result<&Stored, Error> {
while self.window.back().is_none_or(|f| f.frame.number < t) {
let frame = self.frames.next().ok_or(Error::InvalidArgument("position past the range"))??;
self.window.push_back(Stored { frame, decoded: None });
}
while self.window.front().is_some_and(|f| f.frame.number.saturating_add(WINDOW) < t) {
self.window.pop_front();
}
let front = self.window.front().map_or(t, |f| f.frame.number);
let i = t.checked_sub(front).ok_or(Error::InvalidArgument("position no longer held"))?;
let held = self.window.get_mut(i as usize).ok_or(Error::InvalidArgument("position not held"))?;
if decode && held.decoded.is_none() {
held.decoded = Some(audio::decode_frame(&mut self.decoder, held.frame.clone(), self.channels)?);
}
Ok(held)
}
}
impl<R: Read + Seek> PositionSource for StoredWindow<'_, R> {
fn content(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
let held = self.get(t, true)?;
Ok(Cow::Borrowed(held.decoded.as_ref().map_or(&[][..], |d| &d.data)))
}
fn dst_equivalent(&mut self, t: u32) -> Result<Cow<'_, [u8]>, Error> {
let channels = self.channels;
let replace = self.invalid == InvalidDst::Replaced;
let held = self.get(t, replace)?;
let invalid = matches!(held.frame.content, FrameContent::Dst(_))
&& held.decoded.as_ref().is_some_and(|d| matches!(d.status, audio::FrameStatus::Invalid(_)));
if invalid {
return Ok(Cow::Owned(dsdiff_dst::replaced(channels)));
}
held.frame.content.dst_equivalent(channels)
}
}