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.

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