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.

1842 lines
63KB

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