Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 54 additions & 6 deletions src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ pub(crate) struct Audio {
#[n(8)]
pub(crate) samples: u64,
#[n(9)]
pub(crate) title: Text,
pub(crate) size: u64,
#[n(10)]
pub(crate) track: u64,
pub(crate) title: Text,
#[n(11)]
pub(crate) tracks: u64,
pub(crate) track: u64,
#[n(12)]
pub(crate) tracks: u64,
#[n(13)]
#[serde(rename = "type")]
pub(crate) ty: AudioType,
}
Expand Down Expand Up @@ -162,6 +164,7 @@ impl Audio {
sample_bits,
sample_rate,
samples,
size,
title,
track,
tracks,
Expand All @@ -175,6 +178,7 @@ impl Audio {
self.sample_bits = sample_bits;
self.sample_rate = sample_rate;
self.samples = samples;
self.size = size;
self.title = title;
self.track = track;
self.tracks = tracks;
Expand Down Expand Up @@ -234,6 +238,7 @@ impl FromStr for Audio {
sample_bits: None,
sample_rate: 0,
samples: 0,
size: 0,
title: Text::new(),
track: 0,
tracks: 0,
Expand All @@ -260,6 +265,13 @@ impl Item for Audio {
.map(|sample_bits| format!("{sample_bits}-bit")),
)
.value("sample rate", DisplaySampleRate(self.sample_rate))
.optional(
"bit rate",
DisplayBitrate::new(
u64::try_from(self.duration().as_millis()).unwrap_or(u64::MAX),
self.size,
),
)
.value("channels", self.channels)
.value(
"compression mode",
Expand Down Expand Up @@ -470,6 +482,7 @@ mod tests {
sample_bits: None,
sample_rate: 0,
samples: 0,
size: 0,
title: Text::new(),
track: 0,
tracks: 0,
Expand All @@ -489,6 +502,7 @@ mod tests {
sample_bits: None,
sample_rate: 0,
samples: 0,
size: 0,
title: Text::new(),
track: 0,
tracks: 0,
Expand Down Expand Up @@ -523,6 +537,7 @@ mod tests {
audio.sample_bits = Some(16);
audio.sample_rate = 44100;
audio.samples = 66150;
audio.size = 750;
audio.title = "bar".parse().unwrap();
audio.track = 3;
audio.tracks = 4;
Expand All @@ -546,6 +561,7 @@ mod tests {
("type".into(), Info::Value("FLAC".into())),
("sample bits".into(), Info::Value("16-bit".into())),
("sample rate".into(), Info::Value("44.1 kHz".into())),
("bit rate".into(), Info::Value("4 kbit/s".into())),
("channels".into(), Info::Value("2".into())),
("compression mode".into(), Info::Value("lossless".into())),
("samples".into(), Info::Value("66150".into())),
Expand All @@ -560,6 +576,7 @@ mod tests {
audio.discs = 2;
audio.sample_rate = 44100;
audio.samples = 66150;
audio.size = 750;
audio.title = "bar".parse().unwrap();
audio.track = 3;
audio.tracks = 4;
Expand All @@ -582,11 +599,39 @@ mod tests {
("duration".into(), Info::Value("0:01".into())),
("type".into(), Info::Value("MP3".into())),
("sample rate".into(), Info::Value("44.1 kHz".into())),
("bit rate".into(), Info::Value("4 kbit/s".into())),
("channels".into(), Info::Value("2".into())),
("compression mode".into(), Info::Value("lossy".into())),
("samples".into(), Info::Value("66150".into())),
]),
);

let mut audio = "foo.flac".parse::<Audio>().unwrap();
audio.size = 750;

assert_eq!(
Item::info(&audio, "bob".into()),
Info::Map(vec![
(
"filename".into(),
Info::Link {
text: "foo.flac".into(),
url: "bob".into(),
},
),
("title".into(), Info::Value(String::new())),
("artist".into(), Info::Value(String::new())),
("album".into(), Info::Value(String::new())),
("disc".into(), Info::Value("0 of 0".into())),
("track".into(), Info::Value("0 of 0".into())),
("duration".into(), Info::Value("0:00".into())),
("type".into(), Info::Value("FLAC".into())),
("sample rate".into(), Info::Value("0 kHz".into())),
("channels".into(), Info::Value("0".into())),
("compression mode".into(), Info::Value("lossless".into())),
("samples".into(), Info::Value("0".into())),
]),
);
}

#[test]
Expand Down Expand Up @@ -634,6 +679,7 @@ mod tests {
sample_bits: Some(16),
sample_rate: 44100,
samples: 66150,
size: 1024,
title: "bar".parse().unwrap(),
track: 3,
tracks: 4,
Expand All @@ -656,6 +702,7 @@ mod tests {
sample_bits: None,
sample_rate: 44100,
samples: 2304,
size: 834,
title: "bar".parse().unwrap(),
track: 3,
tracks: 4,
Expand All @@ -668,12 +715,12 @@ mod tests {
fn serialize() {
assert_eq!(
serde_json::to_string(&"foo.flac".parse::<Audio>().unwrap()).unwrap(),
r#"{"album":"","artist":"","channels":0,"disc":0,"discs":0,"filename":"foo.flac","sample_rate":0,"samples":0,"title":"","track":0,"tracks":0,"type":"flac"}"#,
r#"{"album":"","artist":"","channels":0,"disc":0,"discs":0,"filename":"foo.flac","sample_rate":0,"samples":0,"size":0,"title":"","track":0,"tracks":0,"type":"flac"}"#,
);

assert_eq!(
serde_json::to_string(&"foo.mp3".parse::<Audio>().unwrap()).unwrap(),
r#"{"album":"","artist":"","channels":0,"disc":0,"discs":0,"filename":"foo.mp3","sample_rate":0,"samples":0,"title":"","track":0,"tracks":0,"type":"mp3"}"#,
r#"{"album":"","artist":"","channels":0,"disc":0,"discs":0,"filename":"foo.mp3","sample_rate":0,"samples":0,"size":0,"title":"","track":0,"tracks":0,"type":"mp3"}"#,
);

assert_eq!(
Expand All @@ -687,13 +734,14 @@ mod tests {
sample_bits: Some(7),
sample_rate: 1,
samples: 2,
size: 9,
title: "bar".parse().unwrap(),
track: 5,
tracks: 6,
ty: AudioType::Flac,
})
.unwrap(),
r#"{"album":"qux","artist":"baz","channels":8,"disc":3,"discs":4,"filename":"foo.flac","sample_bits":7,"sample_rate":1,"samples":2,"title":"bar","track":5,"tracks":6,"type":"flac"}"#,
r#"{"album":"qux","artist":"baz","channels":8,"disc":3,"discs":4,"filename":"foo.flac","sample_bits":7,"sample_rate":1,"samples":2,"size":9,"title":"bar","track":5,"tracks":6,"type":"flac"}"#,
);
}
}
2 changes: 2 additions & 0 deletions src/audio_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ pub enum AudioError {
FlacDecode { source: claxon::Error },
#[snafu(display("unknown sample count"))]
FlacSampleCountUnknown,
#[snafu(display("truncated FLAC metadata block"))]
FlacTruncated,
#[snafu(display("failed to decode MP3"))]
Mp3Decode { source: Mp3Error },
#[snafu(display("failed to read ID3 tag"))]
Expand Down
1 change: 1 addition & 0 deletions src/audio_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub(crate) struct AudioMetadata {
pub(crate) sample_bits: Option<u64>,
pub(crate) sample_rate: u64,
pub(crate) samples: u64,
pub(crate) size: u64,
pub(crate) title: Text,
pub(crate) track: u64,
pub(crate) tracks: u64,
Expand Down
21 changes: 18 additions & 3 deletions src/display_bitrate.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
use super::*;

pub(crate) struct DisplayBitrate {
pub(crate) duration: u64,
pub(crate) size: u64,
duration: u64,
size: u64,
}

impl DisplayBitrate {
pub(crate) fn new(duration: u64, size: u64) -> Option<Self> {
(duration > 0).then_some(Self { duration, size })
}
}

impl Display for DisplayBitrate {
Expand Down Expand Up @@ -32,7 +38,10 @@ mod tests {
fn display() {
#[track_caller]
fn case(size: u64, duration: u64, expected: &str) {
assert_eq!(DisplayBitrate { duration, size }.to_string(), expected);
assert_eq!(
DisplayBitrate::new(duration, size).unwrap().to_string(),
expected,
);
}

case(0, 1000, "0 bits/s");
Expand All @@ -44,4 +53,10 @@ mod tests {
case(437_500, 1000, "3.5 Mbit/s");
case(125_000_000, 1000, "1 Gbit/s");
}

#[test]
fn new() {
assert!(DisplayBitrate::new(0, 1).is_none());
assert!(DisplayBitrate::new(1, 1).is_some());
}
}
72 changes: 59 additions & 13 deletions src/flac_decoder.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use super::*;

pub(crate) struct FlacDecoder<T: io::Read> {
reader: FlacReader<T>,
pub(crate) struct FlacDecoder<'a> {
reader: FlacReader<&'a [u8]>,
}

impl<T: io::Read> FlacDecoder<T> {
fn decode(reader: T) -> Result<AudioMetadata, AudioError> {
impl<'a> FlacDecoder<'a> {
fn decode(data: &'a [u8]) -> Result<AudioMetadata, AudioError> {
let decoder = Self {
reader: FlacReader::new(reader).context(audio_error::FlacDecode)?,
reader: FlacReader::new(data).context(audio_error::FlacDecode)?,
};

let streaminfo = decoder.reader.streaminfo();
Expand All @@ -25,17 +25,45 @@ impl<T: io::Read> FlacDecoder<T> {
sample_bits: Some(streaminfo.bits_per_sample.into()),
sample_rate: streaminfo.sample_rate.into(),
samples,
size: (data.len() - Self::frame_offset(data)?).into_u64(),
title: decoder.text_tag("title")?,
track: decoder.number_tag("tracknumber")?,
tracks: decoder.number_tag("tracktotal")?,
})
}

fn frame_offset(data: &[u8]) -> Result<usize, AudioError> {
let mut offset = 4;

loop {
let header = data
.get(offset..offset + 4)
.context(audio_error::FlacTruncated)?;

let length =
usize::from(header[1]) << 16 | usize::from(header[2]) << 8 | usize::from(header[3]);

offset += 4 + length;

ensure!(offset <= data.len(), audio_error::FlacTruncated);

if header[0] & 0x80 != 0 {
return Ok(offset);
}
}
}

fn number_tag(&self, tag: &'static str) -> Result<u64, AudioError> {
let value = self.tag(tag)?;
parse_number(value).context(audio_error::TagInteger { tag })
}

pub(crate) fn read(path: &Utf8Path) -> Result<AudioMetadata> {
let data = filesystem::read(path)?;

FlacDecoder::decode(&data).context(error::Audio { path })
}

fn tag(&self, tag: &'static str) -> Result<&str, AudioError> {
Audio::tag(self.reader.get_tag(tag), tag)
}
Expand All @@ -48,14 +76,6 @@ impl<T: io::Read> FlacDecoder<T> {
}
}

impl FlacDecoder<fs::File> {
pub(crate) fn read(path: &Utf8Path) -> Result<AudioMetadata> {
let file = filesystem::open(path)?;

Self::decode(file).context(error::Audio { path })
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -246,6 +266,31 @@ mod tests {
);
}

#[test]
fn frame_offset() {
let bytes = flac(&[], 44100);
assert_eq!(
FlacDecoder::frame_offset(&bytes).unwrap(),
bytes.len() - 1024,
);

let bytes = flac(&["foo=bar"], 44100);
assert_eq!(
FlacDecoder::frame_offset(&bytes).unwrap(),
bytes.len() - 1024,
);

assert_matches!(
FlacDecoder::frame_offset(b"fLaC"),
Err(AudioError::FlacTruncated),
);

assert_matches!(
FlacDecoder::frame_offset(&[b"fLaC".as_slice(), &[0x80, 0x00, 0x00, 0x22]].concat()),
Err(AudioError::FlacTruncated),
);
}

#[test]
fn read_ok() {
let (_tempdir, root) = tempdir();
Expand Down Expand Up @@ -280,6 +325,7 @@ mod tests {
sample_bits: Some(16),
sample_rate: 44100,
samples: 66150,
size: 1024,
title: "bar".parse().unwrap(),
track: 3,
tracks: 4,
Expand Down
1 change: 1 addition & 0 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ mod tests {
sample_bits: Some(7),
sample_rate: 1,
samples: 2,
size: 9,
title: "foo".parse().unwrap(),
track: 5,
tracks: 6,
Expand Down
Loading