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.

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