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.

4012 lines
149KB

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