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.

3407 lines
126KB

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