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.

4008 lines
148KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include <juce_core/system/juce_TargetPlatform.h>
  19. #include <juce_core/system/juce_CompilerWarnings.h>
  20. //==============================================================================
  21. #if JucePlugin_Build_VST3 && (JUCE_MAC || JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD)
  22. JUCE_BEGIN_NO_SANITIZE ("vptr")
  23. #if JUCE_PLUGINHOST_VST3
  24. #if JUCE_MAC
  25. #include <CoreFoundation/CoreFoundation.h>
  26. #endif
  27. #undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
  28. #define JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY 1
  29. #endif
  30. #include <juce_audio_processors/format_types/juce_VST3Headers.h>
  31. #undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
  32. #define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
  33. #include "../utility/juce_CheckSettingMacros.h"
  34. #include "../utility/juce_IncludeSystemHeaders.h"
  35. #include "../utility/juce_IncludeModuleHeaders.h"
  36. #include "../utility/juce_WindowsHooks.h"
  37. #include "../utility/juce_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
  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 (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 (MessageManager::getInstance()->isThisTheMessageThread())
  920. beginEdit (vstParamId);
  921. }
  922. void endGesture (Vst::ParamID vstParamId)
  923. {
  924. if (MessageManager::getInstance()->isThisTheMessageThread())
  925. endEdit (vstParamId);
  926. }
  927. void paramChanged (Steinberg::int32 parameterIndex, Vst::ParamID vstParamId, double newValue)
  928. {
  929. if (inParameterChangedCallback)
  930. return;
  931. if (MessageManager::getInstance()->isThisTheMessageThread())
  932. {
  933. // NB: Cubase has problems if performEdit is called without setParamNormalized
  934. EditController::setParamNormalized (vstParamId, newValue);
  935. performEdit (vstParamId, newValue);
  936. }
  937. else
  938. {
  939. audioProcessor->setParameterValue (parameterIndex, (float) newValue);
  940. }
  941. }
  942. //==============================================================================
  943. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override
  944. {
  945. beginGesture (audioProcessor->getVSTParamIDForIndex (index));
  946. }
  947. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override
  948. {
  949. endGesture (audioProcessor->getVSTParamIDForIndex (index));
  950. }
  951. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  952. {
  953. paramChanged (index, audioProcessor->getVSTParamIDForIndex (index), newValue);
  954. }
  955. void audioProcessorChanged (AudioProcessor*, const ChangeDetails& details) override
  956. {
  957. int32 flags = 0;
  958. if (details.parameterInfoChanged)
  959. {
  960. for (int32 i = 0; i < parameters.getParameterCount(); ++i)
  961. if (auto* param = dynamic_cast<Param*> (parameters.getParameterByIndex (i)))
  962. if (param->updateParameterInfo() && (flags & Vst::kParamTitlesChanged) == 0)
  963. flags |= Vst::kParamTitlesChanged;
  964. }
  965. if (auto* pluginInstance = getPluginInstance())
  966. {
  967. if (details.programChanged)
  968. {
  969. const auto programParameterId = audioProcessor->getProgramParamID();
  970. if (audioProcessor->getParamForVSTParamID (programParameterId) != nullptr)
  971. {
  972. const auto currentProgram = pluginInstance->getCurrentProgram();
  973. const auto paramValue = roundToInt (EditController::normalizedParamToPlain (programParameterId,
  974. EditController::getParamNormalized (programParameterId)));
  975. if (currentProgram != paramValue)
  976. {
  977. beginGesture (programParameterId);
  978. paramChanged (audioProcessor->findCacheIndexForParamID (programParameterId),
  979. programParameterId,
  980. EditController::plainParamToNormalized (programParameterId, currentProgram));
  981. endGesture (programParameterId);
  982. flags |= Vst::kParamValuesChanged;
  983. }
  984. }
  985. }
  986. auto latencySamples = pluginInstance->getLatencySamples();
  987. if (details.latencyChanged && latencySamples != lastLatencySamples)
  988. {
  989. flags |= Vst::kLatencyChanged;
  990. lastLatencySamples = latencySamples;
  991. }
  992. }
  993. if (details.nonParameterStateChanged)
  994. flags |= pluginShouldBeMarkedDirtyFlag;
  995. if (inSetupProcessing)
  996. flags &= Vst::kLatencyChanged;
  997. componentRestarter.restart (flags);
  998. }
  999. //==============================================================================
  1000. AudioProcessor* getPluginInstance() const noexcept
  1001. {
  1002. if (audioProcessor != nullptr)
  1003. return audioProcessor->get();
  1004. return nullptr;
  1005. }
  1006. static constexpr auto pluginShouldBeMarkedDirtyFlag = 1 << 16;
  1007. private:
  1008. friend class JuceVST3Component;
  1009. friend struct Param;
  1010. //==============================================================================
  1011. VSTComSmartPtr<JuceAudioProcessor> audioProcessor;
  1012. struct MidiController
  1013. {
  1014. int channel = -1, ctrlNumber = -1;
  1015. };
  1016. ComponentRestarter componentRestarter { *this };
  1017. enum { numMIDIChannels = 16 };
  1018. Vst::ParamID parameterToMidiControllerOffset;
  1019. MidiController parameterToMidiController[(int) numMIDIChannels * (int) Vst::kCountCtrlNumber];
  1020. Vst::ParamID midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
  1021. void restartComponentOnMessageThread (int32 flags) override
  1022. {
  1023. if ((flags & pluginShouldBeMarkedDirtyFlag) != 0)
  1024. setDirty (true);
  1025. flags &= ~pluginShouldBeMarkedDirtyFlag;
  1026. if (auto* handler = componentHandler)
  1027. handler->restartComponent (flags);
  1028. }
  1029. //==============================================================================
  1030. struct OwnedParameterListener : public AudioProcessorParameter::Listener
  1031. {
  1032. OwnedParameterListener (JuceVST3EditController& editController,
  1033. AudioProcessorParameter& parameter,
  1034. Vst::ParamID paramID,
  1035. int cacheIndex)
  1036. : owner (editController),
  1037. vstParamID (paramID),
  1038. parameterIndex (cacheIndex)
  1039. {
  1040. // We shouldn't be using an OwnedParameterListener for parameters that have
  1041. // been added directly to the AudioProcessor. We observe those via the
  1042. // normal audioProcessorParameterChanged mechanism.
  1043. jassert (parameter.getParameterIndex() == -1);
  1044. // The parameter must have a non-negative index in the parameter cache.
  1045. jassert (parameterIndex >= 0);
  1046. parameter.addListener (this);
  1047. }
  1048. void parameterValueChanged (int, float newValue) override
  1049. {
  1050. owner.paramChanged (parameterIndex, vstParamID, newValue);
  1051. }
  1052. void parameterGestureChanged (int, bool gestureIsStarting) override
  1053. {
  1054. if (gestureIsStarting)
  1055. owner.beginGesture (vstParamID);
  1056. else
  1057. owner.endGesture (vstParamID);
  1058. }
  1059. JuceVST3EditController& owner;
  1060. const Vst::ParamID vstParamID = Vst::kNoParamId;
  1061. const int parameterIndex = -1;
  1062. };
  1063. std::vector<std::unique_ptr<OwnedParameterListener>> ownedParameterListeners;
  1064. //==============================================================================
  1065. std::atomic<bool> vst3IsPlaying { false },
  1066. inSetupProcessing { false };
  1067. int lastLatencySamples = 0;
  1068. #if ! JUCE_MAC
  1069. float lastScaleFactorReceived = 1.0f;
  1070. #endif
  1071. InterfaceResultWithDeferredAddRef queryInterfaceInternal (const TUID targetIID)
  1072. {
  1073. const auto result = testForMultiple (*this,
  1074. targetIID,
  1075. UniqueBase<FObject>{},
  1076. UniqueBase<JuceVST3EditController>{},
  1077. UniqueBase<Vst::IEditController>{},
  1078. UniqueBase<Vst::IEditController2>{},
  1079. UniqueBase<Vst::IConnectionPoint>{},
  1080. UniqueBase<Vst::IMidiMapping>{},
  1081. UniqueBase<Vst::IUnitInfo>{},
  1082. UniqueBase<Vst::ChannelContext::IInfoListener>{},
  1083. SharedBase<IPluginBase, Vst::IEditController>{},
  1084. UniqueBase<IDependent>{},
  1085. SharedBase<FUnknown, Vst::IEditController>{});
  1086. if (result.isOk())
  1087. return result;
  1088. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  1089. return { kResultOk, audioProcessor.get() };
  1090. return {};
  1091. }
  1092. void installAudioProcessor (const VSTComSmartPtr<JuceAudioProcessor>& newAudioProcessor)
  1093. {
  1094. audioProcessor = newAudioProcessor;
  1095. if (auto* extensions = dynamic_cast<VST3ClientExtensions*> (audioProcessor->get()))
  1096. {
  1097. extensions->setIComponentHandler (componentHandler);
  1098. extensions->setIHostApplication (hostContext.get());
  1099. }
  1100. if (auto* pluginInstance = getPluginInstance())
  1101. {
  1102. lastLatencySamples = pluginInstance->getLatencySamples();
  1103. pluginInstance->addListener (this);
  1104. // as the bypass is not part of the regular parameters we need to listen for it explicitly
  1105. if (! audioProcessor->isBypassRegularParameter())
  1106. {
  1107. const auto paramID = audioProcessor->getBypassParamID();
  1108. ownedParameterListeners.push_back (std::make_unique<OwnedParameterListener> (*this,
  1109. *audioProcessor->getParamForVSTParamID (paramID),
  1110. paramID,
  1111. audioProcessor->findCacheIndexForParamID (paramID)));
  1112. }
  1113. if (parameters.getParameterCount() <= 0)
  1114. {
  1115. auto n = audioProcessor->getParamIDs().size();
  1116. for (int i = 0; i < n; ++i)
  1117. {
  1118. auto vstParamID = audioProcessor->getVSTParamIDForIndex (i);
  1119. if (vstParamID == audioProcessor->getProgramParamID())
  1120. continue;
  1121. auto* juceParam = audioProcessor->getParamForVSTParamID (vstParamID);
  1122. auto* parameterGroup = pluginInstance->getParameterTree().getGroupsForParameter (juceParam).getLast();
  1123. auto unitID = JuceAudioProcessor::getUnitID (parameterGroup);
  1124. parameters.addParameter (new Param (*this, *juceParam, vstParamID, unitID,
  1125. (vstParamID == audioProcessor->getBypassParamID())));
  1126. }
  1127. const auto programParamId = audioProcessor->getProgramParamID();
  1128. if (auto* programParam = audioProcessor->getParamForVSTParamID (programParamId))
  1129. {
  1130. ownedParameterListeners.push_back (std::make_unique<OwnedParameterListener> (*this,
  1131. *programParam,
  1132. programParamId,
  1133. audioProcessor->findCacheIndexForParamID (programParamId)));
  1134. parameters.addParameter (new ProgramChangeParameter (*pluginInstance, audioProcessor->getProgramParamID()));
  1135. }
  1136. }
  1137. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1138. parameterToMidiControllerOffset = static_cast<Vst::ParamID> (audioProcessor->isUsingManagedParameters() ? JuceAudioProcessor::paramMidiControllerOffset
  1139. : parameters.getParameterCount());
  1140. initialiseMidiControllerMappings();
  1141. #endif
  1142. audioProcessorChanged (pluginInstance, ChangeDetails().withParameterInfoChanged (true));
  1143. }
  1144. }
  1145. void initialiseMidiControllerMappings()
  1146. {
  1147. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  1148. {
  1149. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  1150. {
  1151. midiControllerToParameter[c][i] = static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset;
  1152. parameterToMidiController[p].channel = c;
  1153. parameterToMidiController[p].ctrlNumber = i;
  1154. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  1155. static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset, nullptr, 0, 0,
  1156. 0, Vst::kRootUnitId));
  1157. }
  1158. }
  1159. }
  1160. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  1161. {
  1162. jassert (hostContext != nullptr);
  1163. if (auto* message = allocateMessage())
  1164. {
  1165. const FReleaser releaser (message);
  1166. message->setMessageID (idTag);
  1167. message->getAttributes()->setInt (idTag, value);
  1168. sendMessage (message);
  1169. }
  1170. }
  1171. class EditorContextMenu : public HostProvidedContextMenu
  1172. {
  1173. public:
  1174. EditorContextMenu (AudioProcessorEditor& editorIn,
  1175. VSTComSmartPtr<Steinberg::Vst::IContextMenu> contextMenuIn)
  1176. : editor (editorIn), contextMenu (contextMenuIn) {}
  1177. PopupMenu getEquivalentPopupMenu() const override
  1178. {
  1179. using MenuItem = Steinberg::Vst::IContextMenuItem;
  1180. using MenuTarget = Steinberg::Vst::IContextMenuTarget;
  1181. struct Submenu
  1182. {
  1183. PopupMenu menu;
  1184. String name;
  1185. bool enabled;
  1186. };
  1187. std::vector<Submenu> menuStack (1);
  1188. for (int32_t i = 0, end = contextMenu->getItemCount(); i < end; ++i)
  1189. {
  1190. MenuItem item{};
  1191. MenuTarget* target = nullptr;
  1192. contextMenu->getItem (i, item, &target);
  1193. if ((item.flags & MenuItem::kIsGroupStart) == MenuItem::kIsGroupStart)
  1194. {
  1195. menuStack.push_back ({ PopupMenu{},
  1196. toString (item.name),
  1197. (item.flags & MenuItem::kIsDisabled) == 0 });
  1198. }
  1199. else if ((item.flags & MenuItem::kIsGroupEnd) == MenuItem::kIsGroupEnd)
  1200. {
  1201. const auto back = menuStack.back();
  1202. menuStack.pop_back();
  1203. if (menuStack.empty())
  1204. {
  1205. // malformed menu
  1206. jassertfalse;
  1207. return {};
  1208. }
  1209. menuStack.back().menu.addSubMenu (back.name, back.menu, back.enabled);
  1210. }
  1211. else if ((item.flags & MenuItem::kIsSeparator) == MenuItem::kIsSeparator)
  1212. {
  1213. menuStack.back().menu.addSeparator();
  1214. }
  1215. else
  1216. {
  1217. VSTComSmartPtr<MenuTarget> ownedTarget (target);
  1218. const auto tag = item.tag;
  1219. menuStack.back().menu.addItem (toString (item.name),
  1220. (item.flags & MenuItem::kIsDisabled) == 0,
  1221. (item.flags & MenuItem::kIsChecked) != 0,
  1222. [ownedTarget, tag] { ownedTarget->executeMenuItem (tag); });
  1223. }
  1224. }
  1225. if (menuStack.size() != 1)
  1226. {
  1227. // malformed menu
  1228. jassertfalse;
  1229. return {};
  1230. }
  1231. return menuStack.back().menu;
  1232. }
  1233. void showNativeMenu (Point<int> pos) const override
  1234. {
  1235. const auto scaled = pos * Component::getApproximateScaleFactorForComponent (&editor);
  1236. contextMenu->popup (scaled.x, scaled.y);
  1237. }
  1238. private:
  1239. AudioProcessorEditor& editor;
  1240. VSTComSmartPtr<Steinberg::Vst::IContextMenu> contextMenu;
  1241. };
  1242. class EditorHostContext : public AudioProcessorEditorHostContext
  1243. {
  1244. public:
  1245. EditorHostContext (JuceAudioProcessor& processorIn,
  1246. AudioProcessorEditor& editorIn,
  1247. Steinberg::Vst::IComponentHandler* handler,
  1248. Steinberg::IPlugView* viewIn)
  1249. : processor (processorIn), editor (editorIn), componentHandler (handler), view (viewIn) {}
  1250. std::unique_ptr<HostProvidedContextMenu> getContextMenuForParameterIndex (const AudioProcessorParameter* parameter) const override
  1251. {
  1252. if (componentHandler == nullptr || view == nullptr)
  1253. return {};
  1254. Steinberg::FUnknownPtr<Steinberg::Vst::IComponentHandler3> handler (componentHandler);
  1255. if (handler == nullptr)
  1256. return {};
  1257. const auto idToUse = parameter != nullptr ? processor.getVSTParamIDForIndex (parameter->getParameterIndex()) : 0;
  1258. const auto menu = VSTComSmartPtr<Steinberg::Vst::IContextMenu> (handler->createContextMenu (view, &idToUse));
  1259. return std::make_unique<EditorContextMenu> (editor, menu);
  1260. }
  1261. private:
  1262. JuceAudioProcessor& processor;
  1263. AudioProcessorEditor& editor;
  1264. Steinberg::Vst::IComponentHandler* componentHandler = nullptr;
  1265. Steinberg::IPlugView* view = nullptr;
  1266. };
  1267. //==============================================================================
  1268. class JuceVST3Editor : public Vst::EditorView,
  1269. public Steinberg::IPlugViewContentScaleSupport,
  1270. private Timer
  1271. {
  1272. public:
  1273. JuceVST3Editor (JuceVST3EditController& ec, JuceAudioProcessor& p)
  1274. : EditorView (&ec, nullptr),
  1275. owner (&ec),
  1276. pluginInstance (*p.get())
  1277. {
  1278. createContentWrapperComponentIfNeeded();
  1279. #if JUCE_MAC
  1280. if (getHostType().type == PluginHostType::SteinbergCubase10)
  1281. cubase10Workaround.reset (new Cubase10WindowResizeWorkaround (*this));
  1282. #else
  1283. if (! approximatelyEqual (editorScaleFactor, ec.lastScaleFactorReceived))
  1284. setContentScaleFactor (ec.lastScaleFactorReceived);
  1285. #endif
  1286. }
  1287. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1288. {
  1289. const auto result = testFor (*this, targetIID, UniqueBase<IPlugViewContentScaleSupport>{});
  1290. if (result.isOk())
  1291. return result.extract (obj);
  1292. return Vst::EditorView::queryInterface (targetIID, obj);
  1293. }
  1294. REFCOUNT_METHODS (Vst::EditorView)
  1295. //==============================================================================
  1296. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  1297. {
  1298. if (type != nullptr && pluginInstance.hasEditor())
  1299. {
  1300. #if JUCE_WINDOWS
  1301. if (strcmp (type, kPlatformTypeHWND) == 0)
  1302. #elif JUCE_MAC
  1303. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  1304. #elif JUCE_LINUX || JUCE_BSD
  1305. if (strcmp (type, kPlatformTypeX11EmbedWindowID) == 0)
  1306. #endif
  1307. return kResultTrue;
  1308. }
  1309. return kResultFalse;
  1310. }
  1311. tresult PLUGIN_API attached (void* parent, FIDString type) override
  1312. {
  1313. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  1314. return kResultFalse;
  1315. #if JUCE_LINUX || JUCE_BSD
  1316. eventHandler->registerHandlerForFrame (plugFrame);
  1317. #endif
  1318. systemWindow = parent;
  1319. createContentWrapperComponentIfNeeded();
  1320. #if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
  1321. component->setOpaque (true);
  1322. component->addToDesktop (0, (void*) systemWindow);
  1323. component->setVisible (true);
  1324. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1325. component->checkHostWindowScaleFactor();
  1326. component->startTimer (500);
  1327. #endif
  1328. #else
  1329. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  1330. macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
  1331. #endif
  1332. component->resizeHostWindow();
  1333. attachedToParent();
  1334. // Life's too short to faff around with wave lab
  1335. if (getHostType().isWavelab())
  1336. startTimer (200);
  1337. return kResultTrue;
  1338. }
  1339. tresult PLUGIN_API removed() override
  1340. {
  1341. if (component != nullptr)
  1342. {
  1343. #if JUCE_WINDOWS
  1344. component->removeFromDesktop();
  1345. #elif JUCE_MAC
  1346. if (macHostWindow != nullptr)
  1347. {
  1348. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  1349. macHostWindow = nullptr;
  1350. }
  1351. #endif
  1352. component = nullptr;
  1353. }
  1354. #if JUCE_LINUX || JUCE_BSD
  1355. eventHandler->unregisterHandlerForFrame (plugFrame);
  1356. #endif
  1357. return CPluginView::removed();
  1358. }
  1359. tresult PLUGIN_API onSize (ViewRect* newSize) override
  1360. {
  1361. if (newSize != nullptr)
  1362. {
  1363. rect = convertFromHostBounds (*newSize);
  1364. if (component != nullptr)
  1365. {
  1366. component->setSize (rect.getWidth(), rect.getHeight());
  1367. #if JUCE_MAC
  1368. if (cubase10Workaround != nullptr)
  1369. {
  1370. cubase10Workaround->triggerAsyncUpdate();
  1371. }
  1372. else
  1373. #endif
  1374. {
  1375. if (auto* peer = component->getPeer())
  1376. peer->updateBounds();
  1377. }
  1378. }
  1379. return kResultTrue;
  1380. }
  1381. jassertfalse;
  1382. return kResultFalse;
  1383. }
  1384. tresult PLUGIN_API getSize (ViewRect* size) override
  1385. {
  1386. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1387. if (getHostType().isAbletonLive() && systemWindow == nullptr)
  1388. return kResultFalse;
  1389. #endif
  1390. if (size != nullptr && component != nullptr)
  1391. {
  1392. auto editorBounds = component->getSizeToContainChild();
  1393. *size = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  1394. return kResultTrue;
  1395. }
  1396. return kResultFalse;
  1397. }
  1398. tresult PLUGIN_API canResize() override
  1399. {
  1400. if (component != nullptr)
  1401. if (auto* editor = component->pluginEditor.get())
  1402. if (editor->isResizable())
  1403. return kResultTrue;
  1404. return kResultFalse;
  1405. }
  1406. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  1407. {
  1408. if (rectToCheck != nullptr && component != nullptr)
  1409. {
  1410. if (auto* editor = component->pluginEditor.get())
  1411. {
  1412. if (auto* constrainer = editor->getConstrainer())
  1413. {
  1414. *rectToCheck = convertFromHostBounds (*rectToCheck);
  1415. auto editorBounds = editor->getLocalArea (component.get(),
  1416. Rectangle<int>::leftTopRightBottom (rectToCheck->left, rectToCheck->top,
  1417. rectToCheck->right, rectToCheck->bottom).toFloat());
  1418. auto minW = (float) constrainer->getMinimumWidth();
  1419. auto maxW = (float) constrainer->getMaximumWidth();
  1420. auto minH = (float) constrainer->getMinimumHeight();
  1421. auto maxH = (float) constrainer->getMaximumHeight();
  1422. auto width = jlimit (minW, maxW, editorBounds.getWidth());
  1423. auto height = jlimit (minH, maxH, editorBounds.getHeight());
  1424. auto aspectRatio = (float) constrainer->getFixedAspectRatio();
  1425. if (aspectRatio != 0.0)
  1426. {
  1427. bool adjustWidth = (width / height > aspectRatio);
  1428. if (getHostType().type == PluginHostType::SteinbergCubase9)
  1429. {
  1430. auto currentEditorBounds = editor->getBounds().toFloat();
  1431. if (currentEditorBounds.getWidth() == width && currentEditorBounds.getHeight() != height)
  1432. adjustWidth = true;
  1433. else if (currentEditorBounds.getHeight() == height && currentEditorBounds.getWidth() != width)
  1434. adjustWidth = false;
  1435. }
  1436. if (adjustWidth)
  1437. {
  1438. width = height * aspectRatio;
  1439. if (width > maxW || width < minW)
  1440. {
  1441. width = jlimit (minW, maxW, width);
  1442. height = width / aspectRatio;
  1443. }
  1444. }
  1445. else
  1446. {
  1447. height = width / aspectRatio;
  1448. if (height > maxH || height < minH)
  1449. {
  1450. height = jlimit (minH, maxH, height);
  1451. width = height * aspectRatio;
  1452. }
  1453. }
  1454. }
  1455. auto constrainedRect = component->getLocalArea (editor, Rectangle<float> (width, height))
  1456. .getSmallestIntegerContainer();
  1457. rectToCheck->right = rectToCheck->left + roundToInt (constrainedRect.getWidth());
  1458. rectToCheck->bottom = rectToCheck->top + roundToInt (constrainedRect.getHeight());
  1459. *rectToCheck = convertToHostBounds (*rectToCheck);
  1460. }
  1461. }
  1462. return kResultTrue;
  1463. }
  1464. jassertfalse;
  1465. return kResultFalse;
  1466. }
  1467. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  1468. {
  1469. #if ! JUCE_MAC
  1470. if (! approximatelyEqual ((float) factor, editorScaleFactor))
  1471. {
  1472. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1473. // Cubase 10 only sends integer scale factors, so correct this for fractional scales
  1474. if (getHostType().type == PluginHostType::SteinbergCubase10)
  1475. {
  1476. auto hostWindowScale = (Steinberg::IPlugViewContentScaleSupport::ScaleFactor) getScaleFactorForWindow ((HWND) systemWindow);
  1477. if (hostWindowScale > 0.0 && ! approximatelyEqual (factor, hostWindowScale))
  1478. factor = hostWindowScale;
  1479. }
  1480. #endif
  1481. editorScaleFactor = (float) factor;
  1482. if (owner != nullptr)
  1483. owner->lastScaleFactorReceived = editorScaleFactor;
  1484. if (component != nullptr)
  1485. component->setEditorScaleFactor (editorScaleFactor);
  1486. }
  1487. return kResultTrue;
  1488. #else
  1489. ignoreUnused (factor);
  1490. return kResultFalse;
  1491. #endif
  1492. }
  1493. private:
  1494. void timerCallback() override
  1495. {
  1496. stopTimer();
  1497. ViewRect viewRect;
  1498. getSize (&viewRect);
  1499. onSize (&viewRect);
  1500. }
  1501. static ViewRect convertToHostBounds (ViewRect pluginRect)
  1502. {
  1503. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1504. if (approximatelyEqual (desktopScale, 1.0f))
  1505. return pluginRect;
  1506. return { roundToInt ((float) pluginRect.left * desktopScale),
  1507. roundToInt ((float) pluginRect.top * desktopScale),
  1508. roundToInt ((float) pluginRect.right * desktopScale),
  1509. roundToInt ((float) pluginRect.bottom * desktopScale) };
  1510. }
  1511. static ViewRect convertFromHostBounds (ViewRect hostRect)
  1512. {
  1513. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1514. if (approximatelyEqual (desktopScale, 1.0f))
  1515. return hostRect;
  1516. return { roundToInt ((float) hostRect.left / desktopScale),
  1517. roundToInt ((float) hostRect.top / desktopScale),
  1518. roundToInt ((float) hostRect.right / desktopScale),
  1519. roundToInt ((float) hostRect.bottom / desktopScale) };
  1520. }
  1521. //==============================================================================
  1522. struct ContentWrapperComponent : public Component
  1523. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1524. , public Timer
  1525. #endif
  1526. {
  1527. ContentWrapperComponent (JuceVST3Editor& editor) : owner (editor)
  1528. {
  1529. setOpaque (true);
  1530. setBroughtToFrontOnMouseClick (true);
  1531. }
  1532. ~ContentWrapperComponent() override
  1533. {
  1534. if (pluginEditor != nullptr)
  1535. {
  1536. PopupMenu::dismissAllActiveMenus();
  1537. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  1538. }
  1539. }
  1540. void createEditor (AudioProcessor& plugin)
  1541. {
  1542. pluginEditor.reset (plugin.createEditorIfNeeded());
  1543. if (pluginEditor != nullptr)
  1544. {
  1545. editorHostContext = std::make_unique<EditorHostContext> (*owner.owner->audioProcessor,
  1546. *pluginEditor,
  1547. owner.owner->getComponentHandler(),
  1548. &owner);
  1549. pluginEditor->setHostContext (editorHostContext.get());
  1550. addAndMakeVisible (pluginEditor.get());
  1551. pluginEditor->setTopLeftPosition (0, 0);
  1552. lastBounds = getSizeToContainChild();
  1553. {
  1554. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1555. setBounds (lastBounds);
  1556. }
  1557. resizeHostWindow();
  1558. }
  1559. else
  1560. {
  1561. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  1562. jassertfalse;
  1563. }
  1564. }
  1565. void paint (Graphics& g) override
  1566. {
  1567. g.fillAll (Colours::black);
  1568. }
  1569. juce::Rectangle<int> getSizeToContainChild()
  1570. {
  1571. if (pluginEditor != nullptr)
  1572. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  1573. return {};
  1574. }
  1575. void childBoundsChanged (Component*) override
  1576. {
  1577. if (resizingChild)
  1578. return;
  1579. auto newBounds = getSizeToContainChild();
  1580. if (newBounds != lastBounds)
  1581. {
  1582. resizeHostWindow();
  1583. #if JUCE_LINUX || JUCE_BSD
  1584. if (getHostType().isBitwigStudio())
  1585. repaint();
  1586. #endif
  1587. lastBounds = newBounds;
  1588. }
  1589. }
  1590. void resized() override
  1591. {
  1592. if (pluginEditor != nullptr)
  1593. {
  1594. if (! resizingParent)
  1595. {
  1596. auto newBounds = getLocalBounds();
  1597. {
  1598. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1599. pluginEditor->setBounds (pluginEditor->getLocalArea (this, newBounds).withPosition (0, 0));
  1600. }
  1601. lastBounds = newBounds;
  1602. }
  1603. }
  1604. }
  1605. void parentSizeChanged() override
  1606. {
  1607. if (pluginEditor != nullptr)
  1608. {
  1609. resizeHostWindow();
  1610. pluginEditor->repaint();
  1611. }
  1612. }
  1613. void resizeHostWindow()
  1614. {
  1615. if (pluginEditor != nullptr)
  1616. {
  1617. if (owner.plugFrame != nullptr)
  1618. {
  1619. auto editorBounds = getSizeToContainChild();
  1620. auto newSize = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  1621. {
  1622. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1623. owner.plugFrame->resizeView (&owner, &newSize);
  1624. }
  1625. auto host = getHostType();
  1626. #if JUCE_MAC
  1627. if (host.isWavelab() || host.isReaper())
  1628. #else
  1629. if (host.isWavelab() || host.isAbletonLive() || host.isBitwigStudio())
  1630. #endif
  1631. setBounds (editorBounds.withPosition (0, 0));
  1632. }
  1633. }
  1634. }
  1635. void setEditorScaleFactor (float scale)
  1636. {
  1637. if (pluginEditor != nullptr)
  1638. {
  1639. auto prevEditorBounds = pluginEditor->getLocalArea (this, lastBounds);
  1640. {
  1641. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1642. pluginEditor->setScaleFactor (scale);
  1643. pluginEditor->setBounds (prevEditorBounds.withPosition (0, 0));
  1644. }
  1645. lastBounds = getSizeToContainChild();
  1646. resizeHostWindow();
  1647. repaint();
  1648. }
  1649. }
  1650. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1651. void checkHostWindowScaleFactor()
  1652. {
  1653. auto hostWindowScale = (float) getScaleFactorForWindow ((HWND) owner.systemWindow);
  1654. if (hostWindowScale > 0.0 && ! approximatelyEqual (hostWindowScale, owner.editorScaleFactor))
  1655. owner.setContentScaleFactor (hostWindowScale);
  1656. }
  1657. void timerCallback() override
  1658. {
  1659. checkHostWindowScaleFactor();
  1660. }
  1661. #endif
  1662. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  1663. private:
  1664. JuceVST3Editor& owner;
  1665. std::unique_ptr<EditorHostContext> editorHostContext;
  1666. Rectangle<int> lastBounds;
  1667. bool resizingChild = false, resizingParent = false;
  1668. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  1669. };
  1670. void createContentWrapperComponentIfNeeded()
  1671. {
  1672. if (component == nullptr)
  1673. {
  1674. #if JUCE_LINUX || JUCE_BSD
  1675. const MessageManagerLock mmLock;
  1676. #endif
  1677. component.reset (new ContentWrapperComponent (*this));
  1678. component->createEditor (pluginInstance);
  1679. }
  1680. }
  1681. //==============================================================================
  1682. ScopedJuceInitialiser_GUI libraryInitialiser;
  1683. #if JUCE_LINUX || JUCE_BSD
  1684. SharedResourcePointer<MessageThread> messageThread;
  1685. SharedResourcePointer<EventHandler> eventHandler;
  1686. #endif
  1687. VSTComSmartPtr<JuceVST3EditController> owner;
  1688. AudioProcessor& pluginInstance;
  1689. #if JUCE_LINUX || JUCE_BSD
  1690. struct MessageManagerLockedDeleter
  1691. {
  1692. template <typename ObjectType>
  1693. void operator() (ObjectType* object) const noexcept
  1694. {
  1695. const MessageManagerLock mmLock;
  1696. delete object;
  1697. }
  1698. };
  1699. std::unique_ptr<ContentWrapperComponent, MessageManagerLockedDeleter> component;
  1700. #else
  1701. std::unique_ptr<ContentWrapperComponent> component;
  1702. #endif
  1703. friend struct ContentWrapperComponent;
  1704. #if JUCE_MAC
  1705. void* macHostWindow = nullptr;
  1706. bool isNSView = false;
  1707. // On macOS Cubase 10 resizes the host window after calling onSize() resulting in the peer
  1708. // bounds being a step behind the plug-in. Calling updateBounds() asynchronously seems to fix things...
  1709. struct Cubase10WindowResizeWorkaround : public AsyncUpdater
  1710. {
  1711. Cubase10WindowResizeWorkaround (JuceVST3Editor& o) : owner (o) {}
  1712. void handleAsyncUpdate() override
  1713. {
  1714. if (owner.component != nullptr)
  1715. if (auto* peer = owner.component->getPeer())
  1716. peer->updateBounds();
  1717. }
  1718. JuceVST3Editor& owner;
  1719. };
  1720. std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
  1721. #else
  1722. float editorScaleFactor = 1.0f;
  1723. #if JUCE_WINDOWS
  1724. WindowsHooks hooks;
  1725. #endif
  1726. #endif
  1727. //==============================================================================
  1728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  1729. };
  1730. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  1731. };
  1732. namespace
  1733. {
  1734. template <typename FloatType> struct AudioBusPointerHelper {};
  1735. template <> struct AudioBusPointerHelper<float> { static float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  1736. template <> struct AudioBusPointerHelper<double> { static double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  1737. template <typename FloatType> struct ChooseBufferHelper {};
  1738. template <> struct ChooseBufferHelper<float> { static AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  1739. template <> struct ChooseBufferHelper<double> { static AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  1740. }
  1741. //==============================================================================
  1742. class JuceVST3Component : public Vst::IComponent,
  1743. public Vst::IAudioProcessor,
  1744. public Vst::IUnitInfo,
  1745. public Vst::IConnectionPoint,
  1746. public Vst::IProcessContextRequirements,
  1747. public AudioPlayHead
  1748. {
  1749. public:
  1750. JuceVST3Component (Vst::IHostApplication* h)
  1751. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  1752. host (h)
  1753. {
  1754. inParameterChangedCallback = false;
  1755. #ifdef JucePlugin_PreferredChannelConfigurations
  1756. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1757. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1758. ignoreUnused (numConfigs);
  1759. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1760. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1761. #endif
  1762. // VST-3 requires your default layout to be non-discrete!
  1763. // For example, your default layout must be mono, stereo, quadrophonic
  1764. // and not AudioChannelSet::discreteChannels (2) etc.
  1765. jassert (checkBusFormatsAreNotDiscrete());
  1766. comPluginInstance = VSTComSmartPtr<JuceAudioProcessor> { new JuceAudioProcessor (pluginInstance) };
  1767. zerostruct (processContext);
  1768. processSetup.maxSamplesPerBlock = 1024;
  1769. processSetup.processMode = Vst::kRealtime;
  1770. processSetup.sampleRate = 44100.0;
  1771. processSetup.symbolicSampleSize = Vst::kSample32;
  1772. pluginInstance->setPlayHead (this);
  1773. // Constructing the underlying static object involves dynamic allocation.
  1774. // This call ensures that the construction won't happen on the audio thread.
  1775. getHostType();
  1776. }
  1777. ~JuceVST3Component() override
  1778. {
  1779. if (juceVST3EditController != nullptr)
  1780. juceVST3EditController->vst3IsPlaying = false;
  1781. if (pluginInstance != nullptr)
  1782. if (pluginInstance->getPlayHead() == this)
  1783. pluginInstance->setPlayHead (nullptr);
  1784. }
  1785. //==============================================================================
  1786. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1787. //==============================================================================
  1788. static const FUID iid;
  1789. JUCE_DECLARE_VST3_COM_REF_METHODS
  1790. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1791. {
  1792. const auto userProvidedInterface = queryAdditionalInterfaces (&getPluginInstance(),
  1793. targetIID,
  1794. &VST3ClientExtensions::queryIAudioProcessor);
  1795. const auto juceProvidedInterface = queryInterfaceInternal (targetIID);
  1796. return extractResult (userProvidedInterface, juceProvidedInterface, obj);
  1797. }
  1798. //==============================================================================
  1799. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1800. {
  1801. if (host != hostContext)
  1802. host.loadFrom (hostContext);
  1803. processContext.sampleRate = processSetup.sampleRate;
  1804. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  1805. return kResultTrue;
  1806. }
  1807. tresult PLUGIN_API terminate() override
  1808. {
  1809. getPluginInstance().releaseResources();
  1810. return kResultTrue;
  1811. }
  1812. //==============================================================================
  1813. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1814. {
  1815. if (other != nullptr && juceVST3EditController == nullptr)
  1816. juceVST3EditController.loadFrom (other);
  1817. return kResultTrue;
  1818. }
  1819. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1820. {
  1821. if (juceVST3EditController != nullptr)
  1822. juceVST3EditController->vst3IsPlaying = false;
  1823. juceVST3EditController = {};
  1824. return kResultTrue;
  1825. }
  1826. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1827. {
  1828. if (message != nullptr && juceVST3EditController == nullptr)
  1829. {
  1830. Steinberg::int64 value = 0;
  1831. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1832. {
  1833. juceVST3EditController = VSTComSmartPtr<JuceVST3EditController> { (JuceVST3EditController*) (pointer_sized_int) value };
  1834. if (juceVST3EditController != nullptr)
  1835. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1836. else
  1837. jassertfalse;
  1838. }
  1839. }
  1840. return kResultTrue;
  1841. }
  1842. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1843. {
  1844. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1845. return kResultTrue;
  1846. }
  1847. //==============================================================================
  1848. tresult PLUGIN_API setActive (TBool state) override
  1849. {
  1850. if (! state)
  1851. {
  1852. getPluginInstance().releaseResources();
  1853. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1854. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1855. }
  1856. else
  1857. {
  1858. auto sampleRate = getPluginInstance().getSampleRate();
  1859. auto bufferSize = getPluginInstance().getBlockSize();
  1860. sampleRate = processSetup.sampleRate > 0.0
  1861. ? processSetup.sampleRate
  1862. : sampleRate;
  1863. bufferSize = processSetup.maxSamplesPerBlock > 0
  1864. ? (int) processSetup.maxSamplesPerBlock
  1865. : bufferSize;
  1866. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1867. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1868. preparePlugin (sampleRate, bufferSize);
  1869. }
  1870. return kResultOk;
  1871. }
  1872. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1873. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1874. //==============================================================================
  1875. bool isBypassed()
  1876. {
  1877. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1878. return (bypassParam->getValue() != 0.0f);
  1879. return false;
  1880. }
  1881. void setBypassed (bool shouldBeBypassed)
  1882. {
  1883. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1884. setValueAndNotifyIfChanged (*bypassParam, shouldBeBypassed ? 1.0f : 0.0f);
  1885. }
  1886. //==============================================================================
  1887. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1888. {
  1889. if (pluginInstance->getBypassParameter() == nullptr)
  1890. {
  1891. ValueTree privateData (kJucePrivateDataIdentifier);
  1892. // for now we only store the bypass value
  1893. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1894. privateData.writeToStream (out);
  1895. }
  1896. }
  1897. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1898. {
  1899. if (pluginInstance->getBypassParameter() == nullptr)
  1900. {
  1901. if (comPluginInstance->getBypassParameter() != nullptr)
  1902. {
  1903. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1904. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1905. }
  1906. }
  1907. }
  1908. void getStateInformation (MemoryBlock& destData)
  1909. {
  1910. pluginInstance->getStateInformation (destData);
  1911. // With bypass support, JUCE now needs to store private state data.
  1912. // Put this at the end of the plug-in state and add a few null characters
  1913. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1914. // this data. Additionally, we need to add some sort of magic identifier
  1915. // at the very end of the private data so that JUCE has some sort of
  1916. // way to figure out if the data was stored with a newer JUCE version.
  1917. MemoryOutputStream extraData;
  1918. extraData.writeInt64 (0);
  1919. writeJucePrivateStateInformation (extraData);
  1920. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1921. extraData.writeInt64 (privateDataSize);
  1922. extraData << kJucePrivateDataIdentifier;
  1923. // write magic string
  1924. destData.append (extraData.getData(), extraData.getDataSize());
  1925. }
  1926. void setStateInformation (const void* data, int sizeAsInt)
  1927. {
  1928. auto size = (uint64) sizeAsInt;
  1929. // Check if this data was written with a newer JUCE version
  1930. // and if it has the JUCE private data magic code at the end
  1931. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1932. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1933. {
  1934. auto buffer = static_cast<const char*> (data);
  1935. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1936. CharPointer_UTF8 (buffer + size));
  1937. if (magic == kJucePrivateDataIdentifier)
  1938. {
  1939. // found a JUCE private data section
  1940. uint64 privateDataSize;
  1941. std::memcpy (&privateDataSize,
  1942. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1943. sizeof (uint64));
  1944. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1945. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1946. if (privateDataSize > 0)
  1947. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1948. size -= sizeof (uint64);
  1949. }
  1950. }
  1951. if (size > 0)
  1952. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1953. }
  1954. //==============================================================================
  1955. #if JUCE_VST3_CAN_REPLACE_VST2
  1956. bool loadVST2VstWBlock (const char* data, int size)
  1957. {
  1958. jassert (ByteOrder::bigEndianInt ("VstW") == htonl ((uint32) readUnaligned<int32> (data)));
  1959. jassert (1 == htonl ((uint32) readUnaligned<int32> (data + 8))); // version should be 1 according to Steinberg's docs
  1960. auto headerLen = (int) htonl ((uint32) readUnaligned<int32> (data + 4)) + 8;
  1961. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1962. }
  1963. bool loadVST2CcnKBlock (const char* data, int size)
  1964. {
  1965. auto* bank = reinterpret_cast<const Vst2::fxBank*> (data);
  1966. jassert (ByteOrder::bigEndianInt ("CcnK") == htonl ((uint32) bank->chunkMagic));
  1967. jassert (ByteOrder::bigEndianInt ("FBCh") == htonl ((uint32) bank->fxMagic));
  1968. jassert (htonl ((uint32) bank->version) == 1 || htonl ((uint32) bank->version) == 2);
  1969. jassert (JucePlugin_VSTUniqueID == htonl ((uint32) bank->fxID));
  1970. setStateInformation (bank->content.data.chunk,
  1971. jmin ((int) (size - (bank->content.data.chunk - data)),
  1972. (int) htonl ((uint32) bank->content.data.size)));
  1973. return true;
  1974. }
  1975. bool loadVST3PresetFile (const char* data, int size)
  1976. {
  1977. if (size < 48)
  1978. return false;
  1979. // At offset 4 there's a little-endian version number which seems to typically be 1
  1980. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1981. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1982. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1983. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1984. jassert (entryCount > 0);
  1985. for (int i = 0; i < entryCount; ++i)
  1986. {
  1987. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1988. if (entryOffset + 20 > size)
  1989. return false;
  1990. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1991. {
  1992. // "Comp" entries seem to contain the data.
  1993. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1994. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1995. if (static_cast<uint64> (chunkOffset + chunkSize) > static_cast<uint64> (size))
  1996. {
  1997. jassertfalse;
  1998. return false;
  1999. }
  2000. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  2001. }
  2002. }
  2003. return true;
  2004. }
  2005. bool loadVST2CompatibleState (const char* data, int size)
  2006. {
  2007. if (size < 4)
  2008. return false;
  2009. auto header = htonl ((uint32) readUnaligned<int32> (data));
  2010. if (header == ByteOrder::bigEndianInt ("VstW"))
  2011. return loadVST2VstWBlock (data, size);
  2012. if (header == ByteOrder::bigEndianInt ("CcnK"))
  2013. return loadVST2CcnKBlock (data, size);
  2014. if (memcmp (data, "VST3", 4) == 0)
  2015. {
  2016. // In Cubase 5, when loading VST3 .vstpreset files,
  2017. // we get the whole content of the files to load.
  2018. // In Cubase 7 we get just the contents within and
  2019. // we go directly to the loadVST2VstW codepath instead.
  2020. return loadVST3PresetFile (data, size);
  2021. }
  2022. return false;
  2023. }
  2024. #endif
  2025. void loadStateData (const void* data, int size)
  2026. {
  2027. #if JUCE_VST3_CAN_REPLACE_VST2
  2028. if (loadVST2CompatibleState ((const char*) data, size))
  2029. return;
  2030. #endif
  2031. setStateInformation (data, size);
  2032. }
  2033. bool readFromMemoryStream (IBStream* state)
  2034. {
  2035. FUnknownPtr<ISizeableStream> s (state);
  2036. Steinberg::int64 size = 0;
  2037. if (s != nullptr
  2038. && s->getStreamSize (size) == kResultOk
  2039. && size > 0
  2040. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  2041. {
  2042. MemoryBlock block (static_cast<size_t> (size));
  2043. // turns out that Cubase 9 might give you the incorrect stream size :-(
  2044. Steinberg::int32 bytesRead = 1;
  2045. int len;
  2046. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  2047. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  2048. break;
  2049. if (len == 0)
  2050. return false;
  2051. block.setSize (static_cast<size_t> (len));
  2052. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  2053. if (getHostType().isAdobeAudition())
  2054. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  2055. return false;
  2056. loadStateData (block.getData(), (int) block.getSize());
  2057. return true;
  2058. }
  2059. return false;
  2060. }
  2061. bool readFromUnknownStream (IBStream* state)
  2062. {
  2063. MemoryOutputStream allData;
  2064. {
  2065. const size_t bytesPerBlock = 4096;
  2066. HeapBlock<char> buffer (bytesPerBlock);
  2067. for (;;)
  2068. {
  2069. Steinberg::int32 bytesRead = 0;
  2070. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  2071. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  2072. break;
  2073. allData.write (buffer, static_cast<size_t> (bytesRead));
  2074. }
  2075. }
  2076. const size_t dataSize = allData.getDataSize();
  2077. if (dataSize <= 0 || dataSize >= 0x7fffffff)
  2078. return false;
  2079. loadStateData (allData.getData(), (int) dataSize);
  2080. return true;
  2081. }
  2082. tresult PLUGIN_API setState (IBStream* state) override
  2083. {
  2084. if (state == nullptr)
  2085. return kInvalidArgument;
  2086. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  2087. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  2088. {
  2089. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  2090. return kResultTrue;
  2091. if (readFromUnknownStream (state))
  2092. return kResultTrue;
  2093. }
  2094. return kResultFalse;
  2095. }
  2096. #if JUCE_VST3_CAN_REPLACE_VST2
  2097. static tresult writeVST2Header (IBStream* state, bool bypassed)
  2098. {
  2099. auto writeVST2IntToState = [state] (uint32 n)
  2100. {
  2101. auto t = (int32) htonl (n);
  2102. return state->write (&t, 4);
  2103. };
  2104. auto status = writeVST2IntToState (ByteOrder::bigEndianInt ("VstW"));
  2105. if (status == kResultOk) status = writeVST2IntToState (8); // header size
  2106. if (status == kResultOk) status = writeVST2IntToState (1); // version
  2107. if (status == kResultOk) status = writeVST2IntToState (bypassed ? 1 : 0); // bypass
  2108. return status;
  2109. }
  2110. #endif
  2111. tresult PLUGIN_API getState (IBStream* state) override
  2112. {
  2113. if (state == nullptr)
  2114. return kInvalidArgument;
  2115. MemoryBlock mem;
  2116. getStateInformation (mem);
  2117. #if JUCE_VST3_CAN_REPLACE_VST2
  2118. tresult status = writeVST2Header (state, isBypassed());
  2119. if (status != kResultOk)
  2120. return status;
  2121. const int bankBlockSize = 160;
  2122. Vst2::fxBank bank;
  2123. zerostruct (bank);
  2124. bank.chunkMagic = (int32) htonl (ByteOrder::bigEndianInt ("CcnK"));
  2125. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  2126. bank.fxMagic = (int32) htonl (ByteOrder::bigEndianInt ("FBCh"));
  2127. bank.version = (int32) htonl (2);
  2128. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  2129. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  2130. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  2131. status = state->write (&bank, bankBlockSize);
  2132. if (status != kResultOk)
  2133. return status;
  2134. #endif
  2135. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  2136. }
  2137. //==============================================================================
  2138. Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
  2139. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
  2140. Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
  2141. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
  2142. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
  2143. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  2144. Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
  2145. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
  2146. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  2147. Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
  2148. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
  2149. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  2150. Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
  2151. Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
  2152. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  2153. Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
  2154. //==============================================================================
  2155. bool getCurrentPosition (CurrentPositionInfo& info) override
  2156. {
  2157. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  2158. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  2159. info.bpm = jmax (1.0, processContext.tempo);
  2160. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  2161. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  2162. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  2163. info.ppqPosition = processContext.projectTimeMusic;
  2164. info.ppqLoopStart = processContext.cycleStartMusic;
  2165. info.ppqLoopEnd = processContext.cycleEndMusic;
  2166. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  2167. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  2168. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  2169. info.frameRate = [&]
  2170. {
  2171. if ((processContext.state & Vst::ProcessContext::kSmpteValid) == 0)
  2172. return fpsUnknown;
  2173. const auto interpretFlags = [&] (FrameRateType basicRate,
  2174. FrameRateType pullDownRate,
  2175. FrameRateType dropRate,
  2176. FrameRateType pullDownDropRate)
  2177. {
  2178. switch (processContext.frameRate.flags & (Vst::FrameRate::kPullDownRate | Vst::FrameRate::kDropRate))
  2179. {
  2180. case Vst::FrameRate::kPullDownRate | Vst::FrameRate::kDropRate:
  2181. return pullDownDropRate;
  2182. case Vst::FrameRate::kPullDownRate:
  2183. return pullDownRate;
  2184. case Vst::FrameRate::kDropRate:
  2185. return dropRate;
  2186. }
  2187. return basicRate;
  2188. };
  2189. switch (processContext.frameRate.framesPerSecond)
  2190. {
  2191. case 24:
  2192. return interpretFlags (fps24, fps23976, fps24, fps23976);
  2193. case 25:
  2194. return interpretFlags (fps25, fps25, fps25, fps25);
  2195. case 30:
  2196. return interpretFlags (fps30, fps2997, fps30drop, fps2997drop);
  2197. case 60:
  2198. return interpretFlags (fps60, fps60, fps60drop, fps60drop);
  2199. }
  2200. return fpsUnknown;
  2201. }();
  2202. const auto baseFps = (double) processContext.frameRate.framesPerSecond;
  2203. const auto effectiveFps = (processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0
  2204. ? baseFps * 1000.0 / 1001.0
  2205. : baseFps;
  2206. info.editOriginTime = (double) processContext.smpteOffsetSubframes / (80.0 * effectiveFps);
  2207. return true;
  2208. }
  2209. //==============================================================================
  2210. int getNumAudioBuses (bool isInput) const
  2211. {
  2212. int busCount = pluginInstance->getBusCount (isInput);
  2213. #ifdef JucePlugin_PreferredChannelConfigurations
  2214. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  2215. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  2216. bool hasOnlyZeroChannels = true;
  2217. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  2218. if (configs[i][isInput ? 0 : 1] != 0)
  2219. hasOnlyZeroChannels = false;
  2220. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  2221. #endif
  2222. return busCount;
  2223. }
  2224. //==============================================================================
  2225. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  2226. {
  2227. if (type == Vst::kAudio)
  2228. return getNumAudioBuses (dir == Vst::kInput);
  2229. if (type == Vst::kEvent)
  2230. {
  2231. #if JucePlugin_WantsMidiInput
  2232. if (dir == Vst::kInput)
  2233. return 1;
  2234. #endif
  2235. #if JucePlugin_ProducesMidiOutput
  2236. if (dir == Vst::kOutput)
  2237. return 1;
  2238. #endif
  2239. }
  2240. return 0;
  2241. }
  2242. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  2243. Steinberg::int32 index, Vst::BusInfo& info) override
  2244. {
  2245. if (type == Vst::kAudio)
  2246. {
  2247. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  2248. return kResultFalse;
  2249. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  2250. {
  2251. info.mediaType = Vst::kAudio;
  2252. info.direction = dir;
  2253. info.channelCount = bus->getLastEnabledLayout().size();
  2254. toString128 (info.name, bus->getName());
  2255. info.busType = [&]
  2256. {
  2257. const auto isFirstBus = (index == 0);
  2258. if (dir == Vst::kInput)
  2259. {
  2260. if (isFirstBus)
  2261. {
  2262. if (auto* extensions = dynamic_cast<VST3ClientExtensions*> (pluginInstance))
  2263. return extensions->getPluginHasMainInput() ? Vst::kMain : Vst::kAux;
  2264. return Vst::kMain;
  2265. }
  2266. return Vst::kAux;
  2267. }
  2268. #if JucePlugin_IsSynth
  2269. return Vst::kMain;
  2270. #else
  2271. return isFirstBus ? Vst::kMain : Vst::kAux;
  2272. #endif
  2273. }();
  2274. #ifdef JucePlugin_PreferredChannelConfigurations
  2275. info.flags = Vst::BusInfo::kDefaultActive;
  2276. #else
  2277. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  2278. #endif
  2279. return kResultTrue;
  2280. }
  2281. }
  2282. if (type == Vst::kEvent)
  2283. {
  2284. info.flags = Vst::BusInfo::kDefaultActive;
  2285. #if JucePlugin_WantsMidiInput
  2286. if (dir == Vst::kInput && index == 0)
  2287. {
  2288. info.mediaType = Vst::kEvent;
  2289. info.direction = dir;
  2290. #ifdef JucePlugin_VSTNumMidiInputs
  2291. info.channelCount = JucePlugin_VSTNumMidiInputs;
  2292. #else
  2293. info.channelCount = 16;
  2294. #endif
  2295. toString128 (info.name, TRANS("MIDI Input"));
  2296. info.busType = Vst::kMain;
  2297. return kResultTrue;
  2298. }
  2299. #endif
  2300. #if JucePlugin_ProducesMidiOutput
  2301. if (dir == Vst::kOutput && index == 0)
  2302. {
  2303. info.mediaType = Vst::kEvent;
  2304. info.direction = dir;
  2305. #ifdef JucePlugin_VSTNumMidiOutputs
  2306. info.channelCount = JucePlugin_VSTNumMidiOutputs;
  2307. #else
  2308. info.channelCount = 16;
  2309. #endif
  2310. toString128 (info.name, TRANS("MIDI Output"));
  2311. info.busType = Vst::kMain;
  2312. return kResultTrue;
  2313. }
  2314. #endif
  2315. }
  2316. zerostruct (info);
  2317. return kResultFalse;
  2318. }
  2319. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  2320. {
  2321. if (type == Vst::kEvent)
  2322. {
  2323. #if JucePlugin_WantsMidiInput
  2324. if (index == 0 && dir == Vst::kInput)
  2325. {
  2326. isMidiInputBusEnabled = (state != 0);
  2327. return kResultTrue;
  2328. }
  2329. #endif
  2330. #if JucePlugin_ProducesMidiOutput
  2331. if (index == 0 && dir == Vst::kOutput)
  2332. {
  2333. isMidiOutputBusEnabled = (state != 0);
  2334. return kResultTrue;
  2335. }
  2336. #endif
  2337. return kResultFalse;
  2338. }
  2339. if (type == Vst::kAudio)
  2340. {
  2341. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  2342. return kResultFalse;
  2343. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  2344. {
  2345. #ifdef JucePlugin_PreferredChannelConfigurations
  2346. auto newLayout = pluginInstance->getBusesLayout();
  2347. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  2348. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  2349. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  2350. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  2351. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  2352. return kResultFalse;
  2353. #endif
  2354. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  2355. }
  2356. }
  2357. return kResultFalse;
  2358. }
  2359. bool checkBusFormatsAreNotDiscrete()
  2360. {
  2361. auto numInputBuses = pluginInstance->getBusCount (true);
  2362. auto numOutputBuses = pluginInstance->getBusCount (false);
  2363. for (int i = 0; i < numInputBuses; ++i)
  2364. {
  2365. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  2366. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  2367. return false;
  2368. }
  2369. for (int i = 0; i < numOutputBuses; ++i)
  2370. {
  2371. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  2372. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  2373. return false;
  2374. }
  2375. return true;
  2376. }
  2377. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  2378. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  2379. {
  2380. auto numInputBuses = pluginInstance->getBusCount (true);
  2381. auto numOutputBuses = pluginInstance->getBusCount (false);
  2382. if (numIns > numInputBuses || numOuts > numOutputBuses)
  2383. return false;
  2384. auto requested = pluginInstance->getBusesLayout();
  2385. for (int i = 0; i < numIns; ++i)
  2386. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  2387. for (int i = 0; i < numOuts; ++i)
  2388. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  2389. #ifdef JucePlugin_PreferredChannelConfigurations
  2390. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  2391. if (! AudioProcessor::containsLayout (requested, configs))
  2392. return kResultFalse;
  2393. #endif
  2394. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  2395. }
  2396. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  2397. {
  2398. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  2399. {
  2400. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  2401. return kResultTrue;
  2402. }
  2403. return kResultFalse;
  2404. }
  2405. //==============================================================================
  2406. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  2407. {
  2408. return (symbolicSampleSize == Vst::kSample32
  2409. || (getPluginInstance().supportsDoublePrecisionProcessing()
  2410. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  2411. }
  2412. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  2413. {
  2414. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  2415. }
  2416. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  2417. {
  2418. ScopedInSetupProcessingSetter inSetupProcessingSetter (juceVST3EditController);
  2419. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  2420. return kResultFalse;
  2421. processSetup = newSetup;
  2422. processContext.sampleRate = processSetup.sampleRate;
  2423. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  2424. ? AudioProcessor::doublePrecision
  2425. : AudioProcessor::singlePrecision);
  2426. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  2427. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  2428. return kResultTrue;
  2429. }
  2430. tresult PLUGIN_API setProcessing (TBool state) override
  2431. {
  2432. if (! state)
  2433. getPluginInstance().reset();
  2434. return kResultTrue;
  2435. }
  2436. Steinberg::uint32 PLUGIN_API getTailSamples() override
  2437. {
  2438. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  2439. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  2440. return Vst::kNoTail;
  2441. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  2442. return Vst::kInfiniteTail;
  2443. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  2444. }
  2445. //==============================================================================
  2446. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  2447. {
  2448. jassert (pluginInstance != nullptr);
  2449. auto numParamsChanged = paramChanges.getParameterCount();
  2450. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  2451. {
  2452. if (auto* paramQueue = paramChanges.getParameterData (i))
  2453. {
  2454. auto numPoints = paramQueue->getPointCount();
  2455. Steinberg::int32 offsetSamples = 0;
  2456. double value = 0.0;
  2457. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  2458. {
  2459. auto vstParamID = paramQueue->getParameterId();
  2460. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  2461. if (juceVST3EditController != nullptr && juceVST3EditController->isMidiControllerParamID (vstParamID))
  2462. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  2463. else
  2464. #endif
  2465. {
  2466. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  2467. setValueAndNotifyIfChanged (*param, (float) value);
  2468. }
  2469. }
  2470. }
  2471. }
  2472. }
  2473. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  2474. {
  2475. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  2476. int channel, ctrlNumber;
  2477. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  2478. {
  2479. if (ctrlNumber == Vst::kAfterTouch)
  2480. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  2481. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  2482. else if (ctrlNumber == Vst::kPitchBend)
  2483. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  2484. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  2485. else
  2486. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  2487. jlimit (0, 127, ctrlNumber),
  2488. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  2489. }
  2490. }
  2491. tresult PLUGIN_API process (Vst::ProcessData& data) override
  2492. {
  2493. if (pluginInstance == nullptr)
  2494. return kResultFalse;
  2495. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  2496. return kResultFalse;
  2497. if (data.processContext != nullptr)
  2498. {
  2499. processContext = *data.processContext;
  2500. if (juceVST3EditController != nullptr)
  2501. juceVST3EditController->vst3IsPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  2502. }
  2503. else
  2504. {
  2505. zerostruct (processContext);
  2506. if (juceVST3EditController != nullptr)
  2507. juceVST3EditController->vst3IsPlaying = false;
  2508. }
  2509. midiBuffer.clear();
  2510. if (data.inputParameterChanges != nullptr)
  2511. processParameterChanges (*data.inputParameterChanges);
  2512. #if JucePlugin_WantsMidiInput
  2513. if (isMidiInputBusEnabled && data.inputEvents != nullptr)
  2514. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  2515. #endif
  2516. if (getHostType().isWavelab())
  2517. {
  2518. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  2519. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  2520. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  2521. && (numInputChans + numOutputChans) == 0)
  2522. return kResultFalse;
  2523. }
  2524. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  2525. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  2526. else jassertfalse;
  2527. #if JucePlugin_ProducesMidiOutput
  2528. if (isMidiOutputBusEnabled && data.outputEvents != nullptr)
  2529. MidiEventList::pluginToHostEventList (*data.outputEvents, midiBuffer);
  2530. #endif
  2531. return kResultTrue;
  2532. }
  2533. private:
  2534. InterfaceResultWithDeferredAddRef queryInterfaceInternal (const TUID targetIID)
  2535. {
  2536. const auto result = testForMultiple (*this,
  2537. targetIID,
  2538. UniqueBase<IPluginBase>{},
  2539. UniqueBase<JuceVST3Component>{},
  2540. UniqueBase<Vst::IComponent>{},
  2541. UniqueBase<Vst::IAudioProcessor>{},
  2542. UniqueBase<Vst::IUnitInfo>{},
  2543. UniqueBase<Vst::IConnectionPoint>{},
  2544. UniqueBase<Vst::IProcessContextRequirements>{},
  2545. SharedBase<FUnknown, Vst::IComponent>{});
  2546. if (result.isOk())
  2547. return result;
  2548. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  2549. return { kResultOk, comPluginInstance.get() };
  2550. return {};
  2551. }
  2552. //==============================================================================
  2553. struct ScopedInSetupProcessingSetter
  2554. {
  2555. ScopedInSetupProcessingSetter (JuceVST3EditController* c)
  2556. : controller (c)
  2557. {
  2558. if (controller != nullptr)
  2559. controller->inSetupProcessing = true;
  2560. }
  2561. ~ScopedInSetupProcessingSetter()
  2562. {
  2563. if (controller != nullptr)
  2564. controller->inSetupProcessing = false;
  2565. }
  2566. private:
  2567. JuceVST3EditController* controller = nullptr;
  2568. };
  2569. //==============================================================================
  2570. template <typename FloatType>
  2571. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  2572. {
  2573. int totalInputChans = 0, totalOutputChans = 0;
  2574. bool tmpBufferNeedsClearing = false;
  2575. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  2576. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  2577. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  2578. const auto countValidChannels = [] (Vst::AudioBusBuffers* buffers, int32 num)
  2579. {
  2580. return int (std::distance (buffers, std::find_if (buffers, buffers + num, [] (Vst::AudioBusBuffers& buf)
  2581. {
  2582. return getPointerForAudioBus<FloatType> (buf) == nullptr && buf.numChannels > 0;
  2583. })));
  2584. };
  2585. const auto vstInputs = countValidChannels (data.inputs, data.numInputs);
  2586. const auto vstOutputs = countValidChannels (data.outputs, data.numOutputs);
  2587. {
  2588. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  2589. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  2590. {
  2591. if (auto* busObject = pluginInstance->getBus (false, bus))
  2592. if (! busObject->isEnabled())
  2593. continue;
  2594. if (bus < vstOutputs)
  2595. {
  2596. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  2597. {
  2598. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  2599. for (int i = 0; i < numChans; ++i)
  2600. {
  2601. if (auto dst = busChannels[i])
  2602. {
  2603. if (totalOutputChans >= plugInInputChannels)
  2604. FloatVectorOperations::clear (dst, (int) data.numSamples);
  2605. channelList.set (totalOutputChans++, busChannels[i]);
  2606. }
  2607. }
  2608. }
  2609. }
  2610. else
  2611. {
  2612. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  2613. for (int i = 0; i < numChans; ++i)
  2614. {
  2615. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  2616. {
  2617. tmpBufferNeedsClearing = true;
  2618. channelList.set (totalOutputChans++, tmpBuffer);
  2619. }
  2620. else
  2621. return;
  2622. }
  2623. }
  2624. }
  2625. }
  2626. {
  2627. auto n = jmax (vstInputs, getNumAudioBuses (true));
  2628. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  2629. {
  2630. if (auto* busObject = pluginInstance->getBus (true, bus))
  2631. if (! busObject->isEnabled())
  2632. continue;
  2633. if (bus < vstInputs)
  2634. {
  2635. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  2636. {
  2637. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  2638. for (int i = 0; i < numChans; ++i)
  2639. {
  2640. if (busChannels[i] != nullptr)
  2641. {
  2642. if (totalInputChans >= totalOutputChans)
  2643. channelList.set (totalInputChans, busChannels[i]);
  2644. else
  2645. {
  2646. auto* dst = channelList.getReference (totalInputChans);
  2647. auto* src = busChannels[i];
  2648. if (dst != src)
  2649. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  2650. }
  2651. }
  2652. ++totalInputChans;
  2653. }
  2654. }
  2655. }
  2656. else
  2657. {
  2658. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  2659. for (int i = 0; i < numChans; ++i)
  2660. {
  2661. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  2662. {
  2663. tmpBufferNeedsClearing = true;
  2664. channelList.set (totalInputChans++, tmpBuffer);
  2665. }
  2666. else
  2667. return;
  2668. }
  2669. }
  2670. }
  2671. }
  2672. if (tmpBufferNeedsClearing)
  2673. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  2674. AudioBuffer<FloatType> buffer;
  2675. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  2676. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  2677. {
  2678. const ScopedLock sl (pluginInstance->getCallbackLock());
  2679. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  2680. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  2681. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  2682. #endif
  2683. if (pluginInstance->isSuspended())
  2684. {
  2685. buffer.clear();
  2686. }
  2687. else
  2688. {
  2689. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  2690. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  2691. {
  2692. if (isBypassed())
  2693. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  2694. else
  2695. pluginInstance->processBlock (buffer, midiBuffer);
  2696. }
  2697. }
  2698. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  2699. /* This assertion is caused when you've added some events to the
  2700. midiMessages array in your processBlock() method, which usually means
  2701. that you're trying to send them somewhere. But in this case they're
  2702. getting thrown away.
  2703. If your plugin does want to send MIDI messages, you'll need to set
  2704. the JucePlugin_ProducesMidiOutput macro to 1 in your
  2705. JucePluginCharacteristics.h file.
  2706. If you don't want to produce any MIDI output, then you should clear the
  2707. midiMessages array at the end of your processBlock() method, to
  2708. indicate that you don't want any of the events to be passed through
  2709. to the output.
  2710. */
  2711. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  2712. #endif
  2713. }
  2714. if (auto* changes = data.outputParameterChanges)
  2715. {
  2716. comPluginInstance->forAllChangedParameters ([&] (Vst::ParamID paramID, float value)
  2717. {
  2718. Steinberg::int32 queueIndex = 0;
  2719. if (auto* queue = changes->addParameterData (paramID, queueIndex))
  2720. {
  2721. Steinberg::int32 pointIndex = 0;
  2722. queue->addPoint (0, value, pointIndex);
  2723. }
  2724. });
  2725. }
  2726. }
  2727. //==============================================================================
  2728. template <typename FloatType>
  2729. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2730. {
  2731. channelList.clearQuick();
  2732. channelList.insertMultiple (0, nullptr, 128);
  2733. auto& p = getPluginInstance();
  2734. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  2735. buffer.clear();
  2736. }
  2737. template <typename FloatType>
  2738. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2739. {
  2740. channelList.clearQuick();
  2741. channelList.resize (0);
  2742. buffer.setSize (0, 0);
  2743. }
  2744. template <typename FloatType>
  2745. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  2746. {
  2747. return AudioBusPointerHelper<FloatType>::impl (data);
  2748. }
  2749. template <typename FloatType>
  2750. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  2751. {
  2752. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  2753. // we can't do anything if the host requests to render many more samples than the
  2754. // block size, we need to bail out
  2755. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  2756. return nullptr;
  2757. return buffer.getWritePointer (channel);
  2758. }
  2759. Steinberg::uint32 PLUGIN_API getProcessContextRequirements() override
  2760. {
  2761. return kNeedSystemTime
  2762. | kNeedContinousTimeSamples
  2763. | kNeedProjectTimeMusic
  2764. | kNeedBarPositionMusic
  2765. | kNeedCycleMusic
  2766. | kNeedSamplesToNextClock
  2767. | kNeedTempo
  2768. | kNeedTimeSignature
  2769. | kNeedChord
  2770. | kNeedFrameRate
  2771. | kNeedTransportState;
  2772. }
  2773. void preparePlugin (double sampleRate, int bufferSize)
  2774. {
  2775. auto& p = getPluginInstance();
  2776. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2777. p.prepareToPlay (sampleRate, bufferSize);
  2778. midiBuffer.ensureSize (2048);
  2779. midiBuffer.clear();
  2780. }
  2781. //==============================================================================
  2782. ScopedJuceInitialiser_GUI libraryInitialiser;
  2783. #if JUCE_LINUX || JUCE_BSD
  2784. SharedResourcePointer<MessageThread> messageThread;
  2785. #endif
  2786. std::atomic<int> refCount { 1 };
  2787. AudioProcessor* pluginInstance = nullptr;
  2788. #if JUCE_LINUX || JUCE_BSD
  2789. template <class T>
  2790. struct LockedVSTComSmartPtr
  2791. {
  2792. LockedVSTComSmartPtr() = default;
  2793. LockedVSTComSmartPtr (const VSTComSmartPtr<T>& ptrIn) : ptr (ptrIn) {}
  2794. ~LockedVSTComSmartPtr()
  2795. {
  2796. const MessageManagerLock mmLock;
  2797. ptr = {};
  2798. }
  2799. T* operator->() { return ptr.operator->(); }
  2800. T* get() const noexcept { return ptr.get(); }
  2801. operator T*() const noexcept { return ptr.get(); }
  2802. template <typename... Args>
  2803. bool loadFrom (Args&&... args) { return ptr.loadFrom (std::forward<Args> (args)...); }
  2804. private:
  2805. VSTComSmartPtr<T> ptr;
  2806. };
  2807. LockedVSTComSmartPtr<Vst::IHostApplication> host;
  2808. LockedVSTComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2809. LockedVSTComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2810. #else
  2811. VSTComSmartPtr<Vst::IHostApplication> host;
  2812. VSTComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2813. VSTComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2814. #endif
  2815. /**
  2816. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  2817. this object needs to be copied on every call to process() to be up-to-date...
  2818. */
  2819. Vst::ProcessContext processContext;
  2820. Vst::ProcessSetup processSetup;
  2821. MidiBuffer midiBuffer;
  2822. Array<float*> channelListFloat;
  2823. Array<double*> channelListDouble;
  2824. AudioBuffer<float> emptyBufferFloat;
  2825. AudioBuffer<double> emptyBufferDouble;
  2826. #if JucePlugin_WantsMidiInput
  2827. std::atomic<bool> isMidiInputBusEnabled { true };
  2828. #endif
  2829. #if JucePlugin_ProducesMidiOutput
  2830. std::atomic<bool> isMidiOutputBusEnabled { true };
  2831. #endif
  2832. static const char* kJucePrivateDataIdentifier;
  2833. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2834. };
  2835. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2836. //==============================================================================
  2837. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4310)
  2838. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wall")
  2839. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2840. DEF_CLASS_IID (JuceAudioProcessor)
  2841. #if JUCE_VST3_CAN_REPLACE_VST2
  2842. FUID getFUIDForVST2ID (bool forControllerUID)
  2843. {
  2844. TUID uuid;
  2845. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  2846. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2847. return FUID (uuid);
  2848. }
  2849. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2850. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2851. #else
  2852. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2853. DEF_CLASS_IID (JuceVST3EditController)
  2854. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2855. DEF_CLASS_IID (JuceVST3Component)
  2856. #endif
  2857. JUCE_END_IGNORE_WARNINGS_MSVC
  2858. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  2859. //==============================================================================
  2860. bool initModule();
  2861. bool initModule()
  2862. {
  2863. #if JUCE_MAC
  2864. initialiseMacVST();
  2865. #endif
  2866. return true;
  2867. }
  2868. bool shutdownModule();
  2869. bool shutdownModule()
  2870. {
  2871. return true;
  2872. }
  2873. #undef JUCE_EXPORTED_FUNCTION
  2874. #if JUCE_WINDOWS
  2875. #define JUCE_EXPORTED_FUNCTION
  2876. #else
  2877. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  2878. #endif
  2879. #if JUCE_WINDOWS
  2880. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2881. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2882. #elif JUCE_LINUX || JUCE_BSD
  2883. void* moduleHandle = nullptr;
  2884. int moduleEntryCounter = 0;
  2885. JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle);
  2886. JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle)
  2887. {
  2888. if (++moduleEntryCounter == 1)
  2889. {
  2890. moduleHandle = sharedLibraryHandle;
  2891. return initModule();
  2892. }
  2893. return true;
  2894. }
  2895. JUCE_EXPORTED_FUNCTION bool ModuleExit();
  2896. JUCE_EXPORTED_FUNCTION bool ModuleExit()
  2897. {
  2898. if (--moduleEntryCounter == 0)
  2899. {
  2900. moduleHandle = nullptr;
  2901. return shutdownModule();
  2902. }
  2903. return true;
  2904. }
  2905. #elif JUCE_MAC
  2906. CFBundleRef globalBundleInstance = nullptr;
  2907. juce::uint32 numBundleRefs = 0;
  2908. juce::Array<CFBundleRef> bundleRefs;
  2909. enum { MaxPathLength = 2048 };
  2910. char modulePath[MaxPathLength] = { 0 };
  2911. void* moduleHandle = nullptr;
  2912. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref);
  2913. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  2914. {
  2915. if (ref != nullptr)
  2916. {
  2917. ++numBundleRefs;
  2918. CFRetain (ref);
  2919. bundleRefs.add (ref);
  2920. if (moduleHandle == nullptr)
  2921. {
  2922. globalBundleInstance = ref;
  2923. moduleHandle = ref;
  2924. CFUniquePtr<CFURLRef> tempURL (CFBundleCopyBundleURL (ref));
  2925. CFURLGetFileSystemRepresentation (tempURL.get(), true, (UInt8*) modulePath, MaxPathLength);
  2926. }
  2927. }
  2928. return initModule();
  2929. }
  2930. JUCE_EXPORTED_FUNCTION bool bundleExit();
  2931. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2932. {
  2933. if (shutdownModule())
  2934. {
  2935. if (--numBundleRefs == 0)
  2936. {
  2937. for (int i = 0; i < bundleRefs.size(); ++i)
  2938. CFRelease (bundleRefs.getUnchecked (i));
  2939. bundleRefs.clear();
  2940. }
  2941. return true;
  2942. }
  2943. return false;
  2944. }
  2945. #endif
  2946. //==============================================================================
  2947. /** This typedef represents VST3's createInstance() function signature */
  2948. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2949. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2950. {
  2951. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2952. }
  2953. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2954. {
  2955. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2956. }
  2957. //==============================================================================
  2958. struct JucePluginFactory;
  2959. static JucePluginFactory* globalFactory = nullptr;
  2960. //==============================================================================
  2961. struct JucePluginFactory : public IPluginFactory3
  2962. {
  2963. JucePluginFactory()
  2964. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2965. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2966. {
  2967. }
  2968. virtual ~JucePluginFactory()
  2969. {
  2970. if (globalFactory == this)
  2971. globalFactory = nullptr;
  2972. }
  2973. //==============================================================================
  2974. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2975. {
  2976. if (createFunction == nullptr)
  2977. {
  2978. jassertfalse;
  2979. return false;
  2980. }
  2981. auto entry = std::make_unique<ClassEntry> (info, createFunction);
  2982. entry->infoW.fromAscii (info);
  2983. classes.push_back (std::move (entry));
  2984. return true;
  2985. }
  2986. //==============================================================================
  2987. JUCE_DECLARE_VST3_COM_REF_METHODS
  2988. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2989. {
  2990. const auto result = testForMultiple (*this,
  2991. targetIID,
  2992. UniqueBase<IPluginFactory3>{},
  2993. UniqueBase<IPluginFactory2>{},
  2994. UniqueBase<IPluginFactory>{},
  2995. UniqueBase<FUnknown>{});
  2996. if (result.isOk())
  2997. return result.extract (obj);
  2998. jassertfalse; // Something new?
  2999. *obj = nullptr;
  3000. return kNotImplemented;
  3001. }
  3002. //==============================================================================
  3003. Steinberg::int32 PLUGIN_API countClasses() override
  3004. {
  3005. return (Steinberg::int32) classes.size();
  3006. }
  3007. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  3008. {
  3009. if (info == nullptr)
  3010. return kInvalidArgument;
  3011. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  3012. return kResultOk;
  3013. }
  3014. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  3015. {
  3016. return getPClassInfo<PClassInfo> (index, info);
  3017. }
  3018. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  3019. {
  3020. return getPClassInfo<PClassInfo2> (index, info);
  3021. }
  3022. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  3023. {
  3024. if (info != nullptr)
  3025. {
  3026. if (auto& entry = classes[(size_t) index])
  3027. {
  3028. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  3029. return kResultOk;
  3030. }
  3031. }
  3032. return kInvalidArgument;
  3033. }
  3034. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  3035. {
  3036. ScopedJuceInitialiser_GUI libraryInitialiser;
  3037. #if JUCE_LINUX || JUCE_BSD
  3038. SharedResourcePointer<MessageThread> messageThread;
  3039. #endif
  3040. *obj = nullptr;
  3041. TUID tuid;
  3042. memcpy (tuid, sourceIid, sizeof (TUID));
  3043. #if VST_VERSION >= 0x030608
  3044. auto sourceFuid = FUID::fromTUID (tuid);
  3045. #else
  3046. FUID sourceFuid;
  3047. sourceFuid = tuid;
  3048. #endif
  3049. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  3050. {
  3051. jassertfalse; // The host you're running in has severe implementation issues!
  3052. return kInvalidArgument;
  3053. }
  3054. TUID iidToQuery;
  3055. sourceFuid.toTUID (iidToQuery);
  3056. for (auto& entry : classes)
  3057. {
  3058. if (doUIDsMatch (entry->infoW.cid, cid))
  3059. {
  3060. if (auto* instance = entry->createFunction (host))
  3061. {
  3062. const FReleaser releaser (instance);
  3063. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  3064. return kResultOk;
  3065. }
  3066. break;
  3067. }
  3068. }
  3069. return kNoInterface;
  3070. }
  3071. tresult PLUGIN_API setHostContext (FUnknown* context) override
  3072. {
  3073. host.loadFrom (context);
  3074. if (host != nullptr)
  3075. {
  3076. Vst::String128 name;
  3077. host->getName (name);
  3078. return kResultTrue;
  3079. }
  3080. return kNotImplemented;
  3081. }
  3082. private:
  3083. //==============================================================================
  3084. std::atomic<int> refCount { 1 };
  3085. const PFactoryInfo factoryInfo;
  3086. VSTComSmartPtr<Vst::IHostApplication> host;
  3087. //==============================================================================
  3088. struct ClassEntry
  3089. {
  3090. ClassEntry() noexcept {}
  3091. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  3092. : info2 (info), createFunction (fn) {}
  3093. PClassInfo2 info2;
  3094. PClassInfoW infoW;
  3095. CreateFunction createFunction = {};
  3096. bool isUnicode = false;
  3097. private:
  3098. JUCE_DECLARE_NON_COPYABLE (ClassEntry)
  3099. };
  3100. std::vector<std::unique_ptr<ClassEntry>> classes;
  3101. //==============================================================================
  3102. template <class PClassInfoType>
  3103. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  3104. {
  3105. if (info != nullptr)
  3106. {
  3107. zerostruct (*info);
  3108. if (auto& entry = classes[(size_t) index])
  3109. {
  3110. if (entry->isUnicode)
  3111. return kResultFalse;
  3112. memcpy (info, (PClassInfoType*) &entry->info2, sizeof (PClassInfoType));
  3113. return kResultOk;
  3114. }
  3115. }
  3116. jassertfalse;
  3117. return kInvalidArgument;
  3118. }
  3119. //==============================================================================
  3120. // no leak detector here to prevent it firing on shutdown when running in hosts that
  3121. // don't release the factory object correctly...
  3122. JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
  3123. };
  3124. } // namespace juce
  3125. //==============================================================================
  3126. #ifndef JucePlugin_Vst3ComponentFlags
  3127. #if JucePlugin_IsSynth
  3128. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  3129. #else
  3130. #define JucePlugin_Vst3ComponentFlags 0
  3131. #endif
  3132. #endif
  3133. #ifndef JucePlugin_Vst3Category
  3134. #if JucePlugin_IsSynth
  3135. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  3136. #else
  3137. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  3138. #endif
  3139. #endif
  3140. using namespace juce;
  3141. //==============================================================================
  3142. // The VST3 plugin entry point.
  3143. extern "C" SMTG_EXPORT_SYMBOL IPluginFactory* PLUGIN_API GetPluginFactory()
  3144. {
  3145. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  3146. #if (JUCE_MSVC || (JUCE_WINDOWS && JUCE_CLANG)) && JUCE_32BIT
  3147. // Cunning trick to force this function to be exported. Life's too short to
  3148. // faff around creating .def files for this kind of thing.
  3149. // Unnecessary for 64-bit builds because those don't use decorated function names.
  3150. #pragma comment(linker, "/EXPORT:GetPluginFactory=_GetPluginFactory@0")
  3151. #endif
  3152. if (globalFactory == nullptr)
  3153. {
  3154. globalFactory = new JucePluginFactory();
  3155. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  3156. PClassInfo::kManyInstances,
  3157. kVstAudioEffectClass,
  3158. JucePlugin_Name,
  3159. JucePlugin_Vst3ComponentFlags,
  3160. JucePlugin_Vst3Category,
  3161. JucePlugin_Manufacturer,
  3162. JucePlugin_VersionString,
  3163. kVstVersionString);
  3164. globalFactory->registerClass (componentClass, createComponentInstance);
  3165. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  3166. PClassInfo::kManyInstances,
  3167. kVstComponentControllerClass,
  3168. JucePlugin_Name,
  3169. JucePlugin_Vst3ComponentFlags,
  3170. JucePlugin_Vst3Category,
  3171. JucePlugin_Manufacturer,
  3172. JucePlugin_VersionString,
  3173. kVstVersionString);
  3174. globalFactory->registerClass (controllerClass, createControllerInstance);
  3175. }
  3176. else
  3177. {
  3178. globalFactory->addRef();
  3179. }
  3180. return dynamic_cast<IPluginFactory*> (globalFactory);
  3181. }
  3182. //==============================================================================
  3183. #if JUCE_WINDOWS
  3184. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  3185. #endif
  3186. JUCE_END_NO_SANITIZE
  3187. #endif //JucePlugin_Build_VST3