use crate::aggregate::{Measures, measures, middle, percentile, upsample_ratio};
use crate::decode::opus::OpusUse;
use crate::engine::{Measured, grid_looked_for};
use crate::flags::{Flag, findings};
use crate::grid::{self, Codec, Evidence, Family, Found};
use crate::limitation::{Limitation, khz};
use crate::thresholds::{EncoderProfile, ReadingThresholds};
use crate::window::{Step, Window};
const HI_RES_TOP_HZ: f64 = 24_000.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Verdict {
Consistent,
LikelyTranscode,
MixedSources,
PossiblyLossy,
Inconclusive,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct EncoderGuess {
pub profile: EncoderProfile,
pub confidence: f64,
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Reading {
pub verdict: Verdict,
pub cutoff_verdict: Verdict,
pub grid: Option<Found>,
pub confidence: f64,
pub flags: Vec<Flag>,
pub encoder_guess: Option<EncoderGuess>,
pub summary: String,
pub measures: Measures,
#[cfg_attr(feature = "serde", serde(serialize_with = "sentences"))]
pub limitations: Vec<Limitation>,
pub cutoff_hz: Option<f64>,
}
struct CutoffReading {
verdict: Verdict,
confidence: f64,
encoder_guess: Option<EncoderGuess>,
summary: String,
limitations: Vec<Limitation>,
cutoff_hz: Option<f64>,
}
#[cfg(feature = "serde")]
fn sentences<S: serde::Serializer>(
limitations: &[Limitation],
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.collect_seq(limitations.iter().map(ToString::to_string))
}
#[derive(Clone, Copy, Debug)]
struct Seen {
cutoff_hz: Option<f64>,
sharp: bool,
seconds: f64,
inner_shelf: Option<Step>,
rms_dbfs: f64,
}
impl Seen {
fn of(window: &Window, top: f64, thresholds: &ReadingThresholds) -> Self {
let floor = window.inner_shelf.filter(|step| {
window
.cutoff_hz
.is_some_and(|c| c >= thresholds.full_band * top)
&& step.drop >= thresholds.inner_shelf_db
&& thresholds.profile_at(step.hz).is_some()
&& step.clearance < thresholds.clear_db
});
match floor {
Some(step) => Self {
cutoff_hz: Some(step.hz),
sharp: true,
inner_shelf: None,
rms_dbfs: window.rms_dbfs,
seconds: window.seconds,
},
None => Self {
cutoff_hz: window.cutoff_hz,
sharp: window.sharp(thresholds),
inner_shelf: window.inner_shelf,
rms_dbfs: window.rms_dbfs,
seconds: window.seconds,
},
}
}
}
struct Heard<'a> {
windows: Vec<Seen>,
top: f64,
thresholds: &'a ReadingThresholds,
}
impl<'a> Heard<'a> {
fn seconds(&self) -> f64 {
self.windows.iter().fold(0.0, |sum, w| sum + w.seconds)
}
fn share(&self, keep: impl Fn(&Seen) -> bool) -> f64 {
let kept = self.windows.iter().filter(|w| keep(w)).count();
kept as f64 / self.windows.len().max(1) as f64
}
fn full(&self, window: &Seen) -> bool {
window
.cutoff_hz
.is_some_and(|c| c >= self.thresholds.full_band * self.top)
}
fn limited(&self, window: &Seen) -> Option<&'a EncoderProfile> {
let cutoff = window.cutoff_hz?;
(!self.full(window) && window.sharp)
.then(|| lower_profile_at(self.thresholds, cutoff))
.flatten()
}
fn stepped(&self, window: &Seen, depth: f64) -> Option<f64> {
let step = window.inner_shelf?;
(self.full(window) && step.drop >= depth).then_some(step.hz)
}
fn layered(&self, window: &Seen) -> Option<f64> {
self
.stepped(window, self.thresholds.inner_shelf_db)
.filter(|hz| lower_profile_at(self.thresholds, *hz).is_some())
}
}
fn lower_profile_at(thresholds: &ReadingThresholds, hz: f64) -> Option<&EncoderProfile> {
thresholds
.profile_at(hz)
.filter(|p| p.kbps < thresholds.high_bitrate_kbps)
}
impl Measured {
pub fn read(&self, thresholds: &ReadingThresholds) -> Reading {
let claimed = &self.claimed;
let nyquist = f64::from(claimed.sample_rate) / 2.0;
let windows: Vec<&Window> = self
.windows
.iter()
.filter(|w| w.cutoff_hz.is_some())
.collect();
let upsample_ratio = (claimed.sample_rate > 48_000).then(|| upsample_ratio(&windows));
let measures = measures(self, &windows, upsample_ratio);
let median = measures.cutoff_median_hz.map(f64::from);
let found_beside = findings(claimed, &windows, median, &measures, thresholds);
let top = found_beside.source_edge.unwrap_or(nyquist);
let windows: Vec<Seen> = windows
.iter()
.map(|w| Seen::of(w, top, thresholds))
.collect();
let cutoffs: Vec<f64> = windows.iter().filter_map(|w| w.cutoff_hz).collect();
let median = (!cutoffs.is_empty()).then(|| middle(&cutoffs));
let heard = Heard {
windows,
top,
thresholds,
};
let mut limitations = self.problems.clone();
if self.sampled {
limitations.push(Limitation::Sampled {
windows: self.windows.len(),
});
}
if self.channels_left_out > 0 {
limitations.push(Limitation::ChannelsLeftOut {
channels: claimed.channels,
});
}
let mut found = verdict(&heard, median, claimed.lossless, self.bitrate_kbps);
let heard_seconds = heard.seconds();
if heard_seconds < thresholds.few_seconds() {
limitations.push(Limitation::LittleAudio {
seconds: heard_seconds,
});
}
if quiet(&heard) {
limitations.push(Limitation::Quiet);
}
let own_cutoff = !claimed.lossless && found.verdict == Verdict::Consistent;
if let Some(edge) = found_beside.source_edge
&& let Some(profile) = thresholds.profile_at(edge)
&& found.verdict != Verdict::MixedSources
&& !own_cutoff
{
found = CutoffReading {
verdict: Verdict::Inconclusive,
confidence: 0.4,
encoder_guess: Some(EncoderGuess {
profile: profile.clone(),
confidence: 0.4,
}),
summary: format!(
"The content stops sharply at {}, both the upper limit of a {} kHz recording and the \
cutoff of an encoder at {}. The file was either upsampled from that rate or \
transcoded from that encoder, and the analyzer cannot tell which.",
khz(edge),
format!("{:.2}", edge * 2.0 / 1000.0)
.trim_end_matches('0')
.trim_end_matches('.'),
profile
),
limitations: Vec::new(),
cutoff_hz: Some(edge),
};
}
if found.verdict != Verdict::Consistent
&& let Some(cut) = found.cutoff_hz
&& let Some(edge) = thresholds
.other_rate_edges
.iter()
.find(|edge| (cut - edge.hz).abs() <= thresholds.cluster_hz)
{
limitations.push(Limitation::OtherRate {
rate: edge.rate.clone(),
hz: edge.hz,
});
}
let cutoff_verdict = found.verdict;
let grid = self
.grid
.as_ref()
.and_then(|scan| grid::found(scan, thresholds));
if grid_looked_for(claimed, self.dsd_rate) {
found = weighed(found, grid.as_ref(), self.grid.is_some(), thresholds);
}
limitations.extend(found.limitations);
if let Some(he_aac) = &self.he_aac {
found.encoder_guess = None;
if let Some(hz) = found.cutoff_hz {
found.summary = format!("The decoded band reaches about {}.", khz(hz));
}
limitations.push(Limitation::RebuiltBand {
hz: he_aac.core_top_hz(),
});
}
if self.dsd_rate.is_some() {
limitations.push(Limitation::Dsd {
pcm_rate: claimed.sample_rate,
});
}
Reading {
verdict: found.verdict,
cutoff_verdict,
grid,
confidence: found.confidence.min(thresholds.confidence_cap),
flags: found_beside.flags,
encoder_guess: found.encoder_guess,
summary: std::iter::once(found.summary)
.chain(found_beside.notes)
.chain(
OpusUse::describe(&self.opus).map(|coding| format!("Its Opus packets are {coding}.")),
)
.chain(self.he_aac.map(|he_aac| format!("The file is {he_aac}.")))
.chain(
self
.dsd_multiple()
.map(|multiple| format!("The file is DSD{multiple}.")),
)
.collect::<Vec<_>>()
.join(" "),
measures,
limitations,
cutoff_hz: found.cutoff_hz,
}
}
}
fn weighed(
found: CutoffReading,
grid: Option<&Found>,
scanned: bool,
thresholds: &ReadingThresholds,
) -> CutoffReading {
if let Some(grid) = grid {
let name = grid.codec;
let a = name.article();
let mut limitations = found.limitations;
let stepped = grid.quantizer.is_some() || matches!(grid.evidence, Evidence::AacSteps { .. });
if grid.codec == Codec::Aac && !stepped {
limitations.push(Limitation::AacGridWithoutSteps);
}
let evidence = match &grid.evidence {
Evidence::Part { segments, scan } => {
return CutoffReading {
verdict: Verdict::MixedSources,
confidence: thresholds.confidence_cap,
summary: format!(
"The samples carry {a} {name} frame grid at offset {} in {segments} of the {} \
stretches scanned (z {:.0}): part of the audio passed through {a} {name} encoder. {}",
scan.offset,
grid::SEGMENTS,
scan.z,
found.summary
),
limitations,
..found
};
}
Evidence::Count(scan) => format!(
"The samples carry {a} {name} frame grid at offset {} (z {:.0}, {} of {} segments \
agreeing), as audio decoded from {name} does.",
scan.offset,
scan.z,
scan.segments_agreeing,
grid::SEGMENTS,
),
Evidence::CountAt { rate, scan } => format!(
"Brought to {} kHz, the samples carry {a} {name} frame grid at offset {} (z {:.0}, {} of \
{} segments agreeing), as audio decoded from {name} at that rate and converted does.",
f64::from(*rate) / 1000.0,
scan.offset,
scan.z,
scan.segments_agreeing,
grid::SEGMENTS,
),
Evidence::Steps { offset, steps } => format!(
"With granules at offset {offset}, the values of {} scalefactor bands sit on whole \
steps of MP3's quantizer, as in audio decoded from MP3.",
steps.whole,
),
Evidence::AacSteps { offset, steps } => format!(
"With frames at offset {offset}, the values of {} scalefactor bands sit on whole steps \
of AAC's quantizer, as in audio decoded from AAC.",
steps.whole,
),
Evidence::Lattice(scan) if scan.frames >= thresholds.opus_grid_frames => format!(
"The band energies of {} frames at offset {} sit on the lattice of Opus's quantizer, as \
in audio decoded from Opus.",
scan.frames, scan.offset,
),
Evidence::Lattice(scan) => format!(
"The band energies of {} frames sit on the lattice of Opus's quantizer, on the frame \
grid of an Opus decode whose start was not cut.",
scan.uncut_frames,
),
Evidence::Shifted { shifted } => {
let (offset, frames) = shifted.most();
format!(
"The band energies of {frames} frames at offset {offset} sit on the lattice of \
Opus's quantizer once one change of level is taken off them, as in audio decoded \
from Opus and made louder or quieter."
)
}
Evidence::Hybrid { hybrid } => {
let (offset, frames, tested) = hybrid.most();
format!(
"The energies of the bands from 9.6 to 15.6 kHz sit on the lattice of Opus's quantizer in \
{frames} of {tested} frames at offset {offset}, as in audio decoded from Opus in its \
hybrid mode."
)
}
Evidence::Unfiltered { unfiltered } => format!(
"The band energies of {} frames sit on the lattice of Opus's quantizer once the pitch \
post-filter of an Opus decoder is taken off them, on the frame grid of an Opus decode \
whose start was not cut.",
unfiltered.frames,
),
Evidence::Short { short } => {
let (offset, frames) = short.most();
format!(
"The band energies of {frames} frames of {} ms at offset {offset} sit on the lattice \
of Opus's quantizer.",
short.milliseconds()
)
}
};
let family = grid.family.map_or_else(String::new, |family| match family {
Family::Fraunhofer => format!(
" The offset is the one an encoder that states no delay leaves in a decode whose start \
was not cut, and the quantizer's steps move from band to band as {family} moves them."
),
_ => format!(" The offset is the one {family} leaves in a decode whose start was not cut."),
});
let quantizer = grid.quantizer.as_ref().map_or_else(String::new, |steps| {
format!(
" The values of {} scalefactor bands sit on whole steps of AAC's quantizer.",
steps.whole
)
});
return CutoffReading {
verdict: Verdict::LikelyTranscode,
confidence: thresholds.confidence_cap,
summary: format!("{evidence}{quantizer}{family} {}", found.summary),
limitations,
..found
};
}
match found.verdict {
Verdict::LikelyTranscode | Verdict::MixedSources => {
let mut limitations = found.limitations;
limitations.push(Limitation::CutoffWithoutGrid);
let unconfirmed = if scanned {
"No MP3, MP2, AAC, Vorbis, WMA, AC-3 or Opus frame grid shows in the samples"
} else {
"The samples were not scanned for a codec's frame grid"
};
CutoffReading {
verdict: Verdict::PossiblyLossy,
confidence: 0.4,
summary: format!(
"{} {unconfirmed}, so the cutoff alone cannot confirm a lossy source.",
found.summary
),
limitations,
..found
}
}
Verdict::Consistent | Verdict::Inconclusive | Verdict::PossiblyLossy => found,
}
}
fn verdict(
heard: &Heard,
median: Option<f64>,
lossless: bool,
bitrate: Option<u32>,
) -> CutoffReading {
let t = heard.thresholds;
let count = heard.windows.len();
let seconds = heard.seconds();
let mut reading = CutoffReading {
verdict: Verdict::Inconclusive,
confidence: 0.3,
encoder_guess: None,
summary: String::new(),
limitations: Vec::new(),
cutoff_hz: median.filter(|m| *m < t.full_band * heard.top),
};
let Some(median) = median.filter(|_| count >= t.min_windows && seconds >= t.min_seconds) else {
reading.confidence = 0.2;
reading.summary = format!(
"Only {seconds:.1} s of the audio is above silence; a reading needs at least {:.0} s.",
t.min_seconds
);
return reading;
};
let near = |hz: f64| heard.share(|w| w.cutoff_hz.is_some_and(|c| (c - hz).abs() <= t.cluster_hz));
let clustered = near(median);
let sharp_share = heard.share(|w| {
w.sharp
&& w
.cutoff_hz
.is_some_and(|c| (c - median).abs() <= t.cluster_hz)
}) / clustered.max(f64::EPSILON);
let below_claim = |profile: &EncoderProfile| {
lossless || bitrate.is_some_and(|kbps| below_bitrate(profile.kbps, kbps))
};
if let Some(profile) = lower_profile_at(t, median).filter(|p| below_claim(p))
&& clustered >= t.transcode_share
&& sharp_share >= 0.5
{
let evidence = 0.6
* ((clustered - t.transcode_share) / (1.0 - t.transcode_share)).clamp(0.0, 1.0)
+ 0.4 * sharp_share;
let confidence = 0.6 + 0.38 * evidence;
reading.limitations.push(Limitation::LowestCutoffOnly);
reading.verdict = Verdict::LikelyTranscode;
reading.confidence = confidence;
reading.encoder_guess = Some(EncoderGuess {
profile: profile.clone(),
confidence: (clustered * (0.5 + 0.5 * sharp_share)).min(t.confidence_cap),
});
reading.cutoff_hz = Some(median);
reading.summary = format!(
"{} of the time stops at {} with a sharp shelf, where an encoder at {} cuts off.",
percent(clustered),
khz(median),
profile
);
return reading;
}
if let Some(profile) = t.profile_at(median).filter(|_| lossless)
&& clustered >= t.transcode_share
&& sharp_share >= 0.5
{
reading.cutoff_hz = Some(median);
reading.encoder_guess = Some(EncoderGuess {
profile: profile.clone(),
confidence: 0.4,
});
reading.limitations.push(Limitation::FilteredAt20Khz);
reading.summary = format!(
"{} of the time stops at {} with a sharp shelf, where an encoder at {} cuts off or where \
a recording was filtered when it was made.",
percent(clustered),
khz(median),
profile
);
return reading;
}
let full = heard.share(|w| heard.full(w));
let limited: Vec<f64> = heard
.windows
.iter()
.filter(|w| heard.limited(w).is_some())
.filter_map(|w| w.cutoff_hz)
.collect();
let limited_share = limited.len() as f64 / count as f64;
if limited_share >= t.mixed_share && full >= t.mixed_share {
let at = middle(&limited);
reading.verdict = Verdict::MixedSources;
reading.confidence = 0.5 + 0.35 * (limited_share.min(full) / 0.5).min(1.0);
reading.encoder_guess = t.profile_at(at).map(|p| EncoderGuess {
profile: p.clone(),
confidence: 0.5,
});
reading.cutoff_hz = Some(at);
reading.summary = format!(
"{} of the time is full-band; {} stops at {} with a sharp shelf, as when part of the \
track comes from a lossy source.",
percent(full),
percent(limited_share),
khz(at)
);
return reading;
}
let layers: Vec<f64> = heard
.windows
.iter()
.filter_map(|w| heard.layered(w))
.collect();
let layered_share = layers.len() as f64 / count as f64;
if layered_share >= t.mixed_share {
let at = middle(&layers);
reading.verdict = Verdict::MixedSources;
reading.confidence = 0.5 + 0.35 * layered_share.min(1.0);
reading.encoder_guess = t.profile_at(at).map(|p| EncoderGuess {
profile: p.clone(),
confidence: 0.5,
});
reading.cutoff_hz = Some(at);
reading.summary = format!(
"The content reaches the top of the band, but {} of the time has a sharp step at {}, as \
when a band-limited layer is mixed with full-band material.",
percent(layered_share),
khz(at)
);
return reading;
}
let high_steps: Vec<f64> = heard
.windows
.iter()
.filter_map(|w| heard.stepped(w, t.high_step_db))
.filter(|hz| {
t.profile_at(*hz)
.is_some_and(|p| p.kbps >= t.high_bitrate_kbps)
})
.collect();
let at = middle(&high_steps);
if high_steps.len() as f64 / count as f64 >= t.mixed_share
&& let Some(profile) = t.profile_at(at)
{
reading.encoder_guess = Some(EncoderGuess {
profile: profile.clone(),
confidence: 0.4,
});
reading.cutoff_hz = Some(at);
reading.limitations.push(Limitation::FilteredAt20Khz);
reading.summary = format!(
"The content reaches the top of the band, but {} of the time has a sharp step at {}, \
where an encoder at {profile} cuts off. A layer at that bitrate and a recording \
filtered there with other material above it look the same.",
percent(high_steps.len() as f64 / count as f64),
khz(at)
);
return reading;
}
let open = heard.share(|w| heard.full(w) || !w.sharp);
if open >= t.consistent_share {
if full >= t.consistent_share {
let windows = ((count - t.min_windows) as f64 / 100.0).min(1.0);
let mut confidence = 0.7 + 0.25 * windows;
if quiet(heard) {
confidence -= 0.1;
}
reading.verdict = Verdict::Consistent;
reading.confidence = confidence;
let stepped = heard
.windows
.iter()
.any(|w| heard.stepped(w, t.high_step_db).is_some());
reading.summary = format!(
"{} of the time reaches {}, near the top of the {} band{}.",
percent(full),
khz(median),
khz(heard.top),
if stepped {
""
} else {
", with no encoder shelf"
}
);
return reading;
}
reading.limitations.push(Limitation::EarlyRollOff);
if median >= t.natural_limit * heard.top {
reading.verdict = Verdict::Consistent;
reading.confidence = 0.7;
reading.summary = format!(
"The content rolls off gently from about {}, without the sharp cutoff of an encoder.",
khz(median)
);
return reading;
}
reading.confidence = 0.4;
let like = if heard.top > HI_RES_TOP_HZ {
"as in many hi-res recordings, where microphones and instruments produce little above \
20 kHz"
} else {
"as in test tones, speech, old masters and lo-fi recordings"
};
reading.summary = format!(
"The content stops at about {}, well below the top of the band, without the sharp shelf \
of an encoder, {like}.",
khz(median)
);
return reading;
}
if !lossless && let Some(kbps) = bitrate {
let cutoffs: Vec<f64> = heard.windows.iter().filter_map(|w| w.cutoff_hz).collect();
let edge = percentile(&cutoffs, t.ceiling).unwrap_or(median);
let too_low = t
.profiles
.iter()
.rev()
.find(|p| below_claim(p))
.map_or(0.0, |p| p.hz);
if edge > too_low + t.cluster_hz {
reading.cutoff_hz = Some(edge);
let profile = t.profile_at(edge);
if keeps_its_bitrate(t, edge, kbps) {
reading.verdict = Verdict::Consistent;
reading.confidence = 0.7 + 0.1 * near(edge);
reading.summary = match profile {
Some(profile) => format!(
"The content stops at about {}, where an encoder at {} cuts off, at or above what \
a file of its bitrate keeps.",
khz(edge),
profile
),
None => format!(
"The content reaches about {}, the top of what a file of its bitrate keeps.",
khz(edge)
),
};
return reading;
}
reading.confidence = 0.4;
reading.encoder_guess = profile.map(|p| EncoderGuess {
profile: p.clone(),
confidence: 0.4,
});
let at = profile.map_or(String::new(), |p| {
format!(", where an encoder at {p} cuts off")
});
reading.summary = format!(
"The content stops at about {}{at}: below what a file of its bitrate keeps, but not \
low enough to call a transcode. A second lossy generation at a nearby bitrate is one \
explanation.",
khz(edge)
);
return reading;
}
}
reading.summary = if sharp_share >= 0.5 && clustered >= t.transcode_share {
format!(
"The content stops at {} with a sharp shelf, which is not the cutoff of a common encoder.",
khz(median)
)
} else {
let cutoffs: Vec<f64> = heard.windows.iter().filter_map(|w| w.cutoff_hz).collect();
let low = khz(percentile(&cutoffs, 0.1).unwrap_or(median));
let high = khz(percentile(&cutoffs, 0.9).unwrap_or(median));
let sharp = heard.share(|w| w.sharp);
let shelf = if sharp > 0.0 {
format!(", with a sharp shelf {} of the time", percent(sharp))
} else {
String::new()
};
if low == high {
format!("The content stops near {low}{shelf}, which fits no one pattern.")
} else {
format!("The cutoff moves between {low} and {high}{shelf}, which fits no one pattern.")
}
};
reading
}
fn below_bitrate(profile_kbps: u32, kbps: u32) -> bool {
u64::from(profile_kbps) * 3 / 2 <= u64::from(kbps)
}
fn keeps_its_bitrate(thresholds: &ReadingThresholds, edge: f64, kbps: u32) -> bool {
let profiles = &thresholds.profiles;
let Some(own) = profiles.iter().map(|p| p.kbps).filter(|p| *p <= kbps).max() else {
return true;
};
match thresholds.profile_at(edge) {
Some(profile) => profile.kbps >= own,
None => profiles
.iter()
.filter(|p| p.kbps == own)
.all(|p| edge > p.hz),
}
}
fn quiet(heard: &Heard) -> bool {
let levels: Vec<f64> = heard.windows.iter().map(|w| w.rms_dbfs).collect();
percentile(&levels, 0.5).is_some_and(|level| level < heard.thresholds.quiet_dbfs)
}
fn percent(share: f64) -> String {
format!("{:.0}%", share * 100.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn heard<'a>(cutoffs: &[f64], thresholds: &'a ReadingThresholds) -> Heard<'a> {
Heard {
windows: cutoffs
.iter()
.map(|c| Seen {
cutoff_hz: Some(*c),
sharp: true,
seconds: 1.0,
inner_shelf: None,
rms_dbfs: -20.0,
})
.collect(),
top: 24_000.0,
thresholds,
}
}
fn spread(cuts: &[(f64, usize)]) -> Vec<f64> {
cuts.iter().flat_map(|(c, n)| [*c].repeat(*n)).collect()
}
#[test]
fn a_bitrate_at_the_top_of_its_type_is_compared_without_overflow() {
assert!(below_bitrate(128, 192));
assert!(!below_bitrate(128, 191));
assert!(!below_bitrate(u32::MAX, u32::MAX));
}
#[test]
fn a_moving_cutoff_at_the_top_of_a_256_kbps_aac_is_its_own() {
let cuts = spread(&[
(20_000.0, 30),
(20_500.0, 30),
(21_000.0, 30),
(15_500.0, 20),
]);
let found = verdict(
&heard(&cuts, &ReadingThresholds::default()),
Some(20_250.0),
false,
Some(256),
);
assert_eq!(found.verdict, Verdict::Consistent, "{}", found.summary);
}
#[test]
fn a_ceiling_too_low_for_the_bitrate_is_not_called_consistent() {
let cuts = spread(&[(15_500.0, 40), (16_500.0, 40), (17_500.0, 40)]);
let found = verdict(
&heard(&cuts, &ReadingThresholds::default()),
Some(16_500.0),
false,
Some(256),
);
assert_ne!(found.verdict, Verdict::Consistent, "{}", found.summary);
}
#[test]
fn a_full_band_minority_too_small_to_mix_does_not_hide_a_transcode() {
let cuts = spread(&[(16_000.0, 88), (20_000.0, 12)]);
let found = verdict(
&heard(&cuts, &ReadingThresholds::default()),
Some(16_000.0),
false,
Some(320),
);
assert_eq!(found.verdict, Verdict::LikelyTranscode, "{}", found.summary);
}
#[test]
fn a_cutoff_below_its_bitrates_own_but_above_two_thirds_of_it_is_inconclusive() {
let cuts = spread(&[(16_000.0, 100)]);
let found = verdict(
&heard(&cuts, &ReadingThresholds::default()),
Some(16_000.0),
false,
Some(190),
);
assert_eq!(found.verdict, Verdict::Inconclusive, "{}", found.summary);
assert_eq!(found.confidence, 0.4);
let guess = found.encoder_guess.unwrap();
assert_eq!(
(guess.profile.to_string().as_str(), guess.confidence),
("MP3 ~128 kbps", 0.4)
);
assert!(
found.summary.contains("second lossy generation"),
"{}",
found.summary
);
let own = verdict(
&heard(&spread(&[(18_600.0, 100)]), &ReadingThresholds::default()),
Some(18_600.0),
false,
Some(190),
);
assert_eq!(own.verdict, Verdict::Consistent, "{}", own.summary);
}
}