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.

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