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.

3361 lines
124KB

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