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.

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