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.

3277 lines
121KB

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