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.

2208 lines
78KB

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