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.

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