The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3441 lines
127KB

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