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.

2140 lines
75KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  18. // and your header search path must make it accessible to the module's files.
  19. #include "AppConfig.h"
  20. //==============================================================================
  21. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  22. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  23. #include "../utility/juce_CheckSettingMacros.h"
  24. #include "../utility/juce_IncludeModuleHeaders.h"
  25. #include "../utility/juce_WindowsHooks.h"
  26. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  27. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  28. #define JUCE_VST3_CAN_REPLACE_VST2 1
  29. #endif
  30. #if JUCE_VST3_CAN_REPLACE_VST2
  31. #if JUCE_MSVC
  32. #pragma warning (push)
  33. #pragma warning (disable: 4514 4996)
  34. #endif
  35. #include <pluginterfaces/vst2.x/vstfxstore.h>
  36. #if JUCE_MSVC
  37. #pragma warning (pop)
  38. #endif
  39. #endif
  40. #undef Point
  41. #undef Component
  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. // We need to account for the bypass parameter in the numParameters passed to
  381. // the next function
  382. initialiseMidiControllerMappings (pluginInstance->getNumParameters() + 1);
  383. audioProcessorChanged (pluginInstance);
  384. }
  385. }
  386. void initialiseMidiControllerMappings (const int numVstParameters)
  387. {
  388. parameterToMidiControllerOffset = numVstParameters;
  389. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  390. {
  391. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  392. {
  393. midiControllerToParameter[c][i] = p + parameterToMidiControllerOffset;
  394. parameterToMidiController[p].channel = c;
  395. parameterToMidiController[p].ctrlNumber = i;
  396. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  397. (Vst::ParamID) (p + parameterToMidiControllerOffset), 0, 0, 0,
  398. Vst::ParameterInfo::kCanAutomate, Vst::kRootUnitId));
  399. }
  400. }
  401. }
  402. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  403. {
  404. jassert (hostContext != nullptr);
  405. if (Vst::IMessage* message = allocateMessage())
  406. {
  407. const FReleaser releaser (message);
  408. message->setMessageID (idTag);
  409. message->getAttributes()->setInt (idTag, value);
  410. sendMessage (message);
  411. }
  412. }
  413. //==============================================================================
  414. class JuceVST3Editor : public Vst::EditorView
  415. {
  416. public:
  417. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  418. : Vst::EditorView (&ec, nullptr),
  419. owner (&ec), pluginInstance (p)
  420. {
  421. #if JUCE_MAC
  422. macHostWindow = nullptr;
  423. isNSView = false;
  424. #endif
  425. component = new ContentWrapperComponent (*this, p);
  426. }
  427. //==============================================================================
  428. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  429. {
  430. if (type != nullptr && pluginInstance.hasEditor())
  431. {
  432. #if JUCE_WINDOWS
  433. if (strcmp (type, kPlatformTypeHWND) == 0)
  434. #else
  435. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  436. #endif
  437. return kResultTrue;
  438. }
  439. return kResultFalse;
  440. }
  441. tresult PLUGIN_API attached (void* parent, FIDString type) override
  442. {
  443. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  444. return kResultFalse;
  445. if (component == nullptr)
  446. component = new ContentWrapperComponent (*this, pluginInstance);
  447. #if JUCE_WINDOWS
  448. component->addToDesktop (0, parent);
  449. component->setOpaque (true);
  450. component->setVisible (true);
  451. #else
  452. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  453. macHostWindow = juce::attachComponentToWindowRefVST (component, parent, isNSView);
  454. #endif
  455. component->resizeHostWindow();
  456. systemWindow = parent;
  457. attachedToParent();
  458. return kResultTrue;
  459. }
  460. tresult PLUGIN_API removed() override
  461. {
  462. if (component != nullptr)
  463. {
  464. #if JUCE_WINDOWS
  465. component->removeFromDesktop();
  466. #else
  467. if (macHostWindow != nullptr)
  468. {
  469. juce::detachComponentFromWindowRefVST (component, macHostWindow, isNSView);
  470. macHostWindow = nullptr;
  471. }
  472. #endif
  473. component = nullptr;
  474. }
  475. return CPluginView::removed();
  476. }
  477. tresult PLUGIN_API onSize (ViewRect* newSize) override
  478. {
  479. if (newSize != nullptr)
  480. {
  481. rect = *newSize;
  482. if (component != nullptr)
  483. component->setSize (rect.getWidth(), rect.getHeight());
  484. return kResultTrue;
  485. }
  486. jassertfalse;
  487. return kResultFalse;
  488. }
  489. tresult PLUGIN_API getSize (ViewRect* size) override
  490. {
  491. if (size != nullptr && component != nullptr)
  492. {
  493. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  494. return kResultTrue;
  495. }
  496. return kResultFalse;
  497. }
  498. tresult PLUGIN_API canResize() override { return kResultTrue; }
  499. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  500. {
  501. if (rectToCheck != nullptr && component != nullptr)
  502. {
  503. rectToCheck->right = rectToCheck->left + component->getWidth();
  504. rectToCheck->bottom = rectToCheck->top + component->getHeight();
  505. return kResultTrue;
  506. }
  507. jassertfalse;
  508. return kResultFalse;
  509. }
  510. private:
  511. //==============================================================================
  512. class ContentWrapperComponent : public juce::Component
  513. {
  514. public:
  515. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  516. : owner (editor),
  517. pluginEditor (plugin.createEditorIfNeeded())
  518. {
  519. setOpaque (true);
  520. setBroughtToFrontOnMouseClick (true);
  521. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  522. jassert (pluginEditor != nullptr);
  523. if (pluginEditor != nullptr)
  524. {
  525. addAndMakeVisible (pluginEditor);
  526. setBounds (pluginEditor->getLocalBounds());
  527. resizeHostWindow();
  528. }
  529. }
  530. ~ContentWrapperComponent()
  531. {
  532. if (pluginEditor != nullptr)
  533. {
  534. PopupMenu::dismissAllActiveMenus();
  535. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  536. }
  537. }
  538. void paint (Graphics& g) override
  539. {
  540. g.fillAll (Colours::black);
  541. }
  542. void childBoundsChanged (Component*) override
  543. {
  544. resizeHostWindow();
  545. }
  546. void resized() override
  547. {
  548. if (pluginEditor != nullptr)
  549. pluginEditor->setBounds (getLocalBounds());
  550. }
  551. void resizeHostWindow()
  552. {
  553. if (pluginEditor != nullptr)
  554. {
  555. const int w = pluginEditor->getWidth();
  556. const int h = pluginEditor->getHeight();
  557. #if JUCE_WINDOWS
  558. setSize (w, h);
  559. #else
  560. if (owner.macHostWindow != nullptr && ! getHostType().isWavelab())
  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 (getHostType().isWavelab())
  568. setBounds (0, 0, w, h);
  569. }
  570. }
  571. }
  572. private:
  573. JuceVST3Editor& owner;
  574. ScopedPointer<AudioProcessorEditor> pluginEditor;
  575. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  576. };
  577. //==============================================================================
  578. ComSmartPtr<JuceVST3EditController> owner;
  579. AudioProcessor& pluginInstance;
  580. ScopedPointer<ContentWrapperComponent> component;
  581. friend class ContentWrapperComponent;
  582. #if JUCE_MAC
  583. void* macHostWindow;
  584. bool isNSView;
  585. #endif
  586. #if JUCE_WINDOWS
  587. WindowsHooks hooks;
  588. #endif
  589. ScopedJuceInitialiser_GUI libraryInitialiser;
  590. //==============================================================================
  591. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  592. };
  593. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  594. };
  595. //==============================================================================
  596. class JuceVST3Component : public Vst::IComponent,
  597. public Vst::IAudioProcessor,
  598. public Vst::IUnitInfo,
  599. public Vst::IConnectionPoint,
  600. public AudioPlayHead
  601. {
  602. public:
  603. JuceVST3Component (Vst::IHostApplication* h)
  604. : refCount (1),
  605. host (h),
  606. audioInputs (Vst::kAudio, Vst::kInput),
  607. audioOutputs (Vst::kAudio, Vst::kOutput),
  608. eventInputs (Vst::kEvent, Vst::kInput),
  609. eventOutputs (Vst::kEvent, Vst::kOutput)
  610. {
  611. pluginInstance = createPluginFilterOfType (AudioProcessor::wrapperType_VST3);
  612. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  613. zerostruct (processContext);
  614. processSetup.maxSamplesPerBlock = 1024;
  615. processSetup.processMode = Vst::kRealtime;
  616. processSetup.sampleRate = 44100.0;
  617. processSetup.symbolicSampleSize = Vst::kSample32;
  618. vstBypassParameterId = pluginInstance->getNumParameters();
  619. pluginInstance->setPlayHead (this);
  620. }
  621. ~JuceVST3Component()
  622. {
  623. if (pluginInstance != nullptr)
  624. if (pluginInstance->getPlayHead() == this)
  625. pluginInstance->setPlayHead (nullptr);
  626. audioInputs.removeAll();
  627. audioOutputs.removeAll();
  628. eventInputs.removeAll();
  629. eventOutputs.removeAll();
  630. }
  631. //==============================================================================
  632. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  633. //==============================================================================
  634. static const FUID iid;
  635. JUCE_DECLARE_VST3_COM_REF_METHODS
  636. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  637. {
  638. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  639. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  640. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  641. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  642. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  643. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  644. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  645. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  646. {
  647. comPluginInstance->addRef();
  648. *obj = comPluginInstance;
  649. return kResultOk;
  650. }
  651. *obj = nullptr;
  652. return kNoInterface;
  653. }
  654. //==============================================================================
  655. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  656. {
  657. if (host != hostContext)
  658. host.loadFrom (hostContext);
  659. #if JucePlugin_MaxNumInputChannels > 0
  660. addAudioBusTo (audioInputs, TRANS("Audio Input"),
  661. getArrangementForNumChannels (JucePlugin_MaxNumInputChannels));
  662. #endif
  663. #if JucePlugin_MaxNumOutputChannels > 0
  664. addAudioBusTo (audioOutputs, TRANS("Audio Output"),
  665. getArrangementForNumChannels (JucePlugin_MaxNumOutputChannels));
  666. #endif
  667. #if JucePlugin_WantsMidiInput
  668. addEventBusTo (eventInputs, TRANS("MIDI Input"));
  669. #endif
  670. #if JucePlugin_ProducesMidiOutput
  671. addEventBusTo (eventOutputs, TRANS("MIDI Output"));
  672. #endif
  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. //==============================================================================
  711. tresult PLUGIN_API getControllerClassId (TUID classID) override
  712. {
  713. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  714. return kResultTrue;
  715. }
  716. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  717. {
  718. if (Vst::BusList* const busList = getBusListFor (type, dir))
  719. return busList->total();
  720. return 0;
  721. }
  722. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  723. Steinberg::int32 index, Vst::BusInfo& info) override
  724. {
  725. if (Vst::BusList* const busList = getBusListFor (type, dir))
  726. {
  727. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  728. {
  729. info.mediaType = type;
  730. info.direction = dir;
  731. if (bus->getInfo (info))
  732. return kResultTrue;
  733. }
  734. }
  735. zerostruct (info);
  736. return kResultFalse;
  737. }
  738. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir,
  739. Steinberg::int32 index, TBool state) override
  740. {
  741. if (Vst::BusList* const busList = getBusListFor (type, dir))
  742. {
  743. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  744. {
  745. bus->setActive (state);
  746. return kResultTrue;
  747. }
  748. }
  749. jassertfalse;
  750. return kResultFalse;
  751. }
  752. tresult PLUGIN_API setActive (TBool state) override
  753. {
  754. if (! state)
  755. {
  756. getPluginInstance().releaseResources();
  757. }
  758. else
  759. {
  760. double sampleRate = getPluginInstance().getSampleRate();
  761. int bufferSize = getPluginInstance().getBlockSize();
  762. sampleRate = processSetup.sampleRate > 0.0
  763. ? processSetup.sampleRate
  764. : sampleRate;
  765. bufferSize = processSetup.maxSamplesPerBlock > 0
  766. ? (int) processSetup.maxSamplesPerBlock
  767. : bufferSize;
  768. channelList.clear();
  769. channelList.insertMultiple (0, nullptr, jmax (JucePlugin_MaxNumInputChannels, JucePlugin_MaxNumOutputChannels) + 1);
  770. preparePlugin (sampleRate, bufferSize);
  771. }
  772. return kResultOk;
  773. }
  774. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  775. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  776. bool isBypassed() { return comPluginInstance->isBypassed; }
  777. void setBypassed (bool bypassed) { comPluginInstance->isBypassed = bypassed; }
  778. //==============================================================================
  779. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  780. {
  781. ValueTree privateData (kJucePrivateDataIdentifier);
  782. // for now we only store the bypass value
  783. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  784. privateData.writeToStream (out);
  785. }
  786. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  787. {
  788. ValueTree privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  789. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  790. }
  791. void getStateInformation (MemoryBlock& destData)
  792. {
  793. pluginInstance->getStateInformation (destData);
  794. // With bypass support, JUCE now needs to store private state data.
  795. // Put this at the end of the plug-in state and add a few null characters
  796. // so that plug-ins built with older versions of JUCE will hopefully ignore
  797. // this data. Additionally, we need to add some sort of magic identifier
  798. // at the very end of the private data so that JUCE has some sort of
  799. // way to figure out if the data was stored with a newer JUCE version.
  800. MemoryOutputStream extraData;
  801. extraData.writeInt64 (0);
  802. writeJucePrivateStateInformation (extraData);
  803. const int64 privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  804. extraData.writeInt64 (privateDataSize);
  805. extraData << kJucePrivateDataIdentifier;
  806. // write magic string
  807. destData.append (extraData.getData(), extraData.getDataSize());
  808. }
  809. void setStateInformation (const void* data, int sizeAsInt)
  810. {
  811. int64 size = sizeAsInt;
  812. // Check if this data was written with a newer JUCE version
  813. // and if it has the JUCE private data magic code at the end
  814. const size_t jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  815. if (size >= jucePrivDataIdentifierSize + sizeof (int64))
  816. {
  817. const char* buffer = static_cast<const char*> (data);
  818. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  819. CharPointer_UTF8 (buffer + size));
  820. if (magic == kJucePrivateDataIdentifier)
  821. {
  822. // found a JUCE private data section
  823. uint64 privateDataSize;
  824. std::memcpy (&privateDataSize,
  825. buffer + (size - jucePrivDataIdentifierSize - sizeof (uint64)),
  826. sizeof (uint64));
  827. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  828. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  829. if (privateDataSize > 0)
  830. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  831. size -= sizeof (uint64);
  832. }
  833. }
  834. if (size >= 0)
  835. pluginInstance->setStateInformation (data, static_cast<int> (size));
  836. }
  837. //==============================================================================
  838. #if JUCE_VST3_CAN_REPLACE_VST2
  839. void loadVST2VstWBlock (const char* data, int size)
  840. {
  841. const int headerLen = static_cast<int> (htonl (*(juce::int32*) (data + 4)));
  842. const struct fxBank* bank = (const struct fxBank*) (data + (8 + headerLen));
  843. const int version = static_cast<int> (htonl (bank->version)); (void) version;
  844. jassert ('VstW' == htonl (*(juce::int32*) data));
  845. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  846. jassert (cMagic == htonl (bank->chunkMagic));
  847. jassert (chunkBankMagic == htonl (bank->fxMagic));
  848. jassert (version == 1 || version == 2);
  849. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  850. setStateInformation (bank->content.data.chunk,
  851. jmin ((int) (size - (bank->content.data.chunk - data)),
  852. (int) htonl (bank->content.data.size)));
  853. }
  854. bool loadVST3PresetFile (const char* data, int size)
  855. {
  856. if (size < 48)
  857. return false;
  858. // At offset 4 there's a little-endian version number which seems to typically be 1
  859. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  860. const int chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  861. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  862. const int entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  863. jassert (entryCount > 0);
  864. for (int i = 0; i < entryCount; ++i)
  865. {
  866. const int entryOffset = chunkListOffset + 8 + 20 * i;
  867. if (entryOffset + 20 > size)
  868. return false;
  869. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  870. {
  871. // "Comp" entries seem to contain the data.
  872. juce::uint64 chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  873. juce::uint64 chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  874. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  875. {
  876. jassertfalse;
  877. return false;
  878. }
  879. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  880. }
  881. }
  882. return true;
  883. }
  884. bool loadVST2CompatibleState (const char* data, int size)
  885. {
  886. if (size < 4)
  887. return false;
  888. if (htonl (*(juce::int32*) data) == 'VstW')
  889. {
  890. loadVST2VstWBlock (data, size);
  891. return true;
  892. }
  893. if (memcmp (data, "VST3", 4) == 0)
  894. {
  895. // In Cubase 5, when loading VST3 .vstpreset files,
  896. // we get the whole content of the files to load.
  897. // In Cubase 7 we get just the contents within and
  898. // we go directly to the loadVST2VstW codepath instead.
  899. return loadVST3PresetFile (data, size);
  900. }
  901. return false;
  902. }
  903. #endif
  904. bool loadStateData (const void* data, int size)
  905. {
  906. #if JUCE_VST3_CAN_REPLACE_VST2
  907. return loadVST2CompatibleState ((const char*) data, size);
  908. #else
  909. setStateInformation (data, size);
  910. return true;
  911. #endif
  912. }
  913. bool readFromMemoryStream (IBStream* state)
  914. {
  915. FUnknownPtr<MemoryStream> s (state);
  916. if (s != nullptr
  917. && s->getData() != nullptr
  918. && s->getSize() > 0
  919. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  920. {
  921. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  922. if (getHostType().isAdobeAudition())
  923. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  924. return false;
  925. return loadStateData (s->getData(), (int) s->getSize());
  926. }
  927. return false;
  928. }
  929. bool readFromUnknownStream (IBStream* state)
  930. {
  931. MemoryOutputStream allData;
  932. {
  933. const size_t bytesPerBlock = 4096;
  934. HeapBlock<char> buffer (bytesPerBlock);
  935. for (;;)
  936. {
  937. Steinberg::int32 bytesRead = 0;
  938. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  939. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  940. break;
  941. allData.write (buffer, static_cast<size_t> (bytesRead));
  942. }
  943. }
  944. const size_t dataSize = allData.getDataSize();
  945. return dataSize > 0 && dataSize < 0x7fffffff
  946. && loadStateData (allData.getData(), (int) dataSize);
  947. }
  948. tresult PLUGIN_API setState (IBStream* state) override
  949. {
  950. if (state == nullptr)
  951. return kInvalidArgument;
  952. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  953. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  954. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  955. return kResultTrue;
  956. return kResultFalse;
  957. }
  958. #if JUCE_VST3_CAN_REPLACE_VST2
  959. static tresult writeVST2Int (IBStream* state, int n)
  960. {
  961. juce::int32 t = (juce::int32) htonl (n);
  962. return state->write (&t, 4);
  963. }
  964. static tresult writeVST2Header (IBStream* state, bool bypassed)
  965. {
  966. tresult status = writeVST2Int (state, 'VstW');
  967. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  968. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  969. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  970. return status;
  971. }
  972. #endif
  973. tresult PLUGIN_API getState (IBStream* state) override
  974. {
  975. if (state == nullptr)
  976. return kInvalidArgument;
  977. juce::MemoryBlock mem;
  978. getStateInformation (mem);
  979. #if JUCE_VST3_CAN_REPLACE_VST2
  980. tresult status = writeVST2Header (state, isBypassed());
  981. if (status != kResultOk)
  982. return status;
  983. const int bankBlockSize = 160;
  984. struct fxBank bank;
  985. zerostruct (bank);
  986. bank.chunkMagic = (VstInt32) htonl (cMagic);
  987. bank.byteSize = (VstInt32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  988. bank.fxMagic = (VstInt32) htonl (chunkBankMagic);
  989. bank.version = (VstInt32) htonl (2);
  990. bank.fxID = (VstInt32) htonl (JucePlugin_VSTUniqueID);
  991. bank.fxVersion = (VstInt32) htonl (JucePlugin_VersionCode);
  992. bank.content.data.size = (VstInt32) htonl ((unsigned int) mem.getSize());
  993. status = state->write (&bank, bankBlockSize);
  994. if (status != kResultOk)
  995. return status;
  996. #endif
  997. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  998. }
  999. //==============================================================================
  1000. Steinberg::int32 PLUGIN_API getUnitCount() override
  1001. {
  1002. return 1;
  1003. }
  1004. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  1005. {
  1006. if (unitIndex == 0)
  1007. {
  1008. info.id = Vst::kRootUnitId;
  1009. info.parentUnitId = Vst::kNoParentUnitId;
  1010. info.programListId = Vst::kNoProgramListId;
  1011. toString128 (info.name, TRANS("Root Unit"));
  1012. return kResultTrue;
  1013. }
  1014. zerostruct (info);
  1015. return kResultFalse;
  1016. }
  1017. Steinberg::int32 PLUGIN_API getProgramListCount() override
  1018. {
  1019. if (getPluginInstance().getNumPrograms() > 0)
  1020. return 1;
  1021. return 0;
  1022. }
  1023. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  1024. {
  1025. if (listIndex == 0)
  1026. {
  1027. info.id = paramPreset;
  1028. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1029. toString128 (info.name, TRANS("Factory Presets"));
  1030. return kResultTrue;
  1031. }
  1032. jassertfalse;
  1033. zerostruct (info);
  1034. return kResultFalse;
  1035. }
  1036. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1037. {
  1038. if (listId == paramPreset
  1039. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1040. {
  1041. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1042. return kResultTrue;
  1043. }
  1044. jassertfalse;
  1045. toString128 (name, juce::String());
  1046. return kResultFalse;
  1047. }
  1048. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1049. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1050. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1051. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1052. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1053. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1054. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection,
  1055. Steinberg::int32, Steinberg::int32,
  1056. Vst::UnitID& unitId) override
  1057. {
  1058. zerostruct (unitId);
  1059. return kNotImplemented;
  1060. }
  1061. //==============================================================================
  1062. bool getCurrentPosition (CurrentPositionInfo& info) override
  1063. {
  1064. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1065. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  1066. info.bpm = jmax (1.0, processContext.tempo);
  1067. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1068. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1069. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1070. info.ppqPosition = processContext.projectTimeMusic;
  1071. info.ppqLoopStart = processContext.cycleStartMusic;
  1072. info.ppqLoopEnd = processContext.cycleEndMusic;
  1073. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1074. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1075. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1076. info.editOriginTime = 0.0;
  1077. info.frameRate = AudioPlayHead::fpsUnknown;
  1078. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1079. {
  1080. switch (processContext.frameRate.framesPerSecond)
  1081. {
  1082. case 24: info.frameRate = AudioPlayHead::fps24; break;
  1083. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1084. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1085. case 30:
  1086. {
  1087. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1088. info.frameRate = AudioPlayHead::fps30drop;
  1089. else
  1090. info.frameRate = AudioPlayHead::fps30;
  1091. }
  1092. break;
  1093. default: break;
  1094. }
  1095. }
  1096. return true;
  1097. }
  1098. //==============================================================================
  1099. static tresult setBusArrangementFor (Vst::BusList& list,
  1100. Vst::SpeakerArrangement* arrangement,
  1101. Steinberg::int32 numBusses)
  1102. {
  1103. if (arrangement != nullptr && numBusses == 1) //Should only be 1 bus per BusList
  1104. {
  1105. Steinberg::int32 counter = 0;
  1106. FOREACH_CAST (IPtr<Vst::Bus>, Vst::AudioBus, bus, list)
  1107. {
  1108. if (counter < numBusses)
  1109. bus->setArrangement (arrangement[counter]);
  1110. counter++;
  1111. }
  1112. ENDFOR
  1113. return kResultTrue;
  1114. }
  1115. return kResultFalse;
  1116. }
  1117. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1118. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1119. {
  1120. (void) inputs; (void) outputs;
  1121. #if JucePlugin_MaxNumInputChannels > 0
  1122. if (setBusArrangementFor (audioInputs, inputs, numIns) != kResultTrue)
  1123. return kResultFalse;
  1124. #else
  1125. if (numIns != 0)
  1126. return kResultFalse;
  1127. #endif
  1128. #if JucePlugin_MaxNumOutputChannels > 0
  1129. if (setBusArrangementFor (audioOutputs, outputs, numOuts) != kResultTrue)
  1130. return kResultFalse;
  1131. #else
  1132. if (numOuts != 0)
  1133. return kResultFalse;
  1134. #endif
  1135. preparePlugin (getPluginInstance().getSampleRate(),
  1136. getPluginInstance().getBlockSize());
  1137. return kResultTrue;
  1138. }
  1139. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1140. {
  1141. if (Vst::BusList* const busList = getBusListFor (Vst::kAudio, dir))
  1142. {
  1143. if (Vst::AudioBus* const audioBus = FCast<Vst::AudioBus> (busList->at (index)))
  1144. {
  1145. arr = audioBus->getArrangement();
  1146. return kResultTrue;
  1147. }
  1148. }
  1149. return kResultFalse;
  1150. }
  1151. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1152. {
  1153. return symbolicSampleSize == Vst::kSample32 ? kResultTrue : kResultFalse;
  1154. }
  1155. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1156. {
  1157. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1158. }
  1159. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1160. {
  1161. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1162. return kResultFalse;
  1163. processSetup = newSetup;
  1164. processContext.sampleRate = processSetup.sampleRate;
  1165. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1166. return kResultTrue;
  1167. }
  1168. tresult PLUGIN_API setProcessing (TBool state) override
  1169. {
  1170. if (! state)
  1171. getPluginInstance().reset();
  1172. return kResultTrue;
  1173. }
  1174. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1175. {
  1176. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1177. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1178. return Vst::kNoTail;
  1179. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1180. }
  1181. //==============================================================================
  1182. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1183. {
  1184. jassert (pluginInstance != nullptr);
  1185. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  1186. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1187. {
  1188. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  1189. {
  1190. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  1191. Steinberg::int32 offsetSamples;
  1192. double value = 0.0;
  1193. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1194. {
  1195. const int id = (int) paramQueue->getParameterId();
  1196. if (isPositiveAndBelow (id, pluginInstance->getNumParameters()))
  1197. pluginInstance->setParameter (id, (float) value);
  1198. else if (id == vstBypassParameterId)
  1199. setBypassed (static_cast<float> (value) != 0.0f);
  1200. else
  1201. addParameterChangeToMidiBuffer (offsetSamples, id, value);
  1202. }
  1203. }
  1204. }
  1205. }
  1206. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const int id, const double value)
  1207. {
  1208. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1209. int channel, ctrlNumber;
  1210. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1211. {
  1212. if (ctrlNumber == Vst::kAfterTouch)
  1213. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1214. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1215. else if (ctrlNumber == Vst::kPitchBend)
  1216. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1217. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1218. else
  1219. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1220. jlimit (0, 127, ctrlNumber),
  1221. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1222. }
  1223. }
  1224. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1225. {
  1226. if (pluginInstance == nullptr)
  1227. return kResultFalse;
  1228. if (data.processContext != nullptr)
  1229. processContext = *data.processContext;
  1230. else
  1231. zerostruct (processContext);
  1232. midiBuffer.clear();
  1233. #if JucePlugin_WantsMidiInput
  1234. if (data.inputEvents != nullptr)
  1235. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1236. #endif
  1237. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1238. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1239. #endif
  1240. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1241. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1242. int totalChans = 0;
  1243. while (totalChans < numInputChans)
  1244. {
  1245. channelList.set (totalChans, data.inputs[0].channelBuffers32[totalChans]);
  1246. ++totalChans;
  1247. }
  1248. while (totalChans < numOutputChans)
  1249. {
  1250. channelList.set (totalChans, data.outputs[0].channelBuffers32[totalChans]);
  1251. ++totalChans;
  1252. }
  1253. AudioSampleBuffer buffer;
  1254. if (totalChans != 0)
  1255. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1256. else if (getHostType().isWavelab()
  1257. && pluginInstance->getNumInputChannels() + pluginInstance->getNumOutputChannels() > 0)
  1258. return kResultFalse;
  1259. {
  1260. const ScopedLock sl (pluginInstance->getCallbackLock());
  1261. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1262. if (data.inputParameterChanges != nullptr)
  1263. processParameterChanges (*data.inputParameterChanges);
  1264. if (pluginInstance->isSuspended())
  1265. {
  1266. buffer.clear();
  1267. }
  1268. else
  1269. {
  1270. if (isBypassed())
  1271. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1272. else
  1273. pluginInstance->processBlock (buffer, midiBuffer);
  1274. }
  1275. }
  1276. for (int i = 0; i < numOutputChans; ++i)
  1277. FloatVectorOperations::copy (data.outputs[0].channelBuffers32[i], buffer.getReadPointer (i), (int) data.numSamples);
  1278. // clear extra busses..
  1279. if (data.outputs != nullptr)
  1280. for (int i = 1; i < data.numOutputs; ++i)
  1281. for (int f = 0; f < data.outputs[i].numChannels; ++f)
  1282. FloatVectorOperations::clear (data.outputs[i].channelBuffers32[f], (int) data.numSamples);
  1283. #if JucePlugin_ProducesMidiOutput
  1284. if (data.outputEvents != nullptr)
  1285. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1286. #elif JUCE_DEBUG
  1287. /* This assertion is caused when you've added some events to the
  1288. midiMessages array in your processBlock() method, which usually means
  1289. that you're trying to send them somewhere. But in this case they're
  1290. getting thrown away.
  1291. If your plugin does want to send MIDI messages, you'll need to set
  1292. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1293. JucePluginCharacteristics.h file.
  1294. If you don't want to produce any MIDI output, then you should clear the
  1295. midiMessages array at the end of your processBlock() method, to
  1296. indicate that you don't want any of the events to be passed through
  1297. to the output.
  1298. */
  1299. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1300. #endif
  1301. return kResultTrue;
  1302. }
  1303. private:
  1304. //==============================================================================
  1305. Atomic<int> refCount;
  1306. AudioProcessor* pluginInstance;
  1307. ComSmartPtr<Vst::IHostApplication> host;
  1308. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1309. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1310. /**
  1311. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1312. this object needs to be copied on every call to process() to be up-to-date...
  1313. */
  1314. Vst::ProcessContext processContext;
  1315. Vst::ProcessSetup processSetup;
  1316. Vst::BusList audioInputs, audioOutputs, eventInputs, eventOutputs;
  1317. MidiBuffer midiBuffer;
  1318. Array<float*> channelList;
  1319. ScopedJuceInitialiser_GUI libraryInitialiser;
  1320. int vstBypassParameterId;
  1321. static const char* kJucePrivateDataIdentifier;
  1322. //==============================================================================
  1323. void addBusTo (Vst::BusList& busList, Vst::Bus* newBus)
  1324. {
  1325. busList.append (IPtr<Vst::Bus> (newBus, false));
  1326. }
  1327. void addAudioBusTo (Vst::BusList& busList, const juce::String& name, Vst::SpeakerArrangement arr)
  1328. {
  1329. addBusTo (busList, new Vst::AudioBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, arr));
  1330. }
  1331. void addEventBusTo (Vst::BusList& busList, const juce::String& name)
  1332. {
  1333. addBusTo (busList, new Vst::EventBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, 16));
  1334. }
  1335. Vst::BusList* getBusListFor (Vst::MediaType type, Vst::BusDirection dir)
  1336. {
  1337. if (type == Vst::kAudio) return dir == Vst::kInput ? &audioInputs : &audioOutputs;
  1338. if (type == Vst::kEvent) return dir == Vst::kInput ? &eventInputs : &eventOutputs;
  1339. return nullptr;
  1340. }
  1341. //==============================================================================
  1342. enum InternalParameters
  1343. {
  1344. paramPreset = 'prst'
  1345. };
  1346. static int getNumChannels (Vst::BusList& busList)
  1347. {
  1348. Vst::BusInfo info;
  1349. info.channelCount = 0;
  1350. if (Vst::Bus* bus = busList.first())
  1351. bus->getInfo (info);
  1352. return (int) info.channelCount;
  1353. }
  1354. void preparePlugin (double sampleRate, int bufferSize)
  1355. {
  1356. getPluginInstance().setPlayConfigDetails (getNumChannels (audioInputs),
  1357. getNumChannels (audioOutputs),
  1358. sampleRate, bufferSize);
  1359. getPluginInstance().prepareToPlay (sampleRate, bufferSize);
  1360. }
  1361. //==============================================================================
  1362. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1363. };
  1364. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1365. Steinberg::FUID getJuceVST3ComponentIID();
  1366. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1367. #endif
  1368. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1369. //==============================================================================
  1370. #if JUCE_MSVC
  1371. #pragma warning (push, 0)
  1372. #pragma warning (disable: 4310)
  1373. #elif JUCE_CLANG
  1374. #pragma clang diagnostic push
  1375. #pragma clang diagnostic ignored "-Wall"
  1376. #endif
  1377. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1378. DEF_CLASS_IID (JuceAudioProcessor)
  1379. #if JUCE_VST3_CAN_REPLACE_VST2
  1380. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1381. static FUID getFUIDForVST2ID (bool forControllerUID)
  1382. {
  1383. char uidString[33];
  1384. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1385. char vstfxidStr[7] = { 0 };
  1386. sprintf (vstfxidStr, "%06X", vstfxid);
  1387. strcpy (uidString, vstfxidStr);
  1388. char uidStr[9] = { 0 };
  1389. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1390. strcat (uidString, uidStr);
  1391. char nameidStr[3] = { 0 };
  1392. const size_t len = strlen (JucePlugin_Name);
  1393. for (size_t i = 0; i <= 8; ++i)
  1394. {
  1395. juce::uint8 c = i < len ? static_cast<juce::uint8> (JucePlugin_Name[i]) : 0;
  1396. if (c >= 'A' && c <= 'Z')
  1397. c += 'a' - 'A';
  1398. sprintf (nameidStr, "%02X", c);
  1399. strcat (uidString, nameidStr);
  1400. }
  1401. FUID newOne;
  1402. newOne.fromString (uidString);
  1403. return newOne;
  1404. }
  1405. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1406. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1407. #else
  1408. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1409. DEF_CLASS_IID (JuceVST3EditController)
  1410. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1411. DEF_CLASS_IID (JuceVST3Component)
  1412. #endif
  1413. #if JUCE_MSVC
  1414. #pragma warning (pop)
  1415. #elif JUCE_CLANG
  1416. #pragma clang diagnostic pop
  1417. #endif
  1418. //==============================================================================
  1419. bool initModule()
  1420. {
  1421. #if JUCE_MAC
  1422. initialiseMacVST();
  1423. #endif
  1424. return true;
  1425. }
  1426. bool shutdownModule()
  1427. {
  1428. return true;
  1429. }
  1430. #undef JUCE_EXPORTED_FUNCTION
  1431. #if JUCE_WINDOWS
  1432. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1433. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1434. #define JUCE_EXPORTED_FUNCTION
  1435. #else
  1436. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1437. CFBundleRef globalBundleInstance = nullptr;
  1438. juce::uint32 numBundleRefs = 0;
  1439. juce::Array<CFBundleRef> bundleRefs;
  1440. enum { MaxPathLength = 2048 };
  1441. char modulePath[MaxPathLength] = { 0 };
  1442. void* moduleHandle = nullptr;
  1443. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1444. {
  1445. if (ref != nullptr)
  1446. {
  1447. ++numBundleRefs;
  1448. CFRetain (ref);
  1449. bundleRefs.add (ref);
  1450. if (moduleHandle == nullptr)
  1451. {
  1452. globalBundleInstance = ref;
  1453. moduleHandle = ref;
  1454. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1455. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1456. CFRelease (tempURL);
  1457. }
  1458. }
  1459. return initModule();
  1460. }
  1461. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1462. {
  1463. if (shutdownModule())
  1464. {
  1465. if (--numBundleRefs == 0)
  1466. {
  1467. for (int i = 0; i < bundleRefs.size(); ++i)
  1468. CFRelease (bundleRefs.getUnchecked (i));
  1469. bundleRefs.clear();
  1470. }
  1471. return true;
  1472. }
  1473. return false;
  1474. }
  1475. #endif
  1476. //==============================================================================
  1477. /** This typedef represents VST3's createInstance() function signature */
  1478. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1479. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1480. {
  1481. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1482. }
  1483. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1484. {
  1485. return (Vst::IEditController*) new JuceVST3EditController (host);
  1486. }
  1487. //==============================================================================
  1488. class JucePluginFactory;
  1489. static JucePluginFactory* globalFactory = nullptr;
  1490. //==============================================================================
  1491. class JucePluginFactory : public IPluginFactory3
  1492. {
  1493. public:
  1494. JucePluginFactory()
  1495. : refCount (1),
  1496. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1497. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1498. {
  1499. }
  1500. virtual ~JucePluginFactory()
  1501. {
  1502. if (globalFactory == this)
  1503. globalFactory = nullptr;
  1504. }
  1505. //==============================================================================
  1506. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1507. {
  1508. if (createFunction == nullptr)
  1509. {
  1510. jassertfalse;
  1511. return false;
  1512. }
  1513. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1514. entry->infoW.fromAscii (info);
  1515. return true;
  1516. }
  1517. bool isClassRegistered (const FUID& cid) const
  1518. {
  1519. for (int i = 0; i < classes.size(); ++i)
  1520. if (classes.getUnchecked (i)->infoW.cid == cid)
  1521. return true;
  1522. return false;
  1523. }
  1524. //==============================================================================
  1525. JUCE_DECLARE_VST3_COM_REF_METHODS
  1526. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1527. {
  1528. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1529. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1530. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1531. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1532. jassertfalse; // Something new?
  1533. *obj = nullptr;
  1534. return kNotImplemented;
  1535. }
  1536. //==============================================================================
  1537. Steinberg::int32 PLUGIN_API countClasses() override
  1538. {
  1539. return (Steinberg::int32) classes.size();
  1540. }
  1541. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1542. {
  1543. if (info == nullptr)
  1544. return kInvalidArgument;
  1545. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1546. return kResultOk;
  1547. }
  1548. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1549. {
  1550. return getPClassInfo<PClassInfo> (index, info);
  1551. }
  1552. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1553. {
  1554. return getPClassInfo<PClassInfo2> (index, info);
  1555. }
  1556. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1557. {
  1558. if (info != nullptr)
  1559. {
  1560. if (ClassEntry* entry = classes[(int) index])
  1561. {
  1562. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1563. return kResultOk;
  1564. }
  1565. }
  1566. return kInvalidArgument;
  1567. }
  1568. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1569. {
  1570. *obj = nullptr;
  1571. FUID sourceFuid = sourceIid;
  1572. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1573. {
  1574. jassertfalse; // The host you're running in has severe implementation issues!
  1575. return kInvalidArgument;
  1576. }
  1577. TUID iidToQuery;
  1578. sourceFuid.toTUID (iidToQuery);
  1579. for (int i = 0; i < classes.size(); ++i)
  1580. {
  1581. const ClassEntry& entry = *classes.getUnchecked (i);
  1582. if (doUIDsMatch (entry.infoW.cid, cid))
  1583. {
  1584. if (FUnknown* const instance = entry.createFunction (host))
  1585. {
  1586. const FReleaser releaser (instance);
  1587. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1588. return kResultOk;
  1589. }
  1590. break;
  1591. }
  1592. }
  1593. return kNoInterface;
  1594. }
  1595. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1596. {
  1597. host.loadFrom (context);
  1598. if (host != nullptr)
  1599. {
  1600. Vst::String128 name;
  1601. host->getName (name);
  1602. return kResultTrue;
  1603. }
  1604. return kNotImplemented;
  1605. }
  1606. private:
  1607. //==============================================================================
  1608. ScopedJuceInitialiser_GUI libraryInitialiser;
  1609. Atomic<int> refCount;
  1610. const PFactoryInfo factoryInfo;
  1611. ComSmartPtr<Vst::IHostApplication> host;
  1612. //==============================================================================
  1613. struct ClassEntry
  1614. {
  1615. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1616. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1617. : info2 (info), createFunction (fn), isUnicode (false) {}
  1618. PClassInfo2 info2;
  1619. PClassInfoW infoW;
  1620. CreateFunction createFunction;
  1621. bool isUnicode;
  1622. private:
  1623. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1624. };
  1625. OwnedArray<ClassEntry> classes;
  1626. //==============================================================================
  1627. template<class PClassInfoType>
  1628. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1629. {
  1630. if (info != nullptr)
  1631. {
  1632. zerostruct (*info);
  1633. if (ClassEntry* entry = classes[(int) index])
  1634. {
  1635. if (entry->isUnicode)
  1636. return kResultFalse;
  1637. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1638. return kResultOk;
  1639. }
  1640. }
  1641. jassertfalse;
  1642. return kInvalidArgument;
  1643. }
  1644. //==============================================================================
  1645. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1646. };
  1647. } // juce namespace
  1648. //==============================================================================
  1649. #ifndef JucePlugin_Vst3ComponentFlags
  1650. #if JucePlugin_IsSynth
  1651. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1652. #else
  1653. #define JucePlugin_Vst3ComponentFlags 0
  1654. #endif
  1655. #endif
  1656. #ifndef JucePlugin_Vst3Category
  1657. #if JucePlugin_IsSynth
  1658. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1659. #else
  1660. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1661. #endif
  1662. #endif
  1663. //==============================================================================
  1664. // The VST3 plugin entry point.
  1665. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1666. {
  1667. #if JUCE_WINDOWS
  1668. // Cunning trick to force this function to be exported. Life's too short to
  1669. // faff around creating .def files for this kind of thing.
  1670. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1671. #endif
  1672. if (globalFactory == nullptr)
  1673. {
  1674. globalFactory = new JucePluginFactory();
  1675. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1676. PClassInfo::kManyInstances,
  1677. kVstAudioEffectClass,
  1678. JucePlugin_Name,
  1679. JucePlugin_Vst3ComponentFlags,
  1680. JucePlugin_Vst3Category,
  1681. JucePlugin_Manufacturer,
  1682. JucePlugin_VersionString,
  1683. kVstVersionString);
  1684. globalFactory->registerClass (componentClass, createComponentInstance);
  1685. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1686. PClassInfo::kManyInstances,
  1687. kVstComponentControllerClass,
  1688. JucePlugin_Name,
  1689. JucePlugin_Vst3ComponentFlags,
  1690. JucePlugin_Vst3Category,
  1691. JucePlugin_Manufacturer,
  1692. JucePlugin_VersionString,
  1693. kVstVersionString);
  1694. globalFactory->registerClass (controllerClass, createControllerInstance);
  1695. }
  1696. else
  1697. {
  1698. globalFactory->addRef();
  1699. }
  1700. return dynamic_cast<IPluginFactory*> (globalFactory);
  1701. }
  1702. #endif //JucePlugin_Build_VST3