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.

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