use crate::aac::AACFile;
use crate::ape::ApeFile;
use crate::error::Result;
use crate::file::{AudioFile, FileType, TaggedFile};
use crate::flac::FlacFile;
use crate::iff::aiff::AiffFile;
use crate::iff::wav::WavFile;
use crate::macros::err;
use crate::mp4::Mp4File;
use crate::mpeg::header::search_for_frame_sync;
use crate::mpeg::MPEGFile;
use crate::ogg::opus::OpusFile;
use crate::ogg::speex::SpeexFile;
use crate::ogg::vorbis::VorbisFile;
use crate::resolve::CUSTOM_RESOLVERS;
use crate::wavpack::WavPackFile;
use std::fs::File;
use std::io::{BufReader, Cursor, Read, Seek, SeekFrom};
use std::path::Path;
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub struct ParseOptions {
pub(crate) read_properties: bool,
pub(crate) use_custom_resolvers: bool,
pub(crate) parsing_mode: ParsingMode,
}
impl Default for ParseOptions {
fn default() -> Self {
Self::new()
}
}
impl ParseOptions {
#[must_use]
pub const fn new() -> Self {
Self {
read_properties: true,
use_custom_resolvers: true,
parsing_mode: ParsingMode::Strict,
}
}
pub fn read_properties(&mut self, read_properties: bool) -> Self {
self.read_properties = read_properties;
*self
}
pub fn use_custom_resolvers(&mut self, use_custom_resolvers: bool) -> Self {
self.use_custom_resolvers = use_custom_resolvers;
*self
}
pub fn parsing_mode(&mut self, parsing_mode: ParsingMode) -> Self {
self.parsing_mode = parsing_mode;
*self
}
}
#[derive(Copy, Clone, Debug)]
#[non_exhaustive]
pub enum ParsingMode {
Strict,
Relaxed,
}
pub struct Probe<R: Read> {
inner: R,
options: Option<ParseOptions>,
f_ty: Option<FileType>,
}
impl<R: Read> Probe<R> {
#[must_use]
pub const fn new(reader: R) -> Self {
Self {
inner: reader,
options: None,
f_ty: None,
}
}
pub fn with_file_type(reader: R, file_type: FileType) -> Self {
Self {
inner: reader,
options: None,
f_ty: Some(file_type),
}
}
pub fn file_type(&self) -> Option<FileType> {
self.f_ty
}
pub fn set_file_type(&mut self, file_type: FileType) {
self.f_ty = Some(file_type)
}
#[must_use]
pub fn options(mut self, options: ParseOptions) -> Self {
self.options = Some(options);
self
}
pub fn into_inner(self) -> R {
self.inner
}
}
impl Probe<BufReader<File>> {
pub fn open<P>(path: P) -> Result<Self>
where
P: AsRef<Path>,
{
let path = path.as_ref();
Ok(Self {
inner: BufReader::new(File::open(path)?),
options: None,
f_ty: FileType::from_path(path),
})
}
}
impl<R: Read + Seek> Probe<R> {
pub fn guess_file_type(mut self) -> std::io::Result<Self> {
let f_ty = self.guess_inner()?;
self.f_ty = f_ty.or(self.f_ty);
Ok(self)
}
#[allow(clippy::shadow_unrelated)]
fn guess_inner(&mut self) -> std::io::Result<Option<FileType>> {
let mut buf = [0; 36];
let starting_position = self.inner.stream_position()?;
let buf_len = std::io::copy(
&mut self.inner.by_ref().take(buf.len() as u64),
&mut Cursor::new(&mut buf[..]),
)? as usize;
self.inner.seek(SeekFrom::Start(starting_position))?;
match FileType::from_buffer_inner(&buf[..buf_len]) {
(Some(f_ty), _) => Ok(Some(f_ty)),
(None, Some(id3_len)) => {
let position_after_id3_block = self
.inner
.seek(SeekFrom::Current(i64::from(10 + id3_len)))?;
let mut ident = [0; 4];
std::io::copy(
&mut self.inner.by_ref().take(ident.len() as u64),
&mut Cursor::new(&mut ident[..]),
)?;
self.inner.seek(SeekFrom::Start(position_after_id3_block))?;
let file_type_after_id3_block = match &ident {
[b'M', b'A', b'C', ..] => Ok(Some(FileType::APE)),
b"fLaC" => Ok(Some(FileType::FLAC)),
_ if search_for_frame_sync(&mut self.inner)?.is_some() => {
self.inner.seek(SeekFrom::Current(-2))?;
let mut buf = [0; 2];
self.inner.read_exact(&mut buf)?;
if buf[1] & 0b10000 > 0 && buf[1] & 0b110 == 0 {
Ok(Some(FileType::AAC))
} else {
Ok(Some(FileType::MPEG))
}
},
_ => Ok(None),
};
self.inner.seek(SeekFrom::Start(starting_position))?;
file_type_after_id3_block
},
_ => {
if let Ok(lock) = CUSTOM_RESOLVERS.lock() {
#[allow(clippy::significant_drop_in_scrutinee)]
for (_, resolve) in lock.iter() {
if let ret @ Some(_) = resolve.guess(&buf[..buf_len]) {
return Ok(ret);
}
}
}
Ok(None)
},
}
}
pub fn read(mut self) -> Result<TaggedFile> {
let reader = &mut self.inner;
let options = self.options.unwrap_or_default();
match self.f_ty {
Some(f_type) => Ok(match f_type {
FileType::AAC => AACFile::read_from(reader, options)?.into(),
FileType::AIFF => AiffFile::read_from(reader, options)?.into(),
FileType::APE => ApeFile::read_from(reader, options)?.into(),
FileType::FLAC => FlacFile::read_from(reader, options)?.into(),
FileType::MPEG => MPEGFile::read_from(reader, options)?.into(),
FileType::Opus => OpusFile::read_from(reader, options)?.into(),
FileType::Vorbis => VorbisFile::read_from(reader, options)?.into(),
FileType::WAV => WavFile::read_from(reader, options)?.into(),
FileType::MP4 => Mp4File::read_from(reader, options)?.into(),
FileType::Speex => SpeexFile::read_from(reader, options)?.into(),
FileType::WavPack => WavPackFile::read_from(reader, options)?.into(),
FileType::Custom(c) => {
if !options.use_custom_resolvers {
err!(UnknownFormat)
}
let resolver = crate::resolve::lookup_resolver(c);
resolver.read_from(reader, options)?
},
}),
None => err!(UnknownFormat),
}
}
}
pub fn read_from(file: &mut File) -> Result<TaggedFile> {
Probe::new(BufReader::new(file)).guess_file_type()?.read()
}
pub fn read_from_path<P>(path: P) -> Result<TaggedFile>
where
P: AsRef<Path>,
{
Probe::open(path)?.read()
}
#[cfg(test)]
mod tests {
use crate::{FileType, Probe};
use std::fs::File;
#[test]
fn mp3_id3v2_trailing_junk() {
let data: [&[u8]; 4] = [
&[0x49, 0x44, 0x33, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23],
&[
0x54, 0x41, 0x4C, 0x42, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x01, 0xFF, 0xFE, 0x61,
0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00, 0x61,
0x00, 0x61, 0x00, 0x61, 0x00, 0x61, 0x00,
],
&[0x20, 0x20, 0x20, 0x20],
&[
0xFF, 0xFB, 0x50, 0xC4, 0x00, 0x03, 0xC0, 0x00, 0x01, 0xA4, 0x00, 0x00, 0x00, 0x20,
0x00, 0x00, 0x34, 0x80, 0x00, 0x00, 0x04,
],
];
let data: Vec<u8> = data.into_iter().flatten().copied().collect();
let data = std::io::Cursor::new(&data);
let probe = Probe::new(data).guess_file_type().unwrap();
assert_eq!(probe.file_type(), Some(FileType::MPEG));
}
fn test_probe(path: &str, expected_file_type_guess: FileType) {
test_probe_file(path, expected_file_type_guess);
test_probe_path(path, expected_file_type_guess);
}
fn test_probe_file(path: &str, expected_file_type_guess: FileType) {
let mut f = File::open(path).unwrap();
let probe = Probe::new(&mut f).guess_file_type().unwrap();
assert_eq!(probe.file_type(), Some(expected_file_type_guess));
}
fn test_probe_path(path: &str, expected_file_type_guess: FileType) {
let probe = Probe::open(path).unwrap();
assert_eq!(probe.file_type(), Some(expected_file_type_guess));
}
#[test]
fn probe_aac() {
test_probe("tests/files/assets/minimal/untagged.aac", FileType::AAC);
}
#[test]
fn probe_aac_with_id3v2() {
test_probe("tests/files/assets/minimal/full_test.aac", FileType::AAC);
}
#[test]
fn probe_aiff() {
test_probe("tests/files/assets/minimal/full_test.aiff", FileType::AIFF);
}
#[test]
fn probe_ape_with_id3v2() {
test_probe("tests/files/assets/minimal/full_test.ape", FileType::APE);
}
#[test]
fn probe_flac() {
test_probe("tests/files/assets/minimal/full_test.flac", FileType::FLAC);
}
#[test]
fn probe_flac_with_id3v2() {
test_probe("tests/files/assets/flac_with_id3v2.flac", FileType::FLAC);
}
#[test]
fn probe_mp3_with_id3v2() {
test_probe("tests/files/assets/minimal/full_test.mp3", FileType::MPEG);
}
#[test]
fn probe_vorbis() {
test_probe("tests/files/assets/minimal/full_test.ogg", FileType::Vorbis);
}
#[test]
fn probe_opus() {
test_probe("tests/files/assets/minimal/full_test.opus", FileType::Opus);
}
#[test]
fn probe_speex() {
test_probe("tests/files/assets/minimal/full_test.spx", FileType::Speex);
}
#[test]
fn probe_mp4() {
test_probe(
"tests/files/assets/minimal/m4a_codec_aac.m4a",
FileType::MP4,
);
}
#[test]
fn probe_wav() {
test_probe(
"tests/files/assets/minimal/wav_format_pcm.wav",
FileType::WAV,
);
}
}