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.

2269 lines
81KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI 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. #include "../../juce_core/system/juce_TargetPlatform.h"
  18. //==============================================================================
  19. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  20. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  21. #include "../utility/juce_CheckSettingMacros.h"
  22. #include "../utility/juce_IncludeModuleHeaders.h"
  23. #include "../utility/juce_WindowsHooks.h"
  24. #include "../utility/juce_PluginBusUtilities.h"
  25. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  26. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  27. #define JUCE_VST3_CAN_REPLACE_VST2 1
  28. #endif
  29. #ifndef JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  30. #define JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS 1
  31. #endif
  32. #if JUCE_VST3_CAN_REPLACE_VST2
  33. #if JUCE_MSVC
  34. #pragma warning (push)
  35. #pragma warning (disable: 4514 4996)
  36. #endif
  37. #include <pluginterfaces/vst2.x/vstfxstore.h>
  38. #if JUCE_MSVC
  39. #pragma warning (pop)
  40. #endif
  41. #endif
  42. JUCE_DEFINE_WRAPPER_TYPE (wrapperType_VST3);
  43. namespace juce
  44. {
  45. using namespace Steinberg;
  46. //==============================================================================
  47. #if JUCE_MAC
  48. extern void initialiseMacVST();
  49. #if ! JUCE_64BIT
  50. extern void updateEditorCompBoundsVST (Component*);
  51. #endif
  52. extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
  53. extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
  54. extern JUCE_API void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  55. #endif
  56. //==============================================================================
  57. class JuceAudioProcessor : public FUnknown
  58. {
  59. public:
  60. JuceAudioProcessor (AudioProcessor* source) noexcept
  61. : isBypassed (false), refCount (0), audioProcessor (source) {}
  62. virtual ~JuceAudioProcessor() {}
  63. AudioProcessor* get() const noexcept { return audioProcessor; }
  64. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  65. JUCE_DECLARE_VST3_COM_REF_METHODS
  66. static const FUID iid;
  67. bool isBypassed;
  68. private:
  69. Atomic<int> refCount;
  70. ScopedPointer<AudioProcessor> audioProcessor;
  71. ScopedJuceInitialiser_GUI libraryInitialiser;
  72. JuceAudioProcessor() JUCE_DELETED_FUNCTION;
  73. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  74. };
  75. //==============================================================================
  76. class JuceVST3EditController : public Vst::EditController,
  77. public Vst::IMidiMapping,
  78. public AudioProcessorListener
  79. {
  80. public:
  81. JuceVST3EditController (Vst::IHostApplication* host)
  82. {
  83. if (host != nullptr)
  84. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  85. }
  86. //==============================================================================
  87. static const FUID iid;
  88. //==============================================================================
  89. #if JUCE_CLANG
  90. #pragma clang diagnostic push
  91. #pragma clang diagnostic ignored "-Winconsistent-missing-override"
  92. #endif
  93. REFCOUNT_METHODS (ComponentBase)
  94. #if JUCE_CLANG
  95. #pragma clang diagnostic pop
  96. #endif
  97. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  98. {
  99. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  100. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  101. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  102. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  103. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  104. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  105. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  106. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  107. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  108. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  109. {
  110. audioProcessor->addRef();
  111. *obj = audioProcessor;
  112. return kResultOk;
  113. }
  114. *obj = nullptr;
  115. return kNoInterface;
  116. }
  117. //==============================================================================
  118. tresult PLUGIN_API initialize (FUnknown* context) override
  119. {
  120. if (hostContext != context)
  121. {
  122. if (hostContext != nullptr)
  123. hostContext->release();
  124. hostContext = context;
  125. if (hostContext != nullptr)
  126. hostContext->addRef();
  127. }
  128. return kResultTrue;
  129. }
  130. tresult PLUGIN_API terminate() override
  131. {
  132. if (AudioProcessor* const pluginInstance = getPluginInstance())
  133. pluginInstance->removeListener (this);
  134. audioProcessor = nullptr;
  135. return EditController::terminate();
  136. }
  137. //==============================================================================
  138. struct Param : public Vst::Parameter
  139. {
  140. Param (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  141. {
  142. info.id = (Vst::ParamID) index;
  143. toString128 (info.title, p.getParameterName (index));
  144. toString128 (info.shortTitle, p.getParameterName (index, 8));
  145. toString128 (info.units, p.getParameterLabel (index));
  146. const int numSteps = p.getParameterNumSteps (index);
  147. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  148. info.defaultNormalizedValue = p.getParameterDefaultValue (index);
  149. jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
  150. info.unitId = Vst::kRootUnitId;
  151. info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
  152. }
  153. virtual ~Param() {}
  154. bool setNormalized (Vst::ParamValue v) override
  155. {
  156. v = jlimit (0.0, 1.0, v);
  157. if (v != valueNormalized)
  158. {
  159. valueNormalized = v;
  160. changed();
  161. return true;
  162. }
  163. return false;
  164. }
  165. void toString (Vst::ParamValue value, Vst::String128 result) const override
  166. {
  167. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  168. toString128 (result, p->getText ((float) value, 128));
  169. else
  170. // remain backward-compatible with old JUCE code
  171. toString128 (result, owner.getParameterText (paramIndex, 128));
  172. }
  173. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  174. {
  175. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  176. {
  177. outValueNormalized = p->getValueForText (getStringFromVstTChars (text));
  178. return true;
  179. }
  180. return false;
  181. }
  182. static String getStringFromVstTChars (const Vst::TChar* text)
  183. {
  184. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  185. }
  186. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  187. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  188. private:
  189. AudioProcessor& owner;
  190. int paramIndex;
  191. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  192. };
  193. //==============================================================================
  194. struct BypassParam : public Vst::Parameter
  195. {
  196. BypassParam (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  197. {
  198. info.id = (Vst::ParamID) index;
  199. toString128 (info.title, "Bypass");
  200. toString128 (info.shortTitle, "Bypass");
  201. toString128 (info.units, "");
  202. info.stepCount = 1;
  203. info.defaultNormalizedValue = 0.0f;
  204. info.unitId = Vst::kRootUnitId;
  205. info.flags = Vst::ParameterInfo::kIsBypass | Vst::ParameterInfo::kCanAutomate;
  206. }
  207. virtual ~BypassParam() {}
  208. bool setNormalized (Vst::ParamValue v) override
  209. {
  210. bool bypass = (v != 0.0f);
  211. v = (bypass ? 1.0f : 0.0f);
  212. if (valueNormalized != v)
  213. {
  214. valueNormalized = v;
  215. changed();
  216. return true;
  217. }
  218. return false;
  219. }
  220. void toString (Vst::ParamValue value, Vst::String128 result) const override
  221. {
  222. bool bypass = (value != 0.0f);
  223. toString128 (result, bypass ? "On" : "Off");
  224. }
  225. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  226. {
  227. const String paramValueString (getStringFromVstTChars (text));
  228. if (paramValueString.equalsIgnoreCase ("on")
  229. || paramValueString.equalsIgnoreCase ("yes")
  230. || paramValueString.equalsIgnoreCase ("true"))
  231. {
  232. outValueNormalized = 1.0f;
  233. return true;
  234. }
  235. if (paramValueString.equalsIgnoreCase ("off")
  236. || paramValueString.equalsIgnoreCase ("no")
  237. || paramValueString.equalsIgnoreCase ("false"))
  238. {
  239. outValueNormalized = 0.0f;
  240. return true;
  241. }
  242. var varValue = JSON::fromString (paramValueString);
  243. if (varValue.isDouble() || varValue.isInt()
  244. || varValue.isInt64() || varValue.isBool())
  245. {
  246. double value = varValue;
  247. outValueNormalized = (value != 0.0) ? 1.0f : 0.0f;
  248. return true;
  249. }
  250. return false;
  251. }
  252. static String getStringFromVstTChars (const Vst::TChar* text)
  253. {
  254. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  255. }
  256. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  257. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  258. private:
  259. AudioProcessor& owner;
  260. int paramIndex;
  261. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BypassParam)
  262. };
  263. //==============================================================================
  264. tresult PLUGIN_API setComponentState (IBStream* stream) override
  265. {
  266. // Cubase and Nuendo need to inform the host of the current parameter values
  267. if (AudioProcessor* const pluginInstance = getPluginInstance())
  268. {
  269. const int numParameters = pluginInstance->getNumParameters();
  270. for (int i = 0; i < numParameters; ++i)
  271. setParamNormalized ((Vst::ParamID) i, (double) pluginInstance->getParameter (i));
  272. setParamNormalized ((Vst::ParamID) numParameters, audioProcessor->isBypassed ? 1.0f : 0.0f);
  273. }
  274. return Vst::EditController::setComponentState (stream);
  275. }
  276. void setAudioProcessor (JuceAudioProcessor* audioProc)
  277. {
  278. if (audioProcessor != audioProc)
  279. {
  280. audioProcessor = audioProc;
  281. setupParameters();
  282. }
  283. }
  284. tresult PLUGIN_API connect (IConnectionPoint* other) override
  285. {
  286. if (other != nullptr && audioProcessor == nullptr)
  287. {
  288. const tresult result = ComponentBase::connect (other);
  289. if (! audioProcessor.loadFrom (other))
  290. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  291. else
  292. setupParameters();
  293. return result;
  294. }
  295. jassertfalse;
  296. return kResultFalse;
  297. }
  298. //==============================================================================
  299. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
  300. Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
  301. {
  302. resultID = (Vst::ParamID) midiControllerToParameter[channel][midiControllerNumber];
  303. return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
  304. }
  305. // Converts an incoming parameter index to a MIDI controller:
  306. bool getMidiControllerForParameter (int index, int& channel, int& ctrlNumber)
  307. {
  308. const int mappedIndex = index - parameterToMidiControllerOffset;
  309. if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
  310. {
  311. const MidiController& mc = parameterToMidiController[mappedIndex];
  312. if (mc.channel != -1 && mc.ctrlNumber != -1)
  313. {
  314. channel = jlimit (1, 16, mc.channel + 1);
  315. ctrlNumber = mc.ctrlNumber;
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. //==============================================================================
  322. IPlugView* PLUGIN_API createView (const char* name) override
  323. {
  324. if (AudioProcessor* const pluginInstance = getPluginInstance())
  325. {
  326. if (pluginInstance->hasEditor() && name != nullptr
  327. && strcmp (name, Vst::ViewType::kEditor) == 0)
  328. {
  329. return new JuceVST3Editor (*this, *pluginInstance);
  330. }
  331. }
  332. return nullptr;
  333. }
  334. //==============================================================================
  335. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit ((Vst::ParamID) index); }
  336. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  337. {
  338. // NB: Cubase has problems if performEdit is called without setParamNormalized
  339. EditController::setParamNormalized ((Vst::ParamID) index, (double) newValue);
  340. performEdit ((Vst::ParamID) index, (double) newValue);
  341. }
  342. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit ((Vst::ParamID) index); }
  343. void audioProcessorChanged (AudioProcessor*) override
  344. {
  345. if (componentHandler != nullptr)
  346. componentHandler->restartComponent (Vst::kLatencyChanged | Vst::kParamValuesChanged);
  347. }
  348. //==============================================================================
  349. AudioProcessor* getPluginInstance() const noexcept
  350. {
  351. if (audioProcessor != nullptr)
  352. return audioProcessor->get();
  353. return nullptr;
  354. }
  355. private:
  356. //==============================================================================
  357. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  358. ScopedJuceInitialiser_GUI libraryInitialiser;
  359. struct MidiController
  360. {
  361. MidiController() noexcept : channel (-1), ctrlNumber (-1) {}
  362. int channel, ctrlNumber;
  363. };
  364. enum { numMIDIChannels = 16 };
  365. int parameterToMidiControllerOffset;
  366. MidiController parameterToMidiController[numMIDIChannels * Vst::kCountCtrlNumber];
  367. int midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
  368. //==============================================================================
  369. void setupParameters()
  370. {
  371. if (AudioProcessor* const pluginInstance = getPluginInstance())
  372. {
  373. pluginInstance->addListener (this);
  374. if (parameters.getParameterCount() <= 0)
  375. {
  376. const int numParameters = pluginInstance->getNumParameters();
  377. for (int i = 0; i < numParameters; ++i)
  378. parameters.addParameter (new Param (*pluginInstance, i));
  379. parameters.addParameter (new BypassParam (*pluginInstance, numParameters));
  380. }
  381. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  382. // (NB: the +1 is to account for the bypass parameter)
  383. initialiseMidiControllerMappings (pluginInstance->getNumParameters() + 1);
  384. #endif
  385. audioProcessorChanged (pluginInstance);
  386. }
  387. }
  388. void initialiseMidiControllerMappings (const int numVstParameters)
  389. {
  390. parameterToMidiControllerOffset = numVstParameters;
  391. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  392. {
  393. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  394. {
  395. midiControllerToParameter[c][i] = p + parameterToMidiControllerOffset;
  396. parameterToMidiController[p].channel = c;
  397. parameterToMidiController[p].ctrlNumber = i;
  398. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  399. (Vst::ParamID) (p + parameterToMidiControllerOffset), 0, 0, 0,
  400. Vst::ParameterInfo::kCanAutomate, Vst::kRootUnitId));
  401. }
  402. }
  403. }
  404. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  405. {
  406. jassert (hostContext != nullptr);
  407. if (Vst::IMessage* message = allocateMessage())
  408. {
  409. const FReleaser releaser (message);
  410. message->setMessageID (idTag);
  411. message->getAttributes()->setInt (idTag, value);
  412. sendMessage (message);
  413. }
  414. }
  415. //==============================================================================
  416. class JuceVST3Editor : public Vst::EditorView
  417. {
  418. public:
  419. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  420. : Vst::EditorView (&ec, nullptr),
  421. owner (&ec), pluginInstance (p)
  422. {
  423. #if JUCE_MAC
  424. macHostWindow = nullptr;
  425. isNSView = false;
  426. #endif
  427. component = new ContentWrapperComponent (*this, p);
  428. }
  429. //==============================================================================
  430. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  431. {
  432. if (type != nullptr && pluginInstance.hasEditor())
  433. {
  434. #if JUCE_WINDOWS
  435. if (strcmp (type, kPlatformTypeHWND) == 0)
  436. #else
  437. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  438. #endif
  439. return kResultTrue;
  440. }
  441. return kResultFalse;
  442. }
  443. tresult PLUGIN_API attached (void* parent, FIDString type) override
  444. {
  445. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  446. return kResultFalse;
  447. if (component == nullptr)
  448. component = new ContentWrapperComponent (*this, pluginInstance);
  449. #if JUCE_WINDOWS
  450. component->addToDesktop (0, parent);
  451. component->setOpaque (true);
  452. component->setVisible (true);
  453. #else
  454. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  455. macHostWindow = juce::attachComponentToWindowRefVST (component, parent, isNSView);
  456. #endif
  457. component->resizeHostWindow();
  458. systemWindow = parent;
  459. attachedToParent();
  460. return kResultTrue;
  461. }
  462. tresult PLUGIN_API removed() override
  463. {
  464. if (component != nullptr)
  465. {
  466. #if JUCE_WINDOWS
  467. component->removeFromDesktop();
  468. #else
  469. if (macHostWindow != nullptr)
  470. {
  471. juce::detachComponentFromWindowRefVST (component, macHostWindow, isNSView);
  472. macHostWindow = nullptr;
  473. }
  474. #endif
  475. component = nullptr;
  476. }
  477. return CPluginView::removed();
  478. }
  479. tresult PLUGIN_API onSize (ViewRect* newSize) override
  480. {
  481. if (newSize != nullptr)
  482. {
  483. rect = *newSize;
  484. if (component != nullptr)
  485. component->setSize (rect.getWidth(), rect.getHeight());
  486. return kResultTrue;
  487. }
  488. jassertfalse;
  489. return kResultFalse;
  490. }
  491. tresult PLUGIN_API getSize (ViewRect* size) override
  492. {
  493. if (size != nullptr && component != nullptr)
  494. {
  495. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  496. return kResultTrue;
  497. }
  498. return kResultFalse;
  499. }
  500. tresult PLUGIN_API canResize() override { return kResultTrue; }
  501. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  502. {
  503. if (rectToCheck != nullptr && component != nullptr)
  504. {
  505. rectToCheck->right = rectToCheck->left + component->getWidth();
  506. rectToCheck->bottom = rectToCheck->top + component->getHeight();
  507. return kResultTrue;
  508. }
  509. jassertfalse;
  510. return kResultFalse;
  511. }
  512. private:
  513. //==============================================================================
  514. class ContentWrapperComponent : public Component
  515. {
  516. public:
  517. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  518. : owner (editor),
  519. pluginEditor (plugin.createEditorIfNeeded())
  520. {
  521. setOpaque (true);
  522. setBroughtToFrontOnMouseClick (true);
  523. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  524. jassert (pluginEditor != nullptr);
  525. if (pluginEditor != nullptr)
  526. {
  527. addAndMakeVisible (pluginEditor);
  528. setBounds (pluginEditor->getLocalBounds());
  529. resizeHostWindow();
  530. }
  531. }
  532. ~ContentWrapperComponent()
  533. {
  534. if (pluginEditor != nullptr)
  535. {
  536. PopupMenu::dismissAllActiveMenus();
  537. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  538. }
  539. }
  540. void paint (Graphics& g) override
  541. {
  542. g.fillAll (Colours::black);
  543. }
  544. void childBoundsChanged (Component*) override
  545. {
  546. resizeHostWindow();
  547. }
  548. void resized() override
  549. {
  550. if (pluginEditor != nullptr)
  551. pluginEditor->setBounds (getLocalBounds());
  552. }
  553. void resizeHostWindow()
  554. {
  555. if (pluginEditor != nullptr)
  556. {
  557. const int w = pluginEditor->getWidth();
  558. const int h = pluginEditor->getHeight();
  559. const PluginHostType host (getHostType());
  560. #if JUCE_WINDOWS
  561. setSize (w, h);
  562. #else
  563. if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper()))
  564. juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
  565. #endif
  566. if (owner.plugFrame != nullptr)
  567. {
  568. ViewRect newSize (0, 0, w, h);
  569. owner.plugFrame->resizeView (&owner, &newSize);
  570. #if JUCE_MAC
  571. if (host.isWavelab() || host.isReaper())
  572. #else
  573. if (host.isWavelab())
  574. #endif
  575. setBounds (0, 0, w, h);
  576. }
  577. }
  578. }
  579. private:
  580. JuceVST3Editor& owner;
  581. ScopedPointer<AudioProcessorEditor> pluginEditor;
  582. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  583. };
  584. //==============================================================================
  585. ComSmartPtr<JuceVST3EditController> owner;
  586. AudioProcessor& pluginInstance;
  587. ScopedPointer<ContentWrapperComponent> component;
  588. friend class ContentWrapperComponent;
  589. #if JUCE_MAC
  590. void* macHostWindow;
  591. bool isNSView;
  592. #endif
  593. #if JUCE_WINDOWS
  594. WindowsHooks hooks;
  595. #endif
  596. ScopedJuceInitialiser_GUI libraryInitialiser;
  597. //==============================================================================
  598. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  599. };
  600. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  601. };
  602. namespace
  603. {
  604. template <typename FloatType> struct AudioBusPointerHelper {};
  605. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  606. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  607. }
  608. //==============================================================================
  609. class JuceVST3Component : public Vst::IComponent,
  610. public Vst::IAudioProcessor,
  611. public Vst::IUnitInfo,
  612. public Vst::IConnectionPoint,
  613. public AudioPlayHead
  614. {
  615. public:
  616. JuceVST3Component (Vst::IHostApplication* h)
  617. : refCount (1),
  618. pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  619. host (h),
  620. isMidiInputBusEnabled (false),
  621. isMidiOutputBusEnabled (false),
  622. busUtils (*pluginInstance, false)
  623. {
  624. #if JucePlugin_WantsMidiInput
  625. isMidiInputBusEnabled = true;
  626. #endif
  627. #if JucePlugin_ProducesMidiOutput
  628. isMidiOutputBusEnabled = true;
  629. #endif
  630. busUtils.init();
  631. // VST-3 requires your default layout to be non-discrete!
  632. // For example, your default layout must be mono, stereo, quadrophonic
  633. // and not AudioChannelSet::discreteChannels (2) etc.
  634. jassert (busUtils.checkBusFormatsAreNotDiscrete());
  635. copyEnabledBuses (lastEnabledBusStates.inputBuses, pluginInstance->busArrangement.inputBuses, Vst::kInput);
  636. copyEnabledBuses (lastEnabledBusStates.outputBuses, pluginInstance->busArrangement.outputBuses, Vst::kOutput);
  637. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  638. zerostruct (processContext);
  639. processSetup.maxSamplesPerBlock = 1024;
  640. processSetup.processMode = Vst::kRealtime;
  641. processSetup.sampleRate = 44100.0;
  642. processSetup.symbolicSampleSize = Vst::kSample32;
  643. vstBypassParameterId = pluginInstance->getNumParameters();
  644. pluginInstance->setPlayHead (this);
  645. }
  646. ~JuceVST3Component()
  647. {
  648. if (pluginInstance != nullptr)
  649. if (pluginInstance->getPlayHead() == this)
  650. pluginInstance->setPlayHead (nullptr);
  651. }
  652. //==============================================================================
  653. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  654. //==============================================================================
  655. static const FUID iid;
  656. JUCE_DECLARE_VST3_COM_REF_METHODS
  657. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  658. {
  659. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  660. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  661. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  662. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  663. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  664. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  665. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  666. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  667. {
  668. comPluginInstance->addRef();
  669. *obj = comPluginInstance;
  670. return kResultOk;
  671. }
  672. *obj = nullptr;
  673. return kNoInterface;
  674. }
  675. //==============================================================================
  676. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  677. {
  678. if (host != hostContext)
  679. host.loadFrom (hostContext);
  680. processContext.sampleRate = processSetup.sampleRate;
  681. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  682. return kResultTrue;
  683. }
  684. tresult PLUGIN_API terminate() override
  685. {
  686. getPluginInstance().releaseResources();
  687. return kResultTrue;
  688. }
  689. //==============================================================================
  690. tresult PLUGIN_API connect (IConnectionPoint* other) override
  691. {
  692. if (other != nullptr && juceVST3EditController == nullptr)
  693. juceVST3EditController.loadFrom (other);
  694. return kResultTrue;
  695. }
  696. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  697. {
  698. juceVST3EditController = nullptr;
  699. return kResultTrue;
  700. }
  701. tresult PLUGIN_API notify (Vst::IMessage* message) override
  702. {
  703. if (message != nullptr && juceVST3EditController == nullptr)
  704. {
  705. Steinberg::int64 value = 0;
  706. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  707. {
  708. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  709. if (juceVST3EditController != nullptr)
  710. juceVST3EditController->setAudioProcessor (comPluginInstance);
  711. else
  712. jassertfalse;
  713. }
  714. }
  715. return kResultTrue;
  716. }
  717. tresult PLUGIN_API getControllerClassId (TUID classID) override
  718. {
  719. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  720. return kResultTrue;
  721. }
  722. //==============================================================================
  723. tresult PLUGIN_API setActive (TBool state) override
  724. {
  725. if (! state)
  726. {
  727. getPluginInstance().releaseResources();
  728. }
  729. else
  730. {
  731. double sampleRate = getPluginInstance().getSampleRate();
  732. int bufferSize = getPluginInstance().getBlockSize();
  733. sampleRate = processSetup.sampleRate > 0.0
  734. ? processSetup.sampleRate
  735. : sampleRate;
  736. bufferSize = processSetup.maxSamplesPerBlock > 0
  737. ? (int) processSetup.maxSamplesPerBlock
  738. : bufferSize;
  739. allocateChannelLists (channelListFloat);
  740. allocateChannelLists (channelListDouble);
  741. preparePlugin (sampleRate, bufferSize);
  742. }
  743. return kResultOk;
  744. }
  745. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  746. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  747. bool isBypassed() { return comPluginInstance->isBypassed; }
  748. void setBypassed (bool bypassed) { comPluginInstance->isBypassed = bypassed; }
  749. //==============================================================================
  750. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  751. {
  752. ValueTree privateData (kJucePrivateDataIdentifier);
  753. // for now we only store the bypass value
  754. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  755. privateData.writeToStream (out);
  756. }
  757. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  758. {
  759. ValueTree privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  760. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  761. }
  762. void getStateInformation (MemoryBlock& destData)
  763. {
  764. pluginInstance->getStateInformation (destData);
  765. // With bypass support, JUCE now needs to store private state data.
  766. // Put this at the end of the plug-in state and add a few null characters
  767. // so that plug-ins built with older versions of JUCE will hopefully ignore
  768. // this data. Additionally, we need to add some sort of magic identifier
  769. // at the very end of the private data so that JUCE has some sort of
  770. // way to figure out if the data was stored with a newer JUCE version.
  771. MemoryOutputStream extraData;
  772. extraData.writeInt64 (0);
  773. writeJucePrivateStateInformation (extraData);
  774. const int64 privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  775. extraData.writeInt64 (privateDataSize);
  776. extraData << kJucePrivateDataIdentifier;
  777. // write magic string
  778. destData.append (extraData.getData(), extraData.getDataSize());
  779. }
  780. void setStateInformation (const void* data, int sizeAsInt)
  781. {
  782. int64 size = sizeAsInt;
  783. // Check if this data was written with a newer JUCE version
  784. // and if it has the JUCE private data magic code at the end
  785. const size_t jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  786. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  787. {
  788. const char* buffer = static_cast<const char*> (data);
  789. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  790. CharPointer_UTF8 (buffer + size));
  791. if (magic == kJucePrivateDataIdentifier)
  792. {
  793. // found a JUCE private data section
  794. uint64 privateDataSize;
  795. std::memcpy (&privateDataSize,
  796. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  797. sizeof (uint64));
  798. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  799. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  800. if (privateDataSize > 0)
  801. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  802. size -= sizeof (uint64);
  803. }
  804. }
  805. if (size >= 0)
  806. pluginInstance->setStateInformation (data, static_cast<int> (size));
  807. }
  808. //==============================================================================
  809. #if JUCE_VST3_CAN_REPLACE_VST2
  810. void loadVST2VstWBlock (const char* data, int size)
  811. {
  812. const int headerLen = static_cast<int> (htonl (*(juce::int32*) (data + 4)));
  813. const struct fxBank* bank = (const struct fxBank*) (data + (8 + headerLen));
  814. const int version = static_cast<int> (htonl (bank->version)); ignoreUnused (version);
  815. jassert ('VstW' == htonl (*(juce::int32*) data));
  816. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  817. jassert (cMagic == htonl (bank->chunkMagic));
  818. jassert (chunkBankMagic == htonl (bank->fxMagic));
  819. jassert (version == 1 || version == 2);
  820. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  821. setStateInformation (bank->content.data.chunk,
  822. jmin ((int) (size - (bank->content.data.chunk - data)),
  823. (int) htonl (bank->content.data.size)));
  824. }
  825. bool loadVST3PresetFile (const char* data, int size)
  826. {
  827. if (size < 48)
  828. return false;
  829. // At offset 4 there's a little-endian version number which seems to typically be 1
  830. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  831. const int chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  832. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  833. const int entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  834. jassert (entryCount > 0);
  835. for (int i = 0; i < entryCount; ++i)
  836. {
  837. const int entryOffset = chunkListOffset + 8 + 20 * i;
  838. if (entryOffset + 20 > size)
  839. return false;
  840. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  841. {
  842. // "Comp" entries seem to contain the data.
  843. juce::uint64 chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  844. juce::uint64 chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  845. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  846. {
  847. jassertfalse;
  848. return false;
  849. }
  850. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  851. }
  852. }
  853. return true;
  854. }
  855. bool loadVST2CompatibleState (const char* data, int size)
  856. {
  857. if (size < 4)
  858. return false;
  859. if (htonl (*(juce::int32*) data) == 'VstW')
  860. {
  861. loadVST2VstWBlock (data, size);
  862. return true;
  863. }
  864. if (memcmp (data, "VST3", 4) == 0)
  865. {
  866. // In Cubase 5, when loading VST3 .vstpreset files,
  867. // we get the whole content of the files to load.
  868. // In Cubase 7 we get just the contents within and
  869. // we go directly to the loadVST2VstW codepath instead.
  870. return loadVST3PresetFile (data, size);
  871. }
  872. return false;
  873. }
  874. #endif
  875. bool loadStateData (const void* data, int size)
  876. {
  877. #if JUCE_VST3_CAN_REPLACE_VST2
  878. return loadVST2CompatibleState ((const char*) data, size);
  879. #else
  880. setStateInformation (data, size);
  881. return true;
  882. #endif
  883. }
  884. bool readFromMemoryStream (IBStream* state)
  885. {
  886. FUnknownPtr<MemoryStream> s (state);
  887. if (s != nullptr
  888. && s->getData() != nullptr
  889. && s->getSize() > 0
  890. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  891. {
  892. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  893. if (getHostType().isAdobeAudition())
  894. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  895. return false;
  896. return loadStateData (s->getData(), (int) s->getSize());
  897. }
  898. return false;
  899. }
  900. bool readFromUnknownStream (IBStream* state)
  901. {
  902. MemoryOutputStream allData;
  903. {
  904. const size_t bytesPerBlock = 4096;
  905. HeapBlock<char> buffer (bytesPerBlock);
  906. for (;;)
  907. {
  908. Steinberg::int32 bytesRead = 0;
  909. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  910. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  911. break;
  912. allData.write (buffer, static_cast<size_t> (bytesRead));
  913. }
  914. }
  915. const size_t dataSize = allData.getDataSize();
  916. return dataSize > 0 && dataSize < 0x7fffffff
  917. && loadStateData (allData.getData(), (int) dataSize);
  918. }
  919. tresult PLUGIN_API setState (IBStream* state) override
  920. {
  921. if (state == nullptr)
  922. return kInvalidArgument;
  923. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  924. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  925. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  926. return kResultTrue;
  927. return kResultFalse;
  928. }
  929. #if JUCE_VST3_CAN_REPLACE_VST2
  930. static tresult writeVST2Int (IBStream* state, int n)
  931. {
  932. juce::int32 t = (juce::int32) htonl (n);
  933. return state->write (&t, 4);
  934. }
  935. static tresult writeVST2Header (IBStream* state, bool bypassed)
  936. {
  937. tresult status = writeVST2Int (state, 'VstW');
  938. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  939. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  940. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  941. return status;
  942. }
  943. #endif
  944. tresult PLUGIN_API getState (IBStream* state) override
  945. {
  946. if (state == nullptr)
  947. return kInvalidArgument;
  948. juce::MemoryBlock mem;
  949. getStateInformation (mem);
  950. #if JUCE_VST3_CAN_REPLACE_VST2
  951. tresult status = writeVST2Header (state, isBypassed());
  952. if (status != kResultOk)
  953. return status;
  954. const int bankBlockSize = 160;
  955. struct fxBank bank;
  956. zerostruct (bank);
  957. bank.chunkMagic = (VstInt32) htonl (cMagic);
  958. bank.byteSize = (VstInt32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  959. bank.fxMagic = (VstInt32) htonl (chunkBankMagic);
  960. bank.version = (VstInt32) htonl (2);
  961. bank.fxID = (VstInt32) htonl (JucePlugin_VSTUniqueID);
  962. bank.fxVersion = (VstInt32) htonl (JucePlugin_VersionCode);
  963. bank.content.data.size = (VstInt32) htonl ((unsigned int) mem.getSize());
  964. status = state->write (&bank, bankBlockSize);
  965. if (status != kResultOk)
  966. return status;
  967. #endif
  968. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  969. }
  970. //==============================================================================
  971. Steinberg::int32 PLUGIN_API getUnitCount() override
  972. {
  973. return 1;
  974. }
  975. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  976. {
  977. if (unitIndex == 0)
  978. {
  979. info.id = Vst::kRootUnitId;
  980. info.parentUnitId = Vst::kNoParentUnitId;
  981. info.programListId = Vst::kNoProgramListId;
  982. toString128 (info.name, TRANS("Root Unit"));
  983. return kResultTrue;
  984. }
  985. zerostruct (info);
  986. return kResultFalse;
  987. }
  988. Steinberg::int32 PLUGIN_API getProgramListCount() override
  989. {
  990. if (getPluginInstance().getNumPrograms() > 0)
  991. return 1;
  992. return 0;
  993. }
  994. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  995. {
  996. if (listIndex == 0)
  997. {
  998. info.id = paramPreset;
  999. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1000. toString128 (info.name, TRANS("Factory Presets"));
  1001. return kResultTrue;
  1002. }
  1003. jassertfalse;
  1004. zerostruct (info);
  1005. return kResultFalse;
  1006. }
  1007. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1008. {
  1009. if (listId == paramPreset
  1010. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1011. {
  1012. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1013. return kResultTrue;
  1014. }
  1015. jassertfalse;
  1016. toString128 (name, juce::String());
  1017. return kResultFalse;
  1018. }
  1019. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1020. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1021. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1022. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1023. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1024. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1025. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1026. {
  1027. zerostruct (unitId);
  1028. return kNotImplemented;
  1029. }
  1030. //==============================================================================
  1031. bool getCurrentPosition (CurrentPositionInfo& info) override
  1032. {
  1033. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1034. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  1035. info.bpm = jmax (1.0, processContext.tempo);
  1036. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1037. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1038. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1039. info.ppqPosition = processContext.projectTimeMusic;
  1040. info.ppqLoopStart = processContext.cycleStartMusic;
  1041. info.ppqLoopEnd = processContext.cycleEndMusic;
  1042. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1043. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1044. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1045. info.editOriginTime = 0.0;
  1046. info.frameRate = AudioPlayHead::fpsUnknown;
  1047. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1048. {
  1049. switch (processContext.frameRate.framesPerSecond)
  1050. {
  1051. case 24: info.frameRate = AudioPlayHead::fps24; break;
  1052. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1053. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1054. case 30:
  1055. {
  1056. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1057. info.frameRate = AudioPlayHead::fps30drop;
  1058. else
  1059. info.frameRate = AudioPlayHead::fps30;
  1060. }
  1061. break;
  1062. default: break;
  1063. }
  1064. }
  1065. return true;
  1066. }
  1067. //==============================================================================
  1068. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1069. {
  1070. if (type == Vst::kAudio)
  1071. return (dir == Vst::kInput ? pluginInstance->busArrangement.inputBuses
  1072. : pluginInstance->busArrangement.outputBuses).size();
  1073. if (type == Vst::kEvent)
  1074. {
  1075. if (dir == Vst::kInput)
  1076. return isMidiInputBusEnabled ? 1 : 0;
  1077. if (dir == Vst::kOutput)
  1078. return isMidiOutputBusEnabled ? 1 : 0;
  1079. }
  1080. return 0;
  1081. }
  1082. static const AudioProcessor::AudioProcessorBus* getAudioBus (AudioProcessor::AudioBusArrangement& busArrangement,
  1083. Vst::BusDirection dir, Steinberg::int32 index) noexcept
  1084. {
  1085. const Array<AudioProcessor::AudioProcessorBus>& buses = dir == Vst::kInput ? busArrangement.inputBuses
  1086. : busArrangement.outputBuses;
  1087. return isPositiveAndBelow (index, static_cast<Steinberg::int32> (buses.size())) ? &buses.getReference (index) : nullptr;
  1088. }
  1089. const AudioProcessor::AudioProcessorBus* getAudioBus (Vst::BusDirection dir, Steinberg::int32 index) const noexcept
  1090. {
  1091. return getAudioBus (pluginInstance->busArrangement, dir, index);
  1092. }
  1093. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1094. Steinberg::int32 index, Vst::BusInfo& info) override
  1095. {
  1096. if (type == Vst::kAudio)
  1097. {
  1098. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (lastEnabledBusStates, dir, index))
  1099. {
  1100. info.mediaType = Vst::kAudio;
  1101. info.direction = dir;
  1102. info.channelCount = bus->channels.size();
  1103. toString128 (info.name, bus->name);
  1104. info.busType = index == 0 ? Vst::kMain : Vst::kAux;
  1105. info.flags = busUtils.isBusEnabledByDefault (dir == Vst::kInput, index) ? Vst::BusInfo::kDefaultActive : 0;
  1106. return kResultTrue;
  1107. }
  1108. }
  1109. if (type == Vst::kEvent)
  1110. {
  1111. info.flags = Vst::BusInfo::kDefaultActive;
  1112. #if JucePlugin_WantsMidiInput
  1113. if (dir == Vst::kInput)
  1114. {
  1115. info.mediaType = Vst::kEvent;
  1116. info.direction = dir;
  1117. info.channelCount = 1;
  1118. toString128 (info.name, TRANS("MIDI Input"));
  1119. info.busType = Vst::kMain;
  1120. return kResultTrue;
  1121. }
  1122. #endif
  1123. #if JucePlugin_ProducesMidiOutput
  1124. if (dir == Vst::kOutput)
  1125. {
  1126. info.mediaType = Vst::kEvent;
  1127. info.direction = dir;
  1128. info.channelCount = 1;
  1129. toString128 (info.name, TRANS("MIDI Output"));
  1130. info.busType = Vst::kMain;
  1131. return kResultTrue;
  1132. }
  1133. #endif
  1134. }
  1135. zerostruct (info);
  1136. return kResultFalse;
  1137. }
  1138. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1139. {
  1140. if (type == Vst::kEvent)
  1141. {
  1142. if (index != 0)
  1143. return kResultFalse;
  1144. if (dir == Vst::kInput)
  1145. isMidiInputBusEnabled = (state != 0);
  1146. else
  1147. isMidiOutputBusEnabled = (state != 0);
  1148. return kResultTrue;
  1149. }
  1150. if (type == Vst::kAudio)
  1151. {
  1152. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (dir, index))
  1153. {
  1154. if (state == (bus->channels.size() > 0))
  1155. return kResultTrue;
  1156. AudioChannelSet newChannels;
  1157. if (state)
  1158. if (const AudioProcessor::AudioProcessorBus* lastBusState = getAudioBus (lastEnabledBusStates, dir, index))
  1159. newChannels = lastBusState->channels;
  1160. if (pluginInstance->setPreferredBusArrangement (dir == Vst::kInput, index, newChannels))
  1161. return kResultTrue;
  1162. }
  1163. }
  1164. return kResultFalse;
  1165. }
  1166. void copyEnabledBuses (Array<AudioProcessor::AudioProcessorBus>& copies,
  1167. const Array<AudioProcessor::AudioProcessorBus>& source,
  1168. Vst::BusDirection dir)
  1169. {
  1170. for (int i = 0; i < source.size(); ++i)
  1171. {
  1172. AudioProcessor::AudioProcessorBus bus = source.getReference (i);
  1173. if (bus.channels.size() == 0 && i < copies.size())
  1174. bus = AudioProcessor::AudioProcessorBus (bus.name, copies.getReference (i).channels);
  1175. if (bus.channels.size() == 0)
  1176. bus = AudioProcessor::AudioProcessorBus (bus.name, busUtils.getDefaultLayoutForBus (dir == Vst::kInput, i));
  1177. copies.set (i, bus);
  1178. }
  1179. }
  1180. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1181. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1182. {
  1183. PluginBusUtilities::ScopedBusRestorer restorer (busUtils);
  1184. for (int i = 0; i < numIns; ++i)
  1185. if (! pluginInstance->setPreferredBusArrangement (true, i, getChannelSetForSpeakerArrangement (inputs[i])))
  1186. return kInvalidArgument;
  1187. for (int i = 0; i < numOuts; ++i)
  1188. if (! pluginInstance->setPreferredBusArrangement (false, i, getChannelSetForSpeakerArrangement (outputs[i])))
  1189. return kInvalidArgument;
  1190. restorer.release();
  1191. preparePlugin (getPluginInstance().getSampleRate(),
  1192. getPluginInstance().getBlockSize());
  1193. copyEnabledBuses (lastEnabledBusStates.inputBuses, pluginInstance->busArrangement.inputBuses, Vst::kInput);
  1194. copyEnabledBuses (lastEnabledBusStates.outputBuses, pluginInstance->busArrangement.outputBuses, Vst::kOutput);
  1195. return kResultTrue;
  1196. }
  1197. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1198. {
  1199. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (lastEnabledBusStates, dir, index))
  1200. {
  1201. arr = getSpeakerArrangement (bus->channels);
  1202. return kResultTrue;
  1203. }
  1204. return kResultFalse;
  1205. }
  1206. //==============================================================================
  1207. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1208. {
  1209. return (symbolicSampleSize == Vst::kSample32
  1210. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1211. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1212. }
  1213. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1214. {
  1215. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1216. }
  1217. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1218. {
  1219. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1220. return kResultFalse;
  1221. processSetup = newSetup;
  1222. processContext.sampleRate = processSetup.sampleRate;
  1223. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1224. ? AudioProcessor::doublePrecision
  1225. : AudioProcessor::singlePrecision);
  1226. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1227. return kResultTrue;
  1228. }
  1229. tresult PLUGIN_API setProcessing (TBool state) override
  1230. {
  1231. if (! state)
  1232. getPluginInstance().reset();
  1233. return kResultTrue;
  1234. }
  1235. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1236. {
  1237. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1238. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1239. return Vst::kNoTail;
  1240. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1241. }
  1242. //==============================================================================
  1243. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1244. {
  1245. jassert (pluginInstance != nullptr);
  1246. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  1247. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1248. {
  1249. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  1250. {
  1251. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  1252. Steinberg::int32 offsetSamples;
  1253. double value = 0.0;
  1254. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1255. {
  1256. const int id = (int) paramQueue->getParameterId();
  1257. if (isPositiveAndBelow (id, pluginInstance->getNumParameters()))
  1258. pluginInstance->setParameter (id, static_cast<float> (value));
  1259. else if (id == vstBypassParameterId)
  1260. setBypassed (static_cast<float> (value) != 0.0f);
  1261. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1262. else
  1263. addParameterChangeToMidiBuffer (offsetSamples, id, value);
  1264. #endif
  1265. }
  1266. }
  1267. }
  1268. }
  1269. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const int id, const double value)
  1270. {
  1271. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1272. int channel, ctrlNumber;
  1273. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1274. {
  1275. if (ctrlNumber == Vst::kAfterTouch)
  1276. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1277. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1278. else if (ctrlNumber == Vst::kPitchBend)
  1279. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1280. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1281. else
  1282. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1283. jlimit (0, 127, ctrlNumber),
  1284. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1285. }
  1286. }
  1287. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1288. {
  1289. if (pluginInstance == nullptr)
  1290. return kResultFalse;
  1291. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1292. return kResultFalse;
  1293. if (data.processContext != nullptr)
  1294. processContext = *data.processContext;
  1295. else
  1296. zerostruct (processContext);
  1297. midiBuffer.clear();
  1298. #if JucePlugin_WantsMidiInput
  1299. if (data.inputEvents != nullptr)
  1300. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1301. #endif
  1302. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1303. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1304. #endif
  1305. if (getHostType().isWavelab())
  1306. {
  1307. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1308. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1309. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1310. && (numInputChans + numOutputChans) == 0)
  1311. return kResultFalse;
  1312. }
  1313. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1314. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1315. else jassertfalse;
  1316. #if JucePlugin_ProducesMidiOutput
  1317. if (data.outputEvents != nullptr)
  1318. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1319. #elif JUCE_DEBUG
  1320. /* This assertion is caused when you've added some events to the
  1321. midiMessages array in your processBlock() method, which usually means
  1322. that you're trying to send them somewhere. But in this case they're
  1323. getting thrown away.
  1324. If your plugin does want to send MIDI messages, you'll need to set
  1325. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1326. JucePluginCharacteristics.h file.
  1327. If you don't want to produce any MIDI output, then you should clear the
  1328. midiMessages array at the end of your processBlock() method, to
  1329. indicate that you don't want any of the events to be passed through
  1330. to the output.
  1331. */
  1332. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1333. #endif
  1334. return kResultTrue;
  1335. }
  1336. private:
  1337. //==============================================================================
  1338. Atomic<int> refCount;
  1339. AudioProcessor* pluginInstance;
  1340. ComSmartPtr<Vst::IHostApplication> host;
  1341. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1342. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1343. /**
  1344. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1345. this object needs to be copied on every call to process() to be up-to-date...
  1346. */
  1347. Vst::ProcessContext processContext;
  1348. Vst::ProcessSetup processSetup;
  1349. MidiBuffer midiBuffer;
  1350. Array<float*> channelListFloat;
  1351. Array<double*> channelListDouble;
  1352. AudioProcessor::AudioBusArrangement lastEnabledBusStates;
  1353. bool isMidiInputBusEnabled, isMidiOutputBusEnabled;
  1354. PluginBusUtilities busUtils;
  1355. ScopedJuceInitialiser_GUI libraryInitialiser;
  1356. int vstBypassParameterId;
  1357. static const char* kJucePrivateDataIdentifier;
  1358. //==============================================================================
  1359. template <typename FloatType>
  1360. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1361. {
  1362. int totalInputChans = 0;
  1363. const int plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1364. const int plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1365. if (data.inputs != nullptr)
  1366. {
  1367. for (int bus = 0; bus < data.numInputs && totalInputChans < plugInInputChannels; ++bus)
  1368. {
  1369. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1370. {
  1371. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1372. for (int i = 0; i < numChans; ++i)
  1373. channelList.set (totalInputChans++, busChannels[i]);
  1374. }
  1375. }
  1376. }
  1377. int totalOutputChans = 0;
  1378. if (data.outputs != nullptr)
  1379. {
  1380. for (int bus = 0; bus < data.numOutputs && totalOutputChans < plugInOutputChannels; ++bus)
  1381. {
  1382. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1383. {
  1384. const int numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1385. for (int i = 0; i < numChans; ++i)
  1386. {
  1387. if (totalOutputChans >= totalInputChans)
  1388. {
  1389. FloatVectorOperations::clear (busChannels[i], data.numSamples);
  1390. channelList.set (totalOutputChans, busChannels[i]);
  1391. }
  1392. ++totalOutputChans;
  1393. }
  1394. }
  1395. }
  1396. }
  1397. AudioBuffer<FloatType> buffer;
  1398. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1399. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1400. {
  1401. const ScopedLock sl (pluginInstance->getCallbackLock());
  1402. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1403. if (data.inputParameterChanges != nullptr)
  1404. processParameterChanges (*data.inputParameterChanges);
  1405. if (pluginInstance->isSuspended())
  1406. {
  1407. buffer.clear();
  1408. }
  1409. else
  1410. {
  1411. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1412. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1413. {
  1414. if (isBypassed())
  1415. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1416. else
  1417. pluginInstance->processBlock (buffer, midiBuffer);
  1418. }
  1419. }
  1420. }
  1421. if (data.outputs != nullptr)
  1422. {
  1423. int outChanIndex = 0;
  1424. for (int bus = 0; bus < data.numOutputs; ++bus)
  1425. {
  1426. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1427. {
  1428. const int numChans = (int) data.outputs[bus].numChannels;
  1429. for (int i = 0; i < numChans; ++i)
  1430. {
  1431. if (outChanIndex < totalInputChans)
  1432. FloatVectorOperations::copy (busChannels[i], buffer.getReadPointer (outChanIndex), (int) data.numSamples);
  1433. else if (outChanIndex >= totalOutputChans)
  1434. FloatVectorOperations::clear (busChannels[i], (int) data.numSamples);
  1435. ++outChanIndex;
  1436. }
  1437. }
  1438. }
  1439. }
  1440. }
  1441. //==============================================================================
  1442. template <typename FloatType>
  1443. void allocateChannelLists (Array<FloatType*>& channelList)
  1444. {
  1445. channelList.clearQuick();
  1446. channelList.insertMultiple (0, nullptr, 128);
  1447. }
  1448. template <typename FloatType>
  1449. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1450. {
  1451. return AudioBusPointerHelper<FloatType>::impl (data);
  1452. }
  1453. //==============================================================================
  1454. enum InternalParameters
  1455. {
  1456. paramPreset = 'prst'
  1457. };
  1458. void preparePlugin (double sampleRate, int bufferSize)
  1459. {
  1460. AudioProcessor& p = getPluginInstance();
  1461. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1462. p.prepareToPlay (sampleRate, bufferSize);
  1463. }
  1464. //==============================================================================
  1465. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1466. };
  1467. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1468. Steinberg::FUID getJuceVST3ComponentIID();
  1469. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1470. #endif
  1471. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1472. //==============================================================================
  1473. #if JUCE_MSVC
  1474. #pragma warning (push, 0)
  1475. #pragma warning (disable: 4310)
  1476. #elif JUCE_CLANG
  1477. #pragma clang diagnostic push
  1478. #pragma clang diagnostic ignored "-Wall"
  1479. #endif
  1480. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1481. DEF_CLASS_IID (JuceAudioProcessor)
  1482. #if JUCE_VST3_CAN_REPLACE_VST2
  1483. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1484. static FUID getFUIDForVST2ID (bool forControllerUID)
  1485. {
  1486. char uidString[33];
  1487. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1488. char vstfxidStr[7] = { 0 };
  1489. sprintf (vstfxidStr, "%06X", vstfxid);
  1490. strcpy (uidString, vstfxidStr);
  1491. char uidStr[9] = { 0 };
  1492. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1493. strcat (uidString, uidStr);
  1494. char nameidStr[3] = { 0 };
  1495. const size_t len = strlen (JucePlugin_Name);
  1496. for (size_t i = 0; i <= 8; ++i)
  1497. {
  1498. juce::uint8 c = i < len ? static_cast<juce::uint8> (JucePlugin_Name[i]) : 0;
  1499. if (c >= 'A' && c <= 'Z')
  1500. c += 'a' - 'A';
  1501. sprintf (nameidStr, "%02X", c);
  1502. strcat (uidString, nameidStr);
  1503. }
  1504. FUID newOne;
  1505. newOne.fromString (uidString);
  1506. return newOne;
  1507. }
  1508. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1509. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1510. #else
  1511. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1512. DEF_CLASS_IID (JuceVST3EditController)
  1513. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1514. DEF_CLASS_IID (JuceVST3Component)
  1515. #endif
  1516. #if JUCE_MSVC
  1517. #pragma warning (pop)
  1518. #elif JUCE_CLANG
  1519. #pragma clang diagnostic pop
  1520. #endif
  1521. //==============================================================================
  1522. bool initModule()
  1523. {
  1524. #if JUCE_MAC
  1525. initialiseMacVST();
  1526. #endif
  1527. return true;
  1528. }
  1529. bool shutdownModule()
  1530. {
  1531. return true;
  1532. }
  1533. #undef JUCE_EXPORTED_FUNCTION
  1534. #if JUCE_WINDOWS
  1535. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1536. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1537. #define JUCE_EXPORTED_FUNCTION
  1538. #else
  1539. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1540. CFBundleRef globalBundleInstance = nullptr;
  1541. juce::uint32 numBundleRefs = 0;
  1542. juce::Array<CFBundleRef> bundleRefs;
  1543. enum { MaxPathLength = 2048 };
  1544. char modulePath[MaxPathLength] = { 0 };
  1545. void* moduleHandle = nullptr;
  1546. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1547. {
  1548. if (ref != nullptr)
  1549. {
  1550. ++numBundleRefs;
  1551. CFRetain (ref);
  1552. bundleRefs.add (ref);
  1553. if (moduleHandle == nullptr)
  1554. {
  1555. globalBundleInstance = ref;
  1556. moduleHandle = ref;
  1557. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1558. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1559. CFRelease (tempURL);
  1560. }
  1561. }
  1562. return initModule();
  1563. }
  1564. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1565. {
  1566. if (shutdownModule())
  1567. {
  1568. if (--numBundleRefs == 0)
  1569. {
  1570. for (int i = 0; i < bundleRefs.size(); ++i)
  1571. CFRelease (bundleRefs.getUnchecked (i));
  1572. bundleRefs.clear();
  1573. }
  1574. return true;
  1575. }
  1576. return false;
  1577. }
  1578. #endif
  1579. //==============================================================================
  1580. /** This typedef represents VST3's createInstance() function signature */
  1581. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1582. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1583. {
  1584. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1585. }
  1586. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1587. {
  1588. return (Vst::IEditController*) new JuceVST3EditController (host);
  1589. }
  1590. //==============================================================================
  1591. class JucePluginFactory;
  1592. static JucePluginFactory* globalFactory = nullptr;
  1593. //==============================================================================
  1594. class JucePluginFactory : public IPluginFactory3
  1595. {
  1596. public:
  1597. JucePluginFactory()
  1598. : refCount (1),
  1599. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1600. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1601. {
  1602. }
  1603. virtual ~JucePluginFactory()
  1604. {
  1605. if (globalFactory == this)
  1606. globalFactory = nullptr;
  1607. }
  1608. //==============================================================================
  1609. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1610. {
  1611. if (createFunction == nullptr)
  1612. {
  1613. jassertfalse;
  1614. return false;
  1615. }
  1616. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1617. entry->infoW.fromAscii (info);
  1618. return true;
  1619. }
  1620. bool isClassRegistered (const FUID& cid) const
  1621. {
  1622. for (int i = 0; i < classes.size(); ++i)
  1623. if (classes.getUnchecked (i)->infoW.cid == cid)
  1624. return true;
  1625. return false;
  1626. }
  1627. //==============================================================================
  1628. JUCE_DECLARE_VST3_COM_REF_METHODS
  1629. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1630. {
  1631. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1632. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1633. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1634. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1635. jassertfalse; // Something new?
  1636. *obj = nullptr;
  1637. return kNotImplemented;
  1638. }
  1639. //==============================================================================
  1640. Steinberg::int32 PLUGIN_API countClasses() override
  1641. {
  1642. return (Steinberg::int32) classes.size();
  1643. }
  1644. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1645. {
  1646. if (info == nullptr)
  1647. return kInvalidArgument;
  1648. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1649. return kResultOk;
  1650. }
  1651. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1652. {
  1653. return getPClassInfo<PClassInfo> (index, info);
  1654. }
  1655. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1656. {
  1657. return getPClassInfo<PClassInfo2> (index, info);
  1658. }
  1659. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1660. {
  1661. if (info != nullptr)
  1662. {
  1663. if (ClassEntry* entry = classes[(int) index])
  1664. {
  1665. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1666. return kResultOk;
  1667. }
  1668. }
  1669. return kInvalidArgument;
  1670. }
  1671. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1672. {
  1673. *obj = nullptr;
  1674. FUID sourceFuid = sourceIid;
  1675. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1676. {
  1677. jassertfalse; // The host you're running in has severe implementation issues!
  1678. return kInvalidArgument;
  1679. }
  1680. TUID iidToQuery;
  1681. sourceFuid.toTUID (iidToQuery);
  1682. for (int i = 0; i < classes.size(); ++i)
  1683. {
  1684. const ClassEntry& entry = *classes.getUnchecked (i);
  1685. if (doUIDsMatch (entry.infoW.cid, cid))
  1686. {
  1687. if (FUnknown* const instance = entry.createFunction (host))
  1688. {
  1689. const FReleaser releaser (instance);
  1690. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1691. return kResultOk;
  1692. }
  1693. break;
  1694. }
  1695. }
  1696. return kNoInterface;
  1697. }
  1698. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1699. {
  1700. host.loadFrom (context);
  1701. if (host != nullptr)
  1702. {
  1703. Vst::String128 name;
  1704. host->getName (name);
  1705. return kResultTrue;
  1706. }
  1707. return kNotImplemented;
  1708. }
  1709. private:
  1710. //==============================================================================
  1711. ScopedJuceInitialiser_GUI libraryInitialiser;
  1712. Atomic<int> refCount;
  1713. const PFactoryInfo factoryInfo;
  1714. ComSmartPtr<Vst::IHostApplication> host;
  1715. //==============================================================================
  1716. struct ClassEntry
  1717. {
  1718. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1719. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1720. : info2 (info), createFunction (fn), isUnicode (false) {}
  1721. PClassInfo2 info2;
  1722. PClassInfoW infoW;
  1723. CreateFunction createFunction;
  1724. bool isUnicode;
  1725. private:
  1726. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1727. };
  1728. OwnedArray<ClassEntry> classes;
  1729. //==============================================================================
  1730. template<class PClassInfoType>
  1731. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1732. {
  1733. if (info != nullptr)
  1734. {
  1735. zerostruct (*info);
  1736. if (ClassEntry* entry = classes[(int) index])
  1737. {
  1738. if (entry->isUnicode)
  1739. return kResultFalse;
  1740. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1741. return kResultOk;
  1742. }
  1743. }
  1744. jassertfalse;
  1745. return kInvalidArgument;
  1746. }
  1747. //==============================================================================
  1748. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1749. };
  1750. } // juce namespace
  1751. //==============================================================================
  1752. #ifndef JucePlugin_Vst3ComponentFlags
  1753. #if JucePlugin_IsSynth
  1754. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1755. #else
  1756. #define JucePlugin_Vst3ComponentFlags 0
  1757. #endif
  1758. #endif
  1759. #ifndef JucePlugin_Vst3Category
  1760. #if JucePlugin_IsSynth
  1761. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1762. #else
  1763. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1764. #endif
  1765. #endif
  1766. //==============================================================================
  1767. // The VST3 plugin entry point.
  1768. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1769. {
  1770. JUCE_DECLARE_WRAPPER_TYPE (wrapperType_VST3);
  1771. #if JUCE_WINDOWS
  1772. // Cunning trick to force this function to be exported. Life's too short to
  1773. // faff around creating .def files for this kind of thing.
  1774. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1775. #endif
  1776. if (globalFactory == nullptr)
  1777. {
  1778. globalFactory = new JucePluginFactory();
  1779. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1780. PClassInfo::kManyInstances,
  1781. kVstAudioEffectClass,
  1782. JucePlugin_Name,
  1783. JucePlugin_Vst3ComponentFlags,
  1784. JucePlugin_Vst3Category,
  1785. JucePlugin_Manufacturer,
  1786. JucePlugin_VersionString,
  1787. kVstVersionString);
  1788. globalFactory->registerClass (componentClass, createComponentInstance);
  1789. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1790. PClassInfo::kManyInstances,
  1791. kVstComponentControllerClass,
  1792. JucePlugin_Name,
  1793. JucePlugin_Vst3ComponentFlags,
  1794. JucePlugin_Vst3Category,
  1795. JucePlugin_Manufacturer,
  1796. JucePlugin_VersionString,
  1797. kVstVersionString);
  1798. globalFactory->registerClass (controllerClass, createControllerInstance);
  1799. }
  1800. else
  1801. {
  1802. globalFactory->addRef();
  1803. }
  1804. return dynamic_cast<IPluginFactory*> (globalFactory);
  1805. }
  1806. #endif //JucePlugin_Build_VST3