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.

3362 lines
124KB

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