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