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.

4004 lines
149KB

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