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.

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