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.

3453 lines
128KB

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