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.

3314 lines
122KB

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