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.

3455 lines
128KB

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