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.

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