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.

2801 lines
102KB

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