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.

1618 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. tresult PLUGIN_API setState (IBStream* state) override
  613. {
  614. if (state != nullptr)
  615. {
  616. // Reset to the beginning of the stream:
  617. if (state->seek (0, IBStream::kIBSeekSet, nullptr) != kResultTrue)
  618. return kResultFalse;
  619. Steinberg::int64 end = -1;
  620. if (end < 0)
  621. {
  622. FUnknownPtr<ISizeableStream> s (state);
  623. if (s != nullptr)
  624. s->getStreamSize (end);
  625. }
  626. if (end < 0)
  627. {
  628. FUnknownPtr<MemoryStream> s (state);
  629. if (s != nullptr)
  630. {
  631. if (getHostType().isAdobeAudition())
  632. {
  633. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  634. bool failed = true;
  635. if (const char* const data = s->getData())
  636. {
  637. if (s->getSize() >= 5 && data[0] != 'V' && data[1] != 'C'
  638. && data[2] != '2' && data[3] != '!' && data[4] != 'E')
  639. {
  640. failed = false;
  641. }
  642. }
  643. else
  644. {
  645. jassertfalse;
  646. }
  647. if (failed)
  648. return kResultFalse;
  649. }
  650. end = (Steinberg::int64) s->getSize();
  651. }
  652. }
  653. if (end <= 0)
  654. return kResultFalse;
  655. // Try reading the data, and setting the plugin state:
  656. Steinberg::int32 numBytes = (Steinberg::int32) jmin ((Steinberg::int64) std::numeric_limits<Steinberg::int32>::max(), end);
  657. Array<char> buff;
  658. buff.ensureStorageAllocated ((int) numBytes);
  659. void* buffer = buff.getRawDataPointer();
  660. if (state->read (buffer, numBytes, &numBytes) == kResultTrue
  661. && buffer != nullptr
  662. && numBytes > 0)
  663. {
  664. pluginInstance->setStateInformation (buffer, (int) numBytes);
  665. return kResultTrue;
  666. }
  667. return kResultFalse;
  668. }
  669. return kInvalidArgument;
  670. }
  671. tresult PLUGIN_API getState (IBStream* state) override
  672. {
  673. if (state != nullptr)
  674. {
  675. juce::MemoryBlock mem;
  676. pluginInstance->getStateInformation (mem);
  677. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  678. }
  679. return kInvalidArgument;
  680. }
  681. //==============================================================================
  682. Steinberg::int32 PLUGIN_API getUnitCount() override
  683. {
  684. return 1;
  685. }
  686. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  687. {
  688. if (unitIndex == 0)
  689. {
  690. info.id = Vst::kRootUnitId;
  691. info.parentUnitId = Vst::kNoParentUnitId;
  692. info.programListId = Vst::kNoProgramListId;
  693. toString128 (info.name, TRANS("Root Unit"));
  694. return kResultTrue;
  695. }
  696. zerostruct (info);
  697. return kResultFalse;
  698. }
  699. Steinberg::int32 PLUGIN_API getProgramListCount() override
  700. {
  701. if (getPluginInstance().getNumPrograms() > 0)
  702. return 1;
  703. return 0;
  704. }
  705. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  706. {
  707. if (listIndex == 0)
  708. {
  709. info.id = paramPreset;
  710. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  711. toString128 (info.name, TRANS("Factory Presets"));
  712. return kResultTrue;
  713. }
  714. jassertfalse;
  715. zerostruct (info);
  716. return kResultFalse;
  717. }
  718. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  719. {
  720. if (listId == paramPreset
  721. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  722. {
  723. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  724. return kResultTrue;
  725. }
  726. jassertfalse;
  727. toString128 (name, juce::String());
  728. return kResultFalse;
  729. }
  730. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  731. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  732. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  733. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  734. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  735. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  736. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection,
  737. Steinberg::int32, Steinberg::int32,
  738. Vst::UnitID& unitId) override
  739. {
  740. zerostruct (unitId);
  741. return kNotImplemented;
  742. }
  743. //==============================================================================
  744. bool getCurrentPosition (CurrentPositionInfo& info) override
  745. {
  746. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  747. info.timeInSeconds = processContext.projectTimeMusic;
  748. info.bpm = jmax (1.0, processContext.tempo);
  749. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  750. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  751. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  752. info.ppqPosition = processContext.projectTimeMusic;
  753. info.ppqLoopStart = processContext.cycleStartMusic;
  754. info.ppqLoopEnd = processContext.cycleEndMusic;
  755. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  756. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  757. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  758. info.editOriginTime = 0.0;
  759. info.frameRate = AudioPlayHead::fpsUnknown;
  760. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  761. {
  762. switch (processContext.frameRate.framesPerSecond)
  763. {
  764. case 24: info.frameRate = AudioPlayHead::fps24; break;
  765. case 25: info.frameRate = AudioPlayHead::fps25; break;
  766. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  767. case 30:
  768. {
  769. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  770. info.frameRate = AudioPlayHead::fps30drop;
  771. else
  772. info.frameRate = AudioPlayHead::fps30;
  773. }
  774. break;
  775. default: break;
  776. }
  777. }
  778. return true;
  779. }
  780. //==============================================================================
  781. static tresult setBusArrangementFor (Vst::BusList& list,
  782. Vst::SpeakerArrangement* arrangement,
  783. Steinberg::int32 numBusses)
  784. {
  785. if (arrangement != nullptr && numBusses == 1) //Should only be 1 bus per BusList
  786. {
  787. Steinberg::int32 counter = 0;
  788. FOREACH_CAST (IPtr<Vst::Bus>, Vst::AudioBus, bus, list)
  789. if (counter < numBusses)
  790. bus->setArrangement (arrangement[counter]);
  791. counter++;
  792. ENDFOR
  793. return kResultTrue;
  794. }
  795. return kResultFalse;
  796. }
  797. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  798. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  799. {
  800. #if JucePlugin_MaxNumInputChannels > 0
  801. if (setBusArrangementFor (audioInputs, inputs, numIns) != kResultTrue)
  802. return kResultFalse;
  803. #else
  804. if (numIns != 0)
  805. return kResultFalse;
  806. #endif
  807. #if JucePlugin_MaxNumOutputChannels > 0
  808. if (setBusArrangementFor (audioOutputs, outputs, numOuts) != kResultTrue)
  809. return kResultFalse;
  810. #else
  811. if (numOuts != 0)
  812. return kResultFalse;
  813. #endif
  814. return kResultTrue;
  815. }
  816. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  817. {
  818. if (Vst::BusList* const busList = getBusListFor (Vst::kAudio, dir))
  819. {
  820. if (Vst::AudioBus* const audioBus = FCast<Vst::AudioBus> (busList->at (index)))
  821. {
  822. arr = audioBus->getArrangement();
  823. return kResultTrue;
  824. }
  825. }
  826. return kResultFalse;
  827. }
  828. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  829. {
  830. return symbolicSampleSize == Vst::kSample32 ? kResultTrue : kResultFalse;
  831. }
  832. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  833. {
  834. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  835. }
  836. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  837. {
  838. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  839. return kResultFalse;
  840. processSetup = newSetup;
  841. processContext.sampleRate = processSetup.sampleRate;
  842. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  843. return kResultTrue;
  844. }
  845. tresult PLUGIN_API setProcessing (TBool state) override
  846. {
  847. if (state == kResultFalse)
  848. getPluginInstance().reset();
  849. return kResultTrue;
  850. }
  851. Steinberg::uint32 PLUGIN_API getTailSamples() override
  852. {
  853. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  854. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  855. return Vst::kNoTail;
  856. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  857. }
  858. //==============================================================================
  859. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  860. {
  861. jassert (pluginInstance != nullptr);
  862. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  863. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  864. {
  865. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  866. {
  867. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  868. Steinberg::int32 offsetSamples;
  869. double value = 0.0;
  870. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  871. {
  872. const int id = (int) paramQueue->getParameterId();
  873. jassert (isPositiveAndBelow (id, pluginInstance->getNumParameters()));
  874. pluginInstance->setParameter (id, (float) value);
  875. }
  876. }
  877. }
  878. }
  879. tresult PLUGIN_API process (Vst::ProcessData& data) override
  880. {
  881. if (pluginInstance == nullptr)
  882. return kResultFalse;
  883. if (data.processContext != nullptr)
  884. processContext = *data.processContext;
  885. else
  886. zerostruct (processContext);
  887. midiBuffer.clear();
  888. #if JucePlugin_WantsMidiInput
  889. if (data.inputEvents != nullptr)
  890. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  891. #endif
  892. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  893. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  894. #endif
  895. const int numInputChans = data.inputs != nullptr ? (int) data.inputs[0].numChannels : 0;
  896. const int numOutputChans = data.outputs != nullptr ? (int) data.outputs[0].numChannels : 0;
  897. int totalChans = 0;
  898. while (totalChans < numInputChans)
  899. {
  900. channelList.set (totalChans, data.inputs[0].channelBuffers32[totalChans]);
  901. ++totalChans;
  902. }
  903. while (totalChans < numOutputChans)
  904. {
  905. channelList.set (totalChans, data.outputs[0].channelBuffers32[totalChans]);
  906. ++totalChans;
  907. }
  908. AudioSampleBuffer buffer (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  909. {
  910. const ScopedLock sl (pluginInstance->getCallbackLock());
  911. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  912. if (data.inputParameterChanges != nullptr)
  913. processParameterChanges (*data.inputParameterChanges);
  914. if (pluginInstance->isSuspended())
  915. buffer.clear();
  916. else
  917. pluginInstance->processBlock (buffer, midiBuffer);
  918. }
  919. for (int i = 0; i < numOutputChans; ++i)
  920. FloatVectorOperations::copy (data.outputs[0].channelBuffers32[i], buffer.getSampleData (i), (int) data.numSamples);
  921. // clear extra busses..
  922. if (data.outputs != nullptr)
  923. for (int i = 1; i < data.numOutputs; ++i)
  924. for (int f = 0; f < data.outputs[i].numChannels; ++f)
  925. FloatVectorOperations::clear (data.outputs[i].channelBuffers32[f], (int) data.numSamples);
  926. #if JucePlugin_ProducesMidiOutput
  927. if (data.outputEvents != nullptr)
  928. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  929. #elif JUCE_DEBUG
  930. /* This assertion is caused when you've added some events to the
  931. midiMessages array in your processBlock() method, which usually means
  932. that you're trying to send them somewhere. But in this case they're
  933. getting thrown away.
  934. If your plugin does want to send MIDI messages, you'll need to set
  935. the JucePlugin_ProducesMidiOutput macro to 1 in your
  936. JucePluginCharacteristics.h file.
  937. If you don't want to produce any MIDI output, then you should clear the
  938. midiMessages array at the end of your processBlock() method, to
  939. indicate that you don't want any of the events to be passed through
  940. to the output.
  941. */
  942. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  943. #endif
  944. return kResultTrue;
  945. }
  946. private:
  947. //==============================================================================
  948. Atomic<int> refCount;
  949. AudioProcessor* pluginInstance;
  950. ComSmartPtr<Vst::IHostApplication> host;
  951. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  952. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  953. /**
  954. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  955. this object needs to be copied on every call to process() to be up-to-date...
  956. */
  957. Vst::ProcessContext processContext;
  958. Vst::ProcessSetup processSetup;
  959. Vst::BusList audioInputs, audioOutputs, eventInputs, eventOutputs;
  960. MidiBuffer midiBuffer;
  961. Array<float*> channelList;
  962. const JuceLibraryRefCount juceCount;
  963. //==============================================================================
  964. void addBusTo (Vst::BusList& busList, Vst::Bus* newBus)
  965. {
  966. busList.append (IPtr<Vst::Bus> (newBus, false));
  967. }
  968. void addAudioBusTo (Vst::BusList& busList, const juce::String& name, Vst::SpeakerArrangement arr)
  969. {
  970. addBusTo (busList, new Vst::AudioBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, arr));
  971. }
  972. void addEventBusTo (Vst::BusList& busList, const juce::String& name)
  973. {
  974. addBusTo (busList, new Vst::EventBus (toString (name), 16, Vst::kMain, Vst::BusInfo::kDefaultActive));
  975. }
  976. Vst::BusList* getBusListFor (Vst::MediaType type, Vst::BusDirection dir)
  977. {
  978. if (type == Vst::kAudio) return dir == Vst::kInput ? &audioInputs : &audioOutputs;
  979. if (type == Vst::kEvent) return dir == Vst::kInput ? &eventInputs : &eventOutputs;
  980. return nullptr;
  981. }
  982. //==============================================================================
  983. enum InternalParameters
  984. {
  985. paramPreset = 'prst'
  986. };
  987. void preparePlugin (double sampleRate, int bufferSize)
  988. {
  989. getPluginInstance().setPlayConfigDetails (JucePlugin_MaxNumInputChannels,
  990. JucePlugin_MaxNumOutputChannels,
  991. sampleRate, bufferSize);
  992. getPluginInstance().prepareToPlay (sampleRate, bufferSize);
  993. }
  994. //==============================================================================
  995. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  996. };
  997. //==============================================================================
  998. #if JUCE_MSVC
  999. #pragma warning (push, 0)
  1000. #pragma warning (disable: 4310)
  1001. #elif JUCE_CLANG
  1002. #pragma clang diagnostic push
  1003. #pragma clang diagnostic ignored "-w"
  1004. #endif
  1005. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1006. DEF_CLASS_IID (JuceAudioProcessor)
  1007. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1008. DEF_CLASS_IID (JuceVST3Component)
  1009. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1010. DEF_CLASS_IID (JuceVST3EditController)
  1011. #if JUCE_MSVC
  1012. #pragma warning (pop)
  1013. #elif JUCE_CLANG
  1014. #pragma clang diagnostic pop
  1015. #endif
  1016. //==============================================================================
  1017. bool initModule()
  1018. {
  1019. #if JUCE_MAC
  1020. initialiseMac();
  1021. #endif
  1022. return true;
  1023. }
  1024. bool shutdownModule()
  1025. {
  1026. return true;
  1027. }
  1028. #undef JUCE_EXPORTED_FUNCTION
  1029. #if JUCE_WINDOWS
  1030. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1031. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1032. #define JUCE_EXPORTED_FUNCTION
  1033. #else
  1034. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1035. CFBundleRef globalBundleInstance = nullptr;
  1036. juce::uint32 numBundleRefs = 0;
  1037. juce::Array<CFBundleRef> bundleRefs;
  1038. enum { MaxPathLength = 2048 };
  1039. char modulePath[MaxPathLength] = { 0 };
  1040. void* moduleHandle = nullptr;
  1041. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1042. {
  1043. if (ref != nullptr)
  1044. {
  1045. ++numBundleRefs;
  1046. CFRetain (ref);
  1047. bundleRefs.add (ref);
  1048. if (moduleHandle == nullptr)
  1049. {
  1050. globalBundleInstance = ref;
  1051. moduleHandle = ref;
  1052. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1053. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1054. CFRelease (tempURL);
  1055. }
  1056. }
  1057. return initModule();
  1058. }
  1059. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1060. {
  1061. if (shutdownModule())
  1062. {
  1063. if (--numBundleRefs == 0)
  1064. {
  1065. for (size_t i = 0; i < bundleRefs.size(); ++i)
  1066. CFRelease (bundleRefs.getUnchecked (i));
  1067. bundleRefs.clear();
  1068. }
  1069. return true;
  1070. }
  1071. return false;
  1072. }
  1073. #endif
  1074. //==============================================================================
  1075. /** This typedef represents VST3's createInstance() function signature */
  1076. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1077. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1078. {
  1079. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1080. }
  1081. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1082. {
  1083. return (Vst::IEditController*) new JuceVST3EditController (host);
  1084. }
  1085. //==============================================================================
  1086. class JucePluginFactory;
  1087. JucePluginFactory* globalFactory = nullptr;
  1088. //==============================================================================
  1089. class JucePluginFactory : public IPluginFactory3
  1090. {
  1091. public:
  1092. JucePluginFactory()
  1093. : refCount (1),
  1094. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1095. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1096. {
  1097. }
  1098. virtual ~JucePluginFactory()
  1099. {
  1100. if (globalFactory == this)
  1101. globalFactory = nullptr;
  1102. }
  1103. //==============================================================================
  1104. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1105. {
  1106. if (createFunction == nullptr)
  1107. {
  1108. jassertfalse;
  1109. return false;
  1110. }
  1111. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1112. entry->infoW.fromAscii (info);
  1113. return true;
  1114. }
  1115. bool isClassRegistered (const FUID& cid) const
  1116. {
  1117. for (int i = 0; i < classes.size(); ++i)
  1118. if (classes.getUnchecked (i)->infoW.cid == cid)
  1119. return true;
  1120. return false;
  1121. }
  1122. //==============================================================================
  1123. JUCE_DECLARE_VST3_COM_REF_METHODS
  1124. tresult PLUGIN_API queryInterface (const TUID iid, void** obj) override
  1125. {
  1126. TEST_FOR_AND_RETURN_IF_VALID (IPluginFactory3)
  1127. TEST_FOR_AND_RETURN_IF_VALID (IPluginFactory2)
  1128. TEST_FOR_AND_RETURN_IF_VALID (IPluginFactory)
  1129. TEST_FOR_AND_RETURN_IF_VALID (FUnknown)
  1130. jassertfalse; // Something new?
  1131. *obj = nullptr;
  1132. return kNotImplemented;
  1133. }
  1134. //==============================================================================
  1135. Steinberg::int32 PLUGIN_API countClasses() override
  1136. {
  1137. return (Steinberg::int32) classes.size();
  1138. }
  1139. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1140. {
  1141. if (info == nullptr)
  1142. return kInvalidArgument;
  1143. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1144. return kResultOk;
  1145. }
  1146. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1147. {
  1148. return getPClassInfo<PClassInfo> (index, info);
  1149. }
  1150. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1151. {
  1152. return getPClassInfo<PClassInfo2> (index, info);
  1153. }
  1154. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1155. {
  1156. if (info != nullptr)
  1157. {
  1158. if (ClassEntry* entry = classes[(int) index])
  1159. {
  1160. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1161. return kResultOk;
  1162. }
  1163. }
  1164. return kInvalidArgument;
  1165. }
  1166. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1167. {
  1168. *obj = nullptr;
  1169. FUID sourceFuid = sourceIid;
  1170. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1171. {
  1172. jassertfalse; // The host you're running in has severe implementation issues!
  1173. return kInvalidArgument;
  1174. }
  1175. TUID iidToQuery;
  1176. sourceFuid.toTUID (iidToQuery);
  1177. for (int i = 0; i < classes.size(); ++i)
  1178. {
  1179. const ClassEntry& entry = *classes.getUnchecked (i);
  1180. if (doUIDsMatch (entry.infoW.cid, cid))
  1181. {
  1182. if (FUnknown* const instance = entry.createFunction (host))
  1183. {
  1184. const FReleaser releaser (instance);
  1185. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1186. return kResultOk;
  1187. }
  1188. break;
  1189. }
  1190. }
  1191. return kNoInterface;
  1192. }
  1193. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1194. {
  1195. host.loadFrom (context);
  1196. if (host != nullptr)
  1197. {
  1198. Vst::String128 name;
  1199. host->getName (name);
  1200. return kResultTrue;
  1201. }
  1202. return kNotImplemented;
  1203. }
  1204. private:
  1205. //==============================================================================
  1206. const JuceLibraryRefCount juceCount;
  1207. Atomic<int> refCount;
  1208. const PFactoryInfo factoryInfo;
  1209. ComSmartPtr<Vst::IHostApplication> host;
  1210. //==============================================================================
  1211. struct ClassEntry
  1212. {
  1213. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1214. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1215. : info2 (info), createFunction (fn), isUnicode (false) {}
  1216. PClassInfo2 info2;
  1217. PClassInfoW infoW;
  1218. CreateFunction createFunction;
  1219. bool isUnicode;
  1220. private:
  1221. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1222. };
  1223. OwnedArray<ClassEntry> classes;
  1224. //==============================================================================
  1225. template<class PClassInfoType>
  1226. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1227. {
  1228. if (info != nullptr)
  1229. {
  1230. zerostruct (*info);
  1231. if (ClassEntry* entry = classes[(int) index])
  1232. {
  1233. if (entry->isUnicode)
  1234. return kResultFalse;
  1235. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1236. return kResultOk;
  1237. }
  1238. }
  1239. jassertfalse;
  1240. return kInvalidArgument;
  1241. }
  1242. //==============================================================================
  1243. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1244. };
  1245. //==============================================================================
  1246. #ifndef JucePlugin_Vst3ComponentFlags
  1247. #if JucePlugin_IsSynth
  1248. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1249. #else
  1250. #define JucePlugin_Vst3ComponentFlags 0
  1251. #endif
  1252. #endif
  1253. #ifndef JucePlugin_Vst3Category
  1254. #if JucePlugin_IsSynth
  1255. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1256. #else
  1257. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1258. #endif
  1259. #endif
  1260. //==============================================================================
  1261. // The VST3 plugin entry point.
  1262. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1263. {
  1264. #if JUCE_WINDOWS
  1265. // Cunning trick to force this function to be exported. Life's too short to
  1266. // faff around creating .def files for this kind of thing.
  1267. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1268. #endif
  1269. if (globalFactory == nullptr)
  1270. {
  1271. globalFactory = new JucePluginFactory();
  1272. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1273. PClassInfo::kManyInstances,
  1274. kVstAudioEffectClass,
  1275. JucePlugin_Name,
  1276. JucePlugin_Vst3ComponentFlags,
  1277. JucePlugin_Vst3Category,
  1278. JucePlugin_Manufacturer,
  1279. JucePlugin_VersionString,
  1280. kVstVersionString);
  1281. globalFactory->registerClass (componentClass, createComponentInstance);
  1282. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1283. PClassInfo::kManyInstances,
  1284. kVstComponentControllerClass,
  1285. JucePlugin_Name,
  1286. JucePlugin_Vst3ComponentFlags,
  1287. JucePlugin_Vst3Category,
  1288. JucePlugin_Manufacturer,
  1289. JucePlugin_VersionString,
  1290. kVstVersionString);
  1291. globalFactory->registerClass (controllerClass, createControllerInstance);
  1292. }
  1293. else
  1294. {
  1295. globalFactory->addRef();
  1296. }
  1297. return dynamic_cast<IPluginFactory*> (globalFactory);
  1298. }
  1299. #endif //JucePlugin_Build_VST3