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