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.

3380 lines
125KB

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