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.

4240 lines
160KB

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