beamer-core 0.2.3

Core abstractions for the Beamer audio plugin (AU, VST3) framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Parameter value formatting and parsing.
//!
//! This module provides the [`Formatter`] enum for converting between
//! plain parameter values and display strings. Each formatter variant
//! handles a specific unit type (dB, Hz, ms, etc.) with appropriate
//! formatting and parsing logic.
//!
//! # Design
//!
//! The formatter separates value formatting from unit strings:
//! - `text()` returns the bare value without units (e.g., "440", "-6.0")
//! - `unit()` returns the unit string (e.g., "Hz", "dB")
//! - The host/UI combines them for display (e.g., "440 Hz", "-6.0 dB")
//!
//! This separation allows proper VST3/AU parameter info where the units
//! field is separate from the formatted value string.
//!
//! # Example
//!
//! ```ignore
//! use beamer_core::parameter_format::Formatter;
//!
//! let db_formatter = Formatter::Decibel { precision: 1 };
//! assert_eq!(db_formatter.text(1.0), "0.0");   // Value only
//! assert_eq!(db_formatter.unit(), "dB");       // Unit separately
//!
//! let hz_formatter = Formatter::Frequency;
//! assert_eq!(hz_formatter.text(440.0), "440");
//! assert_eq!(hz_formatter.text(1500.0), "1.50k");  // Auto-scaled with SI prefix
//! assert_eq!(hz_formatter.unit(), "Hz");
//! ```

/// Parameter value formatter.
///
/// Defines how plain parameter values are converted to display strings
/// and parsed back from user input.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Formatter {
    /// Generic float with configurable precision (e.g., "1.23").
    Float {
        /// Number of decimal places.
        precision: usize,
    },

    /// Decibel formatter for gain/level parameters.
    ///
    /// Input is linear amplitude (0.0 = silence, 1.0 = unity).
    /// Format: "-12.0", "-inf" (unit "dB" via `unit()`)
    Decibel {
        /// Number of decimal places.
        precision: usize,
    },

    /// Direct decibel formatter where input is already in dB.
    ///
    /// Used by `FloatParameter::db()` where the plain value is stored as dB.
    /// Format: "+12.0", "-60.0" (unit "dB" via `unit()`)
    DecibelDirect {
        /// Number of decimal places.
        precision: usize,
        /// Minimum dB value (below this shows "-inf")
        min_db: f64,
    },

    /// Frequency formatter with automatic Hz/kHz scaling.
    ///
    /// Format: "440", "1.50k" (unit "Hz" via `unit()`)
    Frequency,

    /// Milliseconds formatter.
    ///
    /// Format: "10.0" (unit "ms" via `unit()`)
    Milliseconds {
        /// Number of decimal places.
        precision: usize,
    },

    /// Seconds formatter.
    ///
    /// Format: "1.50" (unit "s" via `unit()`)
    Seconds {
        /// Number of decimal places.
        precision: usize,
    },

    /// Percentage formatter.
    ///
    /// Input is 0.0-1.0, display is 0-100.
    /// Format: "75" (unit "%" via `unit()`)
    Percent {
        /// Number of decimal places.
        precision: usize,
    },

    /// Pan formatter for stereo position.
    ///
    /// Input is -1.0 (left) to +1.0 (right).
    /// Display: "L50", "C", "R50"
    Pan,

    /// Ratio formatter for compressors.
    ///
    /// Display: "4.0:1", "∞:1"
    Ratio {
        /// Number of decimal places.
        precision: usize,
    },

    /// Semitones formatter for pitch shifting.
    ///
    /// Format: "+12", "-7", "0" (unit "st" via `unit()`)
    Semitones,

    /// Boolean formatter.
    ///
    /// Display: "On", "Off"
    Boolean,
}

