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.

2456 lines
89KB

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