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.

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