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.

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