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.

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