175 lines
6.6 KiB
Rust
175 lines
6.6 KiB
Rust
//! Decoding through `symphonia` (MPL-2.0): MP3, AAC in MP4/M4A/M4B, WAV. The source is any `Read + Seek` the app
|
|
//! hands over (a file there, a byte buffer in tests); this crate opens nothing itself. Caps keep a hostile file from
|
|
//! running away: channels, sample rate, total decoded time, and consecutive decode errors.
|
|
|
|
use crate::container::AudioError;
|
|
use std::io::{Read, Seek};
|
|
use symphonia::core::audio::SampleBuffer;
|
|
use symphonia::core::codecs::{CODEC_TYPE_NULL, DecoderOptions};
|
|
use symphonia::core::errors::Error as SymError;
|
|
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;
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub struct DecodeCaps {
|
|
pub max_channels: u16,
|
|
pub max_rate: u32,
|
|
pub max_hours: u32,
|
|
/// Decode errors in a row before the stream counts as broken.
|
|
pub max_errors: u32,
|
|
}
|
|
|
|
impl Default for DecodeCaps {
|
|
fn default() -> Self {
|
|
DecodeCaps { max_channels: 8, max_rate: 192_000, max_hours: 200, max_errors: 50 }
|
|
}
|
|
}
|
|
|
|
/// A `Read + Seek` that symphonia can use (it wants `Send + Sync`).
|
|
pub trait Source: Read + Seek + Send + Sync {}
|
|
impl<T: Read + Seek + Send + Sync> Source for T {}
|
|
|
|
struct Seekable<S: Source>(S, Option<u64>);
|
|
impl<S: Source> Read for Seekable<S> {
|
|
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
|
self.0.read(buf)
|
|
}
|
|
}
|
|
impl<S: Source> Seek for Seekable<S> {
|
|
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
|
self.0.seek(pos)
|
|
}
|
|
}
|
|
impl<S: Source> symphonia::core::io::MediaSource for Seekable<S> {
|
|
fn is_seekable(&self) -> bool {
|
|
true
|
|
}
|
|
fn byte_len(&self) -> Option<u64> {
|
|
self.1
|
|
}
|
|
}
|
|
|
|
pub struct Decoder {
|
|
format: Box<dyn FormatReader>,
|
|
decoder: Box<dyn symphonia::core::codecs::Decoder>,
|
|
track: u32,
|
|
pub rate: u32,
|
|
pub channels: u16,
|
|
caps: DecodeCaps,
|
|
decoded_frames: u64,
|
|
errors: u32,
|
|
}
|
|
|
|
fn err(e: SymError) -> AudioError {
|
|
match e {
|
|
SymError::Unsupported(_) => AudioError::Unsupported,
|
|
_ => AudioError::Damaged("the audio stream cannot be read"),
|
|
}
|
|
}
|
|
|
|
impl Decoder {
|
|
/// Opens a stream. `len` is the byte length when known; `ext` only a hint (content decides).
|
|
pub fn open<S: Source + 'static>(
|
|
source: S,
|
|
len: Option<u64>,
|
|
ext: Option<&str>,
|
|
caps: DecodeCaps,
|
|
) -> Result<Decoder, AudioError> {
|
|
let mss = MediaSourceStream::new(Box::new(Seekable(source, len)), Default::default());
|
|
let mut hint = Hint::new();
|
|
if let Some(e) = ext {
|
|
hint.with_extension(e);
|
|
}
|
|
let probed = symphonia::default::get_probe()
|
|
.format(
|
|
&hint,
|
|
mss,
|
|
&FormatOptions { enable_gapless: true, ..Default::default() },
|
|
&MetadataOptions::default(),
|
|
)
|
|
.map_err(err)?;
|
|
let format = probed.format;
|
|
let track =
|
|
format.tracks().iter().find(|t| t.codec_params.codec != CODEC_TYPE_NULL).ok_or(AudioError::Unsupported)?;
|
|
let params = track.codec_params.clone();
|
|
let rate = params.sample_rate.ok_or(AudioError::Damaged("no sample rate"))?;
|
|
let channels = params.channels.map(|c| c.count() as u16).unwrap_or(1);
|
|
if rate < 4_000 || rate > caps.max_rate || channels == 0 || channels > caps.max_channels {
|
|
return Err(AudioError::Damaged("an impossible format"));
|
|
}
|
|
let decoder = symphonia::default::get_codecs().make(¶ms, &DecoderOptions::default()).map_err(err)?;
|
|
Ok(Decoder { track: track.id, format, decoder, rate, channels, caps, decoded_frames: 0, errors: 0 })
|
|
}
|
|
|
|
/// The next block of interleaved samples; `Ok(None)` at the end.
|
|
pub fn next_block(&mut self) -> Result<Option<Vec<f32>>, AudioError> {
|
|
loop {
|
|
if self.decoded_frames > u64::from(self.caps.max_hours) * 3600 * u64::from(self.rate) {
|
|
return Err(AudioError::Damaged("longer than any audiobook"));
|
|
}
|
|
let packet = match self.format.next_packet() {
|
|
Ok(p) => p,
|
|
Err(SymError::IoError(e)) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
|
|
Err(SymError::ResetRequired) => return Ok(None),
|
|
Err(e) => {
|
|
self.errors += 1;
|
|
if self.errors > self.caps.max_errors {
|
|
return Err(err(e));
|
|
}
|
|
// A truncated or damaged file ends here rather than looping.
|
|
return Ok(None);
|
|
}
|
|
};
|
|
if packet.track_id() != self.track {
|
|
continue;
|
|
}
|
|
match self.decoder.decode(&packet) {
|
|
Ok(buf) => {
|
|
self.errors = 0;
|
|
let spec = *buf.spec();
|
|
let frames = buf.frames();
|
|
if frames == 0 {
|
|
continue;
|
|
}
|
|
let mut sb = SampleBuffer::<f32>::new(frames as u64, spec);
|
|
sb.copy_interleaved_ref(buf);
|
|
self.decoded_frames += frames as u64;
|
|
return Ok(Some(sb.samples().to_vec()));
|
|
}
|
|
Err(SymError::DecodeError(_)) => {
|
|
self.errors += 1;
|
|
if self.errors > self.caps.max_errors {
|
|
return Err(AudioError::Damaged("too many decode errors"));
|
|
}
|
|
}
|
|
Err(e) => return Err(err(e)),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Jumps to a position (milliseconds); the next block starts there or just before.
|
|
pub fn seek(&mut self, ms: u64) -> Result<(), AudioError> {
|
|
let time = Time::new(ms / 1000, (ms % 1000) as f64 / 1000.0);
|
|
self.format.seek(SeekMode::Accurate, SeekTo::Time { time, track_id: Some(self.track) }).map_err(err)?;
|
|
self.decoder.reset();
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// For callers that have only bytes (tests, short clips): decodes everything.
|
|
pub fn decode_all(bytes: Vec<u8>, caps: DecodeCaps) -> Result<(u32, u16, Vec<f32>), AudioError> {
|
|
if crate::container::inspect(&bytes, Default::default()) == Err(AudioError::Drm) {
|
|
return Err(AudioError::Drm);
|
|
}
|
|
let len = bytes.len() as u64;
|
|
let mut d = Decoder::open(std::io::Cursor::new(bytes), Some(len), None, caps)?;
|
|
let mut out = Vec::new();
|
|
while let Some(b) = d.next_block()? {
|
|
out.extend_from_slice(&b);
|
|
}
|
|
Ok((d.rate, d.channels, out))
|
|
}
|