The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2249 lines
80KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #include "../../juce_core/system/juce_TargetPlatform.h"
  18. //==============================================================================
  19. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  20. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  21. #include "../utility/juce_CheckSettingMacros.h"
  22. #include "../utility/juce_IncludeModuleHeaders.h"
  23. #include "../utility/juce_WindowsHooks.h"
  24. #include "../utility/juce_PluginBusUtilities.h"
  25. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  26. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  27. #define JUCE_VST3_CAN_REPLACE_VST2 1
  28. #endif
  29. #if JUCE_VST3_CAN_REPLACE_VST2
  30. #if JUCE_MSVC
  31. #pragma warning (push)
  32. #pragma warning (disable: 4514 4996)
  33. #endif
  34. #include <pluginterfaces/vst2.x/vstfxstore.h>
  35. #if JUCE_MSVC
  36. #pragma warning (pop)
  37. #endif
  38. #endif
  39. namespace juce
  40. {
  41. using namespace Steinberg;
  42. //==============================================================================
  43. #if JUCE_MAC
  44. extern void initialiseMacVST();
  45. #if ! JUCE_64BIT
  46. extern void updateEditorCompBoundsVST (Component*);
  47. #endif
  48. extern void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
  49. extern void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
  50. extern void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  51. #endif
  52. //==============================================================================
  53. class JuceAudioProcessor : public FUnknown
  54. {
  55. public:
  56. JuceAudioProcessor (AudioProcessor* source) noexcept
  57. : isBypassed (false), refCount (0), audioProcessor (source) {}
  58. virtual ~JuceAudioProcessor() {}
  59. AudioProcessor* get() const noexcept { return audioProcessor; }
  60. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  61. JUCE_DECLARE_VST3_COM_REF_METHODS
  62. static const FUID iid;
  63. bool isBypassed;
  64. private:
  65. Atomic<int> refCount;
  66. ScopedPointer<AudioProcessor> audioProcessor;
  67. ScopedJuceInitialiser_GUI libraryInitialiser;
  68. JuceAudioProcessor() JUCE_DELETED_FUNCTION;
  69. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  70. };
  71. //==============================================================================
  72. class JuceVST3EditController : public Vst::EditController,
  73. public Vst::IMidiMapping,
  74. public AudioProcessorListener
  75. {
  76. public:
  77. JuceVST3EditController (Vst::IHostApplication* host)
  78. {
  79. if (host != nullptr)
  80. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  81. }
  82. //==============================================================================
  83. static const FUID iid;
  84. //==============================================================================
  85. #if JUCE_CLANG
  86. #pragma clang diagnostic push
  87. #pragma clang diagnostic ignored "-Winconsistent-missing-override"
  88. #endif
  89. REFCOUNT_METHODS (ComponentBase)
  90. #if JUCE_CLANG
  91. #pragma clang diagnostic pop
  92. #endif
  93. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  94. {
  95. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  96. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  97. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  98. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  99. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  100. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  101. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  102. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  103. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  104. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  105. {
  106. audioProcessor->addRef();
  107. *obj = audioProcessor;
  108. return kResultOk;
  109. }
  110. *obj = nullptr;
  111. return kNoInterface;
  112. }
  113. //==============================================================================
  114. tresult PLUGIN_API initialize (FUnknown* context) override
  115. {
  116. if (hostContext != context)
  117. {
  118. if (hostContext != nullptr)
  119. hostContext->release();
  120. hostContext = context;
  121. if (hostContext != nullptr)
  122. hostContext->addRef();
  123. }
  124. return kResultTrue;
  125. }
  126. tresult PLUGIN_API terminate() override
  127. {
  128. if (AudioProcessor* const pluginInstance = getPluginInstance())
  129. pluginInstance->removeListener (this);
  130. audioProcessor = nullptr;
  131. return EditController::terminate();
  132. }
  133. //==============================================================================
  134. struct Param : public Vst::Parameter
  135. {
  136. Param (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  137. {
  138. info.id = (Vst::ParamID) index;
  139. toString128 (info.title, p.getParameterName (index));
  140. toString128 (info.shortTitle, p.getParameterName (index, 8));
  141. toString128 (info.units, p.getParameterLabel (index));
  142. const int numSteps = p.getParameterNumSteps (index);
  143. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  144. info.defaultNormalizedValue = p.getParameterDefaultValue (index);
  145. jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
  146. info.unitId = Vst::kRootUnitId;
  147. info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
  148. }
  149. virtual ~Param() {}
  150. bool setNormalized (Vst::ParamValue v) override
  151. {
  152. v = jlimit (0.0, 1.0, v);
  153. if (v != valueNormalized)
  154. {
  155. valueNormalized = v;
  156. changed();
  157. return true;
  158. }
  159. return false;
  160. }
  161. void toString (Vst::ParamValue value, Vst::String128 result) const override
  162. {
  163. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  164. toString128 (result, p->getText ((float) value, 128));
  165. else
  166. // remain backward-compatible with old JUCE code
  167. toString128 (result, owner.getParameterText (paramIndex, 128));
  168. }
  169. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  170. {
  171. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  172. {
  173. outValueNormalized = p->getValueForText (getStringFromVstTChars (text));
  174. return true;
  175. }
  176. return false;
  177. }
  178. static String getStringFromVstTChars (const Vst::TChar* text)
  179. {
  180. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  181. }
  182. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  183. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  184. private:
  185. AudioProcessor& owner;
  186. int paramIndex;
  187. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  188. };
  189. //==============================================================================
  190. struct BypassParam : public Vst::Parameter
  191. {
  192. BypassParam (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  193. {
  194. info.id = (Vst::ParamID) index;
  195. toString128 (info.title, "Bypass");
  196. toString128 (info.shortTitle, "Bypass");
  197. toString128 (info.units, "");
  198. info.stepCount = 1;
  199. info.defaultNormalizedValue = 0.0f;
  200. info.unitId = Vst::kRootUnitId;
  201. info.flags = Vst::ParameterInfo::kIsBypass;
  202. }
  203. virtual ~BypassParam() {}
  204. bool setNormalized (Vst::ParamValue v) override
  205. {
  206. bool bypass = (v != 0.0f);
  207. v = (bypass ? 1.0f : 0.0f);
  208. if (valueNormalized != v)
  209. {
  210. valueNormalized = v;
  211. changed();
  212. return true;
  213. }
  214. return false;
  215. }
  216. void toString (Vst::ParamValue value, Vst::String128 result) const override
  217. {
  218. bool bypass = (value != 0.0f);
  219. toString128 (result, bypass ? "On" : "Off");
  220. }
  221. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  222. {
  223. const String paramValueString (getStringFromVstTChars (text));
  224. if (paramValueString.equalsIgnoreCase ("on")
  225. || paramValueString.equalsIgnoreCase ("yes")
  226. || paramValueString.equalsIgnoreCase ("true"))
  227. {
  228. outValueNormalized = 1.0f;
  229. return true;
  230. }
  231. if (paramValueString.equalsIgnoreCase ("off")
  232. || paramValueString.equalsIgnoreCase ("no")
  233. || paramValueString.equalsIgnoreCase ("false"))
  234. {
  235. outValueNormalized = 0.0f;
  236. return true;
  237. }
  238. var varValue = JSON::fromString (paramValueString);
  239. if (varValue.isDouble() || varValue.isInt()
  240. || varValue.isInt64() || varValue.isBool())
  241. {
  242. double value = varValue;
  243. outValueNormalized = (value != 0.0) ? 1.0f : 0.0f;
  244. return true;
  245. }
  246. return false;
  247. }
  248. static String getStringFromVstTChars (const Vst::TChar* text)
  249. {
  250. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  251. }
  252. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  253. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  254. private:
  255. AudioProcessor& owner;
  256. int paramIndex;
  257. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BypassParam)
  258. };
  259. //==============================================================================
  260. tresult PLUGIN_API setComponentState (IBStream* stream) override
  261. {
  262. // Cubase and Nuendo need to inform the host of the current parameter values
  263. if (AudioProcessor* const pluginInstance = getPluginInstance())
  264. {
  265. const int numParameters = pluginInstance->getNumParameters();
  266. for (int i = 0; i < numParameters; ++i)
  267. setParamNormalized ((Vst::ParamID) i, (double) pluginInstance->getParameter (i));
  268. setParamNormalized ((Vst::ParamID) numParameters, audioProcessor->isBypassed ? 1.0f : 0.0f);
  269. }
  270. return Vst::EditController::setComponentState (stream);
  271. }
  272. void setAudioProcessor (JuceAudioProcessor* audioProc)
  273. {
  274. if (audioProcessor != audioProc)
  275. {
  276. audioProcessor = audioProc;
  277. setupParameters();
  278. }
  279. }
  280. tresult PLUGIN_API connect (IConnectionPoint* other) override
  281. {
  282. if (other != nullptr && audioProcessor == nullptr)
  283. {
  284. const tresult result = ComponentBase::connect (other);
  285. if (! audioProcessor.loadFrom (other))
  286. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  287. else
  288. setupParameters();
  289. return result;
  290. }
  291. jassertfalse;
  292. return kResultFalse;
  293. }
  294. //==============================================================================
  295. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
  296. Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
  297. {
  298. resultID = (Vst::ParamID) midiControllerToParameter[channel][midiControllerNumber];
  299. return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
  300. }
  301. // Converts an incoming parameter index to a MIDI controller:
  302. bool getMidiControllerForParameter (int index, int& channel, int& ctrlNumber)
  303. {
  304. const int mappedIndex = index - parameterToMidiControllerOffset;
  305. if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
  306. {
  307. const MidiController& mc = parameterToMidiController[mappedIndex];
  308. if (mc.channel != -1 && mc.ctrlNumber != -1)
  309. {
  310. channel = jlimit (1, 16, mc.channel + 1);
  311. ctrlNumber = mc.ctrlNumber;
  312. return true;
  313. }
  314. }
  315. return false;
  316. }
  317. //==============================================================================
  318. IPlugView* PLUGIN_API createView (const char* name) override
  319. {
  320. if (AudioProcessor* const pluginInstance = getPluginInstance())
  321. {
  322. if (pluginInstance->hasEditor() && name != nullptr
  323. && strcmp (name, Vst::ViewType::kEditor) == 0)
  324. {
  325. return new JuceVST3Editor (*this, *pluginInstance);
  326. }
  327. }
  328. return nullptr;
  329. }
  330. //==============================================================================
  331. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit ((Vst::ParamID) index); }
  332. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  333. {
  334. // NB: Cubase has problems if performEdit is called without setParamNormalized
  335. EditController::setParamNormalized ((Vst::ParamID) index, (double) newValue);
  336. performEdit ((Vst::ParamID) index, (double) newValue);
  337. }
  338. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit ((Vst::ParamID) index); }
  339. void audioProcessorChanged (AudioProcessor*) override
  340. {
  341. if (componentHandler != nullptr)
  342. componentHandler->restartComponent (Vst::kLatencyChanged | Vst::kParamValuesChanged);
  343. }
  344. //==============================================================================
  345. AudioProcessor* getPluginInstance() const noexcept
  346. {
  347. if (audioProcessor != nullptr)
  348. return audioProcessor->get();
  349. return nullptr;
  350. }
  351. private:
  352. //==============================================================================
  353. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  354. ScopedJuceInitialiser_GUI libraryInitialiser;
  355. struct MidiController
  356. {
  357. MidiController() noexcept : channel (-1), ctrlNumber (-1) {}
  358. int channel, ctrlNumber;
  359. };
  360. enum { numMIDIChannels = 16 };
  361. int parameterToMidiControllerOffset;
  362. MidiController parameterToMidiController[numMIDIChannels * Vst::kCountCtrlNumber];
  363. int midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
  364. //==============================================================================
  365. void setupParameters()
  366. {
  367. if (AudioProcessor* const pluginInstance = getPluginInstance())
  368. {
  369. pluginInstance->addListener (this);
  370. if (parameters.getParameterCount() <= 0)
  371. {
  372. const int numParameters = pluginInstance->getNumParameters();
  373. for (int i = 0; i < numParameters; ++i)
  374. parameters.addParameter (new Param (*pluginInstance, i));
  375. parameters.addParameter (new BypassParam (*pluginInstance, numParameters));
  376. }
  377. // We need to account for the bypass parameter in the numParameters passed to
  378. // the next function
  379. initialiseMidiControllerMappings (pluginInstance->getNumParameters() + 1);
  380. audioProcessorChanged (pluginInstance);
  381. }
  382. }
  383. void initialiseMidiControllerMappings (const int numVstParameters)
  384. {
  385. parameterToMidiControllerOffset = numVstParameters;
  386. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  387. {
  388. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  389. {
  390. midiControllerToParameter[c][i] = p + parameterToMidiControllerOffset;
  391. parameterToMidiController[p].channel = c;
  392. parameterToMidiController[p].ctrlNumber = i;
  393. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  394. (Vst::ParamID) (p + parameterToMidiControllerOffset), 0, 0, 0,
  395. Vst::ParameterInfo::kCanAutomate, Vst::kRootUnitId));
  396. }
  397. }
  398. }
  399. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  400. {
  401. jassert (hostContext != nullptr);
  402. if (Vst::IMessage* message = allocateMessage())
  403. {
  404. const FReleaser releaser (message);
  405. message->setMessageID (idTag);
  406. message->getAttributes()->setInt (idTag, value);
  407. sendMessage (message);
  408. }
  409. }
  410. //==============================================================================
  411. class JuceVST3Editor : public Vst::EditorView
  412. {
  413. public:
  414. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  415. : Vst::EditorView (&ec, nullptr),
  416. owner (&ec), pluginInstance (p)
  417. {
  418. #if JUCE_MAC
  419. macHostWindow = nullptr;
  420. isNSView = false;
  421. #endif
  422. component = new ContentWrapperComponent (*this, p);
  423. }
  424. //==============================================================================
  425. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  426. {
  427. if (type != nullptr && pluginInstance.hasEditor())
  428. {
  429. #if JUCE_WINDOWS
  430. if (strcmp (type, kPlatformTypeHWND) == 0)
  431. #else
  432. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  433. #endif
  434. return kResultTrue;
  435. }
  436. return kResultFalse;
  437. }
  438. tresult PLUGIN_API attached (void* parent, FIDString type) override
  439. {
  440. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  441. return kResultFalse;
  442. if (component == nullptr)
  443. component = new ContentWrapperComponent (*this, pluginInstance);
  444. #if JUCE_WINDOWS
  445. component->addToDesktop (0, parent);
  446. component->setOpaque (true);
  447. component->setVisible (true);
  448. #else
  449. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  450. macHostWindow = juce::attachComponentToWindowRefVST (component, parent, isNSView);
  451. #endif
  452. component->resizeHostWindow();
  453. systemWindow = parent;
  454. attachedToParent();
  455. return kResultTrue;
  456. }
  457. tresult PLUGIN_API removed() override
  458. {
  459. if (component != nullptr)
  460. {
  461. #if JUCE_WINDOWS
  462. component->removeFromDesktop();
  463. #else
  464. if (macHostWindow != nullptr)
  465. {
  466. juce::detachComponentFromWindowRefVST (component, macHostWindow, isNSView);
  467. macHostWindow = nullptr;
  468. }
  469. #endif
  470. component = nullptr;
  471. }
  472. return CPluginView::removed();
  473. }
  474. tresult PLUGIN_API onSize (ViewRect* newSize) override
  475. {
  476. if (newSize != nullptr)
  477. {
  478. rect = *newSize;
  479. if (component != nullptr)
  480. component->setSize (rect.getWidth(), rect.getHeight());
  481. return kResultTrue;
  482. }
  483. jassertfalse;
  484. return kResultFalse;
  485. }
  486. tresult PLUGIN_API getSize (ViewRect* size) override
  487. {
  488. if (size != nullptr && component != nullptr)
  489. {
  490. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  491. return kResultTrue;
  492. }
  493. return kResultFalse;
  494. }
  495. tresult PLUGIN_API canResize() override { return kResultTrue; }
  496. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  497. {
  498. if (rectToCheck != nullptr && component != nullptr)
  499. {
  500. rectToCheck->right = rectToCheck->left + component->getWidth();
  501. rectToCheck->bottom = rectToCheck->top + component->getHeight();
  502. return kResultTrue;
  503. }
  504. jassertfalse;
  505. return kResultFalse;
  506. }
  507. private:
  508. //==============================================================================
  509. class ContentWrapperComponent : public Component
  510. {
  511. public:
  512. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  513. : owner (editor),
  514. pluginEditor (plugin.createEditorIfNeeded())
  515. {
  516. setOpaque (true);
  517. setBroughtToFrontOnMouseClick (true);
  518. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  519. jassert (pluginEditor != nullptr);
  520. if (pluginEditor != nullptr)
  521. {
  522. addAndMakeVisible (pluginEditor);
  523. setBounds (pluginEditor->getLocalBounds());
  524. resizeHostWindow();
  525. }
  526. }
  527. ~ContentWrapperComponent()
  528. {
  529. if (pluginEditor != nullptr)
  530. {
  531. PopupMenu::dismissAllActiveMenus();
  532. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  533. }
  534. }
  535. void paint (Graphics& g) override
  536. {
  537. g.fillAll (Colours::black);
  538. }
  539. void childBoundsChanged (Component*) override
  540. {
  541. resizeHostWindow();
  542. }
  543. void resized() override
  544. {
  545. if (pluginEditor != nullptr)
  546. pluginEditor->setBounds (getLocalBounds());
  547. }
  548. void resizeHostWindow()
  549. {
  550. if (pluginEditor != nullptr)
  551. {
  552. const int w = pluginEditor->getWidth();
  553. const int h = pluginEditor->getHeight();
  554. const PluginHostType host (getHostType());
  555. #if JUCE_WINDOWS
  556. setSize (w, h);
  557. #else
  558. if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper()))
  559. juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
  560. #endif
  561. if (owner.plugFrame != nullptr)
  562. {
  563. ViewRect newSize (0, 0, w, h);
  564. owner.plugFrame->resizeView (&owner, &newSize);
  565. #if JUCE_MAC
  566. if (host.isWavelab() || host.isReaper())
  567. #else
  568. if (host.isWavelab())
  569. #endif
  570. setBounds (0, 0, w, h);
  571. }
  572. }
  573. }
  574. private:
  575. JuceVST3Editor& owner;
  576. ScopedPointer<AudioProcessorEditor> pluginEditor;
  577. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  578. };
  579. //==============================================================================
  580. ComSmartPtr<JuceVST3EditController> owner;
  581. AudioProcessor& pluginInstance;
  582. ScopedPointer<ContentWrapperComponent> component;
  583. friend class ContentWrapperComponent;
  584. #if JUCE_MAC
  585. void* macHostWindow;
  586. bool isNSView;
  587. #endif
  588. #if JUCE_WINDOWS
  589. WindowsHooks hooks;
  590. #endif
  591. ScopedJuceInitialiser_GUI libraryInitialiser;
  592. //==============================================================================
  593. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  594. };
  595. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  596. };
  597. namespace
  598. {
  599. template <typename FloatType> struct AudioBusPointerHelper {};
  600. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  601. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  602. }
  603. //==============================================================================
  604. class JuceVST3Component : public Vst::IComponent,
  605. public Vst::IAudioProcessor,
  606. public Vst::IUnitInfo,
  607. public Vst::IConnectionPoint,
  608. public AudioPlayHead
  609. {
  610. public:
  611. JuceVST3Component (Vst::IHostApplication* h)
  612. : refCount (1),
  613. pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  614. host (h),
  615. isMidiInputBusEnabled (false),
  616. isMidiOutputBusEnabled (false),
  617. busUtils (*pluginInstance, false)
  618. {
  619. #if JucePlugin_WantsMidiInput
  620. isMidiInputBusEnabled = true;
  621. #endif
  622. #if JucePlugin_ProducesMidiOutput
  623. isMidiOutputBusEnabled = true;
  624. #endif
  625. busUtils.findAllCompatibleLayouts();
  626. copyEnabledBuses (lastEnabledBusStates.inputBuses, pluginInstance->busArrangement.inputBuses, Vst::kInput);
  627. copyEnabledBuses (lastEnabledBusStates.outputBuses, pluginInstance->busArrangement.outputBuses, Vst::kOutput);
  628. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  629. zerostruct (processContext);
  630. processSetup.maxSamplesPerBlock = 1024;
  631. processSetup.processMode = Vst::kRealtime;
  632. processSetup.sampleRate = 44100.0;
  633. processSetup.symbolicSampleSize = Vst::kSample32;
  634. vstBypassParameterId = pluginInstance->getNumParameters();
  635. pluginInstance->setPlayHead (this);
  636. }
  637. ~JuceVST3Component()
  638. {
  639. if (pluginInstance != nullptr)
  640. if (pluginInstance->getPlayHead() == this)
  641. pluginInstance->setPlayHead (nullptr);
  642. }
  643. //==============================================================================
  644. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  645. //==============================================================================
  646. static const FUID iid;
  647. JUCE_DECLARE_VST3_COM_REF_METHODS
  648. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  649. {
  650. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  651. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  652. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  653. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  654. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  655. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  656. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  657. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  658. {
  659. comPluginInstance->addRef();
  660. *obj = comPluginInstance;
  661. return kResultOk;
  662. }
  663. *obj = nullptr;
  664. return kNoInterface;
  665. }
  666. //==============================================================================
  667. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  668. {
  669. if (host != hostContext)
  670. host.loadFrom (hostContext);
  671. processContext.sampleRate = processSetup.sampleRate;
  672. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  673. return kResultTrue;
  674. }
  675. tresult PLUGIN_API terminate() override
  676. {
  677. getPluginInstance().releaseResources();
  678. return kResultTrue;
  679. }
  680. //==============================================================================
  681. tresult PLUGIN_API connect (IConnectionPoint* other) override
  682. {
  683. if (other != nullptr && juceVST3EditController == nullptr)
  684. juceVST3EditController.loadFrom (other);
  685. return kResultTrue;
  686. }
  687. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  688. {
  689. juceVST3EditController = nullptr;
  690. return kResultTrue;
  691. }
  692. tresult PLUGIN_API notify (Vst::IMessage* message) override
  693. {
  694. if (message != nullptr && juceVST3EditController == nullptr)
  695. {
  696. Steinberg::int64 value = 0;
  697. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  698. {
  699. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  700. if (juceVST3EditController != nullptr)
  701. juceVST3EditController->setAudioProcessor (comPluginInstance);
  702. else
  703. jassertfalse;
  704. }
  705. }
  706. return kResultTrue;
  707. }
  708. tresult PLUGIN_API getControllerClassId (TUID classID) override
  709. {
  710. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  711. return kResultTrue;
  712. }
  713. //==============================================================================
  714. tresult PLUGIN_API setActive (TBool state) override
  715. {
  716. if (! state)
  717. {
  718. getPluginInstance().releaseResources();
  719. }
  720. else
  721. {
  722. double sampleRate = getPluginInstance().getSampleRate();
  723. int bufferSize = getPluginInstance().getBlockSize();
  724. sampleRate = processSetup.sampleRate > 0.0
  725. ? processSetup.sampleRate
  726. : sampleRate;
  727. bufferSize = processSetup.maxSamplesPerBlock > 0
  728. ? (int) processSetup.maxSamplesPerBlock
  729. : bufferSize;
  730. allocateChannelLists (channelListFloat);
  731. allocateChannelLists (channelListDouble);
  732. preparePlugin (sampleRate, bufferSize);
  733. }
  734. return kResultOk;
  735. }
  736. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  737. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  738. bool isBypassed() { return comPluginInstance->isBypassed; }
  739. void setBypassed (bool bypassed) { comPluginInstance->isBypassed = bypassed; }
  740. //==============================================================================
  741. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  742. {
  743. ValueTree privateData (kJucePrivateDataIdentifier);
  744. // for now we only store the bypass value
  745. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  746. privateData.writeToStream (out);
  747. }
  748. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  749. {
  750. ValueTree privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  751. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  752. }
  753. void getStateInformation (MemoryBlock& destData)
  754. {
  755. pluginInstance->getStateInformation (destData);
  756. // With bypass support, JUCE now needs to store private state data.
  757. // Put this at the end of the plug-in state and add a few null characters
  758. // so that plug-ins built with older versions of JUCE will hopefully ignore
  759. // this data. Additionally, we need to add some sort of magic identifier
  760. // at the very end of the private data so that JUCE has some sort of
  761. // way to figure out if the data was stored with a newer JUCE version.
  762. MemoryOutputStream extraData;
  763. extraData.writeInt64 (0);
  764. writeJucePrivateStateInformation (extraData);
  765. const int64 privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  766. extraData.writeInt64 (privateDataSize);
  767. extraData << kJucePrivateDataIdentifier;
  768. // write magic string
  769. destData.append (extraData.getData(), extraData.getDataSize());
  770. }
  771. void setStateInformation (const void* data, int sizeAsInt)
  772. {
  773. int64 size = sizeAsInt;
  774. // Check if this data was written with a newer JUCE version
  775. // and if it has the JUCE private data magic code at the end
  776. const size_t jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  777. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  778. {
  779. const char* buffer = static_cast<const char*> (data);
  780. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  781. CharPointer_UTF8 (buffer + size));
  782. if (magic == kJucePrivateDataIdentifier)
  783. {
  784. // found a JUCE private data section
  785. uint64 privateDataSize;
  786. std::memcpy (&privateDataSize,
  787. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  788. sizeof (uint64));
  789. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  790. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  791. if (privateDataSize > 0)
  792. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  793. size -= sizeof (uint64);
  794. }
  795. }
  796. if (size >= 0)
  797. pluginInstance->setStateInformation (data, static_cast<int> (size));
  798. }
  799. //==============================================================================
  800. #if JUCE_VST3_CAN_REPLACE_VST2
  801. void loadVST2VstWBlock (const char* data, int size)
  802. {
  803. const int headerLen = static_cast<int> (htonl (*(juce::int32*) (data + 4)));
  804. const struct fxBank* bank = (const struct fxBank*) (data + (8 + headerLen));
  805. const int version = static_cast<int> (htonl (bank->version)); ignoreUnused (version);
  806. jassert ('VstW' == htonl (*(juce::int32*) data));
  807. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  808. jassert (cMagic == htonl (bank->chunkMagic));
  809. jassert (chunkBankMagic == htonl (bank->fxMagic));
  810. jassert (version == 1 || version == 2);
  811. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  812. setStateInformation (bank->content.data.chunk,
  813. jmin ((int) (size - (bank->content.data.chunk - data)),
  814. (int) htonl (bank->content.data.size)));
  815. }
  816. bool loadVST3PresetFile (const char* data, int size)
  817. {
  818. if (size < 48)
  819. return false;
  820. // At offset 4 there's a little-endian version number which seems to typically be 1
  821. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  822. const int chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  823. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  824. const int entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  825. jassert (entryCount > 0);
  826. for (int i = 0; i < entryCount; ++i)
  827. {
  828. const int entryOffset = chunkListOffset + 8 + 20 * i;
  829. if (entryOffset + 20 > size)
  830. return false;
  831. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  832. {
  833. // "Comp" entries seem to contain the data.
  834. juce::uint64 chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  835. juce::uint64 chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  836. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  837. {
  838. jassertfalse;
  839. return false;
  840. }
  841. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  842. }
  843. }
  844. return true;
  845. }
  846. bool loadVST2CompatibleState (const char* data, int size)
  847. {
  848. if (size < 4)
  849. return false;
  850. if (htonl (*(juce::int32*) data) == 'VstW')
  851. {
  852. loadVST2VstWBlock (data, size);
  853. return true;
  854. }
  855. if (memcmp (data, "VST3", 4) == 0)
  856. {
  857. // In Cubase 5, when loading VST3 .vstpreset files,
  858. // we get the whole content of the files to load.
  859. // In Cubase 7 we get just the contents within and
  860. // we go directly to the loadVST2VstW codepath instead.
  861. return loadVST3PresetFile (data, size);
  862. }
  863. return false;
  864. }
  865. #endif
  866. bool loadStateData (const void* data, int size)
  867. {
  868. #if JUCE_VST3_CAN_REPLACE_VST2
  869. return loadVST2CompatibleState ((const char*) data, size);
  870. #else
  871. setStateInformation (data, size);
  872. return true;
  873. #endif
  874. }
  875. bool readFromMemoryStream (IBStream* state)
  876. {
  877. FUnknownPtr<MemoryStream> s (state);
  878. if (s != nullptr
  879. && s->getData() != nullptr
  880. && s->getSize() > 0
  881. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  882. {
  883. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  884. if (getHostType().isAdobeAudition())
  885. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  886. return false;
  887. return loadStateData (s->getData(), (int) s->getSize());
  888. }
  889. return false;
  890. }
  891. bool readFromUnknownStream (IBStream* state)
  892. {
  893. MemoryOutputStream allData;
  894. {
  895. const size_t bytesPerBlock = 4096;
  896. HeapBlock<char> buffer (bytesPerBlock);
  897. for (;;)
  898. {
  899. Steinberg::int32 bytesRead = 0;
  900. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  901. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  902. break;
  903. allData.write (buffer, static_cast<size_t> (bytesRead));
  904. }
  905. }
  906. const size_t dataSize = allData.getDataSize();
  907. return dataSize > 0 && dataSize < 0x7fffffff
  908. && loadStateData (allData.getData(), (int) dataSize);
  909. }
  910. tresult PLUGIN_API setState (IBStream* state) override
  911. {
  912. if (state == nullptr)
  913. return kInvalidArgument;
  914. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  915. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  916. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  917. return kResultTrue;
  918. return kResultFalse;
  919. }
  920. #if JUCE_VST3_CAN_REPLACE_VST2
  921. static tresult writeVST2Int (IBStream* state, int n)
  922. {
  923. juce::int32 t = (juce::int32) htonl (n);
  924. return state->write (&t, 4);
  925. }
  926. static tresult writeVST2Header (IBStream* state, bool bypassed)
  927. {
  928. tresult status = writeVST2Int (state, 'VstW');
  929. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  930. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  931. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  932. return status;
  933. }
  934. #endif
  935. tresult PLUGIN_API getState (IBStream* state) override
  936. {
  937. if (state == nullptr)
  938. return kInvalidArgument;
  939. juce::MemoryBlock mem;
  940. getStateInformation (mem);
  941. #if JUCE_VST3_CAN_REPLACE_VST2
  942. tresult status = writeVST2Header (state, isBypassed());
  943. if (status != kResultOk)
  944. return status;
  945. const int bankBlockSize = 160;
  946. struct fxBank bank;
  947. zerostruct (bank);
  948. bank.chunkMagic = (VstInt32) htonl (cMagic);
  949. bank.byteSize = (VstInt32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  950. bank.fxMagic = (VstInt32) htonl (chunkBankMagic);
  951. bank.version = (VstInt32) htonl (2);
  952. bank.fxID = (VstInt32) htonl (JucePlugin_VSTUniqueID);
  953. bank.fxVersion = (VstInt32) htonl (JucePlugin_VersionCode);
  954. bank.content.data.size = (VstInt32) htonl ((unsigned int) mem.getSize());
  955. status = state->write (&bank, bankBlockSize);
  956. if (status != kResultOk)
  957. return status;
  958. #endif
  959. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  960. }
  961. //==============================================================================
  962. Steinberg::int32 PLUGIN_API getUnitCount() override
  963. {
  964. return 1;
  965. }
  966. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  967. {
  968. if (unitIndex == 0)
  969. {
  970. info.id = Vst::kRootUnitId;
  971. info.parentUnitId = Vst::kNoParentUnitId;
  972. info.programListId = Vst::kNoProgramListId;
  973. toString128 (info.name, TRANS("Root Unit"));
  974. return kResultTrue;
  975. }
  976. zerostruct (info);
  977. return kResultFalse;
  978. }
  979. Steinberg::int32 PLUGIN_API getProgramListCount() override
  980. {
  981. if (getPluginInstance().getNumPrograms() > 0)
  982. return 1;
  983. return 0;
  984. }
  985. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  986. {
  987. if (listIndex == 0)
  988. {
  989. info.id = paramPreset;
  990. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  991. toString128 (info.name, TRANS("Factory Presets"));
  992. return kResultTrue;
  993. }
  994. jassertfalse;
  995. zerostruct (info);
  996. return kResultFalse;
  997. }
  998. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  999. {
  1000. if (listId == paramPreset
  1001. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1002. {
  1003. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1004. return kResultTrue;
  1005. }
  1006. jassertfalse;
  1007. toString128 (name, juce::String());
  1008. return kResultFalse;
  1009. }
  1010. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1011. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1012. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1013. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1014. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1015. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1016. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1017. {
  1018. zerostruct (unitId);
  1019. return kNotImplemented;
  1020. }
  1021. //==============================================================================
  1022. bool getCurrentPosition (CurrentPositionInfo& info) override
  1023. {
  1024. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1025. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  1026. info.bpm = jmax (1.0, processContext.tempo);
  1027. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1028. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1029. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1030. info.ppqPosition = processContext.projectTimeMusic;
  1031. info.ppqLoopStart = processContext.cycleStartMusic;
  1032. info.ppqLoopEnd = processContext.cycleEndMusic;
  1033. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1034. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1035. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1036. info.editOriginTime = 0.0;
  1037. info.frameRate = AudioPlayHead::fpsUnknown;
  1038. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1039. {
  1040. switch (processContext.frameRate.framesPerSecond)
  1041. {
  1042. case 24: info.frameRate = AudioPlayHead::fps24; break;
  1043. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1044. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1045. case 30:
  1046. {
  1047. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1048. info.frameRate = AudioPlayHead::fps30drop;
  1049. else
  1050. info.frameRate = AudioPlayHead::fps30;
  1051. }
  1052. break;
  1053. default: break;
  1054. }
  1055. }
  1056. return true;
  1057. }
  1058. //==============================================================================
  1059. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1060. {
  1061. if (type == Vst::kAudio)
  1062. return (dir == Vst::kInput ? pluginInstance->busArrangement.inputBuses
  1063. : pluginInstance->busArrangement.outputBuses).size();
  1064. if (type == Vst::kEvent)
  1065. {
  1066. if (dir == Vst::kInput)
  1067. return isMidiInputBusEnabled ? 1 : 0;
  1068. if (dir == Vst::kOutput)
  1069. return isMidiOutputBusEnabled ? 1 : 0;
  1070. }
  1071. return 0;
  1072. }
  1073. static const AudioProcessor::AudioProcessorBus* getAudioBus (AudioProcessor::AudioBusArrangement& busArrangement,
  1074. Vst::BusDirection dir, Steinberg::int32 index) noexcept
  1075. {
  1076. const Array<AudioProcessor::AudioProcessorBus>& buses = dir == Vst::kInput ? busArrangement.inputBuses
  1077. : busArrangement.outputBuses;
  1078. return isPositiveAndBelow (index, static_cast<Steinberg::int32> (buses.size())) ? &buses.getReference (index) : nullptr;
  1079. }
  1080. const AudioProcessor::AudioProcessorBus* getAudioBus (Vst::BusDirection dir, Steinberg::int32 index) const noexcept
  1081. {
  1082. return getAudioBus (pluginInstance->busArrangement, dir, index);
  1083. }
  1084. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1085. Steinberg::int32 index, Vst::BusInfo& info) override
  1086. {
  1087. if (type == Vst::kAudio)
  1088. {
  1089. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (lastEnabledBusStates, dir, index))
  1090. {
  1091. info.mediaType = Vst::kAudio;
  1092. info.direction = dir;
  1093. info.channelCount = bus->channels.size();
  1094. toString128 (info.name, bus->name);
  1095. info.busType = index == 0 ? Vst::kMain : Vst::kAux;
  1096. info.flags = busUtils.getSupportedBusLayouts (dir == Vst::kInput, index).isEnabledByDefault ? Vst::BusInfo::kDefaultActive : 0;
  1097. return kResultTrue;
  1098. }
  1099. }
  1100. if (type == Vst::kEvent)
  1101. {
  1102. info.flags = Vst::BusInfo::kDefaultActive;
  1103. #if JucePlugin_WantsMidiInput
  1104. if (dir == Vst::kInput)
  1105. {
  1106. info.mediaType = Vst::kEvent;
  1107. info.direction = dir;
  1108. info.channelCount = 0;
  1109. toString128 (info.name, TRANS("MIDI Input"));
  1110. info.busType = Vst::kMain;
  1111. return kResultTrue;
  1112. }
  1113. #endif
  1114. #if JucePlugin_ProducesMidiOutput
  1115. if (dir == Vst::kOutput)
  1116. {
  1117. info.mediaType = Vst::kEvent;
  1118. info.direction = dir;
  1119. info.channelCount = 0;
  1120. toString128 (info.name, TRANS("MIDI Output"));
  1121. info.busType = Vst::kMain;
  1122. return kResultTrue;
  1123. }
  1124. #endif
  1125. }
  1126. zerostruct (info);
  1127. return kResultFalse;
  1128. }
  1129. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1130. {
  1131. if (type == Vst::kEvent)
  1132. {
  1133. if (index != 0)
  1134. return kResultFalse;
  1135. if (dir == Vst::kInput)
  1136. isMidiInputBusEnabled = (state != 0);
  1137. else
  1138. isMidiOutputBusEnabled = (state != 0);
  1139. return kResultTrue;
  1140. }
  1141. if (type == Vst::kAudio)
  1142. {
  1143. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (dir, index))
  1144. {
  1145. if (state == (bus->channels.size() > 0))
  1146. return kResultTrue;
  1147. AudioChannelSet newChannels;
  1148. if (state)
  1149. if (const AudioProcessor::AudioProcessorBus* lastBusState = getAudioBus (lastEnabledBusStates, dir, index))
  1150. newChannels = lastBusState->channels;
  1151. if (pluginInstance->setPreferredBusArrangement (dir == Vst::kInput, index, newChannels))
  1152. return kResultTrue;
  1153. }
  1154. }
  1155. return kResultFalse;
  1156. }
  1157. void copyEnabledBuses (Array<AudioProcessor::AudioProcessorBus>& copies,
  1158. const Array<AudioProcessor::AudioProcessorBus>& source,
  1159. Vst::BusDirection dir)
  1160. {
  1161. for (int i = 0; i < source.size(); ++i)
  1162. {
  1163. AudioProcessor::AudioProcessorBus bus = source.getReference (i);
  1164. if (bus.channels.size() == 0 && i < copies.size())
  1165. bus = AudioProcessor::AudioProcessorBus (bus.name, copies.getReference (i).channels);
  1166. if (bus.channels.size() == 0)
  1167. bus = AudioProcessor::AudioProcessorBus (bus.name, busUtils.getDefaultLayoutForBus (dir == Vst::kInput, i));
  1168. copies.set (i, bus);
  1169. }
  1170. }
  1171. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1172. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1173. {
  1174. PluginBusUtilities::ScopedBusRestorer restorer (busUtils);
  1175. for (int i = 0; i < numIns; ++i)
  1176. if (! pluginInstance->setPreferredBusArrangement (true, i, getChannelSetForSpeakerArrangement (inputs[i])))
  1177. return kInvalidArgument;
  1178. for (int i = 0; i < numOuts; ++i)
  1179. if (! pluginInstance->setPreferredBusArrangement (false, i, getChannelSetForSpeakerArrangement (outputs[i])))
  1180. return kInvalidArgument;
  1181. restorer.release();
  1182. preparePlugin (getPluginInstance().getSampleRate(),
  1183. getPluginInstance().getBlockSize());
  1184. copyEnabledBuses (lastEnabledBusStates.inputBuses, pluginInstance->busArrangement.inputBuses, Vst::kInput);
  1185. copyEnabledBuses (lastEnabledBusStates.outputBuses, pluginInstance->busArrangement.outputBuses, Vst::kOutput);
  1186. return kResultTrue;
  1187. }
  1188. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1189. {
  1190. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (lastEnabledBusStates, dir, index))
  1191. {
  1192. arr = getSpeakerArrangement (bus->channels);
  1193. return kResultTrue;
  1194. }
  1195. return kResultFalse;
  1196. }
  1197. //==============================================================================
  1198. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1199. {
  1200. return (symbolicSampleSize == Vst::kSample32
  1201. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1202. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1203. }
  1204. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1205. {
  1206. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1207. }
  1208. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1209. {
  1210. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1211. return kResultFalse;
  1212. processSetup = newSetup;
  1213. processContext.sampleRate = processSetup.sampleRate;
  1214. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1215. ? AudioProcessor::doublePrecision
  1216. : AudioProcessor::singlePrecision);
  1217. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1218. return kResultTrue;
  1219. }
  1220. tresult PLUGIN_API setProcessing (TBool state) override
  1221. {
  1222. if (! state)
  1223. getPluginInstance().reset();
  1224. return kResultTrue;
  1225. }
  1226. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1227. {
  1228. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1229. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1230. return Vst::kNoTail;
  1231. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1232. }
  1233. //==============================================================================
  1234. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1235. {
  1236. jassert (pluginInstance != nullptr);
  1237. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  1238. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1239. {
  1240. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  1241. {
  1242. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  1243. Steinberg::int32 offsetSamples;
  1244. double value = 0.0;
  1245. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1246. {
  1247. const int id = (int) paramQueue->getParameterId();
  1248. if (isPositiveAndBelow (id, pluginInstance->getNumParameters()))
  1249. pluginInstance->setParameter (id, (float) value);
  1250. else if (id == vstBypassParameterId)
  1251. setBypassed (static_cast<float> (value) != 0.0f);
  1252. else
  1253. addParameterChangeToMidiBuffer (offsetSamples, id, value);
  1254. }
  1255. }
  1256. }
  1257. }
  1258. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const int id, const double value)
  1259. {
  1260. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1261. int channel, ctrlNumber;
  1262. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1263. {
  1264. if (ctrlNumber == Vst::kAfterTouch)
  1265. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1266. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1267. else if (ctrlNumber == Vst::kPitchBend)
  1268. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1269. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1270. else
  1271. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1272. jlimit (0, 127, ctrlNumber),
  1273. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1274. }
  1275. }
  1276. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1277. {
  1278. if (pluginInstance == nullptr)
  1279. return kResultFalse;
  1280. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1281. return kResultFalse;
  1282. if (data.processContext != nullptr)
  1283. processContext = *data.processContext;
  1284. else
  1285. zerostruct (processContext);
  1286. midiBuffer.clear();
  1287. #if JucePlugin_WantsMidiInput
  1288. if (data.inputEvents != nullptr)
  1289. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1290. #endif
  1291. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1292. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1293. #endif
  1294. if (getHostType().isWavelab())
  1295. {
  1296. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1297. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1298. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1299. && (numInputChans + numOutputChans) == 0)
  1300. return kResultFalse;
  1301. }
  1302. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1303. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1304. else jassertfalse;
  1305. #if JucePlugin_ProducesMidiOutput
  1306. if (data.outputEvents != nullptr)
  1307. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1308. #elif JUCE_DEBUG
  1309. /* This assertion is caused when you've added some events to the
  1310. midiMessages array in your processBlock() method, which usually means
  1311. that you're trying to send them somewhere. But in this case they're
  1312. getting thrown away.
  1313. If your plugin does want to send MIDI messages, you'll need to set
  1314. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1315. JucePluginCharacteristics.h file.
  1316. If you don't want to produce any MIDI output, then you should clear the
  1317. midiMessages array at the end of your processBlock() method, to
  1318. indicate that you don't want any of the events to be passed through
  1319. to the output.
  1320. */
  1321. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1322. #endif
  1323. return kResultTrue;
  1324. }
  1325. private:
  1326. //==============================================================================
  1327. Atomic<int> refCount;
  1328. AudioProcessor* pluginInstance;
  1329. ComSmartPtr<Vst::IHostApplication> host;
  1330. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1331. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1332. /**
  1333. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1334. this object needs to be copied on every call to process() to be up-to-date...
  1335. */
  1336. Vst::ProcessContext processContext;
  1337. Vst::ProcessSetup processSetup;
  1338. MidiBuffer midiBuffer;
  1339. Array<float*> channelListFloat;
  1340. Array<double*> channelListDouble;
  1341. AudioProcessor::AudioBusArrangement lastEnabledBusStates;
  1342. bool isMidiInputBusEnabled, isMidiOutputBusEnabled;
  1343. PluginBusUtilities busUtils;
  1344. ScopedJuceInitialiser_GUI libraryInitialiser;
  1345. int vstBypassParameterId;
  1346. static const char* kJucePrivateDataIdentifier;
  1347. //==============================================================================
  1348. template <typename FloatType>
  1349. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1350. {
  1351. int totalInputChans = 0;
  1352. const int plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1353. const int plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1354. if (data.inputs != nullptr)
  1355. {
  1356. for (int bus = 0; bus < data.numInputs && totalInputChans < plugInInputChannels; ++bus)
  1357. {
  1358. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1359. {
  1360. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1361. for (int i = 0; i < numChans; ++i)
  1362. channelList.set (totalInputChans++, busChannels[i]);
  1363. }
  1364. }
  1365. }
  1366. int totalOutputChans = 0;
  1367. if (data.outputs != nullptr)
  1368. {
  1369. for (int bus = 0; bus < data.numOutputs && totalOutputChans < plugInOutputChannels; ++bus)
  1370. {
  1371. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1372. {
  1373. const int numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1374. for (int i = 0; i < numChans; ++i)
  1375. {
  1376. if (totalOutputChans >= totalInputChans)
  1377. channelList.set (totalOutputChans, busChannels[i]);
  1378. ++totalOutputChans;
  1379. }
  1380. }
  1381. }
  1382. }
  1383. AudioBuffer<FloatType> buffer;
  1384. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1385. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1386. {
  1387. const ScopedLock sl (pluginInstance->getCallbackLock());
  1388. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1389. if (data.inputParameterChanges != nullptr)
  1390. processParameterChanges (*data.inputParameterChanges);
  1391. if (pluginInstance->isSuspended())
  1392. {
  1393. buffer.clear();
  1394. }
  1395. else
  1396. {
  1397. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1398. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1399. {
  1400. if (isBypassed())
  1401. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1402. else
  1403. pluginInstance->processBlock (buffer, midiBuffer);
  1404. }
  1405. }
  1406. }
  1407. if (data.outputs != nullptr)
  1408. {
  1409. int outChanIndex = 0;
  1410. for (int bus = 0; bus < data.numOutputs; ++bus)
  1411. {
  1412. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1413. {
  1414. const int numChans = (int) data.outputs[bus].numChannels;
  1415. for (int i = 0; i < numChans; ++i)
  1416. {
  1417. if (outChanIndex < totalInputChans)
  1418. FloatVectorOperations::copy (busChannels[i], buffer.getReadPointer (outChanIndex), (int) data.numSamples);
  1419. else if (outChanIndex >= totalOutputChans)
  1420. FloatVectorOperations::clear (busChannels[i], (int) data.numSamples);
  1421. ++outChanIndex;
  1422. }
  1423. }
  1424. }
  1425. }
  1426. }
  1427. //==============================================================================
  1428. template <typename FloatType>
  1429. void allocateChannelLists (Array<FloatType*>& channelList)
  1430. {
  1431. channelList.clearQuick();
  1432. channelList.insertMultiple (0, nullptr, 128);
  1433. }
  1434. template <typename FloatType>
  1435. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1436. {
  1437. return AudioBusPointerHelper<FloatType>::impl (data);
  1438. }
  1439. //==============================================================================
  1440. enum InternalParameters
  1441. {
  1442. paramPreset = 'prst'
  1443. };
  1444. void preparePlugin (double sampleRate, int bufferSize)
  1445. {
  1446. AudioProcessor& p = getPluginInstance();
  1447. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1448. p.prepareToPlay (sampleRate, bufferSize);
  1449. }
  1450. //==============================================================================
  1451. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1452. };
  1453. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1454. Steinberg::FUID getJuceVST3ComponentIID();
  1455. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1456. #endif
  1457. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1458. //==============================================================================
  1459. #if JUCE_MSVC
  1460. #pragma warning (push, 0)
  1461. #pragma warning (disable: 4310)
  1462. #elif JUCE_CLANG
  1463. #pragma clang diagnostic push
  1464. #pragma clang diagnostic ignored "-Wall"
  1465. #endif
  1466. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1467. DEF_CLASS_IID (JuceAudioProcessor)
  1468. #if JUCE_VST3_CAN_REPLACE_VST2
  1469. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1470. static FUID getFUIDForVST2ID (bool forControllerUID)
  1471. {
  1472. char uidString[33];
  1473. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1474. char vstfxidStr[7] = { 0 };
  1475. sprintf (vstfxidStr, "%06X", vstfxid);
  1476. strcpy (uidString, vstfxidStr);
  1477. char uidStr[9] = { 0 };
  1478. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1479. strcat (uidString, uidStr);
  1480. char nameidStr[3] = { 0 };
  1481. const size_t len = strlen (JucePlugin_Name);
  1482. for (size_t i = 0; i <= 8; ++i)
  1483. {
  1484. juce::uint8 c = i < len ? static_cast<juce::uint8> (JucePlugin_Name[i]) : 0;
  1485. if (c >= 'A' && c <= 'Z')
  1486. c += 'a' - 'A';
  1487. sprintf (nameidStr, "%02X", c);
  1488. strcat (uidString, nameidStr);
  1489. }
  1490. FUID newOne;
  1491. newOne.fromString (uidString);
  1492. return newOne;
  1493. }
  1494. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1495. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1496. #else
  1497. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1498. DEF_CLASS_IID (JuceVST3EditController)
  1499. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1500. DEF_CLASS_IID (JuceVST3Component)
  1501. #endif
  1502. #if JUCE_MSVC
  1503. #pragma warning (pop)
  1504. #elif JUCE_CLANG
  1505. #pragma clang diagnostic pop
  1506. #endif
  1507. //==============================================================================
  1508. bool initModule()
  1509. {
  1510. #if JUCE_MAC
  1511. initialiseMacVST();
  1512. #endif
  1513. return true;
  1514. }
  1515. bool shutdownModule()
  1516. {
  1517. return true;
  1518. }
  1519. #undef JUCE_EXPORTED_FUNCTION
  1520. #if JUCE_WINDOWS
  1521. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1522. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1523. #define JUCE_EXPORTED_FUNCTION
  1524. #else
  1525. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1526. CFBundleRef globalBundleInstance = nullptr;
  1527. juce::uint32 numBundleRefs = 0;
  1528. juce::Array<CFBundleRef> bundleRefs;
  1529. enum { MaxPathLength = 2048 };
  1530. char modulePath[MaxPathLength] = { 0 };
  1531. void* moduleHandle = nullptr;
  1532. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1533. {
  1534. if (ref != nullptr)
  1535. {
  1536. ++numBundleRefs;
  1537. CFRetain (ref);
  1538. bundleRefs.add (ref);
  1539. if (moduleHandle == nullptr)
  1540. {
  1541. globalBundleInstance = ref;
  1542. moduleHandle = ref;
  1543. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1544. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1545. CFRelease (tempURL);
  1546. }
  1547. }
  1548. return initModule();
  1549. }
  1550. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1551. {
  1552. if (shutdownModule())
  1553. {
  1554. if (--numBundleRefs == 0)
  1555. {
  1556. for (int i = 0; i < bundleRefs.size(); ++i)
  1557. CFRelease (bundleRefs.getUnchecked (i));
  1558. bundleRefs.clear();
  1559. }
  1560. return true;
  1561. }
  1562. return false;
  1563. }
  1564. #endif
  1565. //==============================================================================
  1566. /** This typedef represents VST3's createInstance() function signature */
  1567. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1568. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1569. {
  1570. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1571. }
  1572. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1573. {
  1574. return (Vst::IEditController*) new JuceVST3EditController (host);
  1575. }
  1576. //==============================================================================
  1577. class JucePluginFactory;
  1578. static JucePluginFactory* globalFactory = nullptr;
  1579. //==============================================================================
  1580. class JucePluginFactory : public IPluginFactory3
  1581. {
  1582. public:
  1583. JucePluginFactory()
  1584. : refCount (1),
  1585. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1586. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1587. {
  1588. }
  1589. virtual ~JucePluginFactory()
  1590. {
  1591. if (globalFactory == this)
  1592. globalFactory = nullptr;
  1593. }
  1594. //==============================================================================
  1595. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1596. {
  1597. if (createFunction == nullptr)
  1598. {
  1599. jassertfalse;
  1600. return false;
  1601. }
  1602. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1603. entry->infoW.fromAscii (info);
  1604. return true;
  1605. }
  1606. bool isClassRegistered (const FUID& cid) const
  1607. {
  1608. for (int i = 0; i < classes.size(); ++i)
  1609. if (classes.getUnchecked (i)->infoW.cid == cid)
  1610. return true;
  1611. return false;
  1612. }
  1613. //==============================================================================
  1614. JUCE_DECLARE_VST3_COM_REF_METHODS
  1615. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1616. {
  1617. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1618. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1619. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1620. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1621. jassertfalse; // Something new?
  1622. *obj = nullptr;
  1623. return kNotImplemented;
  1624. }
  1625. //==============================================================================
  1626. Steinberg::int32 PLUGIN_API countClasses() override
  1627. {
  1628. return (Steinberg::int32) classes.size();
  1629. }
  1630. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1631. {
  1632. if (info == nullptr)
  1633. return kInvalidArgument;
  1634. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1635. return kResultOk;
  1636. }
  1637. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1638. {
  1639. return getPClassInfo<PClassInfo> (index, info);
  1640. }
  1641. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1642. {
  1643. return getPClassInfo<PClassInfo2> (index, info);
  1644. }
  1645. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1646. {
  1647. if (info != nullptr)
  1648. {
  1649. if (ClassEntry* entry = classes[(int) index])
  1650. {
  1651. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1652. return kResultOk;
  1653. }
  1654. }
  1655. return kInvalidArgument;
  1656. }
  1657. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1658. {
  1659. *obj = nullptr;
  1660. FUID sourceFuid = sourceIid;
  1661. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1662. {
  1663. jassertfalse; // The host you're running in has severe implementation issues!
  1664. return kInvalidArgument;
  1665. }
  1666. TUID iidToQuery;
  1667. sourceFuid.toTUID (iidToQuery);
  1668. for (int i = 0; i < classes.size(); ++i)
  1669. {
  1670. const ClassEntry& entry = *classes.getUnchecked (i);
  1671. if (doUIDsMatch (entry.infoW.cid, cid))
  1672. {
  1673. if (FUnknown* const instance = entry.createFunction (host))
  1674. {
  1675. const FReleaser releaser (instance);
  1676. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1677. return kResultOk;
  1678. }
  1679. break;
  1680. }
  1681. }
  1682. return kNoInterface;
  1683. }
  1684. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1685. {
  1686. host.loadFrom (context);
  1687. if (host != nullptr)
  1688. {
  1689. Vst::String128 name;
  1690. host->getName (name);
  1691. return kResultTrue;
  1692. }
  1693. return kNotImplemented;
  1694. }
  1695. private:
  1696. //==============================================================================
  1697. ScopedJuceInitialiser_GUI libraryInitialiser;
  1698. Atomic<int> refCount;
  1699. const PFactoryInfo factoryInfo;
  1700. ComSmartPtr<Vst::IHostApplication> host;
  1701. //==============================================================================
  1702. struct ClassEntry
  1703. {
  1704. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1705. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1706. : info2 (info), createFunction (fn), isUnicode (false) {}
  1707. PClassInfo2 info2;
  1708. PClassInfoW infoW;
  1709. CreateFunction createFunction;
  1710. bool isUnicode;
  1711. private:
  1712. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1713. };
  1714. OwnedArray<ClassEntry> classes;
  1715. //==============================================================================
  1716. template<class PClassInfoType>
  1717. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1718. {
  1719. if (info != nullptr)
  1720. {
  1721. zerostruct (*info);
  1722. if (ClassEntry* entry = classes[(int) index])
  1723. {
  1724. if (entry->isUnicode)
  1725. return kResultFalse;
  1726. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1727. return kResultOk;
  1728. }
  1729. }
  1730. jassertfalse;
  1731. return kInvalidArgument;
  1732. }
  1733. //==============================================================================
  1734. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1735. };
  1736. } // juce namespace
  1737. //==============================================================================
  1738. #ifndef JucePlugin_Vst3ComponentFlags
  1739. #if JucePlugin_IsSynth
  1740. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1741. #else
  1742. #define JucePlugin_Vst3ComponentFlags 0
  1743. #endif
  1744. #endif
  1745. #ifndef JucePlugin_Vst3Category
  1746. #if JucePlugin_IsSynth
  1747. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1748. #else
  1749. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1750. #endif
  1751. #endif
  1752. //==============================================================================
  1753. // The VST3 plugin entry point.
  1754. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1755. {
  1756. #if JUCE_WINDOWS
  1757. // Cunning trick to force this function to be exported. Life's too short to
  1758. // faff around creating .def files for this kind of thing.
  1759. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1760. #endif
  1761. if (globalFactory == nullptr)
  1762. {
  1763. globalFactory = new JucePluginFactory();
  1764. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1765. PClassInfo::kManyInstances,
  1766. kVstAudioEffectClass,
  1767. JucePlugin_Name,
  1768. JucePlugin_Vst3ComponentFlags,
  1769. JucePlugin_Vst3Category,
  1770. JucePlugin_Manufacturer,
  1771. JucePlugin_VersionString,
  1772. kVstVersionString);
  1773. globalFactory->registerClass (componentClass, createComponentInstance);
  1774. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1775. PClassInfo::kManyInstances,
  1776. kVstComponentControllerClass,
  1777. JucePlugin_Name,
  1778. JucePlugin_Vst3ComponentFlags,
  1779. JucePlugin_Vst3Category,
  1780. JucePlugin_Manufacturer,
  1781. JucePlugin_VersionString,
  1782. kVstVersionString);
  1783. globalFactory->registerClass (controllerClass, createControllerInstance);
  1784. }
  1785. else
  1786. {
  1787. globalFactory->addRef();
  1788. }
  1789. return dynamic_cast<IPluginFactory*> (globalFactory);
  1790. }
  1791. #endif //JucePlugin_Build_VST3