196 lines
6.8 KiB
Rust
196 lines
6.8 KiB
Rust
//! A decoded audio file: interleaved `f32` frames from symphonia, with accurate seeking.
|
|
|
|
use std::fs::File;
|
|
use std::io::ErrorKind;
|
|
use std::path::Path;
|
|
use std::time::Duration;
|
|
|
|
use symphonia::core::audio::SampleBuffer;
|
|
use symphonia::core::codecs::{CODEC_TYPE_NULL, Decoder, DecoderOptions};
|
|
use symphonia::core::errors::{Error as SymError, SeekErrorKind};
|
|
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo};
|
|
use symphonia::core::io::MediaSourceStream;
|
|
use symphonia::core::meta::MetadataOptions;
|
|
use symphonia::core::probe::Hint;
|
|
use symphonia::core::units::{Time, TimeBase};
|
|
|
|
use crate::Error;
|
|
|
|
pub(crate) struct Source {
|
|
format: Box<dyn FormatReader>,
|
|
decoder: Box<dyn Decoder>,
|
|
track_id: u32,
|
|
time_base: Option<TimeBase>,
|
|
pub rate: u32,
|
|
pub channels: usize,
|
|
pub duration: Option<Duration>,
|
|
buf: Option<SampleBuffer<f32>>,
|
|
/// Samples at the start of `buf` that precede a seek target.
|
|
offset: usize,
|
|
/// The first packet, decoded by `open` to learn the signal spec, is still unread.
|
|
primed: bool,
|
|
/// After a seek: drop samples before this timestamp.
|
|
seek_ts: Option<u64>,
|
|
ended: bool,
|
|
}
|
|
|
|
impl Source {
|
|
pub fn open(path: &Path) -> Result<Self, Error> {
|
|
let file = File::open(path).map_err(|e| Error::Io(e.to_string()))?;
|
|
let stream = MediaSourceStream::new(Box::new(file), Default::default());
|
|
let mut hint = Hint::new();
|
|
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
|
hint.with_extension(ext);
|
|
}
|
|
let options = FormatOptions {
|
|
enable_gapless: true,
|
|
..Default::default()
|
|
};
|
|
let probed = symphonia::default::get_probe()
|
|
.format(&hint, stream, &options, &MetadataOptions::default())
|
|
.map_err(Error::from)?;
|
|
let format = probed.format;
|
|
let track = format
|
|
.tracks()
|
|
.iter()
|
|
.find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
|
|
.ok_or(Error::Unsupported)?;
|
|
let params = track.codec_params.clone();
|
|
let track_id = track.id;
|
|
let decoder = symphonia::default::get_codecs()
|
|
.make(¶ms, &DecoderOptions::default())
|
|
.map_err(Error::from)?;
|
|
let mut source = Source {
|
|
format,
|
|
decoder,
|
|
track_id,
|
|
time_base: params.time_base,
|
|
rate: 0,
|
|
channels: 0,
|
|
duration: None,
|
|
buf: None,
|
|
offset: 0,
|
|
primed: false,
|
|
seek_ts: None,
|
|
ended: false,
|
|
};
|
|
if !source.decode_next()? {
|
|
return Err(Error::Decode("no audio".into()));
|
|
}
|
|
source.primed = true;
|
|
source.duration = match (params.n_frames, params.time_base) {
|
|
(Some(n), Some(tb)) => Some(time_to_duration(tb.calc_time(n))),
|
|
(Some(n), None) => Some(Duration::from_secs_f64(n as f64 / f64::from(source.rate))),
|
|
_ => None,
|
|
};
|
|
Ok(source)
|
|
}
|
|
|
|
/// Next interleaved frames (`channels` samples each), `None` at the end of the stream.
|
|
pub fn next(&mut self) -> Result<Option<&[f32]>, Error> {
|
|
if self.primed {
|
|
self.primed = false;
|
|
} else if !self.decode_next()? {
|
|
return Ok(None);
|
|
}
|
|
Ok(self.buf.as_ref().map(|b| &b.samples()[self.offset..]))
|
|
}
|
|
|
|
pub fn seek(&mut self, to: Duration) -> Result<(), Error> {
|
|
self.primed = false;
|
|
self.ended = false;
|
|
self.seek_ts = None;
|
|
let time = Time::from(to.as_secs_f64());
|
|
let target = SeekTo::Time {
|
|
time,
|
|
track_id: Some(self.track_id),
|
|
};
|
|
match self.format.seek(SeekMode::Accurate, target) {
|
|
Ok(seeked) => {
|
|
self.decoder.reset();
|
|
self.seek_ts = Some(seeked.required_ts);
|
|
Ok(())
|
|
}
|
|
Err(SymError::SeekError(SeekErrorKind::OutOfRange)) => {
|
|
self.ended = true;
|
|
Ok(())
|
|
}
|
|
Err(e) => Err(e.into()),
|
|
}
|
|
}
|
|
|
|
/// Decodes the next packet of our track into `buf`; false at the end of the stream.
|
|
fn decode_next(&mut self) -> Result<bool, Error> {
|
|
while !self.ended {
|
|
let packet = match self.format.next_packet() {
|
|
Ok(p) => p,
|
|
Err(SymError::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => break,
|
|
Err(SymError::ResetRequired) => break,
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
if packet.track_id() != self.track_id {
|
|
continue;
|
|
}
|
|
if let Some(req) = self.seek_ts
|
|
&& packet.ts() + packet.dur() <= req
|
|
{
|
|
continue;
|
|
}
|
|
let decoded = match self.decoder.decode(&packet) {
|
|
Ok(d) => d,
|
|
// A damaged packet: skip it, like other players do.
|
|
Err(SymError::DecodeError(_)) => continue,
|
|
Err(e) => return Err(e.into()),
|
|
};
|
|
let spec = *decoded.spec();
|
|
let channels = spec.channels.count();
|
|
if self.rate == 0 {
|
|
self.rate = spec.rate;
|
|
self.channels = channels;
|
|
} else if channels != self.channels {
|
|
continue;
|
|
}
|
|
let fits = self
|
|
.buf
|
|
.as_ref()
|
|
.is_some_and(|b| b.capacity() >= decoded.capacity());
|
|
if !fits {
|
|
self.buf = Some(SampleBuffer::new(decoded.capacity() as u64, spec));
|
|
}
|
|
let buf = self.buf.as_mut().expect("buffer just set");
|
|
self.offset = 0;
|
|
buf.copy_interleaved_ref(decoded);
|
|
if let Some(req) = self.seek_ts.take() {
|
|
let ticks = req.saturating_sub(packet.ts());
|
|
let frames = match self.time_base {
|
|
Some(tb) => (ticks as f64 * f64::from(tb.numer) / f64::from(tb.denom)
|
|
* f64::from(self.rate))
|
|
.round() as usize,
|
|
None => ticks as usize,
|
|
};
|
|
let drop = (frames * self.channels).min(buf.len());
|
|
if drop == buf.len() {
|
|
continue;
|
|
}
|
|
self.offset = drop;
|
|
}
|
|
return Ok(true);
|
|
}
|
|
self.ended = true;
|
|
Ok(false)
|
|
}
|
|
}
|
|
|
|
fn time_to_duration(t: Time) -> Duration {
|
|
Duration::from_secs(t.seconds) + Duration::from_secs_f64(t.frac)
|
|
}
|
|
|
|
impl From<SymError> for Error {
|
|
fn from(e: SymError) -> Self {
|
|
match e {
|
|
SymError::Unsupported(_) => Error::Unsupported,
|
|
SymError::IoError(e) => Error::Io(e.to_string()),
|
|
e => Error::Decode(e.to_string()),
|
|
}
|
|
}
|
|
}
|