1use pikopiko::runtime::output::{profile, Band, EqSettings, MAX_BANDS};
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum EqTextError {
31 Item(String),
33 TooMany,
35}
36
37pub fn names() -> String {
39 let mut v: Vec<&str> = profile::NAMED.iter().map(|(n, _)| *n).collect();
40 v.push("flat");
41 v.join(", ")
42}
43
44pub fn parse(text: &str, sample_rate: u32) -> Result<EqSettings, EqTextError> {
46 let bands = parse_bands(text)?;
47 EqSettings::new(&bands, sample_rate).ok_or(EqTextError::TooMany)
48}
49
50pub fn parse_bands(text: &str) -> Result<Vec<Band>, EqTextError> {
52 let items: Vec<&str> = text.split(',').map(str::trim).collect();
53 if items == ["flat"] {
54 return Ok(Vec::new());
55 }
56 let mut bands = Vec::new();
57 for item in items {
58 if let Some(p) = profile::by_name(item) {
59 bands.extend_from_slice(p);
60 } else {
61 bands.push(band(item).ok_or_else(|| EqTextError::Item(item.to_string()))?);
62 }
63 }
64 if bands.len() > MAX_BANDS {
65 return Err(EqTextError::TooMany);
66 }
67 Ok(bands)
68}
69
70fn band(item: &str) -> Option<Band> {
72 let mut parts = item.split(':');
73 let kind = parts.next()?;
74 let nums: Vec<f32> = parts
75 .map(|s| s.trim().parse::<f32>().ok().filter(|v| v.is_finite()))
76 .collect::<Option<_>>()?;
77 let b = match (kind, nums.as_slice()) {
78 ("lowcut1", &[hz]) => Band::LowCut1 { hz },
79 ("highcut1", &[hz]) => Band::HighCut1 { hz },
80 ("lowcut", &[hz]) => Band::LowCut { hz, q: 0.707 },
81 ("lowcut", &[hz, q]) => Band::LowCut { hz, q },
82 ("highcut", &[hz]) => Band::HighCut { hz, q: 0.707 },
83 ("highcut", &[hz, q]) => Band::HighCut { hz, q },
84 ("lowshelf", &[hz, gain_db]) => Band::LowShelf { hz, gain_db },
85 ("highshelf", &[hz, gain_db]) => Band::HighShelf { hz, gain_db },
86 ("peak", &[hz, gain_db]) => Band::Peak {
87 hz,
88 gain_db,
89 q: 1.0,
90 },
91 ("peak", &[hz, gain_db, q]) => Band::Peak { hz, gain_db, q },
92 _ => return None,
93 };
94 Some(b)
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn profiles_and_bands_are_read_in_order() {
103 assert_eq!(
104 parse_bands("small-speaker").unwrap(),
105 profile::SMALL_SPEAKER
106 );
107 assert_eq!(
108 parse_bands(" subsonic , highshelf:8000:-3, peak:2500:-4:1.5 ").unwrap(),
109 vec![
110 Band::LowCut { hz: 30.0, q: 0.707 },
111 Band::HighShelf {
112 hz: 8000.0,
113 gain_db: -3.0
114 },
115 Band::Peak {
116 hz: 2500.0,
117 gain_db: -4.0,
118 q: 1.5
119 },
120 ]
121 );
122 assert_eq!(parse_bands("flat").unwrap(), Vec::<Band>::new());
123 assert!(parse("famicom", 44_100).is_ok());
124 }
125
126 #[test]
127 fn errors_name_the_item() {
128 for bad in [
129 "",
130 "loud",
131 "peak:1000",
132 "lowcut1:abc",
133 "lowcut1:NaN",
134 "flat,subsonic",
135 "peak:1:2:3:4",
136 ] {
137 assert!(
138 matches!(parse_bands(bad), Err(EqTextError::Item(_))),
139 "{bad}"
140 );
141 }
142 assert_eq!(
143 parse_bands("famicom,famicom,lowcut1:10"),
144 Err(EqTextError::TooMany)
145 );
146 }
147}