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.

3749 lines
137KB

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