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.

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