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.

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