insta-fun 2.4.1

Snapshot testing of fundsp units. Visualize output in svg and compare using insta
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
use std::str::FromStr;

use derive_builder::Builder;
use fundsp::DEFAULT_SR;

use crate::warmup::WarmUp;

pub use crate::chart::Layout;

const DEFAULT_HEIGHT: usize = 500;

#[derive(Debug, Clone, Builder)]
/// Configuration for snapshotting an audio unit.
pub struct SnapshotConfig {
    // Audio configuration
    /// Sample rate of the audio unit.
    ///
    /// Default is 44100.0 [fundsp::DEFAULT_SR]
    #[builder(default = "fundsp::DEFAULT_SR")]
    pub sample_rate: f64,
    /// Number of samples to generate.
    ///
    /// Default is 1024
    #[builder(default = "1024")]
    pub num_samples: usize,
    /// Processing mode for snapshotting an audio unit.
    ///
    /// Default - `Tick`
    #[builder(default = "Processing::default()")]
    pub processing_mode: Processing,
    /// Warm-up mode for snapshotting an audio unit.
    ///
    /// Default - `WarmUp::None`
    #[builder(default = "WarmUp::None")]
    pub warm_up: WarmUp,
    /// How to handle abnormal samples: `NaN`,`±Infinity`
    ///
    /// When set to `true` abnormal samples are allowed during processing,
    /// but skipped in actual output. Plotted with labeled dots.
    ///
    /// When set to `false` and encoutered abnormal samples,
    /// the snapshotting process will panic.
    #[builder(default = "false")]
    pub allow_abnormal_samples: bool,

    /// Snaphsot output mode
    ///
    /// Use configurable chart for visual snapshots
    ///
    /// Use Wav16 or Wav32 for audial snapshots
    #[builder(
        default = "SnapshotOutputMode::SvgChart(SvgChartConfig::default())",
        try_setter,
        setter(into)
    )]
    pub output_mode: SnapshotOutputMode,

    /// Assertion applied to the output samples after processing.
    ///
    /// Default - [`OutputAssertion::NonZero`]: panics when all output samples are `0.0`.
    ///
    /// Use [`OutputAssertion::Skip`] to opt out, or [`OutputAssertion::VariesFrom`] to
    /// check that the output differs from an arbitrary baseline value.
    #[builder(default = "OutputAssertion::NonZero")]
    pub output_assertion: OutputAssertion,
}

#[derive(Debug, Clone, Copy, Default)]
pub enum SvgPreserveAspectRatioAlignment {
    #[default]
    None,
    XMinYMin,
    XMidYMin,
    XMaxYMin,
    XMinYMid,
    XMidYMid,
    XMaxYMid,
    XMinYMax,
    XMidYMax,
    XMaxYMax,
}

impl std::fmt::Display for SvgPreserveAspectRatioAlignment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SvgPreserveAspectRatioAlignment::None => write!(f, "none"),
            SvgPreserveAspectRatioAlignment::XMinYMin => write!(f, "xMinYMin"),
            SvgPreserveAspectRatioAlignment::XMidYMin => write!(f, "xMidYMin"),
            SvgPreserveAspectRatioAlignment::XMaxYMin => write!(f, "xMaxYMin"),
            SvgPreserveAspectRatioAlignment::XMinYMid => write!(f, "xMinYMid"),
            SvgPreserveAspectRatioAlignment::XMidYMid => write!(f, "xMidYMid"),
            SvgPreserveAspectRatioAlignment::XMaxYMid => write!(f, "xMaxYMid"),
            SvgPreserveAspectRatioAlignment::XMinYMax => write!(f, "xMinYMax"),
            SvgPreserveAspectRatioAlignment::XMidYMax => write!(f, "xMidYMax"),
            SvgPreserveAspectRatioAlignment::XMaxYMax => write!(f, "xMaxYMax"),
        }
    }
}

impl FromStr for SvgPreserveAspectRatioAlignment {
    type Err = ();

