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.

3761 lines
137KB

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