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.

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