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.

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