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.

3767 lines
138KB

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