rack 0.4.8

A modern Rust library for hosting audio plugins
Documentation
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#include "rack_au.h"
#import <AudioToolbox/AudioToolbox.h>
#import <CoreAudioKit/CoreAudioKit.h>
#import <AppKit/AppKit.h>
#import <CoreFoundation/CoreFoundation.h>
#include <cstring>
#include <dispatch/dispatch.h>

// GUI implementation structure
struct RackAUGui {
    AudioComponentInstance audio_unit;
    NSViewController* view_controller;  // For AUv3
    NSView* view;                      // For AUv2 or generic UI
    NSWindow* window;                  // Optional window for standalone display
    NSMutableArray* slider_targets;     // For generic UI - keeps slider targets alive
    bool owns_view_controller;         // Track ownership for cleanup
    bool owns_view;
    char error_message[256];
};

// Helper class for generic UI slider callbacks
@interface RackAUSliderTarget : NSObject
@property (assign) AudioComponentInstance audioUnit;
@property (assign) AudioUnitParameterID parameterID;
@property (weak) NSTextField* valueLabel;
- (void)sliderChanged:(NSSlider*)slider;
@end

@implementation RackAUSliderTarget
- (void)sliderChanged:(NSSlider*)slider {
    AudioUnitParameterValue value = [slider doubleValue];
    AudioUnitSetParameter(self.audioUnit, self.parameterID, kAudioUnitScope_Global, 0, value, 0);

    // Update value label
    if (self.valueLabel) {
        [self.valueLabel setStringValue:[NSString stringWithFormat:@"%.2f", value]];
    }
}
@end

// Callback type for async GUI creation
typedef void (*RackAUGuiCallback)(void* user_data, RackAUGui* gui, int error_code);

// ============================================================================
// Helper Functions
// ============================================================================

// Get parameter count for generic UI
static UInt32 get_parameter_count(AudioComponentInstance audio_unit) {
    UInt32 param_count = 0;
    UInt32 size = 0;

    // Get size of parameter list
    OSStatus status = AudioUnitGetPropertyInfo(
        audio_unit,
        kAudioUnitProperty_ParameterList,
        kAudioUnitScope_Global,
        0,
        &size,
        NULL
    );

    if (status == noErr && size > 0) {
        param_count = size / sizeof(AudioUnitParameterID);
    }

    return param_count;
}

// Get parameter info for generic UI
static bool get_parameter_info(
    AudioComponentInstance audio_unit,
    AudioUnitParameterID param_id,
    AudioUnitParameterInfo* info,
    char* name_buffer,
    size_t name_buffer_size
) {
    UInt32 size = sizeof(AudioUnitParameterInfo);
    OSStatus status = AudioUnitGetProperty(
        audio_unit,
        kAudioUnitProperty_ParameterInfo,
        kAudioUnitScope_Global,
        param_id,
        info,
        &size
    );

    if (status != noErr) {
        return false;
    }

    // Extract parameter name from CFString
    if (info->cfNameString != NULL) {
        CFStringGetCString(
            info->cfNameString,
            name_buffer,
            name_buffer_size,
            kCFStringEncodingUTF8
        );
    } else {
        snprintf(name_buffer, name_buffer_size, "Parameter %u", (unsigned)param_id);
    }

    return true;
}

