1#[derive(Clone, Copy, Debug, PartialEq)]
7pub struct DynamicRangeLimit {
8 pub standard: f32,
9 pub constrained: f32,
10 pub no_limit: f32,
11}
12
13impl Default for DynamicRangeLimit {
14 fn default() -> Self {
15 Self::NO_LIMIT
16 }
17}
18
19pub const CONSTRAINED_HEADROOM: f32 = 2.0;
21
22impl DynamicRangeLimit {
23 pub const STANDARD: Self = Self::weights(1., 0., 0.);
24 pub const CONSTRAINED: Self = Self::weights(0., 1., 0.);
25 pub const NO_LIMIT: Self = Self::weights(0., 0., 1.);
26
27 const fn weights(standard: f32, constrained: f32, no_limit: f32) -> Self {
28 Self {
29 standard,
30 constrained,
31 no_limit,
32 }
33 }
34
35 pub fn interpolate(self, to: Self, t: f32) -> Self {
37 let mix = |a: f32, b: f32| a + (b - a) * t;
38 Self::weights(
39 mix(self.standard, to.standard),
40 mix(self.constrained, to.constrained),
41 mix(self.no_limit, to.no_limit),
42 )
43 .normalized()
44 .unwrap_or(to)
45 }
46
47 fn normalized(self) -> Option<Self> {
48 let (s, c, n) = (
49 self.standard.max(0.),
50 self.constrained.max(0.),
51 self.no_limit.max(0.),
52 );
53 let sum = s + c + n;
54 (sum > 0. && sum.is_finite()).then(|| Self::weights(s / sum, c / sum, n / sum))
55 }
56
57 pub fn headroom(self, display_headroom: f32) -> f32 {
60 let display = display_headroom.max(1.);
61 let stops = self.constrained * CONSTRAINED_HEADROOM.min(display).log2()
62 + self.no_limit * display.log2();
63 stops.exp2()
64 }
65
66 pub fn to_css(self) -> String {
68 let parts: Vec<(&str, f32)> = [
69 ("standard", self.standard),
70 ("constrained", self.constrained),
71 ("no-limit", self.no_limit),
72 ]
73 .into_iter()
74 .filter(|(_, w)| *w > 1e-6)
75 .collect();
76 match parts.as_slice() {
77 [(keyword, _)] => (*keyword).to_string(),
78 _ => format!(
79 "dynamic-range-limit-mix({})",
80 parts
81 .iter()
82 .map(|(k, w)| format!("{k} {}%", (w * 1e4).round() / 100.))
83 .collect::<Vec<_>>()
84 .join(", ")
85 ),
86 }
87 }
88
89 pub fn parse(text: &str) -> Result<Self, String> {
92 let text = text.trim();
93 let lower = text.to_ascii_lowercase();
94 match lower.as_str() {
95 "standard" => return Ok(Self::STANDARD),
96 "constrained" => return Ok(Self::CONSTRAINED),
97 "no-limit" => return Ok(Self::NO_LIMIT),
98 _ => {}
99 }
100 let inner = lower
101 .strip_prefix("dynamic-range-limit-mix(")
102 .and_then(|rest| rest.strip_suffix(')'))
103 .ok_or_else(|| {
104 format!(
105 "`{text}` is not `standard`, `constrained`, `no-limit` or \
106 `dynamic-range-limit-mix()`"
107 )
108 })?;
109 let items = split_commas(inner);
110 if items.len() < 2 {
111 return Err("`dynamic-range-limit-mix()` takes at least two limits".into());
112 }
113 let mut sum = Self::weights(0., 0., 0.);
114 let mut total = 0.;
115 for item in items {
116 let (limit, percent) = split_percentage(item.trim())
117 .ok_or_else(|| format!("`{}` needs one percentage", item.trim()))?;
118 if !(0. ..=100.).contains(&percent) {
119 return Err(format!("`{percent}%` is outside 0% to 100%"));
120 }
121 let limit = Self::parse(limit)?;
122 let w = percent / 100.;
123 sum.standard += limit.standard * w;
124 sum.constrained += limit.constrained * w;
125 sum.no_limit += limit.no_limit * w;
126 total += w;
127 }
128 if total <= 0. {
129 return Err("the percentages of `dynamic-range-limit-mix()` add up to 0%".into());
130 }
131 sum.normalized()
132 .ok_or_else(|| "the percentages of `dynamic-range-limit-mix()` add up to 0%".into())
133 }
134}
135
136fn split_commas(text: &str) -> Vec<&str> {
137 let mut out = Vec::new();
138 let mut depth = 0usize;
139 let mut start = 0;
140 for (i, c) in text.char_indices() {
141 match c {
142 '(' => depth += 1,
143 ')' => depth = depth.saturating_sub(1),
144 ',' if depth == 0 => {
145 out.push(&text[start..i]);
146 start = i + 1;
147 }
148 _ => {}
149 }
150 }
151 out.push(&text[start..]);
152 out
153}
154
155fn split_percentage(item: &str) -> Option<(&str, f32)> {
157 let percent = |word: &str| word.strip_suffix('%')?.parse::<f32>().ok();
158 if let Some((first, rest)) = item.split_once(char::is_whitespace) {
159 if let Some(p) = percent(first) {
160 return Some((rest.trim(), p));
161 }
162 }
163 let (rest, last) = item.rsplit_once(char::is_whitespace)?;
164 Some((rest.trim(), percent(last)?))
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170
171 fn close(a: DynamicRangeLimit, b: DynamicRangeLimit) -> bool {
172 (a.standard - b.standard).abs() < 1e-5
173 && (a.constrained - b.constrained).abs() < 1e-5
174 && (a.no_limit - b.no_limit).abs() < 1e-5
175 }
176
177 #[test]
178 fn keywords_and_mixes_compute_to_weights() {
179 assert_eq!(
180 DynamicRangeLimit::parse("standard"),
181 Ok(DynamicRangeLimit::STANDARD)
182 );
183 assert_eq!(
184 DynamicRangeLimit::parse(" No-Limit "),
185 Ok(DynamicRangeLimit::NO_LIMIT)
186 );
187 let mixed = DynamicRangeLimit::parse("dynamic-range-limit-mix(standard 30%, no-limit 70%)")
188 .unwrap();
189 assert!(
190 close(mixed, DynamicRangeLimit::weights(0.3, 0., 0.7)),
191 "{mixed:?}"
192 );
193 let reordered =
194 DynamicRangeLimit::parse("dynamic-range-limit-mix(10% constrained, 30% no-limit)")
195 .unwrap();
196 assert!(
197 close(reordered, DynamicRangeLimit::weights(0., 0.25, 0.75)),
198 "{reordered:?}"
199 );
200 }
201
202 #[test]
203 fn mixes_nest() {
204 let nested = DynamicRangeLimit::parse(
205 "dynamic-range-limit-mix(dynamic-range-limit-mix(standard 50%, constrained 50%) 50%, \
206 no-limit 50%)",
207 )
208 .unwrap();
209 assert!(
210 close(nested, DynamicRangeLimit::weights(0.25, 0.25, 0.5)),
211 "{nested:?}"
212 );
213 }
214
215 #[test]
216 fn invalid_mixes_are_refused() {
217 for bad in [
218 "dynamic-range-limit-mix(standard 50%)",
219 "dynamic-range-limit-mix(standard 0%, no-limit 0%)",
220 "dynamic-range-limit-mix(standard 120%, no-limit 10%)",
221 "dynamic-range-limit-mix(standard, no-limit 10%)",
222 "high",
223 ] {
224 assert!(DynamicRangeLimit::parse(bad).is_err(), "{bad}");
225 }
226 }
227
228 #[test]
229 fn interpolation_is_a_mix_of_the_endpoints() {
230 let from = DynamicRangeLimit::STANDARD;
231 let to = DynamicRangeLimit::NO_LIMIT;
232 assert!(close(from.interpolate(to, 0.), from));
233 assert!(close(from.interpolate(to, 1.), to));
234 let mid = from.interpolate(to, 0.25);
235 assert!(
236 close(mid, DynamicRangeLimit::weights(0.75, 0., 0.25)),
237 "{mid:?}"
238 );
239 let mixed = DynamicRangeLimit::weights(0.5, 0.5, 0.);
240 assert!(close(
241 mixed.interpolate(DynamicRangeLimit::CONSTRAINED, 0.5),
242 DynamicRangeLimit::weights(0.25, 0.75, 0.)
243 ));
244 }
245
246 #[test]
247 fn the_headroom_mixes_in_stops() {
248 assert_eq!(DynamicRangeLimit::STANDARD.headroom(8.), 1.);
249 assert_eq!(DynamicRangeLimit::CONSTRAINED.headroom(8.), 2.);
250 assert_eq!(DynamicRangeLimit::CONSTRAINED.headroom(1.5), 1.5);
251 assert_eq!(DynamicRangeLimit::NO_LIMIT.headroom(8.), 8.);
252 let half = DynamicRangeLimit::weights(0.5, 0., 0.5);
253 assert!((half.headroom(4.) - 2.).abs() < 1e-5);
254 assert_eq!(DynamicRangeLimit::NO_LIMIT.headroom(1.), 1.);
255 }
256
257 #[test]
258 fn the_computed_value_serializes() {
259 assert_eq!(DynamicRangeLimit::CONSTRAINED.to_css(), "constrained");
260 assert_eq!(
261 DynamicRangeLimit::weights(0.3, 0., 0.7).to_css(),
262 "dynamic-range-limit-mix(standard 30%, no-limit 70%)"
263 );
264 }
265}