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.

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