    fn from_str(input: &str) -> Result<SvgPreserveAspectRatioAlignment, Self::Err> {
        match input {
            "none" => Ok(SvgPreserveAspectRatioAlignment::None),
            "xMinYMin" => Ok(SvgPreserveAspectRatioAlignment::XMinYMin),
            "xMidYMin" => Ok(SvgPreserveAspectRatioAlignment::XMidYMin),
            "xMaxYMin" => Ok(SvgPreserveAspectRatioAlignment::XMaxYMin),
            "xMinYMid" => Ok(SvgPreserveAspectRatioAlignment::XMinYMid),
            "xMidYMid" => Ok(SvgPreserveAspectRatioAlignment::XMidYMid),
            "xMaxYMid" => Ok(SvgPreserveAspectRatioAlignment::XMaxYMid),
            "xMinYMax" => Ok(SvgPreserveAspectRatioAlignment::XMinYMax),
            "xMidYMax" => Ok(SvgPreserveAspectRatioAlignment::XMidYMax),
            "xMaxYMax" => Ok(SvgPreserveAspectRatioAlignment::XMaxYMax),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub enum SvgPreserveAspectRatioKwd {
    #[default]
    None,
    Meet,
    Slice,
}

impl FromStr for SvgPreserveAspectRatioKwd {
    type Err = ();

    fn from_str(input: &str) -> Result<SvgPreserveAspectRatioKwd, Self::Err> {
        match input {
            "meet" => Ok(SvgPreserveAspectRatioKwd::Meet),
            "slice" => Ok(SvgPreserveAspectRatioKwd::Slice),
            "" => Ok(SvgPreserveAspectRatioKwd::None),
            _ => Err(()),
        }
    }
}

impl std::fmt::Display for SvgPreserveAspectRatioKwd {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SvgPreserveAspectRatioKwd::None => write!(f, ""),
            SvgPreserveAspectRatioKwd::Meet => write!(f, " meet"),
            SvgPreserveAspectRatioKwd::Slice => write!(f, " slice"),
        }
    }
}

#[derive(Debug, Clone, Copy, Default, Builder)]
#[builder(default)]
pub struct SvgPreserveAspectRatio {
    pub alignment: SvgPreserveAspectRatioAlignment,
    pub kwd: SvgPreserveAspectRatioKwd,
}

impl std::fmt::Display for SvgPreserveAspectRatio {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let SvgPreserveAspectRatioAlignment::None = self.alignment {
            write!(f, "none")
        } else {
            write!(f, "{}{}", self.alignment, self.kwd)
        }
    }
}

impl FromStr for SvgPreserveAspectRatio {
    type Err = ();

    fn from_str(input: &str) -> Result<SvgPreserveAspectRatio, Self::Err> {
        let parts: Vec<&str> = input.split_whitespace().collect();
        if parts.is_empty() {
            return Err(());
        }

        let alignment = SvgPreserveAspectRatioAlignment::from_str(parts[0])?;
        let kwd = if parts.len() > 1 {
            SvgPreserveAspectRatioKwd::from_str(parts[1])?
        } else {
            SvgPreserveAspectRatioKwd::None
        };

        Ok(SvgPreserveAspectRatio { alignment, kwd })
    }
}

impl SvgPreserveAspectRatio {
    /// Center content: alignment only (XMidYMid), no scaling keyword.
    /// Useful when you want the SVG to define size explicitly without forcing fit/fill behavior.
    pub fn center() -> Self {
        Self {
            alignment: SvgPreserveAspectRatioAlignment::XMidYMid,
            kwd: SvgPreserveAspectRatioKwd::None,
        }
    }

    /// Scale to fit: center and scale uniformly so the whole viewBox is visible (xMidYMid meet).
    pub fn scale_to_fit() -> Self {
        Self {
            alignment: SvgPreserveAspectRatioAlignment::XMidYMid,
            kwd: SvgPreserveAspectRatioKwd::Meet,
        }
    }

    /// Scale to fill: center and scale uniformly so the viewBox is completely covered (may crop) (xMidYMid slice).
    pub fn scale_to_fill() -> Self {
        Self {
            alignment: SvgPreserveAspectRatioAlignment::XMidYMid,
            kwd: SvgPreserveAspectRatioKwd::Slice,
        }
    }
}