impl Formatter {
    /// Convert a plain value to a display string (without unit).
    ///
    /// The interpretation of `value` depends on the formatter variant:
    /// - `Decibel`: linear amplitude (1.0 = 0 dB)
    /// - `Frequency`: Hz
    /// - `Milliseconds`: ms
    /// - `Seconds`: s
    /// - `Percent`: 0.0-1.0 (displayed as 0-100)
    /// - `Pan`: -1.0 to +1.0
    /// - `Ratio`: ratio value (4.0 = "4:1")
    /// - `Semitones`: integer semitones
    /// - `Boolean`: >0.5 = On, <=0.5 = Off
    pub fn text(&self, value: f64) -> String {
        match self {
            Formatter::Float { precision } => {
                format!("{:.prec$}", value, prec = *precision)
            }

            Formatter::Decibel { precision } => {
                if value < 1e-10 {
                    "-inf".to_string()
                } else {
                    let db = 20.0 * value.log10();
                    if db >= 0.0 {
                        format!("+{:.prec$}", db, prec = *precision)
                    } else {
                        format!("{:.prec$}", db, prec = *precision)
                    }
                }
            }

            Formatter::DecibelDirect { precision, min_db } => {
                // Value is already in dB, just format it
                // Use strict less-than so that min_db itself displays correctly
                if value < *min_db {
                    "-inf".to_string()
                } else if value >= 0.0 {
                    format!("+{:.prec$}", value, prec = *precision)
                } else {
                    format!("{:.prec$}", value, prec = *precision)
                }
            }

            Formatter::Frequency => {
                if value >= 1000.0 {
                    format!("{:.2}k", value / 1000.0)
                } else if value >= 100.0 {
                    format!("{:.0}", value)
                } else {
                    format!("{:.1}", value)
                }
            }

            Formatter::Milliseconds { precision } => {
                format!("{:.prec$}", value, prec = *precision)
            }

            Formatter::Seconds { precision } => {
                format!("{:.prec$}", value, prec = *precision)
            }

            Formatter::Percent { precision } => {
                format!("{:.prec$}", value * 100.0, prec = *precision)
            }

            Formatter::Pan => {
                if value.abs() < 0.005 {
                    "C".to_string()
                } else if value < 0.0 {
                    format!("L{:.0}", value.abs() * 100.0)
                } else {
                    format!("R{:.0}", value * 100.0)
                }
            }

            Formatter::Ratio { precision } => {
                if value > 100.0 {
                    "∞:1".to_string()
                } else {
                    format!("{:.prec$}:1", value, prec = *precision)
                }
            }

            Formatter::Semitones => {
                let st = value.round() as i64;
                if st > 0 {
                    format!("+{}", st)
                } else {
                    format!("{}", st)
                }
            }

            Formatter::Boolean => {
                if value > 0.5 {
                    "On".to_string()
                } else {
                    "Off".to_string()
                }
            }
        }
    }

    /// Parse a display string to a plain value.
    ///
    /// Returns `None` if the string cannot be parsed.
    /// Accepts various formats with or without units.
    pub fn parse(&self, s: &str) -> Option<f64> {
        let s = s.trim();

        match self {
            Formatter::Float { .. } => s.parse().ok(),

            Formatter::Decibel { .. } => {
                let trimmed = s
                    .trim_end_matches(" dB")
                    .trim_end_matches("dB")
                    .trim();

                if trimmed.eq_ignore_ascii_case("-inf")
                    || trimmed.eq_ignore_ascii_case("-∞")
                    || trimmed == "-infinity"
                {
                    return Some(0.0);
                }

                let db: f64 = trimmed.parse().ok()?;
                Some(10.0_f64.powf(db / 20.0))
            }

            Formatter::DecibelDirect { min_db, .. } => {
                // Parse dB value directly (no conversion)
                let trimmed = s
                    .trim_end_matches(" dB")
                    .trim_end_matches("dB")
                    .trim();

                if trimmed.eq_ignore_ascii_case("-inf")
                    || trimmed.eq_ignore_ascii_case("-∞")
                    || trimmed == "-infinity"
                {
                    return Some(*min_db);
                }

                trimmed.parse().ok()
            }

            Formatter::Frequency => {
                // Try kHz first
                if let Some(khz_str) = s
                    .strip_suffix(" kHz")
                    .or_else(|| s.strip_suffix("kHz"))
                    .or_else(|| s.strip_suffix(" khz"))
                    .or_else(|| s.strip_suffix("khz"))
                {
                    return khz_str.trim().parse::<f64>().ok().map(|v| v * 1000.0);
                }

                // Then Hz
                let hz_str = s
                    .trim_end_matches(" Hz")
                    .trim_end_matches("Hz")
                    .trim_end_matches(" hz")
                    .trim_end_matches("hz")
                    .trim();

                hz_str.parse().ok()
            }

            Formatter::Milliseconds { .. } => {
                let trimmed = s
                    .strip_suffix(" ms")
                    .or_else(|| s.strip_suffix("ms"))
                    .unwrap_or(s)
                    .trim();
                trimmed.parse().ok()
            }

            Formatter::Seconds { .. } => {
                let trimmed = s
                    .strip_suffix(" s")
                    .or_else(|| s.strip_suffix("s"))
                    .unwrap_or(s)
                    .trim();
                trimmed.parse().ok()
            }

            Formatter::Percent { .. } => {
                let trimmed = s.trim_end_matches('%').trim();
                trimmed.parse::<f64>().ok().map(|v| v / 100.0)
            }

            Formatter::Pan => {
                let s_upper = s.to_uppercase();
                if s_upper == "C" || s_upper == "CENTER" || s_upper == "0" {
                    return Some(0.0);
                }

                if let Some(left) = s_upper.strip_prefix('L') {
                    return left.trim().parse::<f64>().ok().map(|v| -v / 100.0);
                }

                if let Some(right) = s_upper.strip_prefix('R') {
                    return right.trim().parse::<f64>().ok().map(|v| v / 100.0);
                }

                // Try parsing as raw number (-100 to +100 or -1 to +1)
                if let Ok(v) = s.parse::<f64>() {
                    if v.abs() > 1.0 {
                        return Some(v / 100.0); // Assume -100 to +100
                    }
                    return Some(v); // Assume -1 to +1
                }

                None
            }

            Formatter::Ratio { .. } => {
                // Handle infinity
                if s == "∞:1" || s == "inf:1" || s.eq_ignore_ascii_case("infinity:1") {
                    return Some(f64::INFINITY);
                }

                // Strip ":1" suffix
                let trimmed = s.trim_end_matches(":1").trim();
                trimmed.parse().ok()
            }

            Formatter::Semitones => {
                let trimmed = s.trim_end_matches(" st").trim_end_matches("st").trim();
                trimmed.parse().ok()
            }

            Formatter::Boolean => match s.to_lowercase().as_str() {
                "on" | "true" | "yes" | "1" | "enabled" => Some(1.0),
                "off" | "false" | "no" | "0" | "disabled" => Some(0.0),
                _ => None,
            },
        }
    }