// Create generic parameter UI using NSStackView
static NSView* create_generic_ui(AudioComponentInstance audio_unit, NSMutableArray** out_targets) {
    @autoreleasepool {
        NSMutableArray* targets = [[NSMutableArray alloc] init];
        UInt32 param_count = get_parameter_count(audio_unit);

        if (param_count == 0) {
            // Create empty view with message
            NSTextField* label = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 400, 40)];
            [label setStringValue:@"This plugin has no parameters"];
            [label setBezeled:NO];
            [label setDrawsBackground:NO];
            [label setEditable:NO];
            [label setSelectable:NO];
            [label setAlignment:NSTextAlignmentCenter];
            return label;
        }

        // Create vertical stack view
        NSStackView* stackView = [[NSStackView alloc] init];
        [stackView setOrientation:NSUserInterfaceLayoutOrientationVertical];
        [stackView setAlignment:NSLayoutAttributeLeading];
        [stackView setSpacing:10];

        // Get parameter IDs
        UInt32 size = param_count * sizeof(AudioUnitParameterID);
        AudioUnitParameterID* param_ids = (AudioUnitParameterID*)malloc(size);
        if (!param_ids) {
            // Memory allocation failed
            return stackView;
        }

        OSStatus status = AudioUnitGetProperty(
            audio_unit,
            kAudioUnitProperty_ParameterList,
            kAudioUnitScope_Global,
            0,
            param_ids,
            &size
        );

        if (status != noErr) {
            free(param_ids);
            return stackView;  // Return empty stack view
        }

        // Create UI for each parameter (limit to first 20 for reasonable UI size)
        // TODO (Phase 9): Add scrolling support or make limit configurable
        UInt32 display_count = param_count > 20 ? 20 : param_count;
        for (UInt32 i = 0; i < display_count; i++) {
            AudioUnitParameterID param_id = param_ids[i];
            AudioUnitParameterInfo info;
            char name_buffer[256];

            if (!get_parameter_info(audio_unit, param_id, &info, name_buffer, sizeof(name_buffer))) {
                continue;
            }

            // Create horizontal container for label and slider
            NSStackView* rowView = [[NSStackView alloc] init];
            [rowView setOrientation:NSUserInterfaceLayoutOrientationHorizontal];
            [rowView setSpacing:10];

            // Parameter name label (fixed width)
            NSTextField* nameLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)];
            [nameLabel setStringValue:[NSString stringWithUTF8String:name_buffer]];
            [nameLabel setBezeled:NO];
            [nameLabel setDrawsBackground:NO];
            [nameLabel setEditable:NO];
            [nameLabel setSelectable:NO];
            [nameLabel setAlignment:NSTextAlignmentRight];

            // Slider (fixed width)
            NSSlider* slider = [[NSSlider alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)];
            [slider setMinValue:info.minValue];
            [slider setMaxValue:info.maxValue];
            [slider setDoubleValue:info.defaultValue];

            // Get current value from plugin
            AudioUnitParameterValue currentValue = info.defaultValue;
            AudioUnitGetParameter(audio_unit, param_id, kAudioUnitScope_Global, 0, &currentValue);
            [slider setDoubleValue:currentValue];

            // Value label (fixed width)
            NSTextField* valueLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 80, 24)];
            [valueLabel setStringValue:[NSString stringWithFormat:@"%.2f", currentValue]];
            [valueLabel setBezeled:NO];
            [valueLabel setDrawsBackground:NO];
            [valueLabel setEditable:NO];
            [valueLabel setSelectable:NO];
            [valueLabel setAlignment:NSTextAlignmentLeft];

            // Wire up slider to update parameter
            RackAUSliderTarget* target = [[RackAUSliderTarget alloc] init];
            target.audioUnit = audio_unit;
            target.parameterID = param_id;
            target.valueLabel = valueLabel;
            [slider setTarget:target];
            [slider setAction:@selector(sliderChanged:)];

            // Store target to keep it alive
            [targets addObject:target];

            // Add to row
            [rowView addView:nameLabel inGravity:NSStackViewGravityLeading];
            [rowView addView:slider inGravity:NSStackViewGravityLeading];
            [rowView addView:valueLabel inGravity:NSStackViewGravityLeading];

            // Add row to stack
            [stackView addView:rowView inGravity:NSStackViewGravityTop];
        }

        free(param_ids);

        // Set stack view size
        NSSize contentSize = [stackView fittingSize];
        [stackView setFrameSize:contentSize];

        // Return targets array
        if (out_targets) {
            *out_targets = targets;
        }

        return stackView;
    }
}

// ============================================================================
// AUv3 GUI Loading (Asynchronous)
// ============================================================================

static void try_load_auv3_gui(
    AudioComponentInstance audio_unit,
    void (^completion)(AUViewControllerBase* viewController)
) {
    @autoreleasepool {
        // Get the AudioComponent from the instance
        AudioComponent component = AudioComponentInstanceGetComponent(audio_unit);
        if (component == NULL) {
            completion(nil);
            return;
        }

        // Get component description to instantiate AUv3
        AudioComponentDescription desc;
        if (AudioComponentGetDescription(component, &desc) != noErr) {
            completion(nil);
            return;
        }

        // Try to instantiate as AUv3 (asynchronously)
        [AUAudioUnit instantiateWithComponentDescription:desc
                                                  options:0
                                        completionHandler:^(AUAudioUnit* _Nullable auAudioUnit, NSError* _Nullable error) {
            if (error != nil || auAudioUnit == nil) {
                // Not an AUv3 plugin or instantiation failed
                completion(nil);
                return;
            }

            // Request view controller asynchronously
            [auAudioUnit requestViewControllerWithCompletionHandler:^(AUViewControllerBase* _Nullable viewController) {
                // viewController will be nil if plugin has no GUI
                completion(viewController);
            }];
        }];
    }
}

// ============================================================================
// AUv2 GUI Loading (Synchronous)
// ============================================================================

