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.

3778 lines
138KB

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