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.

4010 lines
149KB

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