use std::fmt;
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Limitation {
OutOfTime,
GridScanOutOfTime,
GridScanIncomplete,
GridNotScanned,
LengthPastBytes,
LengthNotStated {
seconds: u64,
},
LongerThanStated {
seconds: u64,
},
AudioMissing {
seconds: f64,
},
PacketsSkipped {
count: u32,
},
Decoder(String),
Sampled {
windows: usize,
},
OtherTracks {
tracks: usize,
},
ChannelsLeftOut {
channels: u32,
},
LittleAudio {
seconds: f64,
},
Quiet,
OtherRate {
rate: String,
hz: f64,
},
FilteredAt20Khz,
LowestCutoffOnly,
AacGridWithoutSteps,
CutoffWithoutGrid,
EarlyRollOff,
Dsd {
pcm_rate: u32,
},
RebuiltBand {
hz: f64,
},
}
impl fmt::Display for Limitation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfTime => {
f.write_str("The analysis ran out of time and covers only the part read by then")
}
Self::GridScanOutOfTime => {
f.write_str("The analysis ran out of time before the codec grid scan finished")
}
Self::GridScanIncomplete => f.write_str(
"The stretches the codec grid scan reads were not all read, so the scan did not run",
),
Self::GridNotScanned => {
f.write_str("The file does not state its length, so its codec grid was not scanned")
}
Self::LengthPastBytes => f.write_str(
"The file states a longer length than its bytes can hold, so the length they hold is used",
),
Self::LengthNotStated { seconds } => write!(
f,
"The file does not state its length, so the analysis stopped after {}",
minutes(*seconds)
),
Self::LongerThanStated { seconds } => write!(
f,
"The file runs longer than it states, so the analysis stopped after {}",
minutes(*seconds)
),
Self::AudioMissing { seconds } if *seconds < 1.0 => {
write!(f, "The file holds {seconds:.2} s less audio than it states")
}
Self::AudioMissing { seconds } => {
write!(f, "The file holds {seconds:.1} s less audio than it states")
}
Self::PacketsSkipped { count: 1 } => {
f.write_str("1 packet could not be decoded and was skipped")
}
Self::PacketsSkipped { count } => {
write!(f, "{count} packets could not be decoded and were skipped")
}
Self::Decoder(why) => {
let mut chars = why.chars();
match chars.next() {
Some(first) => write!(f, "{}{}", first.to_uppercase(), chars.as_str()),
None => Ok(()),
}
}
Self::Sampled { windows: 1 } => {
f.write_str("Only 1 one-second window of the file was analyzed")
}
Self::Sampled { windows } => write!(
f,
"Only {windows} one-second windows spread over the file were analyzed"
),
Self::OtherTracks { tracks } => {
write!(f, "Only the first of {tracks} audio tracks was analyzed")
}
Self::ChannelsLeftOut { channels } => {
write!(f, "Only the first two of {channels} channels were analyzed")
}
Self::LittleAudio { seconds } => write!(
f,
"Only {seconds:.1} s of the audio is above silence, too little for a reliable reading"
),
Self::Quiet => {
f.write_str("The audio is quiet, which makes the upper band harder to measure")
}
Self::OtherRate { rate, hz } => write!(
f,
"Audio recorded at {rate} and converted to this rate has the same sharp cutoff at {}",
khz(*hz)
),
Self::FilteredAt20Khz => f.write_str(
"A recording filtered at 20 kHz when it was made looks the same as a high-bitrate \
encoder's cutoff",
),
Self::LowestCutoffOnly => {
f.write_str("Of several lossy generations, only the lowest cutoff shows")
}
Self::AacGridWithoutSteps => {
f.write_str("A Vorbis decode's frame grid reads as AAC's, and a WMA decode's can")
}
Self::CutoffWithoutGrid => f.write_str(
"A recording filtered where an encoder cuts, and a decode resampled afterwards, stop at \
an encoder's cutoff without a frame grid",
),
Self::Dsd { pcm_rate } => write!(
f,
"The file is DSD, measured as PCM at {}: the noise its one-bit samples carry above \
the audio band reads as content, and no codec grid is looked for",
khz(f64::from(*pcm_rate))
),
Self::RebuiltBand { hz } => write!(
f,
"The decoder rebuilt the band above the HE-AAC core, which ends at or under {}, from \
the band below, so the cutoff is not where an encoder's lowpass sits",
khz(*hz)
),
Self::EarlyRollOff => f.write_str(
"Old masters, speech, lo-fi material and vinyl or cassette transfers roll off early, and \
heavy equalization can look like a shelf",
),
}
}
}
fn minutes(seconds: u64) -> String {
match seconds {
1 => "a second".to_string(),
60 => "a minute".to_string(),
s if s > 0 && s % 60 == 0 => format!("{} minutes", s / 60),
s => format!("{s} seconds"),
}
}
pub(crate) fn khz(hz: f64) -> String {
let text = format!("{:.1}", hz / 1000.0);
format!("{} kHz", text.strip_suffix(".0").unwrap_or(&text))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_decoders_clause_is_written_as_a_sentence_of_its_own() {
let stopped = Limitation::Decoder("seeking failed: end of stream".to_string());
assert_eq!(stopped.to_string(), "Seeking failed: end of stream");
assert_eq!(Limitation::Decoder(String::new()).to_string(), "");
let whole = Limitation::LengthNotStated { seconds: 120 };
assert!(whole.to_string().ends_with("after 2 minutes"));
}
#[test]
fn one_of_a_thing_is_written_in_the_singular() {
let one = [
Limitation::PacketsSkipped { count: 1 }.to_string(),
Limitation::Sampled { windows: 1 }.to_string(),
Limitation::LengthNotStated { seconds: 1 }.to_string(),
];
assert_eq!(
one,
[
"1 packet could not be decoded and was skipped",
"Only 1 one-second window of the file was analyzed",
"The file does not state its length, so the analysis stopped after a second",
]
);
let two = Limitation::PacketsSkipped { count: 2 }.to_string();
assert_eq!(two, "2 packets could not be decoded and were skipped");
}
}