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.

1612 lines
55KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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 "../../juce_audio_processors/format_types/juce_VST3Common.h"
  26. #undef Point
  27. #undef Component
  28. using namespace Steinberg;
  29. //==============================================================================
  30. class JuceLibraryRefCount
  31. {
  32. public:
  33. JuceLibraryRefCount() { if ((getCount()++) == 0) initialiseJuce_GUI(); }
  34. ~JuceLibraryRefCount() { if ((--getCount()) == 0) shutdownJuce_GUI(); }
  35. private:
  36. int& getCount() noexcept
  37. {
  38. static int count = 0;
  39. return count;
  40. }
  41. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceLibraryRefCount)
  42. };
  43. //==============================================================================
  44. namespace juce
  45. {
  46. #if JUCE_MAC
  47. extern void initialiseMac();
  48. extern void* attachComponentToWindowRef (Component*, void* parent, bool isNSView);
  49. extern void detachComponentFromWindowRef (Component*, void* window, bool isNSView);
  50. extern void setNativeHostWindowSize (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  51. #endif
  52. }
  53. //==============================================================================
  54. class JuceAudioProcessor : public FUnknown
  55. {
  56. public:
  57. JuceAudioProcessor (AudioProcessor* source) noexcept
  58. : refCount (0), audioProcessor (source) {}
  59. virtual ~JuceAudioProcessor() {}
  60. AudioProcessor* get() const noexcept { return audioProcessor; }
  61. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  62. JUCE_DECLARE_VST3_COM_REF_METHODS
  63. static const FUID iid;
  64. private:
  65. Atomic<int> refCount;
  66. ScopedPointer<AudioProcessor> audioProcessor;
  67. JuceAudioProcessor() JUCE_DELETED_FUNCTION;
  68. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  69. };
  70. #define TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID(CommonClassType, SourceClassType) \
  71. if (doUIDsMatch (iid, CommonClassType::iid)) \
  72. { \
  73. addRef(); \
  74. *obj = (CommonClassType*) static_cast<SourceClassType*> (this); \
  75. return Steinberg::kResultOk; \
  76. }
  77. //==============================================================================
  78. class JuceVST3EditController : public Vst::EditController,
  79. public Vst::IMidiMapping,
  80. public AudioProcessorListener
  81. {
  82. public:
  83. JuceVST3EditController (Vst::IHostApplication* host)
  84. {
  85. if (host != nullptr)
  86. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  87. }
  88. //==============================================================================
  89. static const FUID iid;
  90. //==============================================================================
  91. REFCOUNT_METHODS (ComponentBase)
  92. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  93. {
  94. TEST_FOR_AND_RETURN_IF_VALID (FObject)
  95. TEST_FOR_AND_RETURN_IF_VALID (JuceVST3EditController)
  96. TEST_FOR_AND_RETURN_IF_VALID (Vst::IEditController)
  97. TEST_FOR_AND_RETURN_IF_VALID (Vst::IEditController2)
  98. TEST_FOR_AND_RETURN_IF_VALID (Vst::IConnectionPoint)
  99. TEST_FOR_AND_RETURN_IF_VALID (Vst::IMidiMapping)
  100. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (IPluginBase, Vst::IEditController)
  101. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (IDependent, Vst::IEditController)
  102. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (FUnknown, Vst::IEditController)
  103. if (doUIDsMatch (iid, JuceAudioProcessor::iid))
  104. {
  105. audioProcessor->addRef();
  106. *obj = audioProcessor;
  107. return kResultOk;
  108. }
  109. *obj = nullptr;
  110. return kNoInterface;
  111. }
  112. //==============================================================================
  113. tresult PLUGIN_API initialize (FUnknown* context) override
  114. {
  115. if (hostContext != context)
  116. {
  117. if (hostContext != nullptr)
  118. hostContext->release();
  119. hostContext = context;
  120. if (hostContext != nullptr)
  121. hostContext->addRef();
  122. }
  123. return kResultTrue;
  124. }
  125. tresult PLUGIN_API terminate() override
  126. {
  127. if (AudioProcessor* const pluginInstance = getPluginInstance())
  128. pluginInstance->removeListener (this);
  129. audioProcessor = nullptr;
  130. return EditController::terminate();
  131. }
  132. //==============================================================================
  133. struct Param : public Vst::Parameter
  134. {
  135. Param (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  136. {
  137. info.id = (Vst::ParamID) index;
  138. toString128 (info.title, p.getParameterName (index));
  139. toString128 (info.shortTitle, p.getParameterName (index, 8));
  140. toString128 (info.units, p.getParameterLabel (index));
  141. const int numSteps = p.getParameterNumSteps (index);
  142. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  143. info.defaultNormalizedValue = p.getParameterDefaultValue (index);
  144. info.unitId = Vst::kRootUnitId;
  145. info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
  146. }
  147. virtual ~Param() {}
  148. bool setNormalized (Vst::ParamValue v) override
  149. {
  150. v = jlimit (0.0, 1.0, v);
  151. if (v != valueNormalized)
  152. {
  153. valueNormalized = v;
  154. changed();
  155. owner.setParameter (paramIndex, (float) v);
  156. return true;
  157. }
  158. return false;
  159. }
  160. void toString (Vst::ParamValue, Vst::String128 result) const override
  161. {
  162. toString128 (result, owner.getParameterText (paramIndex, 128));
  163. }
  164. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  165. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  166. private:
  167. AudioProcessor& owner;
  168. int paramIndex;
  169. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  170. };
  171. //==============================================================================
  172. void setAudioProcessor (JuceAudioProcessor* audioProc)
  173. {
  174. if (audioProcessor != audioProc)
  175. {
  176. audioProcessor = audioProc;
  177. setupParameters();
  178. }
  179. }
  180. tresult PLUGIN_API connect (IConnectionPoint* other) override
  181. {
  182. if (other != nullptr && audioProcessor == nullptr)
  183. {
  184. const tresult result = ComponentBase::connect (other);
  185. if (! audioProcessor.loadFrom (other))
  186. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  187. else
  188. setupParameters();
  189. return result;
  190. }
  191. jassertfalse;
  192. return kResultFalse;
  193. }
  194. //==============================================================================
  195. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32, Steinberg::int16,
  196. Vst::CtrlNumber,
  197. Vst::ParamID& id) override
  198. {
  199. //TODO
  200. id = 0;
  201. return kNotImplemented;
  202. }
  203. //==============================================================================
  204. IPlugView* PLUGIN_API createView (const char* name) override
  205. {
  206. if (AudioProcessor* const pluginInstance = getPluginInstance())
  207. {
  208. if (pluginInstance->hasEditor() && name != nullptr
  209. && strcmp (name, Vst::ViewType::kEditor) == 0)
  210. {
  211. return new JuceVST3Editor (*this, *pluginInstance);
  212. }
  213. }
  214. return nullptr;
  215. }
  216. //==============================================================================
  217. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit ((Steinberg::uint32) index); }
  218. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override { performEdit ((Steinberg::uint32) index, (double) newValue); }
  219. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit ((Steinberg::uint32) index); }
  220. void audioProcessorChanged (AudioProcessor*) override
  221. {
  222. if (componentHandler != nullptr)
  223. componentHandler->restartComponent (Vst::kLatencyChanged & Vst::kParamValuesChanged);
  224. }
  225. //==============================================================================
  226. AudioProcessor* getPluginInstance() const noexcept
  227. {
  228. if (audioProcessor != nullptr)
  229. return audioProcessor->get();
  230. return nullptr;
  231. }
  232. private:
  233. //==============================================================================
  234. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  235. const JuceLibraryRefCount juceCount;
  236. //==============================================================================
  237. void setupParameters()
  238. {
  239. if (AudioProcessor* const pluginInstance = getPluginInstance())
  240. {
  241. pluginInstance->addListener (this);
  242. if (parameters.getParameterCount() <= 0)
  243. for (int i = 0; i < pluginInstance->getNumParameters(); ++i)
  244. parameters.addParameter (new Param (*pluginInstance, i));
  245. audioProcessorChanged (pluginInstance);
  246. }
  247. }
  248. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  249. {
  250. jassert (hostContext != nullptr);
  251. if (Vst::IMessage* message = allocateMessage())
  252. {
  253. const FReleaser releaser (message);
  254. message->setMessageID (idTag);
  255. message->getAttributes()->setInt (idTag, value);
  256. sendMessage (message);
  257. }
  258. }
  259. //==============================================================================
  260. class JuceVST3Editor : public Vst::EditorView
  261. {
  262. public:
  263. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  264. : Vst::EditorView (&ec, nullptr),
  265. owner (&ec), pluginInstance (p)
  266. {
  267. #if JUCE_MAC
  268. macHostWindow = nullptr;
  269. isNSView = false;
  270. #endif
  271. component = new ContentWrapperComponent (*this, p);
  272. }
  273. //==============================================================================
  274. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  275. {
  276. if (type != nullptr && pluginInstance.hasEditor())
  277. {
  278. #if JUCE_WINDOWS
  279. if (strcmp (type, kPlatformTypeHWND) == 0)
  280. #else
  281. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  282. #endif
  283. return kResultTrue;
  284. }
  285. return kResultFalse;
  286. }
  287. tresult PLUGIN_API attached (void* parent, FIDString type) override
  288. {
  289. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  290. return kResultFalse;
  291. #if JUCE_WINDOWS
  292. component->addToDesktop (0, parent);
  293. component->setOpaque (true);
  294. component->setVisible (true);
  295. #else
  296. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  297. macHostWindow = juce::attachComponentToWindowRef (component, parent, isNSView);
  298. #endif
  299. component->resizeHostWindow();
  300. systemWindow = parent;
  301. attachedToParent();
  302. return kResultTrue;
  303. }
  304. tresult PLUGIN_API removed() override
  305. {
  306. if (component != nullptr)
  307. {
  308. #if JUCE_WINDOWS
  309. component->removeFromDesktop();
  310. #else
  311. if (macHostWindow != nullptr)
  312. {
  313. juce::detachComponentFromWindowRef (component, macHostWindow, isNSView);
  314. macHostWindow = nullptr;
  315. }
  316. #endif
  317. component = nullptr;
  318. }
  319. return CPluginView::removed();
  320. }
  321. tresult PLUGIN_API onSize (ViewRect* newSize) override
  322. {
  323. if (newSize != nullptr)
  324. {
  325. rect = *newSize;
  326. if (component != nullptr)
  327. component->setSize (rect.getWidth(), rect.getHeight());
  328. return kResultTrue;
  329. }
  330. jassertfalse;
  331. return kResultFalse;
  332. }
  333. tresult PLUGIN_API getSize (ViewRect* size) override
  334. {
  335. if (size != nullptr && component != nullptr)
  336. {
  337. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  338. return kResultTrue;
  339. }
  340. return kResultFalse;
  341. }
  342. tresult PLUGIN_API canResize() override { return kResultTrue; }
  343. tresult PLUGIN_API checkSizeConstraint (ViewRect* rect) override
  344. {
  345. if (rect != nullptr && component != nullptr)
  346. {
  347. rect->right = rect->left + component->getWidth();
  348. rect->bottom = rect->top + component->getHeight();
  349. return kResultTrue;
  350. }
  351. jassertfalse;
  352. return kResultFalse;
  353. }
  354. private:
  355. //==============================================================================
  356. class ContentWrapperComponent : public juce::Component
  357. {
  358. public:
  359. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  360. : owner (editor),
  361. pluginEditor (plugin.createEditorIfNeeded())
  362. {
  363. setOpaque (true);
  364. setBroughtToFrontOnMouseClick (true);
  365. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  366. jassert (pluginEditor != nullptr);
  367. if (pluginEditor != nullptr)
  368. {
  369. addAndMakeVisible (pluginEditor);
  370. setBounds (pluginEditor->getLocalBounds());
  371. resizeHostWindow();
  372. }
  373. }
  374. ~ContentWrapperComponent()
  375. {
  376. if (pluginEditor != nullptr)
  377. {
  378. PopupMenu::dismissAllActiveMenus();
  379. pluginEditor->getAudioProcessor()->editorBeingDeleted (pluginEditor);
  380. }
  381. }
  382. void paint (Graphics& g) override
  383. {
  384. g.fillAll (Colours::black);
  385. }
  386. void childBoundsChanged (Component*) override
  387. {
  388. resizeHostWindow();
  389. }
  390. void resized() override
  391. {
  392. if (pluginEditor != nullptr)
  393. pluginEditor->setBounds (getLocalBounds());
  394. }
  395. void resizeHostWindow()
  396. {
  397. if (pluginEditor != nullptr)
  398. {
  399. const int w = pluginEditor->getWidth();
  400. const int h = pluginEditor->getHeight();
  401. #if JUCE_WINDOWS
  402. setSize (w, h);
  403. #else
  404. if (owner.macHostWindow != nullptr)
  405. juce::setNativeHostWindowSize (owner.macHostWindow, this, w, h, owner.isNSView);
  406. #endif
  407. if (owner.plugFrame != nullptr)
  408. {
  409. ViewRect newSize (0, 0, w, h);
  410. owner.plugFrame->resizeView (&owner, &newSize);
  411. }
  412. }
  413. }
  414. private:
  415. JuceVST3Editor& owner;
  416. ScopedPointer<AudioProcessorEditor> pluginEditor;
  417. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  418. };
  419. //==============================================================================
  420. ComSmartPtr<JuceVST3EditController> owner;
  421. AudioProcessor& pluginInstance;
  422. ScopedPointer<ContentWrapperComponent> component;
  423. friend class ContentWrapperComponent;
  424. #if JUCE_MAC
  425. void* macHostWindow;
  426. bool isNSView;
  427. #endif
  428. //==============================================================================
  429. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  430. };
  431. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  432. };
  433. //==============================================================================
  434. class JuceVST3Component : public Vst::IComponent,
  435. public Vst::IAudioProcessor,
  436. public Vst::IUnitInfo,
  437. public Vst::IConnectionPoint,
  438. public AudioPlayHead
  439. {
  440. public:
  441. JuceVST3Component (Vst::IHostApplication* h)
  442. : refCount (1),
  443. host (h),
  444. audioInputs (Vst::kAudio, Vst::kInput),
  445. audioOutputs (Vst::kAudio, Vst::kOutput),
  446. eventInputs (Vst::kEvent, Vst::kInput),
  447. eventOutputs (Vst::kEvent, Vst::kOutput)
  448. {
  449. pluginInstance = createPluginFilterOfType (AudioProcessor::wrapperType_VST3);
  450. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  451. zerostruct (processContext);
  452. processSetup.maxSamplesPerBlock = 1024;
  453. processSetup.processMode = Vst::kRealtime;
  454. processSetup.sampleRate = 44100.0;
  455. processSetup.symbolicSampleSize = Vst::kSample32;
  456. }
  457. ~JuceVST3Component()
  458. {
  459. if (pluginInstance != nullptr)
  460. if (pluginInstance->getPlayHead() == this)
  461. pluginInstance->setPlayHead (nullptr);
  462. audioInputs.removeAll();
  463. audioOutputs.removeAll();
  464. eventInputs.removeAll();
  465. eventOutputs.removeAll();
  466. }
  467. //==============================================================================
  468. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  469. //==============================================================================
  470. static const FUID iid;
  471. JUCE_DECLARE_VST3_COM_REF_METHODS
  472. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  473. {
  474. TEST_FOR_AND_RETURN_IF_VALID (IPluginBase)
  475. TEST_FOR_AND_RETURN_IF_VALID (JuceVST3Component)
  476. TEST_FOR_AND_RETURN_IF_VALID (Vst::IComponent)
  477. TEST_FOR_AND_RETURN_IF_VALID (Vst::IAudioProcessor)
  478. TEST_FOR_AND_RETURN_IF_VALID (Vst::IUnitInfo)
  479. TEST_FOR_AND_RETURN_IF_VALID (Vst::IConnectionPoint)
  480. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (FUnknown, Vst::IComponent)
  481. if (doUIDsMatch (iid, JuceAudioProcessor::iid))
  482. {
  483. comPluginInstance->addRef();
  484. *obj = comPluginInstance;
  485. return kResultOk;
  486. }
  487. *obj = nullptr;
  488. return kNoInterface;
  489. }
  490. //==============================================================================
  491. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  492. {
  493. if (host != hostContext)
  494. host.loadFrom (hostContext);
  495. #if JucePlugin_MaxNumInputChannels > 0
  496. addAudioBusTo (audioInputs, TRANS("Audio Input"),
  497. getArrangementForNumChannels (JucePlugin_MaxNumInputChannels));
  498. #endif
  499. #if JucePlugin_MaxNumOutputChannels > 0
  500. addAudioBusTo (audioOutputs, TRANS("Audio Output"),
  501. getArrangementForNumChannels (JucePlugin_MaxNumOutputChannels));
  502. #endif
  503. #if JucePlugin_WantsMidiInput
  504. addEventBusTo (eventInputs, TRANS("MIDI Input"));
  505. #endif
  506. #if JucePlugin_ProducesMidiOutput
  507. addEventBusTo (eventOutputs, TRANS("MIDI Output"));
  508. #endif
  509. processContext.sampleRate = processSetup.sampleRate;
  510. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  511. return kResultTrue;
  512. }
  513. tresult PLUGIN_API terminate() override
  514. {
  515. getPluginInstance().releaseResources();
  516. return kResultTrue;
  517. }
  518. //==============================================================================
  519. tresult PLUGIN_API connect (IConnectionPoint* other) override
  520. {
  521. if (other != nullptr && juceVST3EditController == nullptr)
  522. juceVST3EditController.loadFrom (other);
  523. return kResultTrue;
  524. }
  525. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  526. {
  527. juceVST3EditController = nullptr;
  528. return kResultTrue;
  529. }
  530. tresult PLUGIN_API notify (Vst::IMessage* message) override
  531. {
  532. if (message != nullptr && juceVST3EditController == nullptr)
  533. {
  534. Steinberg::int64 value = 0;
  535. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  536. {
  537. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  538. if (juceVST3EditController != nullptr)
  539. juceVST3EditController->setAudioProcessor (comPluginInstance);
  540. else
  541. jassertfalse;
  542. }
  543. }
  544. return kResultTrue;
  545. }
  546. //==============================================================================
  547. tresult PLUGIN_API getControllerClassId (TUID classID) override
  548. {
  549. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  550. return kResultTrue;
  551. }
  552. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  553. {
  554. if (Vst::BusList* const busList = getBusListFor (type, dir))
  555. return busList->total();
  556. return 0;
  557. }
  558. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  559. Steinberg::int32 index, Vst::BusInfo& info) override
  560. {
  561. if (Vst::BusList* const busList = getBusListFor (type, dir))
  562. {
  563. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  564. {
  565. info.mediaType = type;
  566. info.direction = dir;
  567. if (bus->getInfo (info))
  568. return kResultTrue;
  569. }
  570. }
  571. zerostruct (info);
  572. return kResultFalse;
  573. }
  574. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir,
  575. Steinberg::int32 index, TBool state) override
  576. {
  577. if (Vst::BusList* const busList = getBusListFor (type, dir))
  578. {
  579. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  580. {
  581. bus->setActive (state);
  582. return kResultTrue;
  583. }
  584. }
  585. jassertfalse;
  586. return kResultFalse;
  587. }
  588. tresult PLUGIN_API setActive (TBool state) override
  589. {
  590. if (state == kResultFalse)
  591. {
  592. getPluginInstance().releaseResources();
  593. }
  594. else
  595. {
  596. double sampleRate = getPluginInstance().getSampleRate();
  597. int bufferSize = getPluginInstance().getBlockSize();
  598. sampleRate = processSetup.sampleRate > 0.0
  599. ? processSetup.sampleRate
  600. : sampleRate;
  601. bufferSize = processSetup.maxSamplesPerBlock > 0
  602. ? (int) processSetup.maxSamplesPerBlock
  603. : bufferSize;
  604. channelList.clear();
  605. channelList.insertMultiple (0, nullptr, jmax (JucePlugin_MaxNumInputChannels, JucePlugin_MaxNumOutputChannels) + 1);
  606. preparePlugin (sampleRate, bufferSize);
  607. }
  608. return kResultOk;
  609. }
  610. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  611. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  612. bool readFromMemoryStream (IBStream* state) const
  613. {
  614. FUnknownPtr<MemoryStream> s (state);
  615. if (s != nullptr
  616. && s->getData() != nullptr
  617. && s->getSize() > 0
  618. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  619. {
  620. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  621. if (getHostType().isAdobeAudition())
  622. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  623. return false;
  624. pluginInstance->setStateInformation (s->getData(), (int) s->getSize());
  625. return true;
  626. }
  627. return false;
  628. }
  629. bool readFromUnknownStream (IBStream* state) const
  630. {
  631. MemoryOutputStream allData;
  632. {
  633. const size_t bytesPerBlock = 4096;
  634. HeapBlock<char> buffer (bytesPerBlock);
  635. for (;;)
  636. {
  637. Steinberg::int32 bytesRead = 0;
  638. if (state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead) == kResultTrue && bytesRead > 0)
  639. {
  640. allData.write (buffer, bytesRead);
  641. continue;
  642. }
  643. break;
  644. }
  645. }
  646. const size_t dataSize = allData.getDataSize();
  647. if (dataSize > 0 && dataSize < 0x7fffffff)
  648. {
  649. pluginInstance->setStateInformation (allData.getData(), (int) dataSize);
  650. return true;
  651. }
  652. return false;
  653. }
  654. tresult PLUGIN_API setState (IBStream* state) override
  655. {
  656. if (state == nullptr)
  657. return kInvalidArgument;
  658. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  659. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  660. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  661. return kResultTrue;
  662. return kResultFalse;
  663. }
  664. tresult PLUGIN_API getState (IBStream* state) override
  665. {
  666. if (state != nullptr)
  667. {
  668. juce::MemoryBlock mem;
  669. pluginInstance->getStateInformation (mem);
  670. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  671. }
  672. return kInvalidArgument;
  673. }
  674. //==============================================================================
  675. Steinberg::int32 PLUGIN_API getUnitCount() override
  676. {
  677. return 1;
  678. }
  679. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  680. {
  681. if (unitIndex == 0)
  682. {
  683. info.id = Vst::kRootUnitId;
  684. info.parentUnitId = Vst::kNoParentUnitId;
  685. info.programListId = Vst::kNoProgramListId;
  686. toString128 (info.name, TRANS("Root Unit"));
  687. return kResultTrue;
  688. }
  689. zerostruct (info);
  690. return kResultFalse;
  691. }
  692. Steinberg::int32 PLUGIN_API getProgramListCount() override
  693. {
  694. if (getPluginInstance().getNumPrograms() > 0)
  695. return 1;
  696. return 0;
  697. }
  698. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  699. {
  700. if (listIndex == 0)
  701. {
  702. info.id = paramPreset;
  703. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  704. toString128 (info.name, TRANS("Factory Presets"));
  705. return kResultTrue;
  706. }
  707. jassertfalse;
  708. zerostruct (info);
  709. return kResultFalse;
  710. }
  711. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  712. {
  713. if (listId == paramPreset
  714. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  715. {
  716. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  717. return kResultTrue;
  718. }
  719. jassertfalse;
  720. toString128 (name, juce::String());
  721. return kResultFalse;
  722. }
  723. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  724. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  725. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  726. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  727. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  728. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  729. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection,
  730. Steinberg::int32, Steinberg::int32,
  731. Vst::UnitID& unitId) override
  732. {
  733. zerostruct (unitId);
  734. return kNotImplemented;
  735. }
  736. //==============================================================================
  737. bool getCurrentPosition (CurrentPositionInfo& info) override
  738. {
  739. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  740. info.timeInSeconds = processContext.projectTimeMusic;
  741. info.bpm = jmax (1.0, processContext.tempo);
  742. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  743. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  744. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  745. info.ppqPosition = processContext.projectTimeMusic;
  746. info.ppqLoopStart = processContext.cycleStartMusic;
  747. info.ppqLoopEnd = processContext.cycleEndMusic;
  748. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  749. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  750. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  751. info.editOriginTime = 0.0;
  752. info.frameRate = AudioPlayHead::fpsUnknown;
  753. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  754. {
  755. switch (processContext.frameRate.framesPerSecond)
  756. {
  757. case 24: info.frameRate = AudioPlayHead::fps24; break;
  758. case 25: info.frameRate = AudioPlayHead::fps25; break;
  759. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  760. case 30:
  761. {
  762. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  763. info.frameRate = AudioPlayHead::fps30drop;
  764. else
  765. info.frameRate = AudioPlayHead::fps30;
  766. }
  767. break;
  768. default: break;
  769. }
  770. }
  771. return true;
  772. }
  773. //==============================================================================
  774. static tresult setBusArrangementFor (Vst::BusList& list,
  775. Vst::SpeakerArrangement* arrangement,
  776. Steinberg::int32 numBusses)
  777. {
  778. if (arrangement != nullptr && numBusses == 1) //Should only be 1 bus per BusList
  779. {
  780. Steinberg::int32 counter = 0;
  781. FOREACH_CAST (IPtr<Vst::Bus>, Vst::AudioBus, bus, list)
  782. if (counter < numBusses)
  783. bus->setArrangement (arrangement[counter]);
  784. counter++;
  785. ENDFOR
  786. return kResultTrue;
  787. }
  788. return kResultFalse;
  789. }
  790. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  791. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  792. {
  793. #if JucePlugin_MaxNumInputChannels > 0
  794. if (setBusArrangementFor (audioInputs, inputs, numIns) != kResultTrue)
  795. return kResultFalse;
  796. #else
  797. if (numIns != 0)
  798. return kResultFalse;
  799. #endif
  800. #if JucePlugin_MaxNumOutputChannels > 0
  801. if (setBusArrangementFor (audioOutputs, outputs, numOuts) != kResultTrue)
  802. return kResultFalse;
  803. #else
  804. if (numOuts != 0)
  805. return kResultFalse;
  806. #endif
  807. return kResultTrue;
  808. }
  809. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  810. {
  811. if (Vst::BusList* const busList = getBusListFor (Vst::kAudio, dir))
  812. {
  813. if (Vst::AudioBus* const audioBus = FCast<Vst::AudioBus> (busList->at (index)))
  814. {
  815. arr = audioBus->getArrangement();
  816. return kResultTrue;
  817. }
  818. }
  819. return kResultFalse;
  820. }
  821. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  822. {
  823. return symbolicSampleSize == Vst::kSample32 ? kResultTrue : kResultFalse;
  824. }
  825. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  826. {
  827. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  828. }
  829. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  830. {
  831. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  832. return kResultFalse;
  833. processSetup = newSetup;
  834. processContext.sampleRate = processSetup.sampleRate;
  835. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  836. return kResultTrue;
  837. }
  838. tresult PLUGIN_API setProcessing (TBool state) override
  839. {
  840. if (state == kResultFalse)
  841. getPluginInstance().reset();
  842. return kResultTrue;
  843. }
  844. Steinberg::uint32 PLUGIN_API getTailSamples() override
  845. {
  846. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  847. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  848. return Vst::kNoTail;
  849. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  850. }
  851. //==============================================================================
  852. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  853. {
  854. jassert (pluginInstance != nullptr);
  855. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  856. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  857. {
  858. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  859. {
  860. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  861. Steinberg::int32 offsetSamples;
  862. double value = 0.0;
  863. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  864. {
  865. const int id = (int) paramQueue->getParameterId();
  866. jassert (isPositiveAndBelow (id, pluginInstance->getNumParameters()));
  867. pluginInstance->setParameter (id, (float) value);
  868. }
  869. }
  870. }
  871. }
  872. tresult PLUGIN_API process (Vst::ProcessData& data) override
  873. {
  874. if (pluginInstance == nullptr)
  875. return kResultFalse;
  876. if (data.processContext != nullptr)
  877. processContext = *data.processContext;
  878. else
  879. zerostruct (processContext);
  880. midiBuffer.clear();
  881. #if JucePlugin_WantsMidiInput
  882. if (data.inputEvents != nullptr)
  883. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  884. #endif
  885. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  886. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  887. #endif
  888. const int numInputChans = data.inputs != nullptr ? (int) data.inputs[0].numChannels : 0;
  889. const int numOutputChans = data.outputs != nullptr ? (int) data.outputs[0].numChannels : 0;
  890. int totalChans = 0;
  891. while (totalChans < numInputChans)
  892. {
  893. channelList.set (totalChans, data.inputs[0].channelBuffers32[totalChans]);
  894. ++totalChans;
  895. }
  896. while (totalChans < numOutputChans)
  897. {
  898. channelList.set (totalChans, data.outputs[0].channelBuffers32[totalChans]);
  899. ++totalChans;
  900. }
  901. AudioSampleBuffer buffer (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  902. {
  903. const ScopedLock sl (pluginInstance->getCallbackLock());
  904. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  905. if (data.inputParameterChanges != nullptr)
  906. processParameterChanges (*data.inputParameterChanges);
  907. if (pluginInstance->isSuspended())
  908. buffer.clear();
  909. else
  910. pluginInstance->processBlock (buffer, midiBuffer);
  911. }
  912. for (int i = 0; i < numOutputChans; ++i)
  913. FloatVectorOperations::copy (data.outputs[0].channelBuffers32[i], buffer.getSampleData (i), (int) data.numSamples);
  914. // clear extra busses..
  915. if (data.outputs != nullptr)
  916. for (int i = 1; i < data.numOutputs; ++i)
  917. for (int f = 0; f < data.outputs[i].numChannels; ++f)
  918. FloatVectorOperations::clear (data.outputs[i].channelBuffers32[f], (int) data.numSamples);
  919. #if JucePlugin_ProducesMidiOutput
  920. if (data.outputEvents != nullptr)
  921. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  922. #elif JUCE_DEBUG
  923. /* This assertion is caused when you've added some events to the
  924. midiMessages array in your processBlock() method, which usually means
  925. that you're trying to send them somewhere. But in this case they're
  926. getting thrown away.
  927. If your plugin does want to send MIDI messages, you'll need to set
  928. the JucePlugin_ProducesMidiOutput macro to 1 in your
  929. JucePluginCharacteristics.h file.
  930. If you don't want to produce any MIDI output, then you should clear the
  931. midiMessages array at the end of your processBlock() method, to
  932. indicate that you don't want any of the events to be passed through
  933. to the output.
  934. */
  935. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  936. #endif
  937. return kResultTrue;
  938. }
  939. private:
  940. //==============================================================================
  941. Atomic<int> refCount;
  942. AudioProcessor* pluginInstance;
  943. ComSmartPtr<Vst::IHostApplication> host;
  944. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  945. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  946. /**
  947. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  948. this object needs to be copied on every call to process() to be up-to-date...
  949. */
  950. Vst::ProcessContext processContext;
  951. Vst::ProcessSetup processSetup;
  952. Vst::BusList audioInputs, audioOutputs, eventInputs, eventOutputs;
  953. MidiBuffer midiBuffer;
  954. Array<float*> channelList;
  955. const JuceLibraryRefCount juceCount;
  956. //==============================================================================
  957. void addBusTo (Vst::BusList& busList, Vst::Bus* newBus)
  958. {
  959. busList.append (IPtr<Vst::Bus> (newBus, false));
  960. }
  961. void addAudioBusTo (Vst::BusList& busList, const juce::String& name, Vst::SpeakerArrangement arr)
  962. {
  963. addBusTo (busList, new Vst::AudioBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, arr));
  964. }
  965. void addEventBusTo (Vst::BusList& busList, const juce::String& name)
  966. {
  967. addBusTo (busList, new Vst::EventBus (toString (name), 16, Vst::kMain, Vst::BusInfo::kDefaultActive));
  968. }
  969. Vst::BusList* getBusListFor (Vst::MediaType type, Vst::BusDirection dir)
  970. {
  971. if (type == Vst::kAudio) return dir == Vst::kInput ? &audioInputs : &audioOutputs;
  972. if (type == Vst::kEvent) return dir == Vst::kInput ? &eventInputs : &eventOutputs;
  973. return nullptr;
  974. }
  975. //==============================================================================
  976. enum InternalParameters
  977. {
  978. paramPreset = 'prst'
  979. };
  980. void preparePlugin (double sampleRate, int bufferSize)
  981. {
  982. getPluginInstance().setPlayConfigDetails (JucePlugin_MaxNumInputChannels,
  983. JucePlugin_MaxNumOutputChannels,
  984. sampleRate, bufferSize);
  985. getPluginInstance().prepareToPlay (sampleRate, bufferSize);
  986. }
  987. //==============================================================================
  988. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  989. };
  990. //==============================================================================
  991. #if JUCE_MSVC
  992. #pragma warning (push, 0)
  993. #pragma warning (disable: 4310)
  994. #elif JUCE_CLANG
  995. #pragma clang diagnostic push
  996. #pragma clang diagnostic ignored "-w"
  997. #endif
  998. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  999. DEF_CLASS_IID (JuceAudioProcessor)
  1000. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1001. DEF_CLASS_IID (JuceVST3Component)
  1002. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1003. DEF_CLASS_IID (JuceVST3EditController)
  1004. #if JUCE_MSVC
  1005. #pragma warning (pop)
  1006. #elif JUCE_CLANG
  1007. #pragma clang diagnostic pop
  1008. #endif
  1009. //==============================================================================
  1010. bool initModule()
  1011. {
  1012. #if JUCE_MAC
  1013. initialiseMac();
  1014. #endif
  1015. return true;
  1016. }
  1017. bool shutdownModule()
  1018. {
  1019. return true;
  1020. }
  1021. #undef JUCE_EXPORTED_FUNCTION
  1022. #if JUCE_WINDOWS
  1023. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1024. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1025. #define JUCE_EXPORTED_FUNCTION
  1026. #else
  1027. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1028. CFBundleRef globalBundleInstance = nullptr;
  1029. juce::uint32 numBundleRefs = 0;
  1030. juce::Array<CFBundleRef> bundleRefs;
  1031. enum { MaxPathLength = 2048 };
  1032. char modulePath[MaxPathLength] = { 0 };
  1033. void* moduleHandle = nullptr;
  1034. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1035. {
  1036. if (ref != nullptr)
  1037. {
  1038. ++numBundleRefs;
  1039. CFRetain (ref);
  1040. bundleRefs.add (ref);
  1041. if (moduleHandle == nullptr)
  1042. {
  1043. globalBundleInstance = ref;
  1044. moduleHandle = ref;
  1045. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1046. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1047. CFRelease (tempURL);
  1048. }
  1049. }
  1050. return initModule();
  1051. }
  1052. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1053. {
  1054. if (shutdownModule())
  1055. {
  1056. if (--numBundleRefs == 0)
  1057. {
  1058. for (size_t i = 0; i < bundleRefs.size(); ++i)
  1059. CFRelease (bundleRefs.getUnchecked (i));
  1060. bundleRefs.clear();
  1061. }
  1062. return true;
  1063. }
  1064. return false;
  1065. }
  1066. #endif
  1067. //==============================================================================
  1068. /** This typedef represents VST3's createInstance() function signature */
  1069. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1070. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1071. {
  1072. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1073. }
  1074. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1075. {
  1076. return (Vst::IEditController*) new JuceVST3EditController (host);
  1077. }
  1078. //==============================================================================
  1079. class JucePluginFactory;
  1080. JucePluginFactory* globalFactory = nullptr;
  1081. //==============================================================================
  1082. class JucePluginFactory : public IPluginFactory3
  1083. {
  1084. public:
  1085. JucePluginFactory()
  1086. : refCount (1),
  1087. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1088. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1089. {
  1090. }
  1091. virtual ~JucePluginFactory()
  1092. {
  1093. if (globalFactory == this)
  1094. globalFactory = nullptr;
  1095. }
  1096. //==============================================================================
  1097. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1098. {
  1099. if (createFunction == nullptr)
  1100. {
  1101. jassertfalse;
  1102. return false;
  1103. }
  1104. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1105. entry->infoW.fromAscii (info);
  1106. return true;
  1107. }
  1108. bool isClassRegistered (const FUID& cid) const
  1109. {
  1110. for (int i = 0; i < classes.size(); ++i)
  1111. if (classes.getUnchecked (i)->infoW.cid == cid)
  1112. return true;
  1113. return false;
  1114. }
  1115. //==============================================================================
  1116. JUCE_DECLARE_VST3_COM_REF_METHODS
  1117. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  1118. {
  1119. TEST_FOR_AND_RETURN_IF_VALID (IPluginFactory3)
  1120. TEST_FOR_AND_RETURN_IF_VALID (IPluginFactory2)
  1121. TEST_FOR_AND_RETURN_IF_VALID (IPluginFactory)
  1122. TEST_FOR_AND_RETURN_IF_VALID (FUnknown)
  1123. jassertfalse; // Something new?
  1124. *obj = nullptr;
  1125. return kNotImplemented;
  1126. }
  1127. //==============================================================================
  1128. Steinberg::int32 PLUGIN_API countClasses() override
  1129. {
  1130. return (Steinberg::int32) classes.size();
  1131. }
  1132. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1133. {
  1134. if (info == nullptr)
  1135. return kInvalidArgument;
  1136. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1137. return kResultOk;
  1138. }
  1139. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1140. {
  1141. return getPClassInfo<PClassInfo> (index, info);
  1142. }
  1143. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1144. {
  1145. return getPClassInfo<PClassInfo2> (index, info);
  1146. }
  1147. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1148. {
  1149. if (info != nullptr)
  1150. {
  1151. if (ClassEntry* entry = classes[(int) index])
  1152. {
  1153. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1154. return kResultOk;
  1155. }
  1156. }
  1157. return kInvalidArgument;
  1158. }
  1159. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1160. {
  1161. *obj = nullptr;
  1162. FUID sourceFuid = sourceIid;
  1163. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1164. {
  1165. jassertfalse; // The host you're running in has severe implementation issues!
  1166. return kInvalidArgument;
  1167. }
  1168. TUID iidToQuery;
  1169. sourceFuid.toTUID (iidToQuery);
  1170. for (int i = 0; i < classes.size(); ++i)
  1171. {
  1172. const ClassEntry& entry = *classes.getUnchecked (i);
  1173. if (doUIDsMatch (entry.infoW.cid, cid))
  1174. {
  1175. if (FUnknown* const instance = entry.createFunction (host))
  1176. {
  1177. const FReleaser releaser (instance);
  1178. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1179. return kResultOk;
  1180. }
  1181. break;
  1182. }
  1183. }
  1184. return kNoInterface;
  1185. }
  1186. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1187. {
  1188. host.loadFrom (context);
  1189. if (host != nullptr)
  1190. {
  1191. Vst::String128 name;
  1192. host->getName (name);
  1193. return kResultTrue;
  1194. }
  1195. return kNotImplemented;
  1196. }
  1197. private:
  1198. //==============================================================================
  1199. const JuceLibraryRefCount juceCount;
  1200. Atomic<int> refCount;
  1201. const PFactoryInfo factoryInfo;
  1202. ComSmartPtr<Vst::IHostApplication> host;
  1203. //==============================================================================
  1204. struct ClassEntry
  1205. {
  1206. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1207. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1208. : info2 (info), createFunction (fn), isUnicode (false) {}
  1209. PClassInfo2 info2;
  1210. PClassInfoW infoW;
  1211. CreateFunction createFunction;
  1212. bool isUnicode;
  1213. private:
  1214. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1215. };
  1216. OwnedArray<ClassEntry> classes;
  1217. //==============================================================================
  1218. template<class PClassInfoType>
  1219. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1220. {
  1221. if (info != nullptr)
  1222. {
  1223. zerostruct (*info);
  1224. if (ClassEntry* entry = classes[(int) index])
  1225. {
  1226. if (entry->isUnicode)
  1227. return kResultFalse;
  1228. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1229. return kResultOk;
  1230. }
  1231. }
  1232. jassertfalse;
  1233. return kInvalidArgument;
  1234. }
  1235. //==============================================================================
  1236. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1237. };
  1238. //==============================================================================
  1239. #ifndef JucePlugin_Vst3ComponentFlags
  1240. #if JucePlugin_IsSynth
  1241. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1242. #else
  1243. #define JucePlugin_Vst3ComponentFlags 0
  1244. #endif
  1245. #endif
  1246. #ifndef JucePlugin_Vst3Category
  1247. #if JucePlugin_IsSynth
  1248. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1249. #else
  1250. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1251. #endif
  1252. #endif
  1253. //==============================================================================
  1254. // The VST3 plugin entry point.
  1255. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1256. {
  1257. #if JUCE_WINDOWS
  1258. // Cunning trick to force this function to be exported. Life's too short to
  1259. // faff around creating .def files for this kind of thing.
  1260. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1261. #endif
  1262. if (globalFactory == nullptr)
  1263. {
  1264. globalFactory = new JucePluginFactory();
  1265. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1266. PClassInfo::kManyInstances,
  1267. kVstAudioEffectClass,
  1268. JucePlugin_Name,
  1269. JucePlugin_Vst3ComponentFlags,
  1270. JucePlugin_Vst3Category,
  1271. JucePlugin_Manufacturer,
  1272. JucePlugin_VersionString,
  1273. kVstVersionString);
  1274. globalFactory->registerClass (componentClass, createComponentInstance);
  1275. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1276. PClassInfo::kManyInstances,
  1277. kVstComponentControllerClass,
  1278. JucePlugin_Name,
  1279. JucePlugin_Vst3ComponentFlags,
  1280. JucePlugin_Vst3Category,
  1281. JucePlugin_Manufacturer,
  1282. JucePlugin_VersionString,
  1283. kVstVersionString);
  1284. globalFactory->registerClass (controllerClass, createControllerInstance);
  1285. }
  1286. else
  1287. {
  1288. globalFactory->addRef();
  1289. }
  1290. return dynamic_cast<IPluginFactory*> (globalFactory);
  1291. }
  1292. #endif //JucePlugin_Build_VST3