static NSView* try_load_auv2_gui(AudioComponentInstance audio_unit) {
    @autoreleasepool {
        AudioUnitCocoaViewInfo viewInfo;
        UInt32 dataSize = sizeof(AudioUnitCocoaViewInfo);

        OSStatus status = AudioUnitGetProperty(
            audio_unit,
            kAudioUnitProperty_CocoaUI,
            kAudioUnitScope_Global,
            0,
            &viewInfo,
            &dataSize
        );

        if (status != noErr || viewInfo.mCocoaAUViewBundleLocation == NULL) {
            return nil;
        }

        // Use @try/@finally to ensure CFRelease happens even if exceptions occur
        NSView* auView = nil;
        @try {
            // Convert CFURLRef to NSURL
            // AudioUnitGetProperty returns owned CF objects (Create Rule)
            // __bridge doesn't transfer ownership to ARC, so manual CFRelease required
            NSURL* bundleURL = (__bridge NSURL*)viewInfo.mCocoaAUViewBundleLocation;
            NSBundle* viewBundle = [NSBundle bundleWithURL:bundleURL];

            if (viewBundle == nil) {
                return nil;
            }

            // Get view class name
            NSString* viewClassName = (__bridge NSString*)viewInfo.mCocoaAUViewClass[0];
            Class viewClass = [viewBundle classNamed:viewClassName];

            if (viewClass == nil) {
                return nil;
            }

            // Create view instance
            // The view class should have an initWithAudioUnit: method
            if ([viewClass instancesRespondToSelector:@selector(initWithAudioUnit:)]) {
                // Use NSInvocation to avoid performSelector warning
                SEL selector = @selector(initWithAudioUnit:);
                NSMethodSignature *signature = [viewClass instanceMethodSignatureForSelector:selector];
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
                [invocation setSelector:selector];
                id instance = [[viewClass alloc] init];
                [invocation setTarget:instance];
                [invocation setArgument:&audio_unit atIndex:2]; // arg 0 is self, arg 1 is _cmd
                [invocation invoke];
                [invocation getReturnValue:&auView];
            }
        }
        @finally {
            // Always clean up CoreFoundation objects, even if exception thrown
            CFRelease(viewInfo.mCocoaAUViewBundleLocation);
            if (viewInfo.mCocoaAUViewClass[0] != NULL) {
                CFRelease(viewInfo.mCocoaAUViewClass[0]);
            }
        }

        return auView;
    }
}

// Helper to get AudioComponentInstance from RackAUPlugin
// We need this because RackAUPlugin is opaque in this file
extern "C" AudioComponentInstance rack_au_plugin_get_audio_unit(RackAUPlugin* plugin);

// ============================================================================
// Public C API
// ============================================================================

