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.

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