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.

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