RAM2118 commited on
Commit
0e80263
·
verified ·
1 Parent(s): ef91ceb

Upload Source/Helper/HelperPluginHost.mm

Browse files
Files changed (1) hide show
  1. Source/Helper/HelperPluginHost.mm +464 -0
Source/Helper/HelperPluginHost.mm ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "HelperPluginHost.h"
2
+ #include "Constants.h"
3
+ #include "IPCProtocol.h"
4
+ #include <juce_audio_basics/juce_audio_basics.h>
5
+ #include <pthread.h>
6
+ #include <sched.h>
7
+
8
+ #if JUCE_MAC
9
+ #import <Cocoa/Cocoa.h>
10
+ #import <QuartzCore/QuartzCore.h>
11
+ #endif
12
+
13
+ HelperPluginHost::HelperPluginHost()
14
+ {
15
+ #if JUCE_PLUGINHOST_VST3
16
+ formatManager.addFormat(new juce::VST3PluginFormat());
17
+ #endif
18
+ #if JUCE_PLUGINHOST_AU
19
+ formatManager.addFormat(new juce::AudioUnitPluginFormat());
20
+ #endif
21
+ }
22
+
23
+ HelperPluginHost::~HelperPluginHost()
24
+ {
25
+ stopProcessing();
26
+ hideGui();
27
+ unloadPlugin();
28
+ }
29
+
30
+ bool HelperPluginHost::loadPlugin(const juce::String& path, double sampleRate, int blockSize)
31
+ {
32
+ unloadPlugin();
33
+
34
+ currentSampleRate = sampleRate;
35
+ currentBlockSize = blockSize;
36
+
37
+ juce::File pluginFile(path);
38
+ if (!pluginFile.exists())
39
+ return false;
40
+
41
+ juce::OwnedArray<juce::PluginDescription> typesFound;
42
+
43
+ for (int i = 0; i < formatManager.getNumFormats(); ++i)
44
+ {
45
+ auto* format = formatManager.getFormat(i);
46
+ bool isVST3 = pluginFile.getFileExtension() == ".vst3";
47
+ bool isAU = pluginFile.getFileExtension() == ".component";
48
+
49
+ if (isVST3 && format->getName() != "VST3") continue;
50
+ if (isAU && format->getName() != "AudioUnit") continue;
51
+
52
+ format->findAllTypesForFile(typesFound, pluginFile.getFullPathName());
53
+ if (typesFound.size() > 0)
54
+ break;
55
+ }
56
+
57
+ if (typesFound.isEmpty())
58
+ return false;
59
+
60
+ juce::String errorMessage;
61
+ plugin = formatManager.createPluginInstance(*typesFound[0], sampleRate, blockSize, errorMessage);
62
+
63
+ if (plugin == nullptr)
64
+ {
65
+ DBG("HelperPluginHost: Failed to create plugin: " + errorMessage);
66
+ return false;
67
+ }
68
+
69
+ plugin->enableAllBuses();
70
+
71
+ auto layout = juce::AudioProcessor::BusesLayout();
72
+ layout.inputBuses.add(juce::AudioChannelSet::stereo());
73
+ layout.outputBuses.add(juce::AudioChannelSet::stereo());
74
+
75
+ if (plugin->checkBusesLayoutSupported(layout))
76
+ plugin->setBusesLayout(layout);
77
+
78
+ plugin->prepareToPlay(sampleRate, blockSize);
79
+
80
+ DBG("HelperPluginHost: Loaded " + getPluginName() + " (" + juce::String(getParameterCount()) + " params)");
81
+ return true;
82
+ }
83
+
84
+ void HelperPluginHost::unloadPlugin()
85
+ {
86
+ hideGui();
87
+ if (plugin)
88
+ {
89
+ plugin->releaseResources();
90
+ plugin.reset();
91
+ }
92
+ }
93
+
94
+ juce::String HelperPluginHost::getPluginName() const
95
+ {
96
+ return plugin ? plugin->getName() : juce::String();
97
+ }
98
+
99
+ int HelperPluginHost::getParameterCount() const
100
+ {
101
+ return plugin ? plugin->getParameters().size() : 0;
102
+ }
103
+
104
+ // --- Audio ---
105
+
106
+ void HelperPluginHost::setSharedAudio(SharedAudioBuffer* shm, SharedSemaphore* inSem, SharedSemaphore* outSem)
107
+ {
108
+ sharedAudio = shm;
109
+ inputSem = inSem;
110
+ outputSem = outSem;
111
+ }
112
+
113
+ void HelperPluginHost::startProcessing()
114
+ {
115
+ if (processing.load()) return;
116
+ processing.store(true);
117
+ audioThread = std::thread([this]() { audioProcessingLoop(); });
118
+ }
119
+
120
+ void HelperPluginHost::stopProcessing()
121
+ {
122
+ processing.store(false);
123
+ if (inputSem) inputSem->signal();
124
+ if (audioThread.joinable())
125
+ audioThread.join();
126
+ }
127
+
128
+ void HelperPluginHost::audioProcessingLoop()
129
+ {
130
+ struct sched_param param;
131
+ param.sched_priority = sched_get_priority_max(SCHED_FIFO);
132
+ pthread_setschedparam(pthread_self(), SCHED_FIFO, &param);
133
+
134
+ while (processing.load())
135
+ {
136
+ if (!inputSem->wait(100))
137
+ continue;
138
+
139
+ if (!processing.load()) break;
140
+ if (!plugin || !sharedAudio) continue;
141
+
142
+ auto* header = sharedAudio->getHeader();
143
+ int numChannels = header->numChannels.load();
144
+ int blockSize = header->blockSize.load();
145
+
146
+ juce::AudioBuffer<float> buffer(numChannels, blockSize);
147
+ float* channelPtrs[2] = { buffer.getWritePointer(0),
148
+ numChannels > 1 ? buffer.getWritePointer(1) : nullptr };
149
+ sharedAudio->readInput(channelPtrs, numChannels, blockSize);
150
+
151
+ juce::MidiBuffer midi;
152
+ plugin->processBlock(buffer, midi);
153
+
154
+ const float* constPtrs[2] = { buffer.getReadPointer(0),
155
+ numChannels > 1 ? buffer.getReadPointer(1) : nullptr };
156
+ sharedAudio->writeOutput(constPtrs, numChannels, blockSize);
157
+
158
+ header->state.store(kStateOutputReady);
159
+ outputSem->signal();
160
+ }
161
+ }
162
+
163
+ // --- Parameters ---
164
+
165
+ std::vector<HelperPluginHost::ParamInfo> HelperPluginHost::searchParams(const juce::String& keyword) const
166
+ {
167
+ std::vector<ParamInfo> results;
168
+ if (!plugin) return results;
169
+
170
+ auto& params = plugin->getParameters();
171
+ auto keywordLower = keyword.toLowerCase();
172
+
173
+ for (int i = 0; i < params.size(); ++i)
174
+ {
175
+ auto* param = params[i];
176
+ auto name = param->getName(128);
177
+
178
+ if (keyword.isEmpty() || name.toLowerCase().contains(keywordLower))
179
+ {
180
+ ParamInfo info;
181
+ info.index = i;
182
+ info.name = name;
183
+ info.value = param->getValue();
184
+ info.displayText = param->getText(param->getValue(), 64);
185
+
186
+ if (auto* hosted = dynamic_cast<juce::AudioPluginInstance::HostedParameter*>(param))
187
+ info.id = hosted->getParameterID();
188
+ else
189
+ info.id = juce::String(i);
190
+
191
+ results.push_back(info);
192
+ if (results.size() >= PluginBridgeConstants::kMaxParamResults)
193
+ break;
194
+ }
195
+ }
196
+
197
+ return results;
198
+ }
199
+
200
+ std::vector<std::pair<int, float>> HelperPluginHost::getParams(const std::vector<int>& ids) const
201
+ {
202
+ std::vector<std::pair<int, float>> results;
203
+ if (!plugin) return results;
204
+
205
+ auto& params = plugin->getParameters();
206
+ for (int idx : ids)
207
+ {
208
+ if (idx >= 0 && idx < params.size())
209
+ results.push_back({idx, params[idx]->getValue()});
210
+ }
211
+ return results;
212
+ }
213
+
214
+ bool HelperPluginHost::setParams(const std::map<int, float>& values)
215
+ {
216
+ if (!plugin) return false;
217
+
218
+ auto& params = plugin->getParameters();
219
+ for (auto& [idx, val] : values)
220
+ {
221
+ if (idx >= 0 && idx < params.size())
222
+ {
223
+ auto* param = params[idx];
224
+ param->beginChangeGesture();
225
+ param->setValueNotifyingHost(juce::jlimit(0.0f, 1.0f, val));
226
+ param->endChangeGesture();
227
+ }
228
+ }
229
+ return true;
230
+ }
231
+
232
+ // --- GUI via CARemoteLayerServer ---
233
+
234
+ void HelperPluginHost::showGui()
235
+ {
236
+ #if JUCE_MAC
237
+ if (!plugin || !plugin->hasEditor()) return;
238
+ if (editor) return; // already showing
239
+
240
+ juce::MessageManager::callAsync([this]()
241
+ {
242
+ if (!plugin) return;
243
+
244
+ editor.reset(plugin->createEditor());
245
+ if (!editor) return;
246
+
247
+ guiWidth = editor->getWidth();
248
+ guiHeight = editor->getHeight();
249
+
250
+ // Create a hidden NSWindow to host the editor (needed for layer-backed rendering)
251
+ NSWindow* window = [[NSWindow alloc]
252
+ initWithContentRect:NSMakeRect(0, 0, guiWidth, guiHeight)
253
+ styleMask:NSWindowStyleMaskBorderless
254
+ backing:NSBackingStoreBuffered
255
+ defer:NO];
256
+ [window setReleasedWhenClosed:NO];
257
+
258
+ // Make the window layer-backed
259
+ [[window contentView] setWantsLayer:YES];
260
+
261
+ // Add the JUCE editor as a child view
262
+ editor->addToDesktop(0, (void*)[window contentView]);
263
+ if (auto* peer = editor->getPeer())
264
+ {
265
+ NSView* editorView = (NSView*)peer->getNativeHandle();
266
+ [[window contentView] addSubview:editorView];
267
+ [editorView setFrame:[[window contentView] bounds]];
268
+ }
269
+
270
+ // Set up CARemoteLayerServer
271
+ CARemoteLayerServer* server = [CARemoteLayerServer sharedServer];
272
+ remoteLayerServer = (__bridge_retained void*)server;
273
+
274
+ // Register the server port via NSMachBootstrapServer
275
+ mach_port_t port = server.serverPort;
276
+ NSMachPort* machPort = [NSMachPort portWithMachPort:port];
277
+ NSString* portName = [NSString stringWithUTF8String:
278
+ layerPortName.toRawUTF8()];
279
+ [[NSMachBootstrapServer sharedInstance] registerPort:machPort name:portName];
280
+
281
+ // The window's content layer IS the remote layer content
282
+ // CARemoteLayerServer automatically serves the process's layer tree
283
+
284
+ guiWindow = (__bridge_retained void*)window;
285
+
286
+ DBG("HelperPluginHost: GUI created, layer port: " + layerPortName +
287
+ " size: " + juce::String(guiWidth) + "x" + juce::String(guiHeight));
288
+ });
289
+ #endif
290
+ }
291
+
292
+ void HelperPluginHost::hideGui()
293
+ {
294
+ #if JUCE_MAC
295
+ juce::MessageManager::callAsync([this]()
296
+ {
297
+ editor.reset();
298
+
299
+ if (guiWindow)
300
+ {
301
+ NSWindow* window = (__bridge_transfer NSWindow*)guiWindow;
302
+ [window close];
303
+ guiWindow = nullptr;
304
+ }
305
+
306
+ if (remoteLayerServer)
307
+ {
308
+ // Unregister port
309
+ NSString* portName = [NSString stringWithUTF8String:layerPortName.toRawUTF8()];
310
+ [[NSMachBootstrapServer sharedInstance] registerPort:nil name:portName];
311
+
312
+ CFRelease(remoteLayerServer);
313
+ remoteLayerServer = nullptr;
314
+ }
315
+ });
316
+ #endif
317
+ }
318
+
319
+ // --- Event Injection ---
320
+
321
+ void HelperPluginHost::injectMouseDown(float x, float y, int button)
322
+ {
323
+ #if JUCE_MAC
324
+ if (!guiWindow) return;
325
+ NSWindow* window = (__bridge NSWindow*)guiWindow;
326
+ NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDown
327
+ location:NSMakePoint(x, guiHeight - y) // flip Y
328
+ modifierFlags:0
329
+ timestamp:[[NSProcessInfo processInfo] systemUptime]
330
+ windowNumber:[window windowNumber]
331
+ context:nil eventNumber:0 clickCount:1 pressure:1.0];
332
+ [NSApp postEvent:event atStart:NO];
333
+ #endif
334
+ }
335
+
336
+ void HelperPluginHost::injectMouseUp(float x, float y, int button)
337
+ {
338
+ #if JUCE_MAC
339
+ if (!guiWindow) return;
340
+ NSWindow* window = (__bridge NSWindow*)guiWindow;
341
+ NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeLeftMouseUp
342
+ location:NSMakePoint(x, guiHeight - y)
343
+ modifierFlags:0
344
+ timestamp:[[NSProcessInfo processInfo] systemUptime]
345
+ windowNumber:[window windowNumber]
346
+ context:nil eventNumber:0 clickCount:1 pressure:0.0];
347
+ [NSApp postEvent:event atStart:NO];
348
+ #endif
349
+ }
350
+
351
+ void HelperPluginHost::injectMouseMove(float x, float y)
352
+ {
353
+ #if JUCE_MAC
354
+ if (!guiWindow) return;
355
+ NSWindow* window = (__bridge NSWindow*)guiWindow;
356
+ NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeMouseMoved
357
+ location:NSMakePoint(x, guiHeight - y)
358
+ modifierFlags:0
359
+ timestamp:[[NSProcessInfo processInfo] systemUptime]
360
+ windowNumber:[window windowNumber]
361
+ context:nil eventNumber:0 clickCount:0 pressure:0.0];
362
+ [NSApp postEvent:event atStart:NO];
363
+ #endif
364
+ }
365
+
366
+ void HelperPluginHost::injectMouseDrag(float x, float y, int button)
367
+ {
368
+ #if JUCE_MAC
369
+ if (!guiWindow) return;
370
+ NSWindow* window = (__bridge NSWindow*)guiWindow;
371
+ NSEvent* event = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDragged
372
+ location:NSMakePoint(x, guiHeight - y)
373
+ modifierFlags:0
374
+ timestamp:[[NSProcessInfo processInfo] systemUptime]
375
+ windowNumber:[window windowNumber]
376
+ context:nil eventNumber:0 clickCount:0 pressure:1.0];
377
+ [NSApp postEvent:event atStart:NO];
378
+ #endif
379
+ }
380
+
381
+ void HelperPluginHost::injectMouseScroll(float x, float y, float dx, float dy)
382
+ {
383
+ #if JUCE_MAC
384
+ if (!guiWindow) return;
385
+ CGEventRef scrollEvent = CGEventCreateScrollWheelEvent(NULL,
386
+ kCGScrollEventUnitPixel, 2, (int32_t)dy, (int32_t)dx);
387
+ NSEvent* event = [NSEvent eventWithCGEvent:scrollEvent];
388
+ CFRelease(scrollEvent);
389
+ [NSApp postEvent:event atStart:NO];
390
+ #endif
391
+ }
392
+
393
+ void HelperPluginHost::injectKeyDown(int keyCode, const juce::String& chars, int modifiers)
394
+ {
395
+ #if JUCE_MAC
396
+ if (!guiWindow) return;
397
+ NSWindow* window = (__bridge NSWindow*)guiWindow;
398
+ NSString* nsChars = [NSString stringWithUTF8String:chars.toRawUTF8()];
399
+ NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown
400
+ location:NSZeroPoint
401
+ modifierFlags:(NSEventModifierFlags)modifiers
402
+ timestamp:[[NSProcessInfo processInfo] systemUptime]
403
+ windowNumber:[window windowNumber]
404
+ context:nil
405
+ characters:nsChars
406
+ charactersIgnoringModifiers:nsChars
407
+ isARepeat:NO
408
+ keyCode:(unsigned short)keyCode];
409
+ [NSApp postEvent:event atStart:NO];
410
+ #endif
411
+ }
412
+
413
+ void HelperPluginHost::injectKeyUp(int keyCode, const juce::String& chars, int modifiers)
414
+ {
415
+ #if JUCE_MAC
416
+ if (!guiWindow) return;
417
+ NSWindow* window = (__bridge NSWindow*)guiWindow;
418
+ NSString* nsChars = [NSString stringWithUTF8String:chars.toRawUTF8()];
419
+ NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyUp
420
+ location:NSZeroPoint
421
+ modifierFlags:(NSEventModifierFlags)modifiers
422
+ timestamp:[[NSProcessInfo processInfo] systemUptime]
423
+ windowNumber:[window windowNumber]
424
+ context:nil
425
+ characters:nsChars
426
+ charactersIgnoringModifiers:nsChars
427
+ isARepeat:NO
428
+ keyCode:(unsigned short)keyCode];
429
+ [NSApp postEvent:event atStart:NO];
430
+ #endif
431
+ }
432
+
433
+ // --- State ---
434
+
435
+ juce::String HelperPluginHost::getStateBase64() const
436
+ {
437
+ if (!plugin) return {};
438
+ juce::MemoryBlock stateData;
439
+ plugin->getStateInformation(stateData);
440
+ return stateData.toBase64Encoding();
441
+ }
442
+
443
+ bool HelperPluginHost::setStateBase64(const juce::String& base64State)
444
+ {
445
+ if (!plugin) return false;
446
+ juce::MemoryBlock stateData;
447
+ if (!stateData.fromBase64Encoding(base64State))
448
+ return false;
449
+ plugin->setStateInformation(stateData.getData(), (int)stateData.getSize());
450
+ return true;
451
+ }
452
+
453
+ void HelperPluginHost::configure(double sampleRate, int blockSize, int channels)
454
+ {
455
+ currentSampleRate = sampleRate;
456
+ currentBlockSize = blockSize;
457
+ currentChannels = channels;
458
+
459
+ if (plugin)
460
+ {
461
+ plugin->releaseResources();
462
+ plugin->prepareToPlay(sampleRate, blockSize);
463
+ }
464
+ }