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.

2255 lines
81KB

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