#[derive(Debug, Clone, Builder)]
pub struct SvgChartConfig {
    // Chart configuration
    /// Chart layout
    ///
    /// Whether to plot channels on separate charts or combined charts.
    ///
    /// Default - `Layout::Separate`
    #[builder(default)]
    pub chart_layout: Layout,
    /// Whether to include inputs in snapshot
    ///
    /// Default - `false`
    #[builder(default)]
    pub with_inputs: bool,
    /// Optional width of the SVG `viewBox`
    ///
    /// `None` means proportional to num_samples
    #[builder(default, setter(strip_option))]
    pub svg_width: Option<usize>,
    /// Height of one chart row in the SVG `viewBox`
    ///
    /// For `Layout::SeparateChannels`, one row equals one channel.
    /// For combined layouts, one row equals one combined chart.
    ///
    /// Default - 500
    #[builder(default = "DEFAULT_HEIGHT")]
    pub svg_height_per_channel: usize,
    /// SVG aspect ratio preservation
    ///
    /// Default - `None`
    #[builder(default, try_setter, setter(strip_option, into))]
    pub preserve_aspect_ratio: Option<SvgPreserveAspectRatio>,

    // Chart labels
    /// Show ax- labels
    ///
    /// Default - `true`
    #[builder(default = "true")]
    pub show_labels: bool,
    /// X axis labels format
    ///
    /// Whether to format X axis labels as time
    ///
    /// Default - `false`
    #[builder(default)]
    pub format_x_axis_labels_as_time: bool,
    /// Maximum number of labels along X axis
    ///
    /// Default - `Some(5)`
    #[builder(default = "Some(5)")]
    pub max_labels_x_axis: Option<usize>,
    /// Optional chart title
    ///
    /// Default - `None`
    #[builder(default, setter(into, strip_option))]
    pub chart_title: Option<String>,
    /// Optional titles for output channels
    ///
    /// Default - empty `Vec`
    #[builder(default, setter(into, each(into, name = "output_title")))]
    pub output_titles: Vec<String>,
    /// Optional titles for input channels
    ///
    /// Default - empty `Vec`
    #[builder(default, setter(into, each(into, name = "input_title")))]
    pub input_titles: Vec<String>,

    // Lines
    /// Show grid lines on the chart
    ///
    /// Default - `false`
    #[builder(default)]
    pub show_grid: bool,
    /// Waveform line thickness
    ///
    /// Default - 2.0
    #[builder(default = "2.0")]
    pub line_width: f32,

    // Chart colors
    /// Chart background color (hex string)
    ///
    /// Default - "#000000" (black)
    #[builder(default = "\"#000000\".to_string()", setter(into))]
    pub background_color: String,
    /// Custom colors for output channels (hex strings)
    ///
    /// Default - `None` (uses default palette)
    #[builder(default, setter(into, strip_option, each(into, name = "output_color")))]
    pub output_colors: Option<Vec<String>>,
    /// Custom colors for input channels (hex strings)
    ///
    /// Default - `None` (uses default palette)
    #[builder(default, setter(into, strip_option, each(into, name = "input_color")))]
    pub input_colors: Option<Vec<String>>,
}

#[derive(Debug, Clone)]
pub enum WavOutput {
    Wav16,
    Wav32,
}

#[derive(Debug, Clone)]
pub enum SnapshotOutputMode {
    SvgChart(SvgChartConfig),
    Wav(WavOutput),
}

/// Controls the assertion applied to output samples after processing.
///
/// By default, `NonZero` asserts that at least one output sample across all channels
/// is not `0.0`. Use `Skip` to opt out, or `VariesFrom` to check against an
/// arbitrary baseline value.
#[derive(Debug, Clone, Copy, Default)]
pub enum OutputAssertion {
    /// Assert that at least one output sample (across all channels) is not `0.0`.
    ///
    /// Panics if all output samples are `0.0`.
    #[default]
    NonZero,
    /// Skip the output assertion entirely.
    Skip,
    /// Assert that at least one output sample (across all channels) differs from
    /// the given `baseline` value.
    ///
    /// Panics if all output samples equal `baseline`.
    VariesFrom(f32),
}

/// Processing mode for snapshotting an audio unit.
#[derive(Debug, Clone, Copy, Default)]
pub enum Processing {
    #[default]
    /// Process one sample at a time.
    Tick,
    /// Process a batch of samples at a time.
    ///
    /// max batch size is 64 [fundsp::MAX_BUFFER_SIZE]
    Batch(u8),
}