    /// Get the unit string for this formatter.
    pub fn unit(&self) -> &'static str {
        match self {
            Formatter::Float { .. } => "",
            Formatter::Decibel { .. } => "dB",
            Formatter::DecibelDirect { .. } => "dB",
            Formatter::Frequency => "Hz",
            Formatter::Milliseconds { .. } => "ms",
            Formatter::Seconds { .. } => "s",
            Formatter::Percent { .. } => "%",
            Formatter::Pan => "",
            Formatter::Ratio { .. } => "",
            Formatter::Semitones => "st",
            Formatter::Boolean => "",
        }
    }
}

impl Default for Formatter {
    fn default() -> Self {
        Formatter::Float { precision: 2 }
    }
}

impl Formatter {
    /// Return a new `Formatter` with updated precision.
    ///
    /// For formatter variants that have a `precision` field, this returns
    /// a new formatter with the updated precision. For variants without
    /// precision (e.g., `Pan`, `Boolean`, `Semitones`, `Frequency`), this
    /// returns `self` unchanged.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let formatter = Formatter::DecibelDirect { precision: 1, min_db: -60.0 };
    /// let high_precision = formatter.with_precision(3);
    /// // high_precision is DecibelDirect { precision: 3, min_db: -60.0 }
    ///
    /// let pan = Formatter::Pan;
    /// let same_pan = pan.with_precision(2);
    /// // same_pan is still Pan (no precision field)
    /// ```
    pub fn with_precision(self, precision: usize) -> Self {
        match self {
            Formatter::Float { .. } => Formatter::Float { precision },
            Formatter::Decibel { .. } => Formatter::Decibel { precision },
            Formatter::DecibelDirect { min_db, .. } => {
                Formatter::DecibelDirect { precision, min_db }
            }
            Formatter::Milliseconds { .. } => Formatter::Milliseconds { precision },
            Formatter::Seconds { .. } => Formatter::Seconds { precision },
            Formatter::Percent { .. } => Formatter::Percent { precision },
            Formatter::Ratio { .. } => Formatter::Ratio { precision },
            // Variants without precision return self unchanged
            Formatter::Frequency
            | Formatter::Pan
            | Formatter::Semitones
            | Formatter::Boolean => self,
        }
    }

    /// Check if this formatter variant supports precision customization.
    ///
    /// Returns `true` for variants with a `precision` field, `false` otherwise.
    pub fn supports_precision(&self) -> bool {
        matches!(
            self,
            Formatter::Float { .. }
                | Formatter::Decibel { .. }
                | Formatter::DecibelDirect { .. }
                | Formatter::Milliseconds { .. }
                | Formatter::Seconds { .. }
                | Formatter::Percent { .. }
                | Formatter::Ratio { .. }
        )
    }

