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.

3348 lines
123KB

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