impl TryFrom<SvgChartConfigBuilder> for SnapshotOutputMode {
    type Error = SvgChartConfigBuilderError;

    fn try_from(value: SvgChartConfigBuilder) -> Result<Self, Self::Error> {
        let inner = value.build()?;
        Ok(SnapshotOutputMode::SvgChart(inner))
    }
}

impl From<WavOutput> for SnapshotOutputMode {
    fn from(value: WavOutput) -> Self {
        SnapshotOutputMode::Wav(value)
    }
}

impl From<SvgChartConfig> for SnapshotOutputMode {
    fn from(value: SvgChartConfig) -> Self {
        SnapshotOutputMode::SvgChart(value)
    }
}

impl Default for SnapshotConfig {
    fn default() -> Self {
        Self {
            num_samples: 1024,
            sample_rate: DEFAULT_SR,
            processing_mode: Processing::default(),
            warm_up: WarmUp::default(),
            allow_abnormal_samples: false,
            output_mode: SnapshotOutputMode::SvgChart(SvgChartConfig::default()),
            output_assertion: OutputAssertion::NonZero,
        }
    }
}

impl Default for SvgChartConfig {
    fn default() -> Self {
        Self {
            svg_width: None,
            svg_height_per_channel: DEFAULT_HEIGHT,
            preserve_aspect_ratio: None,
            with_inputs: false,
            chart_title: None,
            output_titles: Vec::new(),
            input_titles: Vec::new(),
            show_grid: false,
            show_labels: true,
            max_labels_x_axis: Some(5),
            output_colors: None,
            input_colors: None,
            background_color: "#000000".to_string(),
            line_width: 2.0,
            chart_layout: Layout::default(),
            format_x_axis_labels_as_time: false,
        }
    }
}

impl SnapshotConfig {
    /// Intnded for internal use only
    ///
    /// Used by macros to determine snapshot filename
    pub fn file_name(&self, name: Option<&'_ str>) -> String {
        match &self.output_mode {
            SnapshotOutputMode::SvgChart(svg_chart_config) => match name {
                Some(name) => format!("{name}.svg"),
                None => match &svg_chart_config.chart_title {
                    Some(name) => format!("{name}.svg"),
                    None => ".svg".to_string(),
                },
            },
            SnapshotOutputMode::Wav(_) => match name {
                Some(name) => format!("{name}.wav"),
                None => ".wav".to_string(),
            },
        }
    }

    /// Intnded for internal use only
    ///
    /// Used by macros to set chart title if not already set
    pub fn maybe_title(&mut self, name: &str) {
        if matches!(
            self.output_mode,
            SnapshotOutputMode::SvgChart(SvgChartConfig {
                chart_title: None,
                ..
            })
        ) && let SnapshotOutputMode::SvgChart(ref mut svg_chart_config) = self.output_mode
        {
            svg_chart_config.chart_title = Some(name.to_string());
        }
    }
}

/// Legacy (v1.x) compatibility helpers
impl SnapshotConfigBuilder {
    /// Internal helper to ensure we have a mutable reference to an underlying `SvgChartConfig`
    /// Creating a default one if `output_mode` is `None` or replacing a `Wav` variant.
    fn legacy_svg_mut(&mut self) -> &mut SvgChartConfig {
        // If already a chart, return it.
        if let Some(SnapshotOutputMode::SvgChart(ref mut chart)) = self.output_mode {
            return chart;
        }
        // Otherwise replace (None or Wav) with default chart.
        self.output_mode = Some(SnapshotOutputMode::SvgChart(SvgChartConfig::default()));
        match self.output_mode {
            Some(SnapshotOutputMode::SvgChart(ref mut chart)) => chart,
            _ => unreachable!("Output mode was just set to SvgChart"),
        }
    }

    /// Set chart layout.
    pub fn chart_layout(&mut self, value: Layout) -> &mut Self {
        self.legacy_svg_mut().chart_layout = value;
        self
    }

    /// Include inputs in chart.
    pub fn with_inputs(&mut self, value: bool) -> &mut Self {
        self.legacy_svg_mut().with_inputs = value;
        self
    }