    /// Get the current precision, if applicable.
    ///
    /// Returns `Some(precision)` for variants with a `precision` field,
    /// `None` otherwise.
    pub fn precision(&self) -> Option<usize> {
        match self {
            Formatter::Float { precision }
            | Formatter::Decibel { precision }
            | Formatter::DecibelDirect { precision, .. }
            | Formatter::Milliseconds { precision }
            | Formatter::Seconds { precision }
            | Formatter::Percent { precision }
            | Formatter::Ratio { precision } => Some(*precision),
            Formatter::Frequency | Formatter::Pan | Formatter::Semitones | Formatter::Boolean => {
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_with_precision_float() {
        let formatter = Formatter::Float { precision: 2 };
        let updated = formatter.with_precision(4);
        assert_eq!(updated.precision(), Some(4));
        assert_eq!(updated.text(1.2345), "1.2345");
    }

    #[test]
    fn test_with_precision_decibel() {
        let formatter = Formatter::Decibel { precision: 1 };
        let updated = formatter.with_precision(2);
        assert_eq!(updated.precision(), Some(2));
        assert_eq!(updated.text(1.0), "+0.00"); // 0 dB
    }

    #[test]
    fn test_with_precision_decibel_direct() {
        let formatter = Formatter::DecibelDirect {
            precision: 1,
            min_db: -60.0,
        };
        let updated = formatter.with_precision(3);
        assert_eq!(updated.precision(), Some(3));
        // Verify min_db is preserved
        if let Formatter::DecibelDirect { min_db, precision } = updated {
            assert_eq!(min_db, -60.0);
            assert_eq!(precision, 3);
        } else {
            panic!("Expected DecibelDirect variant");
        }
        assert_eq!(updated.text(-6.5), "-6.500");
    }

    #[test]
    fn test_with_precision_milliseconds() {
        let formatter = Formatter::Milliseconds { precision: 1 };
        let updated = formatter.with_precision(0);
        assert_eq!(updated.precision(), Some(0));
        assert_eq!(updated.text(10.5), "10"); // Rounded to 0 decimal places
    }

    #[test]
    fn test_with_precision_seconds() {
        let formatter = Formatter::Seconds { precision: 2 };
        let updated = formatter.with_precision(3);
        assert_eq!(updated.precision(), Some(3));
        assert_eq!(updated.text(1.5), "1.500");
    }

    #[test]
    fn test_with_precision_percent() {
        let formatter = Formatter::Percent { precision: 0 };
        let updated = formatter.with_precision(1);
        assert_eq!(updated.precision(), Some(1));
        assert_eq!(updated.text(0.755), "75.5"); // 0.755 * 100 = 75.5
    }

    #[test]
    fn test_with_precision_ratio() {
        let formatter = Formatter::Ratio { precision: 1 };
        let updated = formatter.with_precision(2);
        assert_eq!(updated.precision(), Some(2));
        assert_eq!(updated.text(4.0), "4.00:1");
    }

    #[test]
    fn test_with_precision_no_effect_on_frequency() {
        let formatter = Formatter::Frequency;
        let updated = formatter.with_precision(5);
        assert_eq!(updated, Formatter::Frequency);
        assert_eq!(updated.precision(), None);
    }

    #[test]
    fn test_with_precision_no_effect_on_pan() {
        let formatter = Formatter::Pan;
        let updated = formatter.with_precision(3);
        assert_eq!(updated, Formatter::Pan);
        assert_eq!(updated.precision(), None);
    }

    #[test]
    fn test_with_precision_no_effect_on_semitones() {
        let formatter = Formatter::Semitones;
        let updated = formatter.with_precision(2);
        assert_eq!(updated, Formatter::Semitones);
        assert_eq!(updated.precision(), None);
    }

    #[test]
    fn test_with_precision_no_effect_on_boolean() {
        let formatter = Formatter::Boolean;
        let updated = formatter.with_precision(1);
        assert_eq!(updated, Formatter::Boolean);
        assert_eq!(updated.precision(), None);
    }

    #[test]
    fn test_supports_precision() {
        assert!(Formatter::Float { precision: 2 }.supports_precision());
        assert!(Formatter::Decibel { precision: 1 }.supports_precision());
        assert!(Formatter::DecibelDirect {
            precision: 1,
            min_db: -60.0
        }
        .supports_precision());
        assert!(Formatter::Milliseconds { precision: 1 }.supports_precision());
        assert!(Formatter::Seconds { precision: 2 }.supports_precision());
        assert!(Formatter::Percent { precision: 0 }.supports_precision());
        assert!(Formatter::Ratio { precision: 1 }.supports_precision());

        assert!(!Formatter::Frequency.supports_precision());
        assert!(!Formatter::Pan.supports_precision());
        assert!(!Formatter::Semitones.supports_precision());
        assert!(!Formatter::Boolean.supports_precision());
    }

    #[test]
    fn test_precision_getter() {
        assert_eq!(Formatter::Float { precision: 3 }.precision(), Some(3));
        assert_eq!(Formatter::Decibel { precision: 2 }.precision(), Some(2));
        assert_eq!(
            Formatter::DecibelDirect {
                precision: 1,
                min_db: -60.0
            }
            .precision(),
            Some(1)
        );
        assert_eq!(Formatter::Frequency.precision(), None);
        assert_eq!(Formatter::Pan.precision(), None);
    }
}