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