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.

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