use pikopiko::runtime::output::{profile, Band, EqSettings, MAX_BANDS};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EqTextError {
Item(String),
TooMany,
}
pub fn names() -> String {
let mut v: Vec<&str> = profile::NAMED.iter().map(|(n, _)| *n).collect();
v.push("flat");
v.join(", ")
}
pub fn parse(text: &str, sample_rate: u32) -> Result<EqSettings, EqTextError> {
let bands = parse_bands(text)?;
EqSettings::new(&bands, sample_rate).ok_or(EqTextError::TooMany)
}
pub fn parse_bands(text: &str) -> Result<Vec<Band>, EqTextError> {
let items: Vec<&str> = text.split(',').map(str::trim).collect();
if items == ["flat"] {
return Ok(Vec::new());
}
let mut bands = Vec::new();
for item in items {
if let Some(p) = profile::by_name(item) {
bands.extend_from_slice(p);
} else {
bands.push(band(item).ok_or_else(|| EqTextError::Item(item.to_string()))?);
}
}
if bands.len() > MAX_BANDS {
return Err(EqTextError::TooMany);
}
Ok(bands)
}
fn band(item: &str) -> Option<Band> {
let mut parts = item.split(':');
let kind = parts.next()?;
let nums: Vec<f32> = parts
.map(|s| s.trim().parse::<f32>().ok().filter(|v| v.is_finite()))
.collect::<Option<_>>()?;
let b = match (kind, nums.as_slice()) {
("lowcut1", &[hz]) => Band::LowCut1 { hz },
("highcut1", &[hz]) => Band::HighCut1 { hz },
("lowcut", &[hz]) => Band::LowCut { hz, q: 0.707 },
("lowcut", &[hz, q]) => Band::LowCut { hz, q },
("highcut", &[hz]) => Band::HighCut { hz, q: 0.707 },
("highcut", &[hz, q]) => Band::HighCut { hz, q },
("lowshelf", &[hz, gain_db]) => Band::LowShelf { hz, gain_db },
("highshelf", &[hz, gain_db]) => Band::HighShelf { hz, gain_db },
("peak", &[hz, gain_db]) => Band::Peak {
hz,
gain_db,
q: 1.0,
},
("peak", &[hz, gain_db, q]) => Band::Peak { hz, gain_db, q },
_ => return None,
};
Some(b)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn profiles_and_bands_are_read_in_order() {
assert_eq!(
parse_bands("small-speaker").unwrap(),
profile::SMALL_SPEAKER
);
assert_eq!(
parse_bands(" subsonic , highshelf:8000:-3, peak:2500:-4:1.5 ").unwrap(),
vec![
Band::LowCut { hz: 30.0, q: 0.707 },
Band::HighShelf {
hz: 8000.0,
gain_db: -3.0
},
Band::Peak {
hz: 2500.0,
gain_db: -4.0,
q: 1.5
},
]
);
assert_eq!(parse_bands("flat").unwrap(), Vec::<Band>::new());
assert!(parse("famicom", 44_100).is_ok());
}
#[test]
fn errors_name_the_item() {
for bad in [
"",
"loud",
"peak:1000",
"lowcut1:abc",
"lowcut1:NaN",
"flat,subsonic",
"peak:1:2:3:4",
] {
assert!(
matches!(parse_bands(bad), Err(EqTextError::Item(_))),
"{bad}"
);
}
assert_eq!(
parse_bands("famicom,famicom,lowcut1:10"),
Err(EqTextError::TooMany)
);
}
}