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.

3997 lines
148KB

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