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.

4170 lines
156KB

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