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.

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