wavecraft_dsp/traits.rs
1//! Core DSP traits for user-implemented audio processors.
2//!
3//! This module defines the primary extension points for users building plugins
4//! with Wavecraft. The `Processor` trait is the main interface for custom DSP code.
5
6/// Transport information for timing-aware DSP.
7///
8/// Provides context about playback state, tempo, and position.
9#[derive(Debug, Clone, Copy, Default)]
10pub struct Transport {
11 /// Current tempo in BPM (beats per minute).
12 pub tempo: Option<f64>,
13
14 /// Current playback position in samples.
15 pub pos_samples: i64,
16
17 /// True if the host is playing.
18 pub playing: bool,
19}
20
21/// Trait for defining processor parameters.
22///
23/// This trait provides metadata about a processor's parameters,
24/// enabling automatic UI generation and nih-plug integration.
25///
26/// Typically implemented via `#[derive(ProcessorParams)]` rather than manually.
27pub trait ProcessorParams: Default + Send + Sync + 'static {
28 /// Returns the parameter specifications for this processor.
29 fn param_specs() -> &'static [ParamSpec];
30}
31
32/// Specification for a single parameter.
33#[derive(Debug, Clone)]
34pub struct ParamSpec {
35 /// Display name of the parameter (e.g., "Frequency").
36 pub name: &'static str,
37
38 /// ID suffix for this parameter (e.g., "frequency").
39 /// Full ID will be prefixed with processor name: "my_filter_frequency"
40 pub id_suffix: &'static str,
41
42 /// Value range for this parameter.
43 pub range: ParamRange,
44
45 /// Default value.
46 pub default: f64,
47
48 /// Unit string (e.g., "dB", "Hz", "%").
49 pub unit: &'static str,
50
51 /// Optional group name for UI organization (e.g., "Input", "Processing", "Output").
52 pub group: Option<&'static str>,
53}
54
55/// Parameter value range definition.
56#[derive(Debug, Clone)]
57pub enum ParamRange {
58 /// Linear range from min to max.
59 Linear { min: f64, max: f64 },
60
61 /// Skewed range with exponential/logarithmic scaling.
62 /// Factor > 1.0 = logarithmic, factor < 1.0 = exponential.
63 Skewed { min: f64, max: f64, factor: f64 },
64
65 /// Integer stepped range (for enums, switches).
66 Stepped { min: i32, max: i32 },
67}
68
69/// Unit type has no parameters.
70impl ProcessorParams for () {
71 fn param_specs() -> &'static [ParamSpec] {
72 &[]
73 }
74}
75
76/// Trait for user-implemented DSP processors.
77///
78/// Implement this trait to define custom audio processing logic.
79/// All methods must be real-time safe (no allocations, locks, or syscalls).
80///
81/// # Example
82///
83/// ```rust,no_run
84/// use wavecraft_dsp::{ParamRange, ParamSpec, Processor, ProcessorParams, Transport};
85///
86/// #[derive(Default)]
87/// struct MyGainParams {
88/// level: f32,
89/// }
90///
91/// impl ProcessorParams for MyGainParams {
92/// fn param_specs() -> &'static [ParamSpec] {
93/// &[ParamSpec {
94/// name: "Level",
95/// id_suffix: "level",
96/// range: ParamRange::Linear { min: 0.0, max: 2.0 },
97/// default: 1.0,
98/// unit: "x",
99/// group: None,
100/// }]
101/// }
102/// }
103///
104/// struct MyGain {
105/// sample_rate: f32,
106/// }
107///
108/// impl Processor for MyGain {
109/// type Params = MyGainParams;
110///
111/// fn process(
112/// &mut self,
113/// buffer: &mut [&mut [f32]],
114/// _transport: &Transport,
115/// params: &Self::Params,
116/// ) {
117/// for channel in buffer.iter_mut() {
118/// for sample in channel.iter_mut() {
119/// *sample *= params.level;
120/// }
121/// }
122/// }
123/// }
124/// ```
125pub trait Processor: Send + 'static {
126 /// Associated parameter type for this processor.
127 ///
128 /// Use `()` for processors with no parameters, or define a struct
129 /// with `#[derive(ProcessorParams)]`.
130 type Params: ProcessorParams + Default + Send + Sync + 'static;
131
132 /// Process a buffer of audio samples.
133 ///
134 /// The buffer is provided as a slice of mutable slices, one per channel.
135 /// Modify samples in-place to apply your DSP effect.
136 ///
137 /// # Arguments
138 /// * `buffer` - Audio channels as `[L, R, ...]` where each channel is `[samples]`
139 /// * `transport` - Playback timing information
140 /// * `params` - Current parameter values
141 ///
142 /// # Real-Time Safety
143 /// This method is called on the audio thread. It MUST be real-time safe:
144 /// - No allocations (`Vec::push`, `String`, `Box::new`)
145 /// - No locks (`Mutex`, `RwLock`)
146 /// - No syscalls (file I/O, logging, network)
147 /// - No panics (use `debug_assert!` only)
148 fn process(&mut self, buffer: &mut [&mut [f32]], transport: &Transport, params: &Self::Params);
149
150 /// Called when the sample rate changes.
151 ///
152 /// Use this to update internal state that depends on sample rate
153 /// (e.g., filter coefficients, delay line sizes).
154 ///
155 /// # Arguments
156 /// * `sample_rate` - New sample rate in Hz (e.g., 44100.0, 48000.0)
157 ///
158 /// # Default
159 /// No-op by default. Override if your processor needs sample rate.
160 fn set_sample_rate(&mut self, _sample_rate: f32) {}
161
162 /// Reset processor state.
163 ///
164 /// Called when the host stops playback or when the user resets the plugin.
165 /// Use this to clear delay lines, reset filters, etc.
166 ///
167 /// # Default
168 /// No-op by default. Override if your processor maintains state.
169 fn reset(&mut self) {}
170}