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.

2125 lines
74KB

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