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 #[cfg(feature = "editor")]
148 type Editor: Editor;
149
150 // To avoid rust-analyzer from getting confused.
151 #[cfg(not(feature = "editor"))]
152 type Editor;
153
154 /// The plugin's SysEx message type if it supports sending or receiving MIDI SysEx messages, or
155 /// `()` if it does not. This type can be a struct or enum wrapping around one or more message
156 /// types, and the [`SysExMessage`] trait is then used to convert between this type and basic
157 /// byte buffers. The [`MIDI_INPUT`][Self::MIDI_INPUT] and [`MIDI_OUTPUT`][Self::MIDI_OUTPUT]
158 /// fields need to be set to [`MidiConfig::Basic`] or above to be able to send and receive
159 /// SysEx.
160 type SysExMessage: SysExMessage;
161
162 /// A type encoding the different background tasks this plugin wants to run, or `()` if it
163 /// doesn't have any background tasks. This is usually set to an enum type. The task type should
164 /// not contain any heap allocated data like [`Vec`]s and [`Box`]es. Tasks can be send using the
165 /// methods on the various [`*Context`][crate::context] objects.
166 //
167 // NOTE: Sadly it's not yet possible to default this and the `async_executor()` function to
168 // `()`: https://github.com/rust-lang/rust/issues/29661
169 type BackgroundTask: Send;
170
171 /// A function that executes the plugin's tasks. When implementing this you will likely want to
172 /// pattern match on the task type, and then send any resulting data back over a channel or
173 /// triple buffer. See [`BackgroundTask`][Self::BackgroundTask].
174 ///
175 /// Queried only once immediately after the plugin instance is created. This function takes
176 /// `&mut self` to make it easier to move data into the closure.
177 fn task_executor(&mut self) -> TaskExecutor<Self> {
178 // In the default implementation we can simply ignore the value
179 Box::new(|_| ())
180 }
181
182 /// The plugin's parameters. The host will update the parameter values before calling
183 /// `process()`. These string parameter IDs parameters should never change as they are used to
184 /// distinguish between parameters.
185 ///
186 /// Queried only once immediately after the plugin instance is created.
187 fn params(&self) -> Arc<dyn Params>;
188
189 /// Returns an extension struct for interacting with the plugin's editor, if it has one. Later
190 /// the host may call [`Editor::spawn()`] to create an editor instance. To read the current
191 /// parameter values, you will need to clone and move the `Arc` containing your `Params` object
192 /// into the editor. You can later modify the parameters through the
193 /// [`GuiContext`][crate::context::gui::GuiContext] and
194 /// [`ParamSetter`][crate::context::gui::ParamSetter] after the editor GUI has been created.
195 /// nice-plug comes with wrappers for several common GUI frameworks that may have their own ways
196 /// of interacting with parameters. See the repo's readme for more information.
197 ///
198 /// Queried only once immediately after the plugin instance is created. This function takes
199 /// `&mut self` to make it easier to move data into the `Editor` implementation.
200 #[cfg(feature = "editor")]
201 fn editor(&mut self, async_executor: AsyncExecutor<Self>) -> Option<Self::Editor> {
202 None
203 }
204
205 /// This function is always called just before a [`PluginState`] is loaded. This lets you
206 /// directly modify old plugin state to perform migrations based on the [`PluginState::version`]
207 /// field. Some examples of use cases for this are renaming parameter indices, remapping
208 /// parameter values, and preserving old preset compatibility when introducing new parameters
209 /// with default values that would otherwise change the sound of a preset. Keep in mind that
210 /// automation may still be broken in the first two use cases.
211 ///
212 /// # Note
213 ///
214 /// This is an advanced feature that the vast majority of plugins won't need to implement.
215 fn filter_state(state: &mut PluginState) {}
216
217 //
218 // The following functions follow the lifetime of the plugin.
219 //
220
221 /// Activate the plugin for the given audio IO configuration. From this point onwards the
222 /// audio IO layouts and the buffer sizes are fixed until this function is called again.
223 ///
224 /// Before this point, the plugin should not have done any expensive initialization. Please
225 /// don't be that plugin that takes twenty seconds to scan.
226 ///
227 /// After this function [`reset()`][Self::reset()] will always be called. If you need to clear
228 /// state, such as filters or envelopes, then you should do so in that function instead.
229 ///
230 /// - If you need to access this information in your process function, then you can copy the
231 /// values to your plugin instance's object.
232 /// - If the plugin is being restored from an old state,
233 /// then that state will have already been restored at this point.
234 /// - If based on those parameters (or for any reason whatsoever) the plugin needs to introduce
235 /// latency, then you can do so here using the process context.
236 /// - Depending on how the host restores plugin state, this function may be called multiple
237 /// times in rapid succession. It may thus be useful to check if the initialization work for
238 /// the current bufffer and audio IO configurations has already been performed first.
239 /// - If the plugin fails to activate for whatever reason, then this should return `false`.
240 fn activate(
241 &mut self,
242 audio_io_layout: &AudioIOLayout,
243 buffer_config: &BufferConfig,
244 context: &mut impl ActivateContext<Self>,
245 ) -> bool {
246 true
247 }
248
249 /// Clear internal state such as filters and envelopes. This is always called after
250 /// [`activate()`][Self::activate()], and it may also be called at any other time from the
251 /// audio thread. You should thus not do any allocations in this function.
252 fn reset(&mut self) {}
253
254 /// Process audio. The host's input buffers have already been copied to the output buffers if
255 /// they are not processing audio in place (most hosts do however). All channels are also
256 /// guaranteed to contain the same number of samples. Lastly, denormals have already been taken
257 /// case of by nice-plug, and you can optionally enable the `assert_process_allocs` feature to
258 /// abort the program when any allocation occurs in the process function while running in debug
259 /// mode.
260 ///
261 /// The framework provides convenient iterators on the [`Buffer`] object to process audio either
262 /// either per-sample per-channel, or per-block per-channel per-sample. The first approach is
263 /// preferred for plugins that don't require block-based processing because of their use of
264 /// per-sample SIMD or excessive branching. The parameter smoothers can also work in both modes:
265 /// use [`Smoother::next()`][crate::params::smoothing::Smoother::next()] for per-sample processing,
266 /// and [`Smoother::next_block()`][crate::params::smoothing::Smoother::next_block()] for
267 /// block-based processing.
268 ///
269 /// The `context` object contains context information as well as callbacks for working with note
270 /// events. The [`AuxiliaryBuffers`] contain the plugin's sidechain input buffers and
271 /// auxiliary output buffers if it has any.
272 ///
273 /// TODO: Provide a way to access auxiliary input channels if the IO configuration is
274 /// asymmetric
275 fn process(
276 &mut self,
277 buffer: &mut Buffer,
278 aux: &mut AuxiliaryBuffers,
279 context: &mut impl ProcessContext<Self>,
280 ) -> ProcessStatus;
281
282 /// Called when the host is about to deactivate the plugin or when it is about to send the plugin
283 /// to sleep.
284 ///
285 /// This is currently only used in the CLAP backend.
286 fn stop_processing(&mut self) {}
287
288 /// Called when the plugin is deactivated. The host will call
289 /// [`activate()`][Self::activate()] again before the plugin resumes processing audio. These
290 /// two functions will not be called when the host only temporarily stops processing audio. You
291 /// can clean up or deallocate resources here. In most cases you can safely ignore this.
292 ///
293 /// There is no one-to-one relationship between calls to `activate()` and `deactivate()`.
294 /// `activate()` may be called more than once before `deactivate()` is called, for instance
295 /// when restoring state while the plugin is still activate.
296 fn deactivate(&mut self) {}
297
298 /// Configure the global logger here.
299 ///
300 /// If setting up the logger was successful, return `Some(true)`. If it failed return `Some(false)`.
301 ///
302 /// Otherwise, returning `None` will do one of the following:
303 /// * If the `tracing-subscriber` feature is enabled, then nice-plug will automatically set up a
304 /// logger with the default settings (uses LevelFilter::DEBUG when compiled in debug mode, and
305 /// LevelFilter::INFO when compiled in release mode).
306 /// * If the `tracing-subscriber` feature is not enabled, then no logging will occur.
307 ///
308 /// Called once when the program starts (or when the shared library is loaded). If this plugin is
309 /// part of a bundle, then only the first plugin that appears in the export macro will have its
310 /// `setup_logger` method called.
311 ///
312 /// By default this returns `None`.
313 fn setup_logger() -> Option<bool> {
314 None
315 }
316}
317
318/// Indicates the current situation after the plugin has processed audio.
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320pub enum ProcessStatus {
321 /// Something went wrong while processing audio.
322 Error(&'static str),
323 /// The plugin has finished processing audio. When the input is silent, the host may suspend the
324 /// plugin to save resources as it sees fit.
325 Normal,
326 /// The plugin has a (reverb) tail with a specific length in samples.
327 Tail(u32),
328 /// This plugin will continue to produce sound regardless of whether or not the input is silent,
329 /// and should thus not be deactivated by the host. This is essentially the same as having an
330 /// infinite tail.
331 KeepAlive,
332}