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.

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