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.

2441 lines
88KB

  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 { return kResultTrue; }
  565. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  566. {
  567. if (rectToCheck != nullptr && component != nullptr)
  568. {
  569. rectToCheck->right = rectToCheck->left + component->getWidth();
  570. rectToCheck->bottom = rectToCheck->top + component->getHeight();
  571. return kResultTrue;
  572. }
  573. jassertfalse;
  574. return kResultFalse;
  575. }
  576. private:
  577. //==============================================================================
  578. class ContentWrapperComponent : public Component
  579. {
  580. public:
  581. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  582. : owner (editor),
  583. pluginEditor (plugin.createEditorIfNeeded())
  584. {
  585. setOpaque (true);
  586. setBroughtToFrontOnMouseClick (true);
  587. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  588. jassert (pluginEditor != nullptr);
  589. if (pluginEditor != nullptr)
  590. {
  591. addAndMakeVisible (pluginEditor);
  592. setBounds (pluginEditor->getLocalBounds());
  593. resizeHostWindow();
  594. }
  595. }
  596. ~ContentWrapperComponent()
  597. {
  598. if (pluginEditor != nullptr)
  599. {
  600. PopupMenu::dismissAllActiveMenus();
  601. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  602. }
  603. }
  604. void paint (Graphics& g) override
  605. {
  606. g.fillAll (Colours::black);
  607. }
  608. void childBoundsChanged (Component*) override
  609. {
  610. resizeHostWindow();
  611. }
  612. void resized() override
  613. {
  614. if (pluginEditor != nullptr)
  615. pluginEditor->setBounds (getLocalBounds());
  616. }
  617. void resizeHostWindow()
  618. {
  619. if (pluginEditor != nullptr)
  620. {
  621. const int w = pluginEditor->getWidth();
  622. const int h = pluginEditor->getHeight();
  623. const PluginHostType host (getHostType());
  624. #if JUCE_WINDOWS
  625. setSize (w, h);
  626. #else
  627. if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper()))
  628. juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
  629. #endif
  630. if (owner.plugFrame != nullptr)
  631. {
  632. ViewRect newSize (0, 0, w, h);
  633. owner.plugFrame->resizeView (&owner, &newSize);
  634. #if JUCE_MAC
  635. if (host.isWavelab() || host.isReaper())
  636. #else
  637. if (host.isWavelab())
  638. #endif
  639. setBounds (0, 0, w, h);
  640. }
  641. }
  642. }
  643. private:
  644. JuceVST3Editor& owner;
  645. ScopedPointer<AudioProcessorEditor> pluginEditor;
  646. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  647. };
  648. //==============================================================================
  649. ComSmartPtr<JuceVST3EditController> owner;
  650. AudioProcessor& pluginInstance;
  651. ScopedPointer<ContentWrapperComponent> component;
  652. friend class ContentWrapperComponent;
  653. #if JUCE_MAC
  654. void* macHostWindow;
  655. bool isNSView;
  656. #endif
  657. #if JUCE_WINDOWS
  658. WindowsHooks hooks;
  659. #endif
  660. ScopedJuceInitialiser_GUI libraryInitialiser;
  661. //==============================================================================
  662. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  663. };
  664. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  665. };
  666. namespace
  667. {
  668. template <typename FloatType> struct AudioBusPointerHelper {};
  669. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  670. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  671. }
  672. //==============================================================================
  673. class JuceVST3Component : public Vst::IComponent,
  674. public Vst::IAudioProcessor,
  675. public Vst::IUnitInfo,
  676. public Vst::IConnectionPoint,
  677. public AudioPlayHead
  678. {
  679. public:
  680. JuceVST3Component (Vst::IHostApplication* h)
  681. : refCount (1),
  682. pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  683. host (h),
  684. isMidiInputBusEnabled (false),
  685. isMidiOutputBusEnabled (false),
  686. busUtils (*pluginInstance, false)
  687. {
  688. #if JucePlugin_WantsMidiInput
  689. isMidiInputBusEnabled = true;
  690. #endif
  691. #if JucePlugin_ProducesMidiOutput
  692. isMidiOutputBusEnabled = true;
  693. #endif
  694. busUtils.init();
  695. // VST-3 requires your default layout to be non-discrete!
  696. // For example, your default layout must be mono, stereo, quadrophonic
  697. // and not AudioChannelSet::discreteChannels (2) etc.
  698. jassert (busUtils.checkBusFormatsAreNotDiscrete());
  699. copyBusArrangements (currentBusState.inputBuses, pluginInstance->busArrangement.inputBuses, Vst::kInput);
  700. copyBusArrangements (currentBusState.outputBuses, pluginInstance->busArrangement.outputBuses, Vst::kOutput);
  701. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  702. zerostruct (processContext);
  703. processSetup.maxSamplesPerBlock = 1024;
  704. processSetup.processMode = Vst::kRealtime;
  705. processSetup.sampleRate = 44100.0;
  706. processSetup.symbolicSampleSize = Vst::kSample32;
  707. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  708. vstBypassParameterId = static_cast<Vst::ParamID> (pluginInstance->getNumParameters());
  709. #else
  710. cacheParameterIDs();
  711. #endif
  712. pluginInstance->setPlayHead (this);
  713. }
  714. ~JuceVST3Component()
  715. {
  716. if (pluginInstance != nullptr)
  717. if (pluginInstance->getPlayHead() == this)
  718. pluginInstance->setPlayHead (nullptr);
  719. }
  720. //==============================================================================
  721. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  722. //==============================================================================
  723. static const FUID iid;
  724. JUCE_DECLARE_VST3_COM_REF_METHODS
  725. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  726. {
  727. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  728. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  729. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  730. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  731. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  732. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  733. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  734. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  735. {
  736. comPluginInstance->addRef();
  737. *obj = comPluginInstance;
  738. return kResultOk;
  739. }
  740. *obj = nullptr;
  741. return kNoInterface;
  742. }
  743. //==============================================================================
  744. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  745. {
  746. if (host != hostContext)
  747. host.loadFrom (hostContext);
  748. processContext.sampleRate = processSetup.sampleRate;
  749. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  750. return kResultTrue;
  751. }
  752. tresult PLUGIN_API terminate() override
  753. {
  754. getPluginInstance().releaseResources();
  755. return kResultTrue;
  756. }
  757. //==============================================================================
  758. tresult PLUGIN_API connect (IConnectionPoint* other) override
  759. {
  760. if (other != nullptr && juceVST3EditController == nullptr)
  761. juceVST3EditController.loadFrom (other);
  762. return kResultTrue;
  763. }
  764. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  765. {
  766. juceVST3EditController = nullptr;
  767. return kResultTrue;
  768. }
  769. tresult PLUGIN_API notify (Vst::IMessage* message) override
  770. {
  771. if (message != nullptr && juceVST3EditController == nullptr)
  772. {
  773. Steinberg::int64 value = 0;
  774. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  775. {
  776. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  777. if (juceVST3EditController != nullptr)
  778. juceVST3EditController->setAudioProcessor (comPluginInstance);
  779. else
  780. jassertfalse;
  781. }
  782. }
  783. return kResultTrue;
  784. }
  785. tresult PLUGIN_API getControllerClassId (TUID classID) override
  786. {
  787. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  788. return kResultTrue;
  789. }
  790. //==============================================================================
  791. tresult PLUGIN_API setActive (TBool state) override
  792. {
  793. if (! state)
  794. {
  795. getPluginInstance().releaseResources();
  796. }
  797. else
  798. {
  799. double sampleRate = getPluginInstance().getSampleRate();
  800. int bufferSize = getPluginInstance().getBlockSize();
  801. sampleRate = processSetup.sampleRate > 0.0
  802. ? processSetup.sampleRate
  803. : sampleRate;
  804. bufferSize = processSetup.maxSamplesPerBlock > 0
  805. ? (int) processSetup.maxSamplesPerBlock
  806. : bufferSize;
  807. allocateChannelLists (channelListFloat);
  808. allocateChannelLists (channelListDouble);
  809. preparePlugin (sampleRate, bufferSize);
  810. }
  811. return kResultOk;
  812. }
  813. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  814. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  815. bool isBypassed() { return comPluginInstance->isBypassed; }
  816. void setBypassed (bool bypassed) { comPluginInstance->isBypassed = bypassed; }
  817. //==============================================================================
  818. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  819. {
  820. ValueTree privateData (kJucePrivateDataIdentifier);
  821. // for now we only store the bypass value
  822. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  823. privateData.writeToStream (out);
  824. }
  825. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  826. {
  827. ValueTree privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  828. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  829. }
  830. void getStateInformation (MemoryBlock& destData)
  831. {
  832. pluginInstance->getStateInformation (destData);
  833. // With bypass support, JUCE now needs to store private state data.
  834. // Put this at the end of the plug-in state and add a few null characters
  835. // so that plug-ins built with older versions of JUCE will hopefully ignore
  836. // this data. Additionally, we need to add some sort of magic identifier
  837. // at the very end of the private data so that JUCE has some sort of
  838. // way to figure out if the data was stored with a newer JUCE version.
  839. MemoryOutputStream extraData;
  840. extraData.writeInt64 (0);
  841. writeJucePrivateStateInformation (extraData);
  842. const int64 privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  843. extraData.writeInt64 (privateDataSize);
  844. extraData << kJucePrivateDataIdentifier;
  845. // write magic string
  846. destData.append (extraData.getData(), extraData.getDataSize());
  847. }
  848. void setStateInformation (const void* data, int sizeAsInt)
  849. {
  850. int64 size = sizeAsInt;
  851. // Check if this data was written with a newer JUCE version
  852. // and if it has the JUCE private data magic code at the end
  853. const size_t jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  854. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  855. {
  856. const char* buffer = static_cast<const char*> (data);
  857. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  858. CharPointer_UTF8 (buffer + size));
  859. if (magic == kJucePrivateDataIdentifier)
  860. {
  861. // found a JUCE private data section
  862. uint64 privateDataSize;
  863. std::memcpy (&privateDataSize,
  864. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  865. sizeof (uint64));
  866. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  867. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  868. if (privateDataSize > 0)
  869. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  870. size -= sizeof (uint64);
  871. }
  872. }
  873. if (size >= 0)
  874. pluginInstance->setStateInformation (data, static_cast<int> (size));
  875. }
  876. //==============================================================================
  877. #if JUCE_VST3_CAN_REPLACE_VST2
  878. void loadVST2VstWBlock (const char* data, int size)
  879. {
  880. const int headerLen = static_cast<int> (htonl (*(juce::int32*) (data + 4)));
  881. const struct fxBank* bank = (const struct fxBank*) (data + (8 + headerLen));
  882. const int version = static_cast<int> (htonl (bank->version)); ignoreUnused (version);
  883. jassert ('VstW' == htonl (*(juce::int32*) data));
  884. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  885. jassert (cMagic == htonl (bank->chunkMagic));
  886. jassert (chunkBankMagic == htonl (bank->fxMagic));
  887. jassert (version == 1 || version == 2);
  888. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  889. setStateInformation (bank->content.data.chunk,
  890. jmin ((int) (size - (bank->content.data.chunk - data)),
  891. (int) htonl (bank->content.data.size)));
  892. }
  893. bool loadVST3PresetFile (const char* data, int size)
  894. {
  895. if (size < 48)
  896. return false;
  897. // At offset 4 there's a little-endian version number which seems to typically be 1
  898. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  899. const int chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  900. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  901. const int entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  902. jassert (entryCount > 0);
  903. for (int i = 0; i < entryCount; ++i)
  904. {
  905. const int entryOffset = chunkListOffset + 8 + 20 * i;
  906. if (entryOffset + 20 > size)
  907. return false;
  908. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  909. {
  910. // "Comp" entries seem to contain the data.
  911. juce::uint64 chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  912. juce::uint64 chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  913. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  914. {
  915. jassertfalse;
  916. return false;
  917. }
  918. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  919. }
  920. }
  921. return true;
  922. }
  923. bool loadVST2CompatibleState (const char* data, int size)
  924. {
  925. if (size < 4)
  926. return false;
  927. if (htonl (*(juce::int32*) data) == 'VstW')
  928. {
  929. loadVST2VstWBlock (data, size);
  930. return true;
  931. }
  932. if (memcmp (data, "VST3", 4) == 0)
  933. {
  934. // In Cubase 5, when loading VST3 .vstpreset files,
  935. // we get the whole content of the files to load.
  936. // In Cubase 7 we get just the contents within and
  937. // we go directly to the loadVST2VstW codepath instead.
  938. return loadVST3PresetFile (data, size);
  939. }
  940. return false;
  941. }
  942. #endif
  943. bool loadStateData (const void* data, int size)
  944. {
  945. #if JUCE_VST3_CAN_REPLACE_VST2
  946. return loadVST2CompatibleState ((const char*) data, size);
  947. #else
  948. setStateInformation (data, size);
  949. return true;
  950. #endif
  951. }
  952. bool readFromMemoryStream (IBStream* state)
  953. {
  954. FUnknownPtr<MemoryStream> s (state);
  955. if (s != nullptr
  956. && s->getData() != nullptr
  957. && s->getSize() > 0
  958. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  959. {
  960. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  961. if (getHostType().isAdobeAudition())
  962. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  963. return false;
  964. return loadStateData (s->getData(), (int) s->getSize());
  965. }
  966. return false;
  967. }
  968. bool readFromUnknownStream (IBStream* state)
  969. {
  970. MemoryOutputStream allData;
  971. {
  972. const size_t bytesPerBlock = 4096;
  973. HeapBlock<char> buffer (bytesPerBlock);
  974. for (;;)
  975. {
  976. Steinberg::int32 bytesRead = 0;
  977. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  978. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  979. break;
  980. allData.write (buffer, static_cast<size_t> (bytesRead));
  981. }
  982. }
  983. const size_t dataSize = allData.getDataSize();
  984. return dataSize > 0 && dataSize < 0x7fffffff
  985. && loadStateData (allData.getData(), (int) dataSize);
  986. }
  987. tresult PLUGIN_API setState (IBStream* state) override
  988. {
  989. if (state == nullptr)
  990. return kInvalidArgument;
  991. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  992. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  993. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  994. return kResultTrue;
  995. return kResultFalse;
  996. }
  997. #if JUCE_VST3_CAN_REPLACE_VST2
  998. static tresult writeVST2Int (IBStream* state, int n)
  999. {
  1000. juce::int32 t = (juce::int32) htonl (n);
  1001. return state->write (&t, 4);
  1002. }
  1003. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1004. {
  1005. tresult status = writeVST2Int (state, 'VstW');
  1006. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1007. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1008. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1009. return status;
  1010. }
  1011. #endif
  1012. tresult PLUGIN_API getState (IBStream* state) override
  1013. {
  1014. if (state == nullptr)
  1015. return kInvalidArgument;
  1016. juce::MemoryBlock mem;
  1017. getStateInformation (mem);
  1018. #if JUCE_VST3_CAN_REPLACE_VST2
  1019. tresult status = writeVST2Header (state, isBypassed());
  1020. if (status != kResultOk)
  1021. return status;
  1022. const int bankBlockSize = 160;
  1023. struct fxBank bank;
  1024. zerostruct (bank);
  1025. bank.chunkMagic = (VstInt32) htonl (cMagic);
  1026. bank.byteSize = (VstInt32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1027. bank.fxMagic = (VstInt32) htonl (chunkBankMagic);
  1028. bank.version = (VstInt32) htonl (2);
  1029. bank.fxID = (VstInt32) htonl (JucePlugin_VSTUniqueID);
  1030. bank.fxVersion = (VstInt32) htonl (JucePlugin_VersionCode);
  1031. bank.content.data.size = (VstInt32) htonl ((unsigned int) mem.getSize());
  1032. status = state->write (&bank, bankBlockSize);
  1033. if (status != kResultOk)
  1034. return status;
  1035. #endif
  1036. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1037. }
  1038. //==============================================================================
  1039. Steinberg::int32 PLUGIN_API getUnitCount() override
  1040. {
  1041. return 1;
  1042. }
  1043. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  1044. {
  1045. if (unitIndex == 0)
  1046. {
  1047. info.id = Vst::kRootUnitId;
  1048. info.parentUnitId = Vst::kNoParentUnitId;
  1049. info.programListId = Vst::kNoProgramListId;
  1050. toString128 (info.name, TRANS("Root Unit"));
  1051. return kResultTrue;
  1052. }
  1053. zerostruct (info);
  1054. return kResultFalse;
  1055. }
  1056. Steinberg::int32 PLUGIN_API getProgramListCount() override
  1057. {
  1058. if (getPluginInstance().getNumPrograms() > 0)
  1059. return 1;
  1060. return 0;
  1061. }
  1062. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  1063. {
  1064. if (listIndex == 0)
  1065. {
  1066. info.id = paramPreset;
  1067. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1068. toString128 (info.name, TRANS("Factory Presets"));
  1069. return kResultTrue;
  1070. }
  1071. jassertfalse;
  1072. zerostruct (info);
  1073. return kResultFalse;
  1074. }
  1075. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1076. {
  1077. if (listId == paramPreset
  1078. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1079. {
  1080. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1081. return kResultTrue;
  1082. }
  1083. jassertfalse;
  1084. toString128 (name, juce::String());
  1085. return kResultFalse;
  1086. }
  1087. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1088. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1089. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1090. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1091. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1092. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1093. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1094. {
  1095. zerostruct (unitId);
  1096. return kNotImplemented;
  1097. }
  1098. //==============================================================================
  1099. bool getCurrentPosition (CurrentPositionInfo& info) override
  1100. {
  1101. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1102. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  1103. info.bpm = jmax (1.0, processContext.tempo);
  1104. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1105. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1106. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1107. info.ppqPosition = processContext.projectTimeMusic;
  1108. info.ppqLoopStart = processContext.cycleStartMusic;
  1109. info.ppqLoopEnd = processContext.cycleEndMusic;
  1110. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1111. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1112. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1113. info.editOriginTime = 0.0;
  1114. info.frameRate = AudioPlayHead::fpsUnknown;
  1115. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1116. {
  1117. switch (processContext.frameRate.framesPerSecond)
  1118. {
  1119. case 24: info.frameRate = AudioPlayHead::fps24; break;
  1120. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1121. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1122. case 30:
  1123. {
  1124. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1125. info.frameRate = AudioPlayHead::fps30drop;
  1126. else
  1127. info.frameRate = AudioPlayHead::fps30;
  1128. }
  1129. break;
  1130. default: break;
  1131. }
  1132. }
  1133. return true;
  1134. }
  1135. //==============================================================================
  1136. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1137. {
  1138. if (type == Vst::kAudio)
  1139. return (dir == Vst::kInput ? pluginInstance->busArrangement.inputBuses
  1140. : pluginInstance->busArrangement.outputBuses).size();
  1141. if (type == Vst::kEvent)
  1142. {
  1143. if (dir == Vst::kInput)
  1144. return isMidiInputBusEnabled ? 1 : 0;
  1145. if (dir == Vst::kOutput)
  1146. return isMidiOutputBusEnabled ? 1 : 0;
  1147. }
  1148. return 0;
  1149. }
  1150. static const AudioProcessor::AudioProcessorBus* getAudioBus (AudioProcessor::AudioBusArrangement& busArrangement,
  1151. Vst::BusDirection dir, Steinberg::int32 index) noexcept
  1152. {
  1153. const Array<AudioProcessor::AudioProcessorBus>& buses = dir == Vst::kInput ? busArrangement.inputBuses
  1154. : busArrangement.outputBuses;
  1155. return isPositiveAndBelow (index, static_cast<Steinberg::int32> (buses.size())) ? &buses.getReference (index) : nullptr;
  1156. }
  1157. const AudioProcessor::AudioProcessorBus* getAudioBus (Vst::BusDirection dir, Steinberg::int32 index) const noexcept
  1158. {
  1159. return getAudioBus (pluginInstance->busArrangement, dir, index);
  1160. }
  1161. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1162. Steinberg::int32 index, Vst::BusInfo& info) override
  1163. {
  1164. if (type == Vst::kAudio)
  1165. {
  1166. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (currentBusState, dir, index))
  1167. {
  1168. info.mediaType = Vst::kAudio;
  1169. info.direction = dir;
  1170. info.channelCount = bus->channels.size();
  1171. toString128 (info.name, bus->name);
  1172. #if JucePlugin_IsSynth
  1173. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1174. #else
  1175. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1176. #endif
  1177. info.flags = busUtils.isBusEnabledByDefault (dir == Vst::kInput, index) ? Vst::BusInfo::kDefaultActive : 0;
  1178. return kResultTrue;
  1179. }
  1180. }
  1181. if (type == Vst::kEvent)
  1182. {
  1183. info.flags = Vst::BusInfo::kDefaultActive;
  1184. #if JucePlugin_WantsMidiInput
  1185. if (dir == Vst::kInput)
  1186. {
  1187. info.mediaType = Vst::kEvent;
  1188. info.direction = dir;
  1189. info.channelCount = 16;
  1190. toString128 (info.name, TRANS("MIDI Input"));
  1191. info.busType = Vst::kMain;
  1192. return kResultTrue;
  1193. }
  1194. #endif
  1195. #if JucePlugin_ProducesMidiOutput
  1196. if (dir == Vst::kOutput)
  1197. {
  1198. info.mediaType = Vst::kEvent;
  1199. info.direction = dir;
  1200. info.channelCount = 16;
  1201. toString128 (info.name, TRANS("MIDI Output"));
  1202. info.busType = Vst::kMain;
  1203. return kResultTrue;
  1204. }
  1205. #endif
  1206. }
  1207. zerostruct (info);
  1208. return kResultFalse;
  1209. }
  1210. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1211. {
  1212. if (type == Vst::kEvent)
  1213. {
  1214. if (index != 0)
  1215. return kResultFalse;
  1216. if (dir == Vst::kInput)
  1217. isMidiInputBusEnabled = (state != 0);
  1218. else
  1219. isMidiOutputBusEnabled = (state != 0);
  1220. return kResultTrue;
  1221. }
  1222. if (type == Vst::kAudio)
  1223. {
  1224. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (dir, index))
  1225. {
  1226. if (state == (bus->channels.size() > 0))
  1227. return kResultTrue;
  1228. AudioChannelSet newChannels;
  1229. if (state)
  1230. if (const AudioProcessor::AudioProcessorBus* lastBusState = getAudioBus (currentBusState, dir, index))
  1231. newChannels = lastBusState->channels;
  1232. if (pluginInstance->setPreferredBusArrangement (dir == Vst::kInput, index, newChannels))
  1233. return kResultTrue;
  1234. }
  1235. }
  1236. return kResultFalse;
  1237. }
  1238. void copyBusArrangements (Array<AudioProcessor::AudioProcessorBus>& copies,
  1239. const Array<AudioProcessor::AudioProcessorBus>& source,
  1240. Vst::BusDirection dir)
  1241. {
  1242. for (int i = 0; i < source.size(); ++i)
  1243. {
  1244. AudioProcessor::AudioProcessorBus bus = source.getReference (i);
  1245. if (bus.channels.size() == 0 && i < copies.size())
  1246. bus = AudioProcessor::AudioProcessorBus (bus.name, copies.getReference (i).channels);
  1247. if (bus.channels.size() == 0)
  1248. bus = AudioProcessor::AudioProcessorBus (bus.name, busUtils.getDefaultLayoutForBus (dir == Vst::kInput, i));
  1249. copies.set (i, bus);
  1250. }
  1251. }
  1252. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1253. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1254. {
  1255. PluginBusUtilities::ScopedBusRestorer restorer (busUtils);
  1256. Array<bool> inputsEnabled, outputsEnabled;
  1257. // save enabled/disabled state of buses
  1258. for (int i = 0; i < busUtils.getBusCount (true); ++i)
  1259. inputsEnabled.add (busUtils.isBusEnabled (true, i));
  1260. for (int i = 0; i < busUtils.getBusCount (false); ++i)
  1261. outputsEnabled.add (busUtils.isBusEnabled (false, i));
  1262. // set the buses
  1263. for (int i = 0; i < numIns; ++i)
  1264. if (! pluginInstance->setPreferredBusArrangement (true, i, getChannelSetForSpeakerArrangement (inputs[i])))
  1265. return kInvalidArgument;
  1266. for (int i = 0; i < numOuts; ++i)
  1267. if (! pluginInstance->setPreferredBusArrangement (false, i, getChannelSetForSpeakerArrangement (outputs[i])))
  1268. return kInvalidArgument;
  1269. // re-check if the bus arrangement mateches the request
  1270. for (int i = 0; i < numIns; ++i)
  1271. if (getChannelSetForSpeakerArrangement (inputs[i]) != busUtils.getChannelSet (true, i))
  1272. return kInvalidArgument;
  1273. for (int i = 0; i < numOuts; ++i)
  1274. if (getChannelSetForSpeakerArrangement (outputs[i]) != busUtils.getChannelSet (false, i))
  1275. return kInvalidArgument;
  1276. // save the state of the plug-in layout
  1277. copyBusArrangements (currentBusState.inputBuses, pluginInstance->busArrangement.inputBuses, Vst::kInput);
  1278. copyBusArrangements (currentBusState.outputBuses, pluginInstance->busArrangement.outputBuses, Vst::kOutput);
  1279. // re-enable/disable the buses
  1280. for (int i = 0; i < busUtils.getBusCount (true); ++i)
  1281. if (! inputsEnabled.getReference (i) && busUtils.isBusEnabled (true, i))
  1282. if (! pluginInstance->setPreferredBusArrangement (true, i, AudioChannelSet()))
  1283. return kInvalidArgument;
  1284. for (int i = 0; i < busUtils.getBusCount (false); ++i)
  1285. if (! outputsEnabled.getReference (i) && busUtils.isBusEnabled (false, i))
  1286. if (! pluginInstance->setPreferredBusArrangement (false, i, AudioChannelSet()))
  1287. return kInvalidArgument;
  1288. restorer.release();
  1289. preparePlugin (getPluginInstance().getSampleRate(),
  1290. getPluginInstance().getBlockSize());
  1291. return kResultTrue;
  1292. }
  1293. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1294. {
  1295. if (const AudioProcessor::AudioProcessorBus* bus = getAudioBus (currentBusState, dir, index))
  1296. {
  1297. arr = getSpeakerArrangement (bus->channels);
  1298. return kResultTrue;
  1299. }
  1300. return kResultFalse;
  1301. }
  1302. //==============================================================================
  1303. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1304. {
  1305. return (symbolicSampleSize == Vst::kSample32
  1306. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1307. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1308. }
  1309. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1310. {
  1311. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1312. }
  1313. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1314. {
  1315. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1316. return kResultFalse;
  1317. processSetup = newSetup;
  1318. processContext.sampleRate = processSetup.sampleRate;
  1319. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1320. ? AudioProcessor::doublePrecision
  1321. : AudioProcessor::singlePrecision);
  1322. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1323. return kResultTrue;
  1324. }
  1325. tresult PLUGIN_API setProcessing (TBool state) override
  1326. {
  1327. if (! state)
  1328. getPluginInstance().reset();
  1329. return kResultTrue;
  1330. }
  1331. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1332. {
  1333. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1334. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1335. return Vst::kNoTail;
  1336. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1337. }
  1338. //==============================================================================
  1339. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1340. {
  1341. jassert (pluginInstance != nullptr);
  1342. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  1343. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1344. {
  1345. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  1346. {
  1347. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  1348. Steinberg::int32 offsetSamples;
  1349. double value = 0.0;
  1350. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1351. {
  1352. const Vst::ParamID vstParamID = paramQueue->getParameterId();
  1353. if (vstParamID == vstBypassParameterId)
  1354. setBypassed (static_cast<float> (value) != 0.0f);
  1355. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1356. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1357. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1358. #endif
  1359. else
  1360. {
  1361. const int index = getJuceIndexForVSTParamID (vstParamID);
  1362. if (isPositiveAndBelow (index, pluginInstance->getNumParameters()))
  1363. pluginInstance->setParameter (index, static_cast<float> (value));
  1364. }
  1365. }
  1366. }
  1367. }
  1368. }
  1369. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1370. {
  1371. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1372. int channel, ctrlNumber;
  1373. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1374. {
  1375. if (ctrlNumber == Vst::kAfterTouch)
  1376. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1377. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1378. else if (ctrlNumber == Vst::kPitchBend)
  1379. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1380. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1381. else
  1382. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1383. jlimit (0, 127, ctrlNumber),
  1384. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1385. }
  1386. }
  1387. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1388. {
  1389. if (pluginInstance == nullptr)
  1390. return kResultFalse;
  1391. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1392. return kResultFalse;
  1393. if (data.processContext != nullptr)
  1394. processContext = *data.processContext;
  1395. else
  1396. zerostruct (processContext);
  1397. midiBuffer.clear();
  1398. #if JucePlugin_WantsMidiInput
  1399. if (data.inputEvents != nullptr)
  1400. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1401. #endif
  1402. if (getHostType().isWavelab())
  1403. {
  1404. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1405. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1406. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1407. && (numInputChans + numOutputChans) == 0)
  1408. return kResultFalse;
  1409. }
  1410. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1411. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1412. else jassertfalse;
  1413. #if JucePlugin_ProducesMidiOutput
  1414. if (data.outputEvents != nullptr)
  1415. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1416. #endif
  1417. return kResultTrue;
  1418. }
  1419. private:
  1420. //==============================================================================
  1421. Atomic<int> refCount;
  1422. AudioProcessor* pluginInstance;
  1423. ComSmartPtr<Vst::IHostApplication> host;
  1424. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1425. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1426. /**
  1427. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1428. this object needs to be copied on every call to process() to be up-to-date...
  1429. */
  1430. Vst::ProcessContext processContext;
  1431. Vst::ProcessSetup processSetup;
  1432. MidiBuffer midiBuffer;
  1433. Array<float*> channelListFloat;
  1434. Array<double*> channelListDouble;
  1435. AudioProcessor::AudioBusArrangement currentBusState;
  1436. bool isMidiInputBusEnabled, isMidiOutputBusEnabled;
  1437. PluginBusUtilities busUtils;
  1438. ScopedJuceInitialiser_GUI libraryInitialiser;
  1439. #if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1440. bool usingManagedParameter;
  1441. Array<Vst::ParamID> vstParamIDs;
  1442. HashMap<int32, int> paramMap;
  1443. #endif
  1444. Vst::ParamID vstBypassParameterId;
  1445. static const char* kJucePrivateDataIdentifier;
  1446. //==============================================================================
  1447. template <typename FloatType>
  1448. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1449. {
  1450. int totalInputChans = 0;
  1451. const int plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1452. const int plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1453. if (data.inputs != nullptr)
  1454. {
  1455. for (int bus = 0; bus < data.numInputs && totalInputChans < plugInInputChannels; ++bus)
  1456. {
  1457. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1458. {
  1459. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1460. for (int i = 0; i < numChans; ++i)
  1461. if (busChannels[i] != nullptr)
  1462. channelList.set (totalInputChans++, busChannels[i]);
  1463. }
  1464. }
  1465. }
  1466. int totalOutputChans = 0;
  1467. if (data.outputs != nullptr)
  1468. {
  1469. for (int bus = 0; bus < data.numOutputs && totalOutputChans < plugInOutputChannels; ++bus)
  1470. {
  1471. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1472. {
  1473. const int numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1474. for (int i = 0; i < numChans; ++i)
  1475. {
  1476. if (busChannels[i] != nullptr)
  1477. {
  1478. if (totalOutputChans >= totalInputChans)
  1479. {
  1480. FloatVectorOperations::clear (busChannels[i], data.numSamples);
  1481. channelList.set (totalOutputChans, busChannels[i]);
  1482. }
  1483. ++totalOutputChans;
  1484. }
  1485. }
  1486. }
  1487. }
  1488. }
  1489. AudioBuffer<FloatType> buffer;
  1490. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1491. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1492. {
  1493. const ScopedLock sl (pluginInstance->getCallbackLock());
  1494. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1495. if (data.inputParameterChanges != nullptr)
  1496. processParameterChanges (*data.inputParameterChanges);
  1497. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1498. const int numMidiEventsComingIn = midiBuffer.getNumEvents ();
  1499. #endif
  1500. if (pluginInstance->isSuspended())
  1501. {
  1502. buffer.clear();
  1503. }
  1504. else
  1505. {
  1506. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1507. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1508. {
  1509. if (isBypassed())
  1510. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1511. else
  1512. pluginInstance->processBlock (buffer, midiBuffer);
  1513. }
  1514. }
  1515. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  1516. /* This assertion is caused when you've added some events to the
  1517. midiMessages array in your processBlock() method, which usually means
  1518. that you're trying to send them somewhere. But in this case they're
  1519. getting thrown away.
  1520. If your plugin does want to send MIDI messages, you'll need to set
  1521. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1522. JucePluginCharacteristics.h file.
  1523. If you don't want to produce any MIDI output, then you should clear the
  1524. midiMessages array at the end of your processBlock() method, to
  1525. indicate that you don't want any of the events to be passed through
  1526. to the output.
  1527. */
  1528. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1529. #endif
  1530. }
  1531. if (data.outputs != nullptr)
  1532. {
  1533. int outChanIndex = 0;
  1534. for (int bus = 0; bus < data.numOutputs; ++bus)
  1535. {
  1536. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1537. {
  1538. const int numChans = (int) data.outputs[bus].numChannels;
  1539. for (int i = 0; i < numChans; ++i)
  1540. {
  1541. if (outChanIndex < totalInputChans && busChannels[i] != nullptr)
  1542. FloatVectorOperations::copy (busChannels[i], buffer.getReadPointer (outChanIndex), (int) data.numSamples);
  1543. else if (outChanIndex >= totalOutputChans && busChannels[i] != nullptr)
  1544. FloatVectorOperations::clear (busChannels[i], (int) data.numSamples);
  1545. ++outChanIndex;
  1546. }
  1547. }
  1548. }
  1549. }
  1550. }
  1551. //==============================================================================
  1552. template <typename FloatType>
  1553. void allocateChannelLists (Array<FloatType*>& channelList)
  1554. {
  1555. channelList.clearQuick();
  1556. channelList.insertMultiple (0, nullptr, 128);
  1557. }
  1558. template <typename FloatType>
  1559. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1560. {
  1561. return AudioBusPointerHelper<FloatType>::impl (data);
  1562. }
  1563. //==============================================================================
  1564. enum InternalParameters
  1565. {
  1566. paramPreset = 'prst'
  1567. };
  1568. void preparePlugin (double sampleRate, int bufferSize)
  1569. {
  1570. AudioProcessor& p = getPluginInstance();
  1571. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1572. p.prepareToPlay (sampleRate, bufferSize);
  1573. }
  1574. //==============================================================================
  1575. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1576. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept { return static_cast<Vst::ParamID> (paramIndex); }
  1577. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept { return static_cast<int> (paramID); }
  1578. #else
  1579. void cacheParameterIDs()
  1580. {
  1581. const int numParameters = pluginInstance->getNumParameters();
  1582. usingManagedParameter = (pluginInstance->getParameters().size() == numParameters);
  1583. vstBypassParameterId = static_cast<Vst::ParamID> (usingManagedParameter ? kJuceVST3BypassParamID : numParameters);
  1584. for (int i = 0; i < numParameters; ++i)
  1585. {
  1586. const Vst::ParamID paramID = JuceVST3EditController::generateVSTParamIDForIndex (pluginInstance, i);
  1587. vstParamIDs.add (paramID);
  1588. paramMap.set (static_cast<int32> (paramID), i);
  1589. }
  1590. }
  1591. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
  1592. {
  1593. return usingManagedParameter ? vstParamIDs.getReference (paramIndex)
  1594. : static_cast<Vst::ParamID> (paramIndex);
  1595. }
  1596. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept
  1597. {
  1598. return usingManagedParameter ? paramMap[static_cast<int32> (paramID)]
  1599. : static_cast<int> (paramID);
  1600. }
  1601. #endif
  1602. //==============================================================================
  1603. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1604. };
  1605. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1606. Steinberg::FUID getJuceVST3ComponentIID();
  1607. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1608. #endif
  1609. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1610. //==============================================================================
  1611. #if JUCE_MSVC
  1612. #pragma warning (push, 0)
  1613. #pragma warning (disable: 4310)
  1614. #elif JUCE_CLANG
  1615. #pragma clang diagnostic push
  1616. #pragma clang diagnostic ignored "-Wall"
  1617. #endif
  1618. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1619. DEF_CLASS_IID (JuceAudioProcessor)
  1620. #if JUCE_VST3_CAN_REPLACE_VST2
  1621. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1622. static FUID getFUIDForVST2ID (bool forControllerUID)
  1623. {
  1624. char uidString[33];
  1625. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1626. char vstfxidStr[7] = { 0 };
  1627. sprintf (vstfxidStr, "%06X", vstfxid);
  1628. strcpy (uidString, vstfxidStr);
  1629. char uidStr[9] = { 0 };
  1630. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1631. strcat (uidString, uidStr);
  1632. char nameidStr[3] = { 0 };
  1633. const size_t len = strlen (JucePlugin_Name);
  1634. for (size_t i = 0; i <= 8; ++i)
  1635. {
  1636. juce::uint8 c = i < len ? static_cast<juce::uint8> (JucePlugin_Name[i]) : 0;
  1637. if (c >= 'A' && c <= 'Z')
  1638. c += 'a' - 'A';
  1639. sprintf (nameidStr, "%02X", c);
  1640. strcat (uidString, nameidStr);
  1641. }
  1642. FUID newOne;
  1643. newOne.fromString (uidString);
  1644. return newOne;
  1645. }
  1646. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1647. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1648. #else
  1649. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1650. DEF_CLASS_IID (JuceVST3EditController)
  1651. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1652. DEF_CLASS_IID (JuceVST3Component)
  1653. #endif
  1654. #if JUCE_MSVC
  1655. #pragma warning (pop)
  1656. #elif JUCE_CLANG
  1657. #pragma clang diagnostic pop
  1658. #endif
  1659. //==============================================================================
  1660. bool initModule()
  1661. {
  1662. #if JUCE_MAC
  1663. initialiseMacVST();
  1664. #endif
  1665. return true;
  1666. }
  1667. bool shutdownModule()
  1668. {
  1669. return true;
  1670. }
  1671. #undef JUCE_EXPORTED_FUNCTION
  1672. #if JUCE_WINDOWS
  1673. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1674. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1675. #define JUCE_EXPORTED_FUNCTION
  1676. #else
  1677. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1678. CFBundleRef globalBundleInstance = nullptr;
  1679. juce::uint32 numBundleRefs = 0;
  1680. juce::Array<CFBundleRef> bundleRefs;
  1681. enum { MaxPathLength = 2048 };
  1682. char modulePath[MaxPathLength] = { 0 };
  1683. void* moduleHandle = nullptr;
  1684. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1685. {
  1686. if (ref != nullptr)
  1687. {
  1688. ++numBundleRefs;
  1689. CFRetain (ref);
  1690. bundleRefs.add (ref);
  1691. if (moduleHandle == nullptr)
  1692. {
  1693. globalBundleInstance = ref;
  1694. moduleHandle = ref;
  1695. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1696. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1697. CFRelease (tempURL);
  1698. }
  1699. }
  1700. return initModule();
  1701. }
  1702. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1703. {
  1704. if (shutdownModule())
  1705. {
  1706. if (--numBundleRefs == 0)
  1707. {
  1708. for (int i = 0; i < bundleRefs.size(); ++i)
  1709. CFRelease (bundleRefs.getUnchecked (i));
  1710. bundleRefs.clear();
  1711. }
  1712. return true;
  1713. }
  1714. return false;
  1715. }
  1716. #endif
  1717. //==============================================================================
  1718. /** This typedef represents VST3's createInstance() function signature */
  1719. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1720. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1721. {
  1722. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1723. }
  1724. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1725. {
  1726. return (Vst::IEditController*) new JuceVST3EditController (host);
  1727. }
  1728. //==============================================================================
  1729. class JucePluginFactory;
  1730. static JucePluginFactory* globalFactory = nullptr;
  1731. //==============================================================================
  1732. class JucePluginFactory : public IPluginFactory3
  1733. {
  1734. public:
  1735. JucePluginFactory()
  1736. : refCount (1),
  1737. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1738. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1739. {
  1740. }
  1741. virtual ~JucePluginFactory()
  1742. {
  1743. if (globalFactory == this)
  1744. globalFactory = nullptr;
  1745. }
  1746. //==============================================================================
  1747. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1748. {
  1749. if (createFunction == nullptr)
  1750. {
  1751. jassertfalse;
  1752. return false;
  1753. }
  1754. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1755. entry->infoW.fromAscii (info);
  1756. return true;
  1757. }
  1758. bool isClassRegistered (const FUID& cid) const
  1759. {
  1760. for (int i = 0; i < classes.size(); ++i)
  1761. if (classes.getUnchecked (i)->infoW.cid == cid)
  1762. return true;
  1763. return false;
  1764. }
  1765. //==============================================================================
  1766. JUCE_DECLARE_VST3_COM_REF_METHODS
  1767. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1768. {
  1769. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1770. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1771. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1772. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1773. jassertfalse; // Something new?
  1774. *obj = nullptr;
  1775. return kNotImplemented;
  1776. }
  1777. //==============================================================================
  1778. Steinberg::int32 PLUGIN_API countClasses() override
  1779. {
  1780. return (Steinberg::int32) classes.size();
  1781. }
  1782. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1783. {
  1784. if (info == nullptr)
  1785. return kInvalidArgument;
  1786. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1787. return kResultOk;
  1788. }
  1789. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1790. {
  1791. return getPClassInfo<PClassInfo> (index, info);
  1792. }
  1793. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1794. {
  1795. return getPClassInfo<PClassInfo2> (index, info);
  1796. }
  1797. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1798. {
  1799. if (info != nullptr)
  1800. {
  1801. if (ClassEntry* entry = classes[(int) index])
  1802. {
  1803. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1804. return kResultOk;
  1805. }
  1806. }
  1807. return kInvalidArgument;
  1808. }
  1809. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1810. {
  1811. *obj = nullptr;
  1812. FUID sourceFuid = sourceIid;
  1813. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1814. {
  1815. jassertfalse; // The host you're running in has severe implementation issues!
  1816. return kInvalidArgument;
  1817. }
  1818. TUID iidToQuery;
  1819. sourceFuid.toTUID (iidToQuery);
  1820. for (int i = 0; i < classes.size(); ++i)
  1821. {
  1822. const ClassEntry& entry = *classes.getUnchecked (i);
  1823. if (doUIDsMatch (entry.infoW.cid, cid))
  1824. {
  1825. if (FUnknown* const instance = entry.createFunction (host))
  1826. {
  1827. const FReleaser releaser (instance);
  1828. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1829. return kResultOk;
  1830. }
  1831. break;
  1832. }
  1833. }
  1834. return kNoInterface;
  1835. }
  1836. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1837. {
  1838. host.loadFrom (context);
  1839. if (host != nullptr)
  1840. {
  1841. Vst::String128 name;
  1842. host->getName (name);
  1843. return kResultTrue;
  1844. }
  1845. return kNotImplemented;
  1846. }
  1847. private:
  1848. //==============================================================================
  1849. ScopedJuceInitialiser_GUI libraryInitialiser;
  1850. Atomic<int> refCount;
  1851. const PFactoryInfo factoryInfo;
  1852. ComSmartPtr<Vst::IHostApplication> host;
  1853. //==============================================================================
  1854. struct ClassEntry
  1855. {
  1856. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1857. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1858. : info2 (info), createFunction (fn), isUnicode (false) {}
  1859. PClassInfo2 info2;
  1860. PClassInfoW infoW;
  1861. CreateFunction createFunction;
  1862. bool isUnicode;
  1863. private:
  1864. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1865. };
  1866. OwnedArray<ClassEntry> classes;
  1867. //==============================================================================
  1868. template<class PClassInfoType>
  1869. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1870. {
  1871. if (info != nullptr)
  1872. {
  1873. zerostruct (*info);
  1874. if (ClassEntry* entry = classes[(int) index])
  1875. {
  1876. if (entry->isUnicode)
  1877. return kResultFalse;
  1878. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1879. return kResultOk;
  1880. }
  1881. }
  1882. jassertfalse;
  1883. return kInvalidArgument;
  1884. }
  1885. //==============================================================================
  1886. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1887. };
  1888. } // juce namespace
  1889. //==============================================================================
  1890. #ifndef JucePlugin_Vst3ComponentFlags
  1891. #if JucePlugin_IsSynth
  1892. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1893. #else
  1894. #define JucePlugin_Vst3ComponentFlags 0
  1895. #endif
  1896. #endif
  1897. #ifndef JucePlugin_Vst3Category
  1898. #if JucePlugin_IsSynth
  1899. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1900. #else
  1901. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1902. #endif
  1903. #endif
  1904. //==============================================================================
  1905. // The VST3 plugin entry point.
  1906. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1907. {
  1908. JUCE_DECLARE_WRAPPER_TYPE (wrapperType_VST3);
  1909. #if JUCE_WINDOWS
  1910. // Cunning trick to force this function to be exported. Life's too short to
  1911. // faff around creating .def files for this kind of thing.
  1912. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1913. #endif
  1914. if (globalFactory == nullptr)
  1915. {
  1916. globalFactory = new JucePluginFactory();
  1917. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1918. PClassInfo::kManyInstances,
  1919. kVstAudioEffectClass,
  1920. JucePlugin_Name,
  1921. JucePlugin_Vst3ComponentFlags,
  1922. JucePlugin_Vst3Category,
  1923. JucePlugin_Manufacturer,
  1924. JucePlugin_VersionString,
  1925. kVstVersionString);
  1926. globalFactory->registerClass (componentClass, createComponentInstance);
  1927. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1928. PClassInfo::kManyInstances,
  1929. kVstComponentControllerClass,
  1930. JucePlugin_Name,
  1931. JucePlugin_Vst3ComponentFlags,
  1932. JucePlugin_Vst3Category,
  1933. JucePlugin_Manufacturer,
  1934. JucePlugin_VersionString,
  1935. kVstVersionString);
  1936. globalFactory->registerClass (controllerClass, createControllerInstance);
  1937. }
  1938. else
  1939. {
  1940. globalFactory->addRef();
  1941. }
  1942. return dynamic_cast<IPluginFactory*> (globalFactory);
  1943. }
  1944. #endif //JucePlugin_Build_VST3