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.

1743 lines
59KB

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