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.

3452 lines
128KB

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