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.

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