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.

3265 lines
121KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  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. auto it = fdCallbackMap.find (fd);
  838. if (it != fdCallbackMap.end())
  839. it->second (fd);
  840. }
  841. #endif
  842. //==============================================================================
  843. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  844. {
  845. if (type != nullptr && pluginInstance.hasEditor())
  846. {
  847. #if JUCE_WINDOWS
  848. if (strcmp (type, kPlatformTypeHWND) == 0)
  849. #elif JUCE_MAC
  850. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  851. #elif JUCE_LINUX
  852. if (strcmp (type, kPlatformTypeX11EmbedWindowID) == 0)
  853. #endif
  854. return kResultTrue;
  855. }
  856. return kResultFalse;
  857. }
  858. tresult PLUGIN_API attached (void* parent, FIDString type) override
  859. {
  860. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  861. return kResultFalse;
  862. if (component == nullptr)
  863. component.reset (new ContentWrapperComponent (*this, pluginInstance));
  864. #if JUCE_WINDOWS || JUCE_LINUX
  865. component->addToDesktop (0, parent);
  866. component->setOpaque (true);
  867. component->setVisible (true);
  868. #if JUCE_LINUX
  869. if (auto* runLoop = getHostRunLoop())
  870. {
  871. for (auto& cb : getFdReadCallbacks())
  872. {
  873. fdCallbackMap[cb.first] = cb.second;
  874. runLoop->registerEventHandler (this, cb.first);
  875. }
  876. }
  877. #endif
  878. #else
  879. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  880. macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
  881. #endif
  882. component->resizeHostWindow();
  883. systemWindow = parent;
  884. attachedToParent();
  885. // Life's too short to faff around with wave lab
  886. if (getHostType().isWavelab())
  887. startTimer (200);
  888. return kResultTrue;
  889. }
  890. tresult PLUGIN_API removed() override
  891. {
  892. if (component != nullptr)
  893. {
  894. #if JUCE_WINDOWS || JUCE_LINUX
  895. component->removeFromDesktop();
  896. #if JUCE_LINUX
  897. fdCallbackMap.clear();
  898. if (auto* runLoop = getHostRunLoop())
  899. runLoop->unregisterEventHandler (this);
  900. #endif
  901. #else
  902. if (macHostWindow != nullptr)
  903. {
  904. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  905. macHostWindow = nullptr;
  906. }
  907. #endif
  908. component = nullptr;
  909. }
  910. return CPluginView::removed();
  911. }
  912. tresult PLUGIN_API onSize (ViewRect* newSize) override
  913. {
  914. if (newSize != nullptr)
  915. {
  916. rect = convertFromHostBounds (*newSize);
  917. if (component != nullptr)
  918. {
  919. auto w = rect.getWidth();
  920. auto h = rect.getHeight();
  921. component->setSize (w, h);
  922. #if JUCE_MAC
  923. if (cubase10Workaround != nullptr)
  924. {
  925. cubase10Workaround->triggerAsyncUpdate();
  926. }
  927. else
  928. #endif
  929. {
  930. if (auto* peer = component->getPeer())
  931. peer->updateBounds();
  932. }
  933. }
  934. return kResultTrue;
  935. }
  936. jassertfalse;
  937. return kResultFalse;
  938. }
  939. tresult PLUGIN_API getSize (ViewRect* size) override
  940. {
  941. if (size != nullptr && component != nullptr)
  942. {
  943. auto editorBounds = component->getSizeToContainChild();
  944. *size = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  945. return kResultTrue;
  946. }
  947. return kResultFalse;
  948. }
  949. tresult PLUGIN_API canResize() override
  950. {
  951. if (component != nullptr)
  952. if (auto* editor = component->pluginEditor.get())
  953. if (editor->isResizable())
  954. return kResultTrue;
  955. return kResultFalse;
  956. }
  957. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  958. {
  959. if (rectToCheck != nullptr && component != nullptr)
  960. {
  961. if (auto* editor = component->pluginEditor.get())
  962. {
  963. if (auto* constrainer = editor->getConstrainer())
  964. {
  965. *rectToCheck = convertFromHostBounds (*rectToCheck);
  966. auto transformScale = std::sqrt (std::abs (editor->getTransform().getDeterminant()));
  967. auto minW = (double) (constrainer->getMinimumWidth() * transformScale);
  968. auto maxW = (double) (constrainer->getMaximumWidth() * transformScale);
  969. auto minH = (double) (constrainer->getMinimumHeight() * transformScale);
  970. auto maxH = (double) (constrainer->getMaximumHeight() * transformScale);
  971. auto width = (double) (rectToCheck->right - rectToCheck->left);
  972. auto height = (double) (rectToCheck->bottom - rectToCheck->top);
  973. width = jlimit (minW, maxW, width);
  974. height = jlimit (minH, maxH, height);
  975. auto aspectRatio = constrainer->getFixedAspectRatio();
  976. if (aspectRatio != 0.0)
  977. {
  978. bool adjustWidth = (width / height > aspectRatio);
  979. if (getHostType().type == PluginHostType::SteinbergCubase9)
  980. {
  981. if (editor->getWidth() == width && editor->getHeight() != height)
  982. adjustWidth = true;
  983. else if (editor->getHeight() == height && editor->getWidth() != width)
  984. adjustWidth = false;
  985. }
  986. if (adjustWidth)
  987. {
  988. width = height * aspectRatio;
  989. if (width > maxW || width < minW)
  990. {
  991. width = jlimit (minW, maxW, width);
  992. height = width / aspectRatio;
  993. }
  994. }
  995. else
  996. {
  997. height = width / aspectRatio;
  998. if (height > maxH || height < minH)
  999. {
  1000. height = jlimit (minH, maxH, height);
  1001. width = height * aspectRatio;
  1002. }
  1003. }
  1004. }
  1005. rectToCheck->right = rectToCheck->left + roundToInt (width);
  1006. rectToCheck->bottom = rectToCheck->top + roundToInt (height);
  1007. *rectToCheck = convertToHostBounds (*rectToCheck);
  1008. }
  1009. }
  1010. return kResultTrue;
  1011. }
  1012. jassertfalse;
  1013. return kResultFalse;
  1014. }
  1015. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  1016. {
  1017. #if ! JUCE_MAC
  1018. if (! approximatelyEqual ((float) factor, editorScaleFactor))
  1019. {
  1020. editorScaleFactor = (float) factor;
  1021. if (owner != nullptr)
  1022. owner->lastScaleFactorReceived = editorScaleFactor;
  1023. if (component != nullptr)
  1024. {
  1025. if (auto* editor = component->pluginEditor.get())
  1026. {
  1027. editor->setScaleFactor (editorScaleFactor);
  1028. component->resizeHostWindow();
  1029. component->setTopLeftPosition (0, 0);
  1030. component->repaint();
  1031. }
  1032. }
  1033. }
  1034. return kResultTrue;
  1035. #else
  1036. ignoreUnused (factor);
  1037. return kResultFalse;
  1038. #endif
  1039. }
  1040. private:
  1041. void timerCallback() override
  1042. {
  1043. stopTimer();
  1044. ViewRect viewRect;
  1045. getSize (&viewRect);
  1046. onSize (&viewRect);
  1047. }
  1048. static ViewRect convertToHostBounds (ViewRect pluginRect)
  1049. {
  1050. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1051. if (approximatelyEqual (desktopScale, 1.0f))
  1052. return pluginRect;
  1053. return { roundToInt (pluginRect.left * desktopScale),
  1054. roundToInt (pluginRect.top * desktopScale),
  1055. roundToInt (pluginRect.right * desktopScale),
  1056. roundToInt (pluginRect.bottom * desktopScale) };
  1057. }
  1058. static ViewRect convertFromHostBounds (ViewRect hostRect)
  1059. {
  1060. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1061. if (approximatelyEqual (desktopScale, 1.0f))
  1062. return hostRect;
  1063. return { roundToInt (hostRect.left / desktopScale),
  1064. roundToInt (hostRect.top / desktopScale),
  1065. roundToInt (hostRect.right / desktopScale),
  1066. roundToInt (hostRect.bottom / desktopScale) };
  1067. }
  1068. //==============================================================================
  1069. struct ContentWrapperComponent : public Component
  1070. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1071. , private Timer
  1072. #endif
  1073. {
  1074. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  1075. : pluginEditor (plugin.createEditorIfNeeded()),
  1076. owner (editor)
  1077. {
  1078. setOpaque (true);
  1079. setBroughtToFrontOnMouseClick (true);
  1080. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  1081. jassert (pluginEditor != nullptr);
  1082. if (pluginEditor != nullptr)
  1083. {
  1084. addAndMakeVisible (pluginEditor.get());
  1085. pluginEditor->setTopLeftPosition (0, 0);
  1086. lastBounds = getSizeToContainChild();
  1087. {
  1088. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1089. setBounds (lastBounds);
  1090. }
  1091. resizeHostWindow();
  1092. }
  1093. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1094. startTimer (500);
  1095. #endif
  1096. ignoreUnused (fakeMouseGenerator);
  1097. }
  1098. ~ContentWrapperComponent() override
  1099. {
  1100. if (pluginEditor != nullptr)
  1101. {
  1102. PopupMenu::dismissAllActiveMenus();
  1103. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  1104. }
  1105. }
  1106. void paint (Graphics& g) override
  1107. {
  1108. g.fillAll (Colours::black);
  1109. }
  1110. juce::Rectangle<int> getSizeToContainChild()
  1111. {
  1112. if (pluginEditor != nullptr)
  1113. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  1114. return {};
  1115. }
  1116. void childBoundsChanged (Component*) override
  1117. {
  1118. if (resizingChild)
  1119. return;
  1120. auto b = getSizeToContainChild();
  1121. if (lastBounds != b)
  1122. {
  1123. lastBounds = b;
  1124. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1125. resizeHostWindow();
  1126. }
  1127. }
  1128. void resized() override
  1129. {
  1130. if (pluginEditor != nullptr)
  1131. {
  1132. if (! resizingParent)
  1133. {
  1134. auto newBounds = getLocalBounds();
  1135. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1136. if (! lastBounds.isEmpty() && isWithin (newBounds.toDouble().getAspectRatio(), lastBounds.toDouble().getAspectRatio(), 0.1))
  1137. return;
  1138. #endif
  1139. lastBounds = newBounds;
  1140. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1141. if (auto* constrainer = pluginEditor->getConstrainer())
  1142. {
  1143. auto aspectRatio = constrainer->getFixedAspectRatio();
  1144. if (aspectRatio != 0)
  1145. {
  1146. auto width = (double) lastBounds.getWidth();
  1147. auto height = (double) lastBounds.getHeight();
  1148. if (width / height > aspectRatio)
  1149. setBounds ({ 0, 0, roundToInt (height * aspectRatio), lastBounds.getHeight() });
  1150. else
  1151. setBounds ({ 0, 0, lastBounds.getWidth(), roundToInt (width / aspectRatio) });
  1152. }
  1153. }
  1154. pluginEditor->setTopLeftPosition (0, 0);
  1155. pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
  1156. }
  1157. }
  1158. }
  1159. void resizeHostWindow()
  1160. {
  1161. if (pluginEditor != nullptr)
  1162. {
  1163. auto b = getSizeToContainChild();
  1164. auto w = b.getWidth();
  1165. auto h = b.getHeight();
  1166. auto host = getHostType();
  1167. #if JUCE_WINDOWS
  1168. setSize (w, h);
  1169. #endif
  1170. if (owner.plugFrame != nullptr)
  1171. {
  1172. auto newSize = convertToHostBounds ({ 0, 0, b.getWidth(), b.getHeight() });
  1173. {
  1174. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1175. owner.plugFrame->resizeView (&owner, &newSize);
  1176. }
  1177. #if JUCE_MAC
  1178. if (host.isWavelab() || host.isReaper())
  1179. #else
  1180. if (host.isWavelab() || host.isAbletonLive())
  1181. #endif
  1182. setBounds (0, 0, w, h);
  1183. }
  1184. }
  1185. }
  1186. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  1187. private:
  1188. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1189. void timerCallback() override
  1190. {
  1191. auto hostWindowScale = (float) getScaleFactorForWindow ((HWND) owner.systemWindow);
  1192. if (hostWindowScale > 0.0 && ! approximatelyEqual (hostWindowScale, owner.editorScaleFactor))
  1193. owner.setContentScaleFactor (hostWindowScale);
  1194. }
  1195. #endif
  1196. JuceVST3Editor& owner;
  1197. FakeMouseMoveGenerator fakeMouseGenerator;
  1198. Rectangle<int> lastBounds;
  1199. bool resizingChild = false, resizingParent = false;
  1200. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  1201. };
  1202. //==============================================================================
  1203. ScopedJuceInitialiser_GUI libraryInitialiser;
  1204. ComSmartPtr<JuceVST3EditController> owner;
  1205. AudioProcessor& pluginInstance;
  1206. std::unique_ptr<ContentWrapperComponent> component;
  1207. friend struct ContentWrapperComponent;
  1208. #if JUCE_MAC
  1209. void* macHostWindow = nullptr;
  1210. bool isNSView = false;
  1211. // On macOS Cubase 10 resizes the host window after calling onSize() resulting in the peer
  1212. // bounds being a step behind the plug-in. Calling updateBounds() asynchronously seems to fix things...
  1213. struct Cubase10WindowResizeWorkaround : public AsyncUpdater
  1214. {
  1215. Cubase10WindowResizeWorkaround (JuceVST3Editor& o) : owner (o) {}
  1216. void handleAsyncUpdate() override
  1217. {
  1218. if (owner.component != nullptr)
  1219. if (auto* peer = owner.component->getPeer())
  1220. peer->updateBounds();
  1221. }
  1222. JuceVST3Editor& owner;
  1223. };
  1224. std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
  1225. #else
  1226. float editorScaleFactor = 1.0f;
  1227. #if JUCE_WINDOWS
  1228. WindowsHooks hooks;
  1229. #elif JUCE_LINUX
  1230. std::unordered_map<int, std::function<void(int)>> fdCallbackMap;
  1231. ::Display* display = XWindowSystem::getInstance()->getDisplay();
  1232. Steinberg::Linux::IRunLoop* getHostRunLoop()
  1233. {
  1234. Steinberg::Linux::IRunLoop* runLoop = nullptr;
  1235. if (plugFrame != nullptr)
  1236. plugFrame->queryInterface (Steinberg::Linux::IRunLoop::iid, (void**) &runLoop);
  1237. return runLoop;
  1238. }
  1239. #endif
  1240. #endif
  1241. //==============================================================================
  1242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  1243. };
  1244. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  1245. };
  1246. namespace
  1247. {
  1248. template <typename FloatType> struct AudioBusPointerHelper {};
  1249. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  1250. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  1251. template <typename FloatType> struct ChooseBufferHelper {};
  1252. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  1253. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  1254. }
  1255. //==============================================================================
  1256. class JuceVST3Component : public Vst::IComponent,
  1257. public Vst::IAudioProcessor,
  1258. public Vst::IUnitInfo,
  1259. public Vst::IConnectionPoint,
  1260. public AudioPlayHead
  1261. {
  1262. public:
  1263. JuceVST3Component (Vst::IHostApplication* h)
  1264. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  1265. host (h)
  1266. {
  1267. inParameterChangedCallback = false;
  1268. #ifdef JucePlugin_PreferredChannelConfigurations
  1269. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1270. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1271. ignoreUnused (numConfigs);
  1272. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1273. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1274. #endif
  1275. // VST-3 requires your default layout to be non-discrete!
  1276. // For example, your default layout must be mono, stereo, quadrophonic
  1277. // and not AudioChannelSet::discreteChannels (2) etc.
  1278. jassert (checkBusFormatsAreNotDiscrete());
  1279. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  1280. zerostruct (processContext);
  1281. processSetup.maxSamplesPerBlock = 1024;
  1282. processSetup.processMode = Vst::kRealtime;
  1283. processSetup.sampleRate = 44100.0;
  1284. processSetup.symbolicSampleSize = Vst::kSample32;
  1285. pluginInstance->setPlayHead (this);
  1286. }
  1287. ~JuceVST3Component() override
  1288. {
  1289. if (juceVST3EditController != nullptr)
  1290. juceVST3EditController->vst3IsPlaying = false;
  1291. if (pluginInstance != nullptr)
  1292. if (pluginInstance->getPlayHead() == this)
  1293. pluginInstance->setPlayHead (nullptr);
  1294. }
  1295. //==============================================================================
  1296. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1297. //==============================================================================
  1298. static const FUID iid;
  1299. JUCE_DECLARE_VST3_COM_REF_METHODS
  1300. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1301. {
  1302. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  1303. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  1304. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  1305. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  1306. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  1307. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  1308. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  1309. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  1310. {
  1311. comPluginInstance->addRef();
  1312. *obj = comPluginInstance;
  1313. return kResultOk;
  1314. }
  1315. *obj = nullptr;
  1316. return kNoInterface;
  1317. }
  1318. //==============================================================================
  1319. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1320. {
  1321. if (host != hostContext)
  1322. host.loadFrom (hostContext);
  1323. processContext.sampleRate = processSetup.sampleRate;
  1324. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  1325. return kResultTrue;
  1326. }
  1327. tresult PLUGIN_API terminate() override
  1328. {
  1329. getPluginInstance().releaseResources();
  1330. return kResultTrue;
  1331. }
  1332. //==============================================================================
  1333. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1334. {
  1335. if (other != nullptr && juceVST3EditController == nullptr)
  1336. juceVST3EditController.loadFrom (other);
  1337. return kResultTrue;
  1338. }
  1339. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1340. {
  1341. if (juceVST3EditController != nullptr)
  1342. juceVST3EditController->vst3IsPlaying = false;
  1343. juceVST3EditController = nullptr;
  1344. return kResultTrue;
  1345. }
  1346. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1347. {
  1348. if (message != nullptr && juceVST3EditController == nullptr)
  1349. {
  1350. Steinberg::int64 value = 0;
  1351. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1352. {
  1353. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  1354. if (juceVST3EditController != nullptr)
  1355. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1356. else
  1357. jassertfalse;
  1358. }
  1359. }
  1360. return kResultTrue;
  1361. }
  1362. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1363. {
  1364. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1365. return kResultTrue;
  1366. }
  1367. //==============================================================================
  1368. tresult PLUGIN_API setActive (TBool state) override
  1369. {
  1370. if (! state)
  1371. {
  1372. getPluginInstance().releaseResources();
  1373. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1374. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1375. }
  1376. else
  1377. {
  1378. auto sampleRate = getPluginInstance().getSampleRate();
  1379. auto bufferSize = getPluginInstance().getBlockSize();
  1380. sampleRate = processSetup.sampleRate > 0.0
  1381. ? processSetup.sampleRate
  1382. : sampleRate;
  1383. bufferSize = processSetup.maxSamplesPerBlock > 0
  1384. ? (int) processSetup.maxSamplesPerBlock
  1385. : bufferSize;
  1386. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1387. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1388. preparePlugin (sampleRate, bufferSize);
  1389. }
  1390. return kResultOk;
  1391. }
  1392. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1393. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1394. //==============================================================================
  1395. bool isBypassed()
  1396. {
  1397. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1398. return (bypassParam->getValue() != 0.0f);
  1399. return false;
  1400. }
  1401. void setBypassed (bool shouldBeBypassed)
  1402. {
  1403. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1404. {
  1405. auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
  1406. bypassParam->setValue (floatValue);
  1407. inParameterChangedCallback = true;
  1408. bypassParam->sendValueChangedMessageToListeners (floatValue);
  1409. }
  1410. }
  1411. //==============================================================================
  1412. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1413. {
  1414. if (pluginInstance->getBypassParameter() == nullptr)
  1415. {
  1416. ValueTree privateData (kJucePrivateDataIdentifier);
  1417. // for now we only store the bypass value
  1418. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1419. privateData.writeToStream (out);
  1420. }
  1421. }
  1422. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1423. {
  1424. if (pluginInstance->getBypassParameter() == nullptr)
  1425. {
  1426. if (comPluginInstance->getBypassParameter() != nullptr)
  1427. {
  1428. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1429. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1430. }
  1431. }
  1432. }
  1433. void getStateInformation (MemoryBlock& destData)
  1434. {
  1435. pluginInstance->getStateInformation (destData);
  1436. // With bypass support, JUCE now needs to store private state data.
  1437. // Put this at the end of the plug-in state and add a few null characters
  1438. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1439. // this data. Additionally, we need to add some sort of magic identifier
  1440. // at the very end of the private data so that JUCE has some sort of
  1441. // way to figure out if the data was stored with a newer JUCE version.
  1442. MemoryOutputStream extraData;
  1443. extraData.writeInt64 (0);
  1444. writeJucePrivateStateInformation (extraData);
  1445. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1446. extraData.writeInt64 (privateDataSize);
  1447. extraData << kJucePrivateDataIdentifier;
  1448. // write magic string
  1449. destData.append (extraData.getData(), extraData.getDataSize());
  1450. }
  1451. void setStateInformation (const void* data, int sizeAsInt)
  1452. {
  1453. auto size = (uint64) sizeAsInt;
  1454. // Check if this data was written with a newer JUCE version
  1455. // and if it has the JUCE private data magic code at the end
  1456. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1457. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1458. {
  1459. auto buffer = static_cast<const char*> (data);
  1460. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1461. CharPointer_UTF8 (buffer + size));
  1462. if (magic == kJucePrivateDataIdentifier)
  1463. {
  1464. // found a JUCE private data section
  1465. uint64 privateDataSize;
  1466. std::memcpy (&privateDataSize,
  1467. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1468. sizeof (uint64));
  1469. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1470. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1471. if (privateDataSize > 0)
  1472. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1473. size -= sizeof (uint64);
  1474. }
  1475. }
  1476. if (size > 0)
  1477. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1478. }
  1479. //==============================================================================
  1480. #if JUCE_VST3_CAN_REPLACE_VST2
  1481. bool loadVST2VstWBlock (const char* data, int size)
  1482. {
  1483. jassert ('VstW' == htonl (*(juce::int32*) data));
  1484. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1485. auto headerLen = (int) htonl (*(juce::int32*) (data + 4)) + 8;
  1486. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1487. }
  1488. bool loadVST2CcnKBlock (const char* data, int size)
  1489. {
  1490. auto bank = (const Vst2::fxBank*) data;
  1491. jassert ('CcnK' == htonl (bank->chunkMagic));
  1492. jassert ('FBCh' == htonl (bank->fxMagic));
  1493. jassert (htonl (bank->version) == 1 || htonl (bank->version) == 2);
  1494. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1495. setStateInformation (bank->content.data.chunk,
  1496. jmin ((int) (size - (bank->content.data.chunk - data)),
  1497. (int) htonl (bank->content.data.size)));
  1498. return true;
  1499. }
  1500. bool loadVST3PresetFile (const char* data, int size)
  1501. {
  1502. if (size < 48)
  1503. return false;
  1504. // At offset 4 there's a little-endian version number which seems to typically be 1
  1505. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1506. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1507. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1508. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1509. jassert (entryCount > 0);
  1510. for (int i = 0; i < entryCount; ++i)
  1511. {
  1512. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1513. if (entryOffset + 20 > size)
  1514. return false;
  1515. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1516. {
  1517. // "Comp" entries seem to contain the data.
  1518. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1519. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1520. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1521. {
  1522. jassertfalse;
  1523. return false;
  1524. }
  1525. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1526. }
  1527. }
  1528. return true;
  1529. }
  1530. bool loadVST2CompatibleState (const char* data, int size)
  1531. {
  1532. if (size < 4)
  1533. return false;
  1534. auto header = htonl (*(juce::int32*) data);
  1535. if (header == 'VstW')
  1536. return loadVST2VstWBlock (data, size);
  1537. if (header == 'CcnK')
  1538. return loadVST2CcnKBlock (data, size);
  1539. if (memcmp (data, "VST3", 4) == 0)
  1540. {
  1541. // In Cubase 5, when loading VST3 .vstpreset files,
  1542. // we get the whole content of the files to load.
  1543. // In Cubase 7 we get just the contents within and
  1544. // we go directly to the loadVST2VstW codepath instead.
  1545. return loadVST3PresetFile (data, size);
  1546. }
  1547. return false;
  1548. }
  1549. #endif
  1550. void loadStateData (const void* data, int size)
  1551. {
  1552. #if JUCE_VST3_CAN_REPLACE_VST2
  1553. if (loadVST2CompatibleState ((const char*) data, size))
  1554. return;
  1555. #endif
  1556. setStateInformation (data, size);
  1557. }
  1558. bool readFromMemoryStream (IBStream* state)
  1559. {
  1560. FUnknownPtr<ISizeableStream> s (state);
  1561. Steinberg::int64 size = 0;
  1562. if (s != nullptr
  1563. && s->getStreamSize (size) == kResultOk
  1564. && size > 0
  1565. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1566. {
  1567. MemoryBlock block (static_cast<size_t> (size));
  1568. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1569. Steinberg::int32 bytesRead = 1;
  1570. int len;
  1571. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1572. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1573. break;
  1574. if (len == 0)
  1575. return false;
  1576. block.setSize (static_cast<size_t> (len));
  1577. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1578. if (getHostType().isAdobeAudition())
  1579. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1580. return false;
  1581. loadStateData (block.getData(), (int) block.getSize());
  1582. return true;
  1583. }
  1584. return false;
  1585. }
  1586. bool readFromUnknownStream (IBStream* state)
  1587. {
  1588. MemoryOutputStream allData;
  1589. {
  1590. const size_t bytesPerBlock = 4096;
  1591. HeapBlock<char> buffer (bytesPerBlock);
  1592. for (;;)
  1593. {
  1594. Steinberg::int32 bytesRead = 0;
  1595. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1596. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1597. break;
  1598. allData.write (buffer, static_cast<size_t> (bytesRead));
  1599. }
  1600. }
  1601. const size_t dataSize = allData.getDataSize();
  1602. if (dataSize <= 0 || dataSize >= 0x7fffffff)
  1603. return false;
  1604. loadStateData (allData.getData(), (int) dataSize);
  1605. return true;
  1606. }
  1607. tresult PLUGIN_API setState (IBStream* state) override
  1608. {
  1609. if (state == nullptr)
  1610. return kInvalidArgument;
  1611. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1612. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1613. {
  1614. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1615. return kResultTrue;
  1616. if (readFromUnknownStream (state))
  1617. return kResultTrue;
  1618. }
  1619. return kResultFalse;
  1620. }
  1621. #if JUCE_VST3_CAN_REPLACE_VST2
  1622. static tresult writeVST2Int (IBStream* state, int n)
  1623. {
  1624. juce::int32 t = (juce::int32) htonl (n);
  1625. return state->write (&t, 4);
  1626. }
  1627. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1628. {
  1629. tresult status = writeVST2Int (state, 'VstW');
  1630. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1631. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1632. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1633. return status;
  1634. }
  1635. #endif
  1636. tresult PLUGIN_API getState (IBStream* state) override
  1637. {
  1638. if (state == nullptr)
  1639. return kInvalidArgument;
  1640. juce::MemoryBlock mem;
  1641. getStateInformation (mem);
  1642. #if JUCE_VST3_CAN_REPLACE_VST2
  1643. tresult status = writeVST2Header (state, isBypassed());
  1644. if (status != kResultOk)
  1645. return status;
  1646. const int bankBlockSize = 160;
  1647. Vst2::fxBank bank;
  1648. zerostruct (bank);
  1649. bank.chunkMagic = (int32) htonl ('CcnK');
  1650. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1651. bank.fxMagic = (int32) htonl ('FBCh');
  1652. bank.version = (int32) htonl (2);
  1653. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1654. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  1655. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  1656. status = state->write (&bank, bankBlockSize);
  1657. if (status != kResultOk)
  1658. return status;
  1659. #endif
  1660. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1661. }
  1662. //==============================================================================
  1663. Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
  1664. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
  1665. Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
  1666. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
  1667. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
  1668. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1669. Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
  1670. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
  1671. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1672. Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
  1673. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
  1674. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  1675. Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
  1676. Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
  1677. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  1678. Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
  1679. //==============================================================================
  1680. bool getCurrentPosition (CurrentPositionInfo& info) override
  1681. {
  1682. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1683. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  1684. info.bpm = jmax (1.0, processContext.tempo);
  1685. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1686. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1687. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1688. info.ppqPosition = processContext.projectTimeMusic;
  1689. info.ppqLoopStart = processContext.cycleStartMusic;
  1690. info.ppqLoopEnd = processContext.cycleEndMusic;
  1691. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1692. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1693. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1694. info.editOriginTime = 0.0;
  1695. info.frameRate = AudioPlayHead::fpsUnknown;
  1696. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1697. {
  1698. switch (processContext.frameRate.framesPerSecond)
  1699. {
  1700. case 24:
  1701. {
  1702. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1703. info.frameRate = AudioPlayHead::fps23976;
  1704. else
  1705. info.frameRate = AudioPlayHead::fps24;
  1706. }
  1707. break;
  1708. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1709. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1710. case 30:
  1711. {
  1712. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1713. info.frameRate = AudioPlayHead::fps30drop;
  1714. else
  1715. info.frameRate = AudioPlayHead::fps30;
  1716. }
  1717. break;
  1718. default: break;
  1719. }
  1720. }
  1721. return true;
  1722. }
  1723. //==============================================================================
  1724. int getNumAudioBuses (bool isInput) const
  1725. {
  1726. int busCount = pluginInstance->getBusCount (isInput);
  1727. #ifdef JucePlugin_PreferredChannelConfigurations
  1728. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1729. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1730. bool hasOnlyZeroChannels = true;
  1731. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1732. if (configs[i][isInput ? 0 : 1] != 0)
  1733. hasOnlyZeroChannels = false;
  1734. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1735. #endif
  1736. return busCount;
  1737. }
  1738. //==============================================================================
  1739. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1740. {
  1741. if (type == Vst::kAudio)
  1742. return getNumAudioBuses (dir == Vst::kInput);
  1743. if (type == Vst::kEvent)
  1744. {
  1745. if (dir == Vst::kInput)
  1746. return isMidiInputBusEnabled ? 1 : 0;
  1747. if (dir == Vst::kOutput)
  1748. return isMidiOutputBusEnabled ? 1 : 0;
  1749. }
  1750. return 0;
  1751. }
  1752. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1753. Steinberg::int32 index, Vst::BusInfo& info) override
  1754. {
  1755. if (type == Vst::kAudio)
  1756. {
  1757. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1758. return kResultFalse;
  1759. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1760. {
  1761. info.mediaType = Vst::kAudio;
  1762. info.direction = dir;
  1763. info.channelCount = bus->getLastEnabledLayout().size();
  1764. toString128 (info.name, bus->getName());
  1765. #if JucePlugin_IsSynth
  1766. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1767. #else
  1768. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1769. #endif
  1770. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1771. return kResultTrue;
  1772. }
  1773. }
  1774. if (type == Vst::kEvent)
  1775. {
  1776. info.flags = Vst::BusInfo::kDefaultActive;
  1777. #if JucePlugin_WantsMidiInput
  1778. if (dir == Vst::kInput && index == 0)
  1779. {
  1780. info.mediaType = Vst::kEvent;
  1781. info.direction = dir;
  1782. #ifdef JucePlugin_VSTNumMidiInputs
  1783. info.channelCount = JucePlugin_VSTNumMidiInputs;
  1784. #else
  1785. info.channelCount = 16;
  1786. #endif
  1787. toString128 (info.name, TRANS("MIDI Input"));
  1788. info.busType = Vst::kMain;
  1789. return kResultTrue;
  1790. }
  1791. #endif
  1792. #if JucePlugin_ProducesMidiOutput
  1793. if (dir == Vst::kOutput && index == 0)
  1794. {
  1795. info.mediaType = Vst::kEvent;
  1796. info.direction = dir;
  1797. #ifdef JucePlugin_VSTNumMidiOutputs
  1798. info.channelCount = JucePlugin_VSTNumMidiOutputs;
  1799. #else
  1800. info.channelCount = 16;
  1801. #endif
  1802. toString128 (info.name, TRANS("MIDI Output"));
  1803. info.busType = Vst::kMain;
  1804. return kResultTrue;
  1805. }
  1806. #endif
  1807. }
  1808. zerostruct (info);
  1809. return kResultFalse;
  1810. }
  1811. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1812. {
  1813. if (type == Vst::kEvent)
  1814. {
  1815. if (index != 0)
  1816. return kResultFalse;
  1817. if (dir == Vst::kInput)
  1818. isMidiInputBusEnabled = (state != 0);
  1819. else
  1820. isMidiOutputBusEnabled = (state != 0);
  1821. return kResultTrue;
  1822. }
  1823. if (type == Vst::kAudio)
  1824. {
  1825. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1826. return kResultFalse;
  1827. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1828. {
  1829. #ifdef JucePlugin_PreferredChannelConfigurations
  1830. auto newLayout = pluginInstance->getBusesLayout();
  1831. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1832. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1833. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1834. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1835. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1836. return kResultFalse;
  1837. #endif
  1838. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1839. }
  1840. }
  1841. return kResultFalse;
  1842. }
  1843. bool checkBusFormatsAreNotDiscrete()
  1844. {
  1845. auto numInputBuses = pluginInstance->getBusCount (true);
  1846. auto numOutputBuses = pluginInstance->getBusCount (false);
  1847. for (int i = 0; i < numInputBuses; ++i)
  1848. {
  1849. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  1850. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1851. return false;
  1852. }
  1853. for (int i = 0; i < numOutputBuses; ++i)
  1854. {
  1855. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  1856. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1857. return false;
  1858. }
  1859. return true;
  1860. }
  1861. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1862. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1863. {
  1864. auto numInputBuses = pluginInstance->getBusCount (true);
  1865. auto numOutputBuses = pluginInstance->getBusCount (false);
  1866. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1867. return false;
  1868. auto requested = pluginInstance->getBusesLayout();
  1869. for (int i = 0; i < numIns; ++i)
  1870. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1871. for (int i = 0; i < numOuts; ++i)
  1872. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1873. #ifdef JucePlugin_PreferredChannelConfigurations
  1874. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1875. if (! AudioProcessor::containsLayout (requested, configs))
  1876. return kResultFalse;
  1877. #endif
  1878. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1879. }
  1880. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1881. {
  1882. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1883. {
  1884. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1885. return kResultTrue;
  1886. }
  1887. return kResultFalse;
  1888. }
  1889. //==============================================================================
  1890. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1891. {
  1892. return (symbolicSampleSize == Vst::kSample32
  1893. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1894. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1895. }
  1896. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1897. {
  1898. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1899. }
  1900. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1901. {
  1902. ScopedInSetupProcessingSetter inSetupProcessingSetter (juceVST3EditController);
  1903. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1904. return kResultFalse;
  1905. processSetup = newSetup;
  1906. processContext.sampleRate = processSetup.sampleRate;
  1907. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1908. ? AudioProcessor::doublePrecision
  1909. : AudioProcessor::singlePrecision);
  1910. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  1911. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1912. return kResultTrue;
  1913. }
  1914. tresult PLUGIN_API setProcessing (TBool state) override
  1915. {
  1916. if (! state)
  1917. getPluginInstance().reset();
  1918. return kResultTrue;
  1919. }
  1920. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1921. {
  1922. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1923. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  1924. return Vst::kNoTail;
  1925. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  1926. return Vst::kInfiniteTail;
  1927. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1928. }
  1929. //==============================================================================
  1930. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1931. {
  1932. jassert (pluginInstance != nullptr);
  1933. auto numParamsChanged = paramChanges.getParameterCount();
  1934. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1935. {
  1936. if (auto* paramQueue = paramChanges.getParameterData (i))
  1937. {
  1938. auto numPoints = paramQueue->getPointCount();
  1939. Steinberg::int32 offsetSamples = 0;
  1940. double value = 0.0;
  1941. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1942. {
  1943. auto vstParamID = paramQueue->getParameterId();
  1944. if (vstParamID == JuceAudioProcessor::paramPreset)
  1945. {
  1946. auto numPrograms = pluginInstance->getNumPrograms();
  1947. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1948. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1949. && programValue != pluginInstance->getCurrentProgram())
  1950. pluginInstance->setCurrentProgram (programValue);
  1951. }
  1952. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1953. else if (juceVST3EditController != nullptr && juceVST3EditController->isMidiControllerParamID (vstParamID))
  1954. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1955. #endif
  1956. else
  1957. {
  1958. auto floatValue = static_cast<float> (value);
  1959. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  1960. {
  1961. param->setValue (floatValue);
  1962. inParameterChangedCallback = true;
  1963. param->sendValueChangedMessageToListeners (floatValue);
  1964. }
  1965. }
  1966. }
  1967. }
  1968. }
  1969. }
  1970. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1971. {
  1972. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1973. int channel, ctrlNumber;
  1974. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1975. {
  1976. if (ctrlNumber == Vst::kAfterTouch)
  1977. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1978. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1979. else if (ctrlNumber == Vst::kPitchBend)
  1980. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1981. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1982. else
  1983. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1984. jlimit (0, 127, ctrlNumber),
  1985. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1986. }
  1987. }
  1988. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1989. {
  1990. if (pluginInstance == nullptr)
  1991. return kResultFalse;
  1992. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1993. return kResultFalse;
  1994. if (data.processContext != nullptr)
  1995. {
  1996. processContext = *data.processContext;
  1997. if (juceVST3EditController != nullptr)
  1998. juceVST3EditController->vst3IsPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1999. }
  2000. else
  2001. {
  2002. zerostruct (processContext);
  2003. if (juceVST3EditController != nullptr)
  2004. juceVST3EditController->vst3IsPlaying = false;
  2005. }
  2006. midiBuffer.clear();
  2007. if (data.inputParameterChanges != nullptr)
  2008. processParameterChanges (*data.inputParameterChanges);
  2009. #if JucePlugin_WantsMidiInput
  2010. if (data.inputEvents != nullptr)
  2011. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  2012. #endif
  2013. if (getHostType().isWavelab())
  2014. {
  2015. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  2016. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  2017. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  2018. && (numInputChans + numOutputChans) == 0)
  2019. return kResultFalse;
  2020. }
  2021. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  2022. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  2023. else jassertfalse;
  2024. #if JucePlugin_ProducesMidiOutput
  2025. if (data.outputEvents != nullptr)
  2026. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  2027. #endif
  2028. return kResultTrue;
  2029. }
  2030. private:
  2031. //==============================================================================
  2032. struct ScopedInSetupProcessingSetter
  2033. {
  2034. ScopedInSetupProcessingSetter (JuceVST3EditController* c)
  2035. : controller (c)
  2036. {
  2037. if (controller != nullptr)
  2038. controller->inSetupProcessing = true;
  2039. }
  2040. ~ScopedInSetupProcessingSetter()
  2041. {
  2042. if (controller != nullptr)
  2043. controller->inSetupProcessing = false;
  2044. }
  2045. private:
  2046. JuceVST3EditController* controller = nullptr;
  2047. };
  2048. //==============================================================================
  2049. template <typename FloatType>
  2050. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  2051. {
  2052. int totalInputChans = 0, totalOutputChans = 0;
  2053. bool tmpBufferNeedsClearing = false;
  2054. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  2055. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  2056. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  2057. const auto countValidChannels = [] (Vst::AudioBusBuffers* buffers, int32 num)
  2058. {
  2059. return int (std::distance (buffers, std::find_if (buffers, buffers + num, [] (Vst::AudioBusBuffers& buf)
  2060. {
  2061. return getPointerForAudioBus<FloatType> (buf) == nullptr && buf.numChannels > 0;
  2062. })));
  2063. };
  2064. const auto vstInputs = countValidChannels (data.inputs, data.numInputs);
  2065. const auto vstOutputs = countValidChannels (data.outputs, data.numOutputs);
  2066. {
  2067. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  2068. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  2069. {
  2070. if (auto* busObject = pluginInstance->getBus (false, bus))
  2071. if (! busObject->isEnabled())
  2072. continue;
  2073. if (bus < vstOutputs)
  2074. {
  2075. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  2076. {
  2077. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  2078. for (int i = 0; i < numChans; ++i)
  2079. {
  2080. if (auto dst = busChannels[i])
  2081. {
  2082. if (totalOutputChans >= plugInInputChannels)
  2083. FloatVectorOperations::clear (dst, (int) data.numSamples);
  2084. channelList.set (totalOutputChans++, busChannels[i]);
  2085. }
  2086. }
  2087. }
  2088. }
  2089. else
  2090. {
  2091. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  2092. for (int i = 0; i < numChans; ++i)
  2093. {
  2094. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  2095. {
  2096. tmpBufferNeedsClearing = true;
  2097. channelList.set (totalOutputChans++, tmpBuffer);
  2098. }
  2099. else
  2100. return;
  2101. }
  2102. }
  2103. }
  2104. }
  2105. {
  2106. auto n = jmax (vstInputs, getNumAudioBuses (true));
  2107. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  2108. {
  2109. if (auto* busObject = pluginInstance->getBus (true, bus))
  2110. if (! busObject->isEnabled())
  2111. continue;
  2112. if (bus < vstInputs)
  2113. {
  2114. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  2115. {
  2116. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  2117. for (int i = 0; i < numChans; ++i)
  2118. {
  2119. if (busChannels[i] != nullptr)
  2120. {
  2121. if (totalInputChans >= totalOutputChans)
  2122. channelList.set (totalInputChans, busChannels[i]);
  2123. else
  2124. {
  2125. auto* dst = channelList.getReference (totalInputChans);
  2126. auto* src = busChannels[i];
  2127. if (dst != src)
  2128. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  2129. }
  2130. }
  2131. ++totalInputChans;
  2132. }
  2133. }
  2134. }
  2135. else
  2136. {
  2137. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  2138. for (int i = 0; i < numChans; ++i)
  2139. {
  2140. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  2141. {
  2142. tmpBufferNeedsClearing = true;
  2143. channelList.set (totalInputChans++, tmpBuffer);
  2144. }
  2145. else
  2146. return;
  2147. }
  2148. }
  2149. }
  2150. }
  2151. if (tmpBufferNeedsClearing)
  2152. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  2153. AudioBuffer<FloatType> buffer;
  2154. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  2155. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  2156. {
  2157. const ScopedLock sl (pluginInstance->getCallbackLock());
  2158. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  2159. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  2160. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  2161. #endif
  2162. if (pluginInstance->isSuspended())
  2163. {
  2164. buffer.clear();
  2165. }
  2166. else
  2167. {
  2168. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  2169. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  2170. {
  2171. if (isBypassed())
  2172. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  2173. else
  2174. pluginInstance->processBlock (buffer, midiBuffer);
  2175. }
  2176. }
  2177. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  2178. /* This assertion is caused when you've added some events to the
  2179. midiMessages array in your processBlock() method, which usually means
  2180. that you're trying to send them somewhere. But in this case they're
  2181. getting thrown away.
  2182. If your plugin does want to send MIDI messages, you'll need to set
  2183. the JucePlugin_ProducesMidiOutput macro to 1 in your
  2184. JucePluginCharacteristics.h file.
  2185. If you don't want to produce any MIDI output, then you should clear the
  2186. midiMessages array at the end of your processBlock() method, to
  2187. indicate that you don't want any of the events to be passed through
  2188. to the output.
  2189. */
  2190. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  2191. #endif
  2192. }
  2193. }
  2194. //==============================================================================
  2195. template <typename FloatType>
  2196. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2197. {
  2198. channelList.clearQuick();
  2199. channelList.insertMultiple (0, nullptr, 128);
  2200. auto& p = getPluginInstance();
  2201. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  2202. buffer.clear();
  2203. }
  2204. template <typename FloatType>
  2205. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2206. {
  2207. channelList.clearQuick();
  2208. channelList.resize (0);
  2209. buffer.setSize (0, 0);
  2210. }
  2211. template <typename FloatType>
  2212. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  2213. {
  2214. return AudioBusPointerHelper<FloatType>::impl (data);
  2215. }
  2216. template <typename FloatType>
  2217. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  2218. {
  2219. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  2220. // we can't do anything if the host requests to render many more samples than the
  2221. // block size, we need to bail out
  2222. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  2223. return nullptr;
  2224. return buffer.getWritePointer (channel);
  2225. }
  2226. void preparePlugin (double sampleRate, int bufferSize)
  2227. {
  2228. auto& p = getPluginInstance();
  2229. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2230. p.prepareToPlay (sampleRate, bufferSize);
  2231. midiBuffer.ensureSize (2048);
  2232. midiBuffer.clear();
  2233. }
  2234. //==============================================================================
  2235. ScopedJuceInitialiser_GUI libraryInitialiser;
  2236. std::atomic<int> refCount { 1 };
  2237. AudioProcessor* pluginInstance;
  2238. ComSmartPtr<Vst::IHostApplication> host;
  2239. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2240. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2241. /**
  2242. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  2243. this object needs to be copied on every call to process() to be up-to-date...
  2244. */
  2245. Vst::ProcessContext processContext;
  2246. Vst::ProcessSetup processSetup;
  2247. MidiBuffer midiBuffer;
  2248. Array<float*> channelListFloat;
  2249. Array<double*> channelListDouble;
  2250. AudioBuffer<float> emptyBufferFloat;
  2251. AudioBuffer<double> emptyBufferDouble;
  2252. #if JucePlugin_WantsMidiInput
  2253. bool isMidiInputBusEnabled = true;
  2254. #else
  2255. bool isMidiInputBusEnabled = false;
  2256. #endif
  2257. #if JucePlugin_ProducesMidiOutput
  2258. bool isMidiOutputBusEnabled = true;
  2259. #else
  2260. bool isMidiOutputBusEnabled = false;
  2261. #endif
  2262. static const char* kJucePrivateDataIdentifier;
  2263. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2264. };
  2265. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2266. //==============================================================================
  2267. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4310)
  2268. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wall")
  2269. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2270. DEF_CLASS_IID (JuceAudioProcessor)
  2271. #if JUCE_VST3_CAN_REPLACE_VST2
  2272. FUID getFUIDForVST2ID (bool forControllerUID)
  2273. {
  2274. TUID uuid;
  2275. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  2276. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2277. return FUID (uuid);
  2278. }
  2279. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2280. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2281. #else
  2282. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2283. DEF_CLASS_IID (JuceVST3EditController)
  2284. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2285. DEF_CLASS_IID (JuceVST3Component)
  2286. #endif
  2287. JUCE_END_IGNORE_WARNINGS_MSVC
  2288. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  2289. //==============================================================================
  2290. bool initModule()
  2291. {
  2292. #if JUCE_MAC
  2293. initialiseMacVST();
  2294. #endif
  2295. return true;
  2296. }
  2297. bool shutdownModule()
  2298. {
  2299. return true;
  2300. }
  2301. #undef JUCE_EXPORTED_FUNCTION
  2302. #if JUCE_WINDOWS
  2303. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2304. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2305. #define JUCE_EXPORTED_FUNCTION
  2306. #else
  2307. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  2308. #endif
  2309. #if JUCE_LINUX
  2310. void* moduleHandle = nullptr;
  2311. int moduleEntryCounter = 0;
  2312. JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle)
  2313. {
  2314. if (++moduleEntryCounter == 1)
  2315. {
  2316. moduleHandle = sharedLibraryHandle;
  2317. return initModule();
  2318. }
  2319. return true;
  2320. }
  2321. JUCE_EXPORTED_FUNCTION bool ModuleExit()
  2322. {
  2323. if (--moduleEntryCounter == 0)
  2324. {
  2325. moduleHandle = nullptr;
  2326. return shutdownModule();
  2327. }
  2328. return true;
  2329. }
  2330. #elif JUCE_MAC
  2331. CFBundleRef globalBundleInstance = nullptr;
  2332. juce::uint32 numBundleRefs = 0;
  2333. juce::Array<CFBundleRef> bundleRefs;
  2334. enum { MaxPathLength = 2048 };
  2335. char modulePath[MaxPathLength] = { 0 };
  2336. void* moduleHandle = nullptr;
  2337. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  2338. {
  2339. if (ref != nullptr)
  2340. {
  2341. ++numBundleRefs;
  2342. CFRetain (ref);
  2343. bundleRefs.add (ref);
  2344. if (moduleHandle == nullptr)
  2345. {
  2346. globalBundleInstance = ref;
  2347. moduleHandle = ref;
  2348. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  2349. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  2350. CFRelease (tempURL);
  2351. }
  2352. }
  2353. return initModule();
  2354. }
  2355. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2356. {
  2357. if (shutdownModule())
  2358. {
  2359. if (--numBundleRefs == 0)
  2360. {
  2361. for (int i = 0; i < bundleRefs.size(); ++i)
  2362. CFRelease (bundleRefs.getUnchecked (i));
  2363. bundleRefs.clear();
  2364. }
  2365. return true;
  2366. }
  2367. return false;
  2368. }
  2369. #endif
  2370. //==============================================================================
  2371. /** This typedef represents VST3's createInstance() function signature */
  2372. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2373. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2374. {
  2375. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2376. }
  2377. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2378. {
  2379. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2380. }
  2381. //==============================================================================
  2382. struct JucePluginFactory;
  2383. static JucePluginFactory* globalFactory = nullptr;
  2384. //==============================================================================
  2385. struct JucePluginFactory : public IPluginFactory3
  2386. {
  2387. JucePluginFactory()
  2388. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2389. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2390. {
  2391. }
  2392. virtual ~JucePluginFactory()
  2393. {
  2394. if (globalFactory == this)
  2395. globalFactory = nullptr;
  2396. }
  2397. //==============================================================================
  2398. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2399. {
  2400. if (createFunction == nullptr)
  2401. {
  2402. jassertfalse;
  2403. return false;
  2404. }
  2405. auto entry = std::make_unique<ClassEntry> (info, createFunction);
  2406. entry->infoW.fromAscii (info);
  2407. classes.push_back (std::move (entry));
  2408. return true;
  2409. }
  2410. //==============================================================================
  2411. JUCE_DECLARE_VST3_COM_REF_METHODS
  2412. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2413. {
  2414. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2415. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2416. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2417. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2418. jassertfalse; // Something new?
  2419. *obj = nullptr;
  2420. return kNotImplemented;
  2421. }
  2422. //==============================================================================
  2423. Steinberg::int32 PLUGIN_API countClasses() override
  2424. {
  2425. return (Steinberg::int32) classes.size();
  2426. }
  2427. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2428. {
  2429. if (info == nullptr)
  2430. return kInvalidArgument;
  2431. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2432. return kResultOk;
  2433. }
  2434. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2435. {
  2436. return getPClassInfo<PClassInfo> (index, info);
  2437. }
  2438. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2439. {
  2440. return getPClassInfo<PClassInfo2> (index, info);
  2441. }
  2442. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2443. {
  2444. if (info != nullptr)
  2445. {
  2446. if (auto& entry = classes[(size_t) index])
  2447. {
  2448. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2449. return kResultOk;
  2450. }
  2451. }
  2452. return kInvalidArgument;
  2453. }
  2454. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2455. {
  2456. ScopedJuceInitialiser_GUI libraryInitialiser;
  2457. *obj = nullptr;
  2458. TUID tuid;
  2459. memcpy (tuid, sourceIid, sizeof (TUID));
  2460. #if VST_VERSION >= 0x030608
  2461. auto sourceFuid = FUID::fromTUID (tuid);
  2462. #else
  2463. FUID sourceFuid;
  2464. sourceFuid = tuid;
  2465. #endif
  2466. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2467. {
  2468. jassertfalse; // The host you're running in has severe implementation issues!
  2469. return kInvalidArgument;
  2470. }
  2471. TUID iidToQuery;
  2472. sourceFuid.toTUID (iidToQuery);
  2473. for (auto& entry : classes)
  2474. {
  2475. if (doUIDsMatch (entry->infoW.cid, cid))
  2476. {
  2477. if (auto* instance = entry->createFunction (host))
  2478. {
  2479. const FReleaser releaser (instance);
  2480. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2481. return kResultOk;
  2482. }
  2483. break;
  2484. }
  2485. }
  2486. return kNoInterface;
  2487. }
  2488. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2489. {
  2490. host.loadFrom (context);
  2491. if (host != nullptr)
  2492. {
  2493. Vst::String128 name;
  2494. host->getName (name);
  2495. return kResultTrue;
  2496. }
  2497. return kNotImplemented;
  2498. }
  2499. private:
  2500. //==============================================================================
  2501. std::atomic<int> refCount { 1 };
  2502. const PFactoryInfo factoryInfo;
  2503. ComSmartPtr<Vst::IHostApplication> host;
  2504. //==============================================================================
  2505. struct ClassEntry
  2506. {
  2507. ClassEntry() noexcept {}
  2508. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2509. : info2 (info), createFunction (fn) {}
  2510. PClassInfo2 info2;
  2511. PClassInfoW infoW;
  2512. CreateFunction createFunction = {};
  2513. bool isUnicode = false;
  2514. private:
  2515. JUCE_DECLARE_NON_COPYABLE (ClassEntry)
  2516. };
  2517. std::vector<std::unique_ptr<ClassEntry>> classes;
  2518. //==============================================================================
  2519. template<class PClassInfoType>
  2520. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2521. {
  2522. if (info != nullptr)
  2523. {
  2524. zerostruct (*info);
  2525. if (auto& entry = classes[(size_t) index])
  2526. {
  2527. if (entry->isUnicode)
  2528. return kResultFalse;
  2529. memcpy (info, (PClassInfoType*) &entry->info2, sizeof (PClassInfoType));
  2530. return kResultOk;
  2531. }
  2532. }
  2533. jassertfalse;
  2534. return kInvalidArgument;
  2535. }
  2536. //==============================================================================
  2537. // no leak detector here to prevent it firing on shutdown when running in hosts that
  2538. // don't release the factory object correctly...
  2539. JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
  2540. };
  2541. } // juce namespace
  2542. //==============================================================================
  2543. #ifndef JucePlugin_Vst3ComponentFlags
  2544. #if JucePlugin_IsSynth
  2545. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2546. #else
  2547. #define JucePlugin_Vst3ComponentFlags 0
  2548. #endif
  2549. #endif
  2550. #ifndef JucePlugin_Vst3Category
  2551. #if JucePlugin_IsSynth
  2552. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2553. #else
  2554. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2555. #endif
  2556. #endif
  2557. using namespace juce;
  2558. //==============================================================================
  2559. // The VST3 plugin entry point.
  2560. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2561. {
  2562. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2563. #if JUCE_MSVC
  2564. // Cunning trick to force this function to be exported. Life's too short to
  2565. // faff around creating .def files for this kind of thing.
  2566. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2567. #endif
  2568. if (globalFactory == nullptr)
  2569. {
  2570. globalFactory = new JucePluginFactory();
  2571. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2572. PClassInfo::kManyInstances,
  2573. kVstAudioEffectClass,
  2574. JucePlugin_Name,
  2575. JucePlugin_Vst3ComponentFlags,
  2576. JucePlugin_Vst3Category,
  2577. JucePlugin_Manufacturer,
  2578. JucePlugin_VersionString,
  2579. kVstVersionString);
  2580. globalFactory->registerClass (componentClass, createComponentInstance);
  2581. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2582. PClassInfo::kManyInstances,
  2583. kVstComponentControllerClass,
  2584. JucePlugin_Name,
  2585. JucePlugin_Vst3ComponentFlags,
  2586. JucePlugin_Vst3Category,
  2587. JucePlugin_Manufacturer,
  2588. JucePlugin_VersionString,
  2589. kVstVersionString);
  2590. globalFactory->registerClass (controllerClass, createControllerInstance);
  2591. }
  2592. else
  2593. {
  2594. globalFactory->addRef();
  2595. }
  2596. return dynamic_cast<IPluginFactory*> (globalFactory);
  2597. }
  2598. //==============================================================================
  2599. #if _MSC_VER || JUCE_MINGW
  2600. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2601. #endif
  2602. #endif //JucePlugin_Build_VST3