nice_plug_core/plugin.rs
1//! Traits and structs describing plugins and editors. This includes extension structs for features
2//! that are specific to one or more plugin-APIs.
3
4use std::sync::Arc;
5
6mod state;
7pub use state::*;
8
9#[cfg(feature = "editor")]
10mod track_info;
11#[cfg(feature = "editor")]
12pub use track_info::*;
13
14use crate::{
15 audio_setup::{AudioIOLayout, AuxiliaryBuffers, BufferConfig},
16 buffer::Buffer,
17 context::{activate::ActivateContext, process::ProcessContext},
18 midi::{MidiConfig, sysex::SysExMessage},
19 params::Params,
20};
21
22#[cfg(feature = "editor")]
23use crate::{context::gui::AsyncExecutor, editor::Editor};
24
25/// A function that can execute a plugin's [`BackgroundTask`][Plugin::BackgroundTask]s. A plugin can
26/// dispatch these tasks from the `activate()` function, the `process()` function, or the GUI, so
27/// they can be deferred for later to avoid blocking realtime contexts.
28pub type TaskExecutor<P> = Box<dyn Fn(<P as Plugin>::BackgroundTask) + Send>;
29
30/// The main plugin trait covering functionality common across most plugin formats. Most formats
31/// also have another trait with more specific data and functionality that needs to be implemented
32/// before the plugin can be exported to that format. The wrappers will use this to expose the
33/// plugin in a particular plugin format.
34///
35/// nice-plug is semi-declarative, meaning that most information about a plugin is defined
36/// declaratively but it also doesn't shy away from maintaining state when that is the path of least
37/// resistance. As such, the definitions on this trait fall in one of the following classes:
38///
39/// - `Plugin` objects are stateful. During their lifetime the plugin API wrappers will call the
40/// various lifecycle methods defined below, with the `activate()`, `reset()`, and `process()`
41/// functions being the most important ones.
42/// - Most of the rest of the trait statically describes the plugin. You will find this done in
43/// three different ways:
44/// - Most of this data, including the supported audio IO layouts, is simple enough that it can be
45/// defined through compile-time constants.
46/// - Some of the data is queried through a method as doing everything at compile time would
47/// impose a lot of restrictions on code structure and meta programming without any real
48/// benefits. In those cases the trait defines a method that is queried once and only once,
49/// immediately after instantiating the `Plugin` through `Plugin::default()`. Examples of these
50/// methods are [`Plugin::params()`], and
51/// `ClapPlugin::remote_controls()`.
52/// - Some of the data is defined through associated types. Rust currently sadly does not support
53/// default values for associated types, but all of these types can be set to `()` if you wish
54/// to ignore them. Examples of these types are [`Plugin::SysExMessage`] and
55/// [`Plugin::BackgroundTask`].
56/// - Finally, there are some functions that return extension structs and handlers, similar to how
57/// the `params()` function returns a data structure describing the plugin's parameters. Examples
58/// of these are the [`Plugin::editor()`] and [`Plugin::task_executor()`] functions, and they're
59/// also called once and only once after the plugin object has been created. This allows the audio
60/// thread to have exclusive access to the `Plugin` object, and it makes it easier to compose
61/// these extension structs since they're more loosely coupled to a specific `Plugin`
62/// implementation.
63///
64/// The main thing you need to do is define a `[Params]` struct containing all of your parameters.
65/// See the trait's documentation for more information on how to do that, or check out the examples.
66/// The plugin also needs a `Default` implementation so it can be initialized. Most of the other
67/// functionality is optional and comes with default trait method implementations.
68#[allow(unused_variables)]
69pub trait Plugin: Default + Send + 'static {
70 /// The plugin's name.
71 const NAME: &'static str;
72 /// The name of the plugin's vendor.
73 const VENDOR: &'static str;
74 /// A URL pointing to the plugin's web page.
75 const URL: &'static str;
76 /// The vendor's email address.
77 const EMAIL: &'static str;
78
79 /// Semver compatible version string (e.g. `0.0.1`). Hosts likely won't do anything with this,
80 /// but just in case they do this should only contain decimals values and dots.
81 const VERSION: &'static str;
82
83 /// The plugin's supported audio IO layouts. The first config will be used as the default config
84 /// if the host doesn't or can't select an alternative configuration. Because of that it's
85 /// recommended to begin this slice with a stereo layout. For maximum compatibility with the
86 /// different plugin formats this default layout should also include all of the plugin's
87 /// auxiliary input and output ports, if the plugin has any. If the slice is empty, then the
88 /// plugin will not have any audio IO.
89 ///
90 /// Both [`AudioIOLayout`] and [`PortNames`][crate::audio_setup::PortNames] have
91 /// `.const_default()` functions for compile-time equivalents to `Default::default()`:
92 ///
93 /// ```
94 /// # use nice_plug_core::audio_setup::{AudioIOLayout, new_nonzero_u32};
95 /// # use std::num::NonZeroU32;
96 /// const AUDIO_IO_LAYOUTS: &'static [AudioIOLayout] = &[AudioIOLayout {
97 /// main_input_channels: NonZeroU32::new(2),
98 /// main_output_channels: NonZeroU32::new(2),
99 ///
100 /// aux_input_ports: &[new_nonzero_u32(2)],
101 ///
102 /// ..AudioIOLayout::const_default()
103 /// }];
104 /// ```
105 ///
106 /// # Note
107 ///
108 /// Some plugin hosts, like Ableton Live, don't support MIDI-only plugins and may refuse to load
109 /// plugins with no main output or with zero main output channels.
110 const AUDIO_IO_LAYOUTS: &'static [AudioIOLayout];
111
112 /// Whether the plugin accepts note events, and what which events it wants to receive. If this
113 /// is set to [`MidiConfig::None`], then the plugin won't receive any note events.
114 ///
115 /// Defaults to [`MidiConfig::None`]
116 const MIDI_INPUT: MidiConfig = MidiConfig::None;
117 /// Whether the plugin can output note events. If this is set to [`MidiConfig::None`], then the
118 /// plugin won't have a note output port. When this is set to another value, then in most hosts
119 /// the plugin will consume all note and MIDI CC input. If you don't want that, then you will
120 /// need to forward those events yourself.
121 ///
122 /// Defaults to [`MidiConfig::None`]
123 const MIDI_OUTPUT: MidiConfig = MidiConfig::None;
124 /// If enabled, the audio processing cycle may be split up into multiple smaller chunks if
125 /// parameter values change occur in the middle of the buffer. Depending on the host these
126 /// blocks may be as small as a single sample. Bitwig Studio sends at most one parameter change
127 /// every 64 samples.
128 ///
129 /// Defaults to `false`
130 const SAMPLE_ACCURATE_AUTOMATION: bool = false;
131
132 /// If this is set to true, then the plugin will report itself as having a hard realtime
133 /// processing requirement when the host asks for it. Supported hosts will never ask the plugin
134 /// to do offline processing.
135 ///
136 /// Defaults to `false`
137 const HARD_REALTIME_ONLY: bool = false;
138
139 /// The allocated capacity for the process' input event buffer.
140 ///
141 /// This may need to be increased if your plugin has a lot of parameters or expects a lot
142 /// of MIDI events.
143 ///
144 /// Defaults to `1024`
145 const INPUT_EVENT_CAPACITY: usize = 1024;
146
147 /// The [`Editor`] (GUI) type used in this plugin.
148 ///
149 /// If this plugin does not have an editor, set this to `()`.
150 #[cfg(feature = "editor")]
151 type Editor: Editor;
152
153 /// The [`Editor`] (GUI) type used in this plugin.
154 ///
155 /// If this plugin does not have an editor, set this to `()`.
156 // To avoid rust-analyzer from getting confused.
157 #[cfg(not(feature = "editor"))]
158 type Editor;
159
160 /// The plugin's SysEx message type if it supports sending or receiving MIDI SysEx messages, or
161 /// `()` if it does not. This type can be a struct or enum wrapping around one or more message
162 /// types, and the [`SysExMessage`] trait is then used to convert between this type and basic
163 /// byte buffers. The [`MIDI_INPUT`][Self::MIDI_INPUT] and [`MIDI_OUTPUT`][Self::MIDI_OUTPUT]
164 /// fields need to be set to [`MidiConfig::Basic`] or above to be able to send and receive
165 /// SysEx.
166 type SysExMessage: SysExMessage;
167
168 /// A type encoding the different background tasks this plugin wants to run, or `()` if it
169 /// doesn't have any background tasks. This is usually set to an enum type. The task type should
170 /// not contain any heap allocated data like [`Vec`]s and [`Box`]es. Tasks can be send using the
171 /// methods on the various [`*Context`][crate::context] objects.
172 //
173 // NOTE: Sadly it's not yet possible to default this and the `async_executor()` function to
174 // `()`: https://github.com/rust-lang/rust/issues/29661
175 type BackgroundTask: Send;
176
177 /// A function that executes the plugin's tasks. When implementing this you will likely want to
178 /// pattern match on the task type, and then send any resulting data back over a channel or
179 /// triple buffer. See [`BackgroundTask`][Self::BackgroundTask].
180 ///
181 /// Queried only once immediately after the plugin instance is created. This function takes
182 /// `&mut self` to make it easier to move data into the closure.
183 fn task_executor(&mut self) -> TaskExecutor<Self> {
184 // In the default implementation we can simply ignore the value
185 Box::new(|_| ())
186 }
187
188 /// The plugin's parameters. The host will update the parameter values before calling
189 /// `process()`. These string parameter IDs parameters should never change as they are used to
190 /// distinguish between parameters.
191 ///
192 /// Queried only once immediately after the plugin instance is created.
193 fn params(&self) -> Arc<dyn Params>;
194
195 /// Returns an extension struct for interacting with the plugin's editor, if it has one. Later
196 /// the host may call [`Editor::spawn()`] to create an editor instance. To read the current
197 /// parameter values, you will need to clone and move the `Arc` containing your `Params` object
198 /// into the editor. You can later modify the parameters through the
199 /// [`GuiContext`][crate::context::gui::GuiContext] and
200 /// [`ParamSetter`][crate::context::gui::ParamSetter] after the editor GUI has been created.
201 /// nice-plug comes with wrappers for several common GUI frameworks that may have their own ways
202 /// of interacting with parameters. See the repo's readme for more information.
203 ///
204 /// Queried only once immediately after the plugin instance is created. This function takes
205 /// `&mut self` to make it easier to move data into the `Editor` implementation.
206 #[cfg(feature = "editor")]
207 fn editor(&mut self, async_executor: AsyncExecutor<Self>) -> Option<Self::Editor> {
208 None
209 }
210
211 /// This function is always called just before a [`PluginState`] is loaded. This lets you
212 /// directly modify old plugin state to perform migrations based on the [`PluginState::version`]
213 /// field. Some examples of use cases for this are renaming parameter indices, remapping
214 /// parameter values, and preserving old preset compatibility when introducing new parameters
215 /// with default values that would otherwise change the sound of a preset. Keep in mind that
216 /// automation may still be broken in the first two use cases.
217 ///
218 /// # Note
219 ///
220 /// This is an advanced feature that the vast majority of plugins won't need to implement.
221 fn filter_state(state: &mut PluginState) {}
222
223 //
224 // The following functions follow the lifetime of the plugin.
225 //
226
227 /// Activate the plugin for the given audio IO configuration. From this point onwards the
228 /// audio IO layouts and the buffer sizes are fixed until this function is called again.
229 ///
230 /// Before this point, the plugin should not have done any expensive initialization. Please
231 /// don't be that plugin that takes twenty seconds to scan.
232 ///
233 /// After this function [`reset()`][Self::reset()] will always be called. If you need to clear
234 /// state, such as filters or envelopes, then you should do so in that function instead.
235 ///
236 /// - If you need to access this information in your process function, then you can copy the
237 /// values to your plugin instance's object.
238 /// - If the plugin is being restored from an old state,
239 /// then that state will have already been restored at this point.
240 /// - If based on those parameters (or for any reason whatsoever) the plugin needs to introduce
241 /// latency, then you can do so here using the process context.
242 /// - Depending on how the host restores plugin state, this function may be called multiple
243 /// times in rapid succession. It may thus be useful to check if the initialization work for
244 /// the current bufffer and audio IO configurations has already been performed first.
245 /// - If the plugin fails to activate for whatever reason, then this should return `false`.
246 fn activate(
247 &mut self,
248 audio_io_layout: &AudioIOLayout,
249 buffer_config: &BufferConfig,
250 context: &mut impl ActivateContext<Self>,
251 ) -> bool {
252 true
253 }
254
255 /// Clear internal state such as filters and envelopes. This is always called after
256 /// [`activate()`][Self::activate()], and it may also be called at any other time from the
257 /// audio thread. You should thus not do any allocations in this function.
258 fn reset(&mut self) {}
259
260 /// Process audio. The host's input buffers have already been copied to the output buffers if
261 /// they are not processing audio in place (most hosts do however). All channels are also
262 /// guaranteed to contain the same number of samples. Lastly, denormals have already been taken
263 /// case of by nice-plug, and you can optionally enable the `assert_process_allocs` feature to
264 /// abort the program when any allocation occurs in the process function while running in debug
265 /// mode.
266 ///
267 /// The framework provides convenient iterators on the [`Buffer`] object to process audio either
268 /// either per-sample per-channel, or per-block per-channel per-sample. The first approach is
269 /// preferred for plugins that don't require block-based processing because of their use of
270 /// per-sample SIMD or excessive branching. The parameter smoothers can also work in both modes:
271 /// use [`Smoother::next()`][crate::params::smoothing::Smoother::next()] for per-sample processing,
272 /// and [`Smoother::next_block()`][crate::params::smoothing::Smoother::next_block()] for
273 /// block-based processing.
274 ///
275 /// The `context` object contains context information as well as callbacks for working with note
276 /// events. The [`AuxiliaryBuffers`] contain the plugin's sidechain input buffers and
277 /// auxiliary output buffers if it has any.
278 ///
279 /// TODO: Provide a way to access auxiliary input channels if the IO configuration is
280 /// asymmetric
281 fn process(
282 &mut self,
283 buffer: &mut Buffer,
284 aux: &mut AuxiliaryBuffers,
285 context: &mut impl ProcessContext<Self>,
286 ) -> ProcessStatus;
287
288 /// Called when the host is about to deactivate the plugin or when it is about to send the plugin
289 /// to sleep.
290 ///
291 /// This is currently only used in the CLAP backend.
292 fn stop_processing(&mut self) {}
293
294 /// Called when the plugin is deactivated. The host will call
295 /// [`activate()`][Self::activate()] again before the plugin resumes processing audio. These
296 /// two functions will not be called when the host only temporarily stops processing audio. You
297 /// can clean up or deallocate resources here. In most cases you can safely ignore this.
298 ///
299 /// There is no one-to-one relationship between calls to `activate()` and `deactivate()`.
300 /// `activate()` may be called more than once before `deactivate()` is called, for instance
301 /// when restoring state while the plugin is still activate.
302 fn deactivate(&mut self) {}
303
304 /// Configure the global logger here.
305 ///
306 /// If setting up the logger was successful, return `Some(true)`. If it failed return `Some(false)`.
307 ///
308 /// Otherwise, returning `None` will do one of the following:
309 /// * If the `tracing-subscriber` feature is enabled, then nice-plug will automatically set up a
310 /// logger with the default settings (uses LevelFilter::DEBUG when compiled in debug mode, and
311 /// LevelFilter::INFO when compiled in release mode).
312 /// * If the `tracing-subscriber` feature is not enabled, then no logging will occur.
313 ///
314 /// Called once when the program starts (or when the shared library is loaded). If this plugin is
315 /// part of a bundle, then only the first plugin that appears in the export macro will have its
316 /// `setup_logger` method called.
317 ///
318 /// By default this returns `None`.
319 fn setup_logger() -> Option<bool> {
320 None
321 }
322}
323
324/// Indicates the current situation after the plugin has processed audio.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326pub enum ProcessStatus {
327 /// Something went wrong while processing audio.
328 Error(&'static str),
329 /// The plugin has finished processing audio. When the input is silent, the host may suspend the
330 /// plugin to save resources as it sees fit.
331 Normal,
332 /// The plugin has a (reverb) tail with a specific length in samples.
333 Tail(u32),
334 /// This plugin will continue to produce sound regardless of whether or not the input is silent,
335 /// and should thus not be deactivated by the host. This is essentially the same as having an
336 /// infinite tail.
337 KeepAlive,
338}