1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! MKAU plugin format for modular audio processing chains.
//!
//! This module provides the `Processor` trait for implementing audio plugins
//! and a loader function for dynamically loading `.mkap` plugin files.
//!
//! ## Example Plugin Implementation
//!
//! ```ignore
//! use mkaudiolibrary::buffer::Buffer;
//! use mkaudiolibrary::processor::{Processor, AudioIO};
//!
//! struct GainPlugin
//! {
//! parameters : [(String, f32); 1],
//! internal_buffer : Buffer<f32>
//! }
//!
//! impl GainPlugin
//! {
//! fn new() -> Self
//! {
//! Self
//! {
//! parameters : [(String::from("Gain"), 0.5)],
//! internal_buffer : Buffer::new(1024)
//! }
//! }
//! }
//!
//! impl Processor for GainPlugin
//! {
//! fn init(&mut self) {}
//! fn name(&self) -> String { String::from("Gain") }
//! fn get_parameter(&self, index : usize) -> f32 { self.parameters[index].1 }
//! fn set_parameter(&mut self, index : usize, value : f32) { self.parameters[index].1 = value; }
//! fn get_parameter_name(&self, index : usize) -> String { self.parameters[index].0.clone() }
//!
//! #[cfg(feature = "gui")]
//! fn editor(&mut self) -> Option<&mut dyn PluginEditor> { None }
//!
//! fn prepare_to_play(&mut self, buffer_size : usize, _sample_rate : usize)
//! {
//! self.internal_buffer.resize(buffer_size);
//! }
//!
//! fn run(&self, audio : &mut AudioIO)
//! {
//! let gain = self.parameters[0].1;
//! let Some(input) = audio.input else { return };
//! let num_channels = input.len().min(audio.output.len());
//! for channel in 0..num_channels
//! {
//! let input = input[channel];
//! let output = &mut audio.output[channel];
//! for sample in 0..input.len().min(output.len())
//! {
//! output[sample] = input[sample] * gain;
//! }
//! }
//! }
//!
//! #[cfg(feature = "midi")]
//! fn run_with_midi(&self, audio : &mut AudioIO, _midi : &mut MidiIO)
//! {
//! self.run(audio);
//! }
//! }
//!
//! mkaudiolibrary::declare_plugin!(GainPlugin, GainPlugin::new);
//! ```
//!
//! ## MIDI Processing Example (requires `midi` feature)
//!
//! ```ignore
//! #[cfg(feature = "midi")]
//! use mkaudiolibrary::processor::{Processor, AudioIO, MidiIO};
//!
//! #[cfg(feature = "midi")]
//! fn process_with_midi(processor: &dyn Processor, audio: &mut AudioIO, midi: &mut MidiIO)
//! {
//! // Process incoming MIDI messages
//! for msg in midi.input.iter().flatten()
//! {
//! // Handle MIDI messages (note on/off, CC, etc.)
//! }
//!
//! // Run audio processing
//! processor.run(audio);
//!
//! // Optionally generate MIDI output, if this plugin has any
//! // if let Some(output) = midi.output.as_deref_mut() {
//! // output[0] = Some(MidiMessage::NoteOn { channel: 0, key: 60, velocity: 100 });
//! // }
//! }
//! ```
//!
//! ## Instrument Plugins
//!
//! A synth/generator has no audio input - only MIDI in and audio out.
//! Override `num_inputs` to declare that, so hosts (VST3/AU/MKAP alike)
//! don't connect an input bus that will never be read; `audio.input` will
//! then be `None` in `run`/`run_with_midi`:
//!
//! ```ignore
//! impl Processor for MySynth
//! {
//! fn num_inputs(&self) -> usize { 0 }
//! fn num_outputs(&self) -> usize { 2 }
//!
//! fn run(&self, audio : &mut AudioIO)
//! {
//! debug_assert!(audio.input.is_none());
//! // ...generate audio into audio.output...
//! }
//! }
//! ```
//!
//! ## GUI Example (requires `gui` feature)
//!
//! `Processor::editor()` returns a [`PluginEditor`] - a plugin-embedding
//! editor (widget tree, geometry, and parent-window-handle lifecycle from
//! [mkapk](https://github.com/mkaudio-company/mkapk)), not a standalone
//! application window. The host embeds it into its own parent window:
//!
//! ```ignore
//! #[cfg(feature = "gui")]
//! use mkaudiolibrary::processor::{Processor, AudioIO, ParentWindowHandle};
//!
//! #[cfg(feature = "gui")]
//! fn open_plugin_editor(processor: &mut dyn Processor, parent: ParentWindowHandle, host: &dyn mkaudiolibrary::processor::EditorHost)
//! {
//! if let Some(editor) = processor.editor()
//! {
//! let constraints = editor.size_constraints();
//! editor.open(parent, host);
//! }
//! }
//! ```
//!
//! ## Loading Plugins
//!
//! ```ignore
//! use mkaudiolibrary::processor::load;
//!
//! // Load a plugin from /path/to/plugins/myplugin.mkap
//! let plugin = load("/path/to/plugins", "myplugin").expect("Failed to load plugin");
//! println!("Loaded: {}", plugin.name());
//! ```
extern crate libloading;
use ;
pub use MidiMessage;
pub use ;
pub use ;
/// Standard speaker channel layouts - a convenient way to size the sample
/// storage a caller allocates before borrowing an [`AudioIO`] view into it,
/// without spelling out a raw channel count.
///
/// # Example
/// ```ignore
/// let channels = ChannelLayout::Stereo.num_channels();
/// let storage = vec![vec![0.0f32; 512]; channels];
/// ```
/// Audio I/O view for buffer-based processing.
///
/// A thin, non-owning wrapper over per-channel sample slices - input and
/// sidechain-input channels are borrowed immutably, output and
/// sidechain-output channels mutably. `AudioIO` doesn't allocate or own any
/// sample storage itself: the caller (typically a host driving
/// [`Processor::run`] once per audio callback) owns the actual buffers for
/// the life of the stream and constructs a new `AudioIO` borrowing into
/// them for each block, matching how real audio APIs (VST3's
/// `AudioBusBuffers`, CoreAudio's `AudioBufferList`) hand a plugin raw
/// pointers into host-owned memory rather than copying into a buffer the
/// plugin owns.
///
/// `input`, `sidechain_in`, and `sidechain_out` are `Option`: a generator
/// plugin (synth, noise source, ...) may have no audio input at all, and
/// sidechain busses are commonly absent. `output` is always present -
/// every processor produces *some* output, even if it's silence.
///
/// # Example
/// ```ignore
/// fn process(audio: &mut AudioIO)
/// {
/// let Some(input) = audio.input else { return };
/// for ch in 0..input.len().min(audio.output.len())
/// {
/// let (input, output) = (input[ch], &mut audio.output[ch]);
/// for i in 0..input.len().min(output.len())
/// {
/// output[i] = input[i];
/// }
/// }
/// }
///
/// // Building one for a call, from caller-owned storage:
/// let input_storage = vec![vec![0.0f32; 512]; 2];
/// let mut output_storage = vec![vec![0.0f32; 512]; 2];
/// let input: Vec<&[f32]> = input_storage.iter().map(Vec::as_slice).collect();
/// let mut output: Vec<&mut [f32]> = output_storage.iter_mut().map(Vec::as_mut_slice).collect();
/// let mut audio = AudioIO::new(Some(&input), &mut output, None, None);
/// process(&mut audio);
/// ```
/// MIDI I/O container for MIDI message processing.
///
/// Provides input and output vectors for MIDI messages. The input contains
/// messages received during the current processing block, and output is
/// for messages to be sent after processing.
///
/// Only available with the `midi` feature enabled.
///
/// A thin, non-owning wrapper, the same way as [`AudioIO`]: the caller owns
/// the message slots for the stream's lifetime and borrows a `MidiIO` into
/// them for each block. `output` is `Option`: a plugin that only consumes
/// MIDI (e.g. a MIDI-controlled effect with no MIDI generation/thru of its
/// own) has nowhere to write outgoing messages.
///
/// # Example
/// ```ignore
/// #[cfg(feature = "midi")]
/// fn process_midi(midi: &mut MidiIO)
/// {
/// for msg in midi.input.iter().flatten()
/// {
/// match msg
/// {
/// MidiMessage::NoteOn { channel, key, velocity } =>
/// {
/// // Handle note on
/// }
/// MidiMessage::ControlChange { channel, controller, value } =>
/// {
/// // Handle CC
/// }
/// _ => {}
/// }
/// }
/// // Clear input after processing
/// midi.input.fill(None);
/// }
///
/// // Building one for a call, from caller-owned storage:
/// #[cfg(feature = "midi")]
/// let mut input_storage = vec![None; 512];
/// #[cfg(feature = "midi")]
/// let mut output_storage = vec![None; 512];
/// #[cfg(feature = "midi")]
/// let mut midi = MidiIO::new(&mut input_storage, Some(&mut output_storage));
/// ```
/// Declare a plugin for dynamic loading.
///
/// This macro generates the `_create` extern function required for
/// loading the plugin as a `.mkap` dynamic library.
///
/// # Arguments
/// * `$plugin_type` - The type implementing `Processor`
/// * `$constructor` - Path to the constructor function (e.g., `MyPlugin::new`)
/// Audio processor trait for MKAU plugins.
///
/// Implement this trait to create an audio plugin that can be loaded
/// dynamically or used directly in a processing chain.
///
/// ## Audio I/O
/// The `run` method uses `AudioIO`, a thin non-owning view whose
/// input/output/sidechain channels are plain `&[f32]`/`&mut [f32]` slices
/// borrowed from caller-owned storage -- index into them directly
/// (`audio.input[ch]`/`audio.output[ch]`).
///
/// ## MIDI Support
/// When the `midi` feature is enabled, use `run_with_midi` for processors that
/// need MIDI input/output. The default implementation calls `run` and ignores MIDI.
/// Load a plugin from a `.mkap` dynamic library file.
///
/// # Arguments
/// * `path` - Directory containing the plugin file
/// * `name` - Plugin name (without `.mkap` extension)
///
/// # Returns
/// A boxed `Processor` trait object on success, or a loading error.
///
/// # Safety
/// This function loads and executes code from an external library.
/// Only load plugins from trusted sources.