extern "C" {

// Create GUI asynchronously
// Tries AUv3 (modern) → AUv2 (legacy) → generic UI (fallback)
// Callback is invoked on main thread when GUI is ready
void rack_au_gui_create_async(
    RackAUPlugin* plugin,
    RackAUGuiCallback callback,
    void* user_data
) {
    if (!plugin || !callback) {
        if (callback) {
            callback(user_data, NULL, RACK_AU_ERROR_INVALID_PARAM);
        }
        return;
    }

    // Get AudioComponentInstance from plugin
    AudioComponentInstance audio_unit = rack_au_plugin_get_audio_unit(plugin);
    if (audio_unit == NULL) {
        callback(user_data, NULL, RACK_AU_ERROR_INVALID_PARAM);
        return;
    }

    // Ensure we're on main thread for GUI operations
    dispatch_async(dispatch_get_main_queue(), ^{
        @autoreleasepool {
            // Try AUv3 GUI first (asynchronous)
            try_load_auv3_gui(audio_unit, ^(AUViewControllerBase* viewController) {
                if (viewController != nil) {
                    // AUv3 succeeded
                    RackAUGui* gui = new RackAUGui();
                    gui->audio_unit = audio_unit;
                    gui->view_controller = viewController;
                    gui->view = viewController.view;
                    gui->window = nil;
                    gui->slider_targets = nil;  // No slider targets for AUv3
                    gui->owns_view_controller = true;
                    gui->owns_view = false;  // View is owned by view controller
                    gui->error_message[0] = '\0';

                    callback(user_data, gui, RACK_AU_OK);
                } else {
                    // AUv3 failed, try AUv2
                    NSView* auv2_view = try_load_auv2_gui(audio_unit);

                    if (auv2_view != nil) {
                        // AUv2 succeeded
                        RackAUGui* gui = new RackAUGui();
                        gui->audio_unit = audio_unit;
                        gui->view_controller = nil;
                        gui->view = auv2_view;
                        gui->window = nil;
                        gui->slider_targets = nil;  // No slider targets for AUv2
                        gui->owns_view_controller = false;
                        gui->owns_view = true;
                        gui->error_message[0] = '\0';

                        callback(user_data, gui, RACK_AU_OK);
                    } else {
                        // Both AUv3 and AUv2 failed, create generic parameter UI as fallback
                        RackAUGui* gui = new RackAUGui();
                        NSMutableArray* targets = nil;
                        NSView* generic_view = create_generic_ui(audio_unit, &targets);

                        gui->audio_unit = audio_unit;
                        gui->view_controller = nil;
                        gui->view = generic_view;
                        gui->window = nil;
                        gui->slider_targets = targets;
                        gui->owns_view_controller = false;
                        gui->owns_view = true;
                        gui->error_message[0] = '\0';

                        callback(user_data, gui, RACK_AU_OK);
                    }
                }
            });
        }
    });
}

// Destroy GUI and clean up resources
// IMPORTANT: gui pointer becomes invalid immediately after this call
// Cleanup happens synchronously if on main thread, else dispatches to main thread
// Rust Drop impl ensures this is safe (ownership transferred)
void rack_au_gui_destroy(RackAUGui* gui) {
    if (!gui) {
        return;
    }

    // Lambda for cleanup code (used in both sync and async paths)
    auto cleanup = ^{
        @autoreleasepool {
            // Close window if we created one
            if (gui->window != nil) {
                [gui->window close];
                gui->window = nil;
            }

            // Clean up view controller
            if (gui->owns_view_controller && gui->view_controller != nil) {
                gui->view_controller = nil;  // ARC will handle cleanup
            }

            // Clean up view
            if (gui->owns_view && gui->view != nil) {
                [gui->view removeFromSuperview];
                gui->view = nil;  // ARC will handle cleanup
            }

            // Clean up slider targets (generic UI)
            if (gui->slider_targets != nil) {
                gui->slider_targets = nil;  // ARC will handle cleanup
            }

            delete gui;
        }
    };

    // If already on main thread, cleanup synchronously to avoid race conditions
    // Otherwise dispatch to main thread (required for AppKit operations)
    if ([NSThread isMainThread]) {
        cleanup();
    } else {
        dispatch_sync(dispatch_get_main_queue(), cleanup);
    }
}

// Get native NSView pointer for embedding in host UI
// Returns void* that can be cast to NSView* in Objective-C code
void* rack_au_gui_get_view(RackAUGui* gui) {
    if (!gui) {
        return NULL;
    }

    return (__bridge void*)gui->view;
}

// Get view size
int rack_au_gui_get_size(RackAUGui* gui, float* width, float* height) {
    if (!gui || !gui->view || !width || !height) {
        return RACK_AU_ERROR_INVALID_PARAM;
    }

    NSSize size;
    if ([NSThread isMainThread]) {
        // Already on main thread, get size directly
        size = [gui->view frame].size;
    } else {
        // Not on main thread, dispatch to main thread
        __block NSSize blockSize;
        dispatch_sync(dispatch_get_main_queue(), ^{
            blockSize = [gui->view frame].size;
        });
        size = blockSize;
    }

    *width = size.width;
    *height = size.height;

    return RACK_AU_OK;
}

// Create and show window with GUI
int rack_au_gui_show_window(RackAUGui* gui, const char* title) {
    if (!gui || !gui->view) {
        return RACK_AU_ERROR_INVALID_PARAM;
    }

    // Copy the title string now, before the async block
    // The title pointer from C might be freed before the block executes
    NSString* windowTitle = nil;
    if (title != NULL) {
        windowTitle = [NSString stringWithUTF8String:title];
    } else {
        windowTitle = @"AudioUnit GUI";
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        @autoreleasepool {
            // Ensure NSApp is initialized (required for windows to appear)
            // This is safe to call multiple times
            [NSApplication sharedApplication];
            [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];

            // Get view size
            NSSize viewSize = [gui->view frame].size;

            // Create window if needed
            if (gui->window == nil) {
                NSRect frame = NSMakeRect(100, 100, viewSize.width, viewSize.height);
                gui->window = [[NSWindow alloc] initWithContentRect:frame
                                                          styleMask:(NSWindowStyleMaskTitled |
                                                                   NSWindowStyleMaskClosable |
                                                                   NSWindowStyleMaskMiniaturizable)
                                                            backing:NSBackingStoreBuffered
                                                              defer:NO];

                [gui->window setContentView:gui->view];
                [gui->window setTitle:windowTitle];
            }

            // Activate the app and bring window to front
            [NSApp activateIgnoringOtherApps:YES];
            [gui->window makeKeyAndOrderFront:nil];
            [gui->window center];
            [gui->window setLevel:NSFloatingWindowLevel];  // Keep window on top initially
        }
    });

    return RACK_AU_OK;
}

// Hide window
int rack_au_gui_hide_window(RackAUGui* gui) {
    if (!gui) {
        return RACK_AU_ERROR_INVALID_PARAM;
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        if (gui->window != nil) {
            [gui->window orderOut:nil];
        }
    });

    return RACK_AU_OK;
}

} // extern "C"