    /// Set fixed SVG width.
    pub fn svg_width(&mut self, value: usize) -> &mut Self {
        self.legacy_svg_mut().svg_width = Some(value);
        self
    }

    /// Set SVG height per channel.
    pub fn svg_height_per_channel(&mut self, value: usize) -> &mut Self {
        self.legacy_svg_mut().svg_height_per_channel = value;
        self
    }

    /// Toggle label visibility.
    pub fn show_labels(&mut self, value: bool) -> &mut Self {
        self.legacy_svg_mut().show_labels = value;
        self
    }

    /// Format X axis labels as time.
    pub fn format_x_axis_labels_as_time(&mut self, value: bool) -> &mut Self {
        self.legacy_svg_mut().format_x_axis_labels_as_time = value;
        self
    }

    /// Set maximum number of X axis labels.
    pub fn max_labels_x_axis(&mut self, value: Option<usize>) -> &mut Self {
        self.legacy_svg_mut().max_labels_x_axis = value;
        self
    }

    /// Set chart title.
    pub fn chart_title<S: Into<String>>(&mut self, value: S) -> &mut Self {
        self.legacy_svg_mut().chart_title = Some(value.into());
        self
    }

    /// Add an output channel title.
    pub fn output_title<S: Into<String>>(&mut self, value: S) -> &mut Self {
        self.legacy_svg_mut().output_titles.push(value.into());
        self
    }

    /// Add an input channel title.
    pub fn input_title<S: Into<String>>(&mut self, value: S) -> &mut Self {
        self.legacy_svg_mut().input_titles.push(value.into());
        self
    }

    /// Add output channels' titles.
    pub fn output_titles<S: Into<Vec<String>>>(&mut self, value: S) -> &mut Self {
        self.legacy_svg_mut().output_titles = value.into();
        self
    }

    /// Add input channels' titles.
    pub fn input_titles<S: Into<Vec<String>>>(&mut self, value: S) -> &mut Self {
        self.legacy_svg_mut().input_titles = value.into();
        self
    }

    /// Show grid lines.
    pub fn show_grid(&mut self, value: bool) -> &mut Self {
        self.legacy_svg_mut().show_grid = value;
        self
    }

    /// Set waveform line width.
    pub fn line_width(&mut self, value: f32) -> &mut Self {
        self.legacy_svg_mut().line_width = value;
        self
    }

    /// Set background color.
    pub fn background_color<S: Into<String>>(&mut self, value: S) -> &mut Self {
        self.legacy_svg_mut().background_color = value.into();
        self
    }

    /// Replace all output channel colors.
    pub fn output_colors(&mut self, colors: Vec<String>) -> &mut Self {
        self.legacy_svg_mut().output_colors = Some(colors);
        self
    }

    /// Append one output channel color.
    pub fn output_color<S: Into<String>>(&mut self, value: S) -> &mut Self {
        let chart = self.legacy_svg_mut();
        chart
            .output_colors
            .get_or_insert_with(Vec::new)
            .push(value.into());
        self
    }

    /// Replace all input channel colors.
    pub fn input_colors(&mut self, colors: Vec<String>) -> &mut Self {
        self.legacy_svg_mut().input_colors = Some(colors);
        self
    }

    /// Append one input channel color.
    pub fn input_color<S: Into<String>>(&mut self, value: S) -> &mut Self {
        let chart = self.legacy_svg_mut();
        chart
            .input_colors
            .get_or_insert_with(Vec::new)
            .push(value.into());
        self
    }
}

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

    #[test]
    fn test_default_builder() {
        SnapshotConfigBuilder::default()
            .build()
            .expect("defaul config builds");
    }

    #[test]
    fn legacy_config_compat() {
        SnapshotConfigBuilder::default()
            .chart_title("Complete Waveform Test")
            .show_grid(true)
            .show_labels(true)
            .with_inputs(true)
            .output_color("#FF6B6B")
            .input_color("#95E77E")
            .background_color("#2C3E50")
            .line_width(3.0)
            .svg_width(1200)
            .svg_height_per_channel(120)
            .build()
            .expect("legacy config builds");
    }
}