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.

3974 lines
147KB

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