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.

4160 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. #else
  1381. if (! approximatelyEqual (editorScaleFactor, ec.lastScaleFactorReceived))
  1382. setContentScaleFactor (ec.lastScaleFactorReceived);
  1383. #endif
  1384. }
  1385. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1386. {
  1387. const auto result = testFor (*this, targetIID, UniqueBase<IPlugViewContentScaleSupport>{});
  1388. if (result.isOk())
  1389. return result.extract (obj);
  1390. return Vst::EditorView::queryInterface (targetIID, obj);
  1391. }
  1392. REFCOUNT_METHODS (Vst::EditorView)
  1393. //==============================================================================
  1394. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  1395. {
  1396. if (type != nullptr && pluginInstance.hasEditor())
  1397. {
  1398. #if JUCE_WINDOWS
  1399. if (strcmp (type, kPlatformTypeHWND) == 0)
  1400. #elif JUCE_MAC
  1401. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  1402. #elif JUCE_LINUX || JUCE_BSD
  1403. if (strcmp (type, kPlatformTypeX11EmbedWindowID) == 0)
  1404. #endif
  1405. return kResultTrue;
  1406. }
  1407. return kResultFalse;
  1408. }
  1409. tresult PLUGIN_API attached (void* parent, FIDString type) override
  1410. {
  1411. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  1412. return kResultFalse;
  1413. #if JUCE_LINUX || JUCE_BSD
  1414. eventHandler->registerHandlerForFrame (plugFrame);
  1415. #endif
  1416. systemWindow = parent;
  1417. createContentWrapperComponentIfNeeded();
  1418. #if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
  1419. component->setOpaque (true);
  1420. component->addToDesktop (0, (void*) systemWindow);
  1421. component->setVisible (true);
  1422. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1423. component->checkHostWindowScaleFactor();
  1424. component->startTimer (500);
  1425. #endif
  1426. #else
  1427. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  1428. macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
  1429. #endif
  1430. component->resizeHostWindow();
  1431. attachedToParent();
  1432. // Life's too short to faff around with wave lab
  1433. if (getHostType().isWavelab())
  1434. startTimer (200);
  1435. return kResultTrue;
  1436. }
  1437. tresult PLUGIN_API removed() override
  1438. {
  1439. if (component != nullptr)
  1440. {
  1441. #if JUCE_WINDOWS
  1442. component->removeFromDesktop();
  1443. #elif JUCE_MAC
  1444. if (macHostWindow != nullptr)
  1445. {
  1446. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  1447. macHostWindow = nullptr;
  1448. }
  1449. #endif
  1450. component = nullptr;
  1451. }
  1452. #if JUCE_LINUX || JUCE_BSD
  1453. eventHandler->unregisterHandlerForFrame (plugFrame);
  1454. #endif
  1455. return CPluginView::removed();
  1456. }
  1457. tresult PLUGIN_API onSize (ViewRect* newSize) override
  1458. {
  1459. if (newSize != nullptr)
  1460. {
  1461. rect = convertFromHostBounds (*newSize);
  1462. if (component != nullptr)
  1463. {
  1464. component->setSize (rect.getWidth(), rect.getHeight());
  1465. #if JUCE_MAC
  1466. if (cubase10Workaround != nullptr)
  1467. {
  1468. cubase10Workaround->triggerAsyncUpdate();
  1469. }
  1470. else
  1471. #endif
  1472. {
  1473. if (auto* peer = component->getPeer())
  1474. peer->updateBounds();
  1475. }
  1476. }
  1477. return kResultTrue;
  1478. }
  1479. jassertfalse;
  1480. return kResultFalse;
  1481. }
  1482. tresult PLUGIN_API getSize (ViewRect* size) override
  1483. {
  1484. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1485. if (getHostType().isAbletonLive() && systemWindow == nullptr)
  1486. return kResultFalse;
  1487. #endif
  1488. if (size != nullptr && component != nullptr)
  1489. {
  1490. auto editorBounds = component->getSizeToContainChild();
  1491. *size = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  1492. return kResultTrue;
  1493. }
  1494. return kResultFalse;
  1495. }
  1496. tresult PLUGIN_API canResize() override
  1497. {
  1498. if (component != nullptr)
  1499. if (auto* editor = component->pluginEditor.get())
  1500. if (editor->isResizable())
  1501. return kResultTrue;
  1502. return kResultFalse;
  1503. }
  1504. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  1505. {
  1506. if (rectToCheck != nullptr && component != nullptr)
  1507. {
  1508. if (auto* editor = component->pluginEditor.get())
  1509. {
  1510. if (canResize() == kResultFalse)
  1511. {
  1512. // Ableton Live will call checkSizeConstraint even if the view returns false
  1513. // from canResize. Set the out param to an appropriate size for the editor
  1514. // and return.
  1515. auto constrainedRect = component->getLocalArea (editor, editor->getLocalBounds())
  1516. .getSmallestIntegerContainer();
  1517. *rectToCheck = convertFromHostBounds (*rectToCheck);
  1518. rectToCheck->right = rectToCheck->left + roundToInt (constrainedRect.getWidth());
  1519. rectToCheck->bottom = rectToCheck->top + roundToInt (constrainedRect.getHeight());
  1520. *rectToCheck = convertToHostBounds (*rectToCheck);
  1521. }
  1522. else if (auto* constrainer = editor->getConstrainer())
  1523. {
  1524. *rectToCheck = convertFromHostBounds (*rectToCheck);
  1525. auto editorBounds = editor->getLocalArea (component.get(),
  1526. Rectangle<int>::leftTopRightBottom (rectToCheck->left, rectToCheck->top,
  1527. rectToCheck->right, rectToCheck->bottom).toFloat());
  1528. auto minW = (float) constrainer->getMinimumWidth();
  1529. auto maxW = (float) constrainer->getMaximumWidth();
  1530. auto minH = (float) constrainer->getMinimumHeight();
  1531. auto maxH = (float) constrainer->getMaximumHeight();
  1532. auto width = jlimit (minW, maxW, editorBounds.getWidth());
  1533. auto height = jlimit (minH, maxH, editorBounds.getHeight());
  1534. auto aspectRatio = (float) constrainer->getFixedAspectRatio();
  1535. if (aspectRatio != 0.0)
  1536. {
  1537. bool adjustWidth = (width / height > aspectRatio);
  1538. if (getHostType().type == PluginHostType::SteinbergCubase9)
  1539. {
  1540. auto currentEditorBounds = editor->getBounds().toFloat();
  1541. if (currentEditorBounds.getWidth() == width && currentEditorBounds.getHeight() != height)
  1542. adjustWidth = true;
  1543. else if (currentEditorBounds.getHeight() == height && currentEditorBounds.getWidth() != width)
  1544. adjustWidth = false;
  1545. }
  1546. if (adjustWidth)
  1547. {
  1548. width = height * aspectRatio;
  1549. if (width > maxW || width < minW)
  1550. {
  1551. width = jlimit (minW, maxW, width);
  1552. height = width / aspectRatio;
  1553. }
  1554. }
  1555. else
  1556. {
  1557. height = width / aspectRatio;
  1558. if (height > maxH || height < minH)
  1559. {
  1560. height = jlimit (minH, maxH, height);
  1561. width = height * aspectRatio;
  1562. }
  1563. }
  1564. }
  1565. auto constrainedRect = component->getLocalArea (editor, Rectangle<float> (width, height))
  1566. .getSmallestIntegerContainer();
  1567. rectToCheck->right = rectToCheck->left + roundToInt (constrainedRect.getWidth());
  1568. rectToCheck->bottom = rectToCheck->top + roundToInt (constrainedRect.getHeight());
  1569. *rectToCheck = convertToHostBounds (*rectToCheck);
  1570. }
  1571. }
  1572. return kResultTrue;
  1573. }
  1574. jassertfalse;
  1575. return kResultFalse;
  1576. }
  1577. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  1578. {
  1579. #if ! JUCE_MAC
  1580. if (! approximatelyEqual ((float) factor, editorScaleFactor))
  1581. {
  1582. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1583. // Cubase 10 only sends integer scale factors, so correct this for fractional scales
  1584. if (getHostType().type == PluginHostType::SteinbergCubase10)
  1585. {
  1586. auto hostWindowScale = (Steinberg::IPlugViewContentScaleSupport::ScaleFactor) getScaleFactorForWindow ((HWND) systemWindow);
  1587. if (hostWindowScale > 0.0 && ! approximatelyEqual (factor, hostWindowScale))
  1588. factor = hostWindowScale;
  1589. }
  1590. #endif
  1591. editorScaleFactor = (float) factor;
  1592. if (owner != nullptr)
  1593. owner->lastScaleFactorReceived = editorScaleFactor;
  1594. if (component != nullptr)
  1595. {
  1596. #if JUCE_LINUX || JUCE_BSD
  1597. const MessageManagerLock mmLock;
  1598. #endif
  1599. component->setEditorScaleFactor (editorScaleFactor);
  1600. }
  1601. }
  1602. return kResultTrue;
  1603. #else
  1604. ignoreUnused (factor);
  1605. return kResultFalse;
  1606. #endif
  1607. }
  1608. private:
  1609. void timerCallback() override
  1610. {
  1611. stopTimer();
  1612. ViewRect viewRect;
  1613. getSize (&viewRect);
  1614. onSize (&viewRect);
  1615. }
  1616. static ViewRect convertToHostBounds (ViewRect pluginRect)
  1617. {
  1618. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1619. if (approximatelyEqual (desktopScale, 1.0f))
  1620. return pluginRect;
  1621. return { roundToInt ((float) pluginRect.left * desktopScale),
  1622. roundToInt ((float) pluginRect.top * desktopScale),
  1623. roundToInt ((float) pluginRect.right * desktopScale),
  1624. roundToInt ((float) pluginRect.bottom * desktopScale) };
  1625. }
  1626. static ViewRect convertFromHostBounds (ViewRect hostRect)
  1627. {
  1628. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1629. if (approximatelyEqual (desktopScale, 1.0f))
  1630. return hostRect;
  1631. return { roundToInt ((float) hostRect.left / desktopScale),
  1632. roundToInt ((float) hostRect.top / desktopScale),
  1633. roundToInt ((float) hostRect.right / desktopScale),
  1634. roundToInt ((float) hostRect.bottom / desktopScale) };
  1635. }
  1636. //==============================================================================
  1637. struct ContentWrapperComponent : public Component
  1638. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1639. , public Timer
  1640. #endif
  1641. {
  1642. ContentWrapperComponent (JuceVST3Editor& editor) : owner (editor)
  1643. {
  1644. setOpaque (true);
  1645. setBroughtToFrontOnMouseClick (true);
  1646. }
  1647. ~ContentWrapperComponent() override
  1648. {
  1649. if (pluginEditor != nullptr)
  1650. {
  1651. PopupMenu::dismissAllActiveMenus();
  1652. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  1653. }
  1654. }
  1655. void createEditor (AudioProcessor& plugin)
  1656. {
  1657. pluginEditor.reset (plugin.createEditorIfNeeded());
  1658. #if JucePlugin_Enable_ARA
  1659. jassert (dynamic_cast<AudioProcessorEditorARAExtension*> (pluginEditor.get()) != nullptr);
  1660. // for proper view embedding, ARA plug-ins must be resizable
  1661. jassert (pluginEditor->isResizable());
  1662. #endif
  1663. if (pluginEditor != nullptr)
  1664. {
  1665. editorHostContext = std::make_unique<EditorHostContext> (*owner.owner->audioProcessor,
  1666. *pluginEditor,
  1667. owner.owner->getComponentHandler(),
  1668. &owner);
  1669. pluginEditor->setHostContext (editorHostContext.get());
  1670. #if ! JUCE_MAC
  1671. pluginEditor->setScaleFactor (owner.editorScaleFactor);
  1672. #endif
  1673. addAndMakeVisible (pluginEditor.get());
  1674. pluginEditor->setTopLeftPosition (0, 0);
  1675. lastBounds = getSizeToContainChild();
  1676. {
  1677. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1678. setBounds (lastBounds);
  1679. }
  1680. resizeHostWindow();
  1681. }
  1682. else
  1683. {
  1684. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  1685. jassertfalse;
  1686. }
  1687. }
  1688. void paint (Graphics& g) override
  1689. {
  1690. g.fillAll (Colours::black);
  1691. }
  1692. juce::Rectangle<int> getSizeToContainChild()
  1693. {
  1694. if (pluginEditor != nullptr)
  1695. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  1696. return {};
  1697. }
  1698. void childBoundsChanged (Component*) override
  1699. {
  1700. if (resizingChild)
  1701. return;
  1702. auto newBounds = getSizeToContainChild();
  1703. if (newBounds != lastBounds)
  1704. {
  1705. resizeHostWindow();
  1706. #if JUCE_LINUX || JUCE_BSD
  1707. if (getHostType().isBitwigStudio())
  1708. repaint();
  1709. #endif
  1710. lastBounds = newBounds;
  1711. }
  1712. }
  1713. void resized() override
  1714. {
  1715. if (pluginEditor != nullptr)
  1716. {
  1717. if (! resizingParent)
  1718. {
  1719. auto newBounds = getLocalBounds();
  1720. {
  1721. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1722. pluginEditor->setBounds (pluginEditor->getLocalArea (this, newBounds).withPosition (0, 0));
  1723. }
  1724. lastBounds = newBounds;
  1725. }
  1726. }
  1727. }
  1728. void parentSizeChanged() override
  1729. {
  1730. if (pluginEditor != nullptr)
  1731. {
  1732. resizeHostWindow();
  1733. pluginEditor->repaint();
  1734. }
  1735. }
  1736. void resizeHostWindow()
  1737. {
  1738. if (pluginEditor != nullptr)
  1739. {
  1740. if (owner.plugFrame != nullptr)
  1741. {
  1742. auto editorBounds = getSizeToContainChild();
  1743. auto newSize = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  1744. {
  1745. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1746. owner.plugFrame->resizeView (&owner, &newSize);
  1747. }
  1748. auto host = getHostType();
  1749. #if JUCE_MAC
  1750. if (host.isWavelab() || host.isReaper() || owner.owner->blueCatPatchwork)
  1751. #else
  1752. if (host.isWavelab() || host.isAbletonLive() || host.isBitwigStudio() || owner.owner->blueCatPatchwork)
  1753. #endif
  1754. setBounds (editorBounds.withPosition (0, 0));
  1755. }
  1756. }
  1757. }
  1758. void setEditorScaleFactor (float scale)
  1759. {
  1760. if (pluginEditor != nullptr)
  1761. {
  1762. auto prevEditorBounds = pluginEditor->getLocalArea (this, lastBounds);
  1763. {
  1764. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1765. pluginEditor->setScaleFactor (scale);
  1766. pluginEditor->setBounds (prevEditorBounds.withPosition (0, 0));
  1767. }
  1768. lastBounds = getSizeToContainChild();
  1769. resizeHostWindow();
  1770. repaint();
  1771. }
  1772. }
  1773. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1774. void checkHostWindowScaleFactor()
  1775. {
  1776. auto hostWindowScale = (float) getScaleFactorForWindow ((HWND) owner.systemWindow);
  1777. if (hostWindowScale > 0.0 && ! approximatelyEqual (hostWindowScale, owner.editorScaleFactor))
  1778. owner.setContentScaleFactor (hostWindowScale);
  1779. }
  1780. void timerCallback() override
  1781. {
  1782. checkHostWindowScaleFactor();
  1783. }
  1784. #endif
  1785. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  1786. private:
  1787. JuceVST3Editor& owner;
  1788. std::unique_ptr<EditorHostContext> editorHostContext;
  1789. Rectangle<int> lastBounds;
  1790. bool resizingChild = false, resizingParent = false;
  1791. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  1792. };
  1793. void createContentWrapperComponentIfNeeded()
  1794. {
  1795. if (component == nullptr)
  1796. {
  1797. #if JUCE_LINUX || JUCE_BSD
  1798. const MessageManagerLock mmLock;
  1799. #endif
  1800. component.reset (new ContentWrapperComponent (*this));
  1801. component->createEditor (pluginInstance);
  1802. }
  1803. }
  1804. //==============================================================================
  1805. ScopedJuceInitialiser_GUI libraryInitialiser;
  1806. #if JUCE_LINUX || JUCE_BSD
  1807. SharedResourcePointer<MessageThread> messageThread;
  1808. SharedResourcePointer<EventHandler> eventHandler;
  1809. #endif
  1810. VSTComSmartPtr<JuceVST3EditController> owner;
  1811. AudioProcessor& pluginInstance;
  1812. #if JUCE_LINUX || JUCE_BSD
  1813. struct MessageManagerLockedDeleter
  1814. {
  1815. template <typename ObjectType>
  1816. void operator() (ObjectType* object) const noexcept
  1817. {
  1818. const MessageManagerLock mmLock;
  1819. delete object;
  1820. }
  1821. };
  1822. std::unique_ptr<ContentWrapperComponent, MessageManagerLockedDeleter> component;
  1823. #else
  1824. std::unique_ptr<ContentWrapperComponent> component;
  1825. #endif
  1826. friend struct ContentWrapperComponent;
  1827. #if JUCE_MAC
  1828. void* macHostWindow = nullptr;
  1829. bool isNSView = false;
  1830. // On macOS Cubase 10 resizes the host window after calling onSize() resulting in the peer
  1831. // bounds being a step behind the plug-in. Calling updateBounds() asynchronously seems to fix things...
  1832. struct Cubase10WindowResizeWorkaround : public AsyncUpdater
  1833. {
  1834. Cubase10WindowResizeWorkaround (JuceVST3Editor& o) : owner (o) {}
  1835. void handleAsyncUpdate() override
  1836. {
  1837. if (owner.component != nullptr)
  1838. if (auto* peer = owner.component->getPeer())
  1839. peer->updateBounds();
  1840. }
  1841. JuceVST3Editor& owner;
  1842. };
  1843. std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
  1844. #else
  1845. float editorScaleFactor = 1.0f;
  1846. #if JUCE_WINDOWS
  1847. WindowsHooks hooks;
  1848. #endif
  1849. #endif
  1850. //==============================================================================
  1851. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  1852. };
  1853. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  1854. };
  1855. //==============================================================================
  1856. #if JucePlugin_Enable_ARA
  1857. class JuceARAFactory : public ARA::IMainFactory
  1858. {
  1859. public:
  1860. JuceARAFactory() = default;
  1861. virtual ~JuceARAFactory() = default;
  1862. JUCE_DECLARE_VST3_COM_REF_METHODS
  1863. tresult PLUGIN_API queryInterface (const ::Steinberg::TUID targetIID, void** obj) override
  1864. {
  1865. const auto result = testForMultiple (*this,
  1866. targetIID,
  1867. UniqueBase<ARA::IMainFactory>{},
  1868. UniqueBase<FUnknown>{});
  1869. if (result.isOk())
  1870. return result.extract (obj);
  1871. if (doUIDsMatch (targetIID, JuceARAFactory::iid))
  1872. {
  1873. addRef();
  1874. *obj = this;
  1875. return kResultOk;
  1876. }
  1877. *obj = nullptr;
  1878. return kNoInterface;
  1879. }
  1880. //---from ARA::IMainFactory-------
  1881. const ARA::ARAFactory* PLUGIN_API getFactory() SMTG_OVERRIDE
  1882. {
  1883. return createARAFactory();
  1884. }
  1885. static const FUID iid;
  1886. private:
  1887. //==============================================================================
  1888. std::atomic<int> refCount { 1 };
  1889. };
  1890. #endif
  1891. //==============================================================================
  1892. class JuceVST3Component : public Vst::IComponent,
  1893. public Vst::IAudioProcessor,
  1894. public Vst::IUnitInfo,
  1895. public Vst::IConnectionPoint,
  1896. public Vst::IProcessContextRequirements,
  1897. #if JucePlugin_Enable_ARA
  1898. public ARA::IPlugInEntryPoint,
  1899. public ARA::IPlugInEntryPoint2,
  1900. #endif
  1901. public AudioPlayHead
  1902. {
  1903. public:
  1904. JuceVST3Component (Vst::IHostApplication* h)
  1905. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  1906. host (h)
  1907. {
  1908. inParameterChangedCallback = false;
  1909. #ifdef JucePlugin_PreferredChannelConfigurations
  1910. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1911. const int numConfigs = numElementsInArray (configs);
  1912. ignoreUnused (numConfigs);
  1913. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1914. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1915. #endif
  1916. // VST-3 requires your default layout to be non-discrete!
  1917. // For example, your default layout must be mono, stereo, quadrophonic
  1918. // and not AudioChannelSet::discreteChannels (2) etc.
  1919. jassert (checkBusFormatsAreNotDiscrete());
  1920. comPluginInstance = VSTComSmartPtr<JuceAudioProcessor> { new JuceAudioProcessor (pluginInstance) };
  1921. zerostruct (processContext);
  1922. processSetup.maxSamplesPerBlock = 1024;
  1923. processSetup.processMode = Vst::kRealtime;
  1924. processSetup.sampleRate = 44100.0;
  1925. processSetup.symbolicSampleSize = Vst::kSample32;
  1926. pluginInstance->setPlayHead (this);
  1927. // Constructing the underlying static object involves dynamic allocation.
  1928. // This call ensures that the construction won't happen on the audio thread.
  1929. getHostType();
  1930. }
  1931. ~JuceVST3Component() override
  1932. {
  1933. if (juceVST3EditController != nullptr)
  1934. juceVST3EditController->vst3IsPlaying = false;
  1935. if (pluginInstance != nullptr)
  1936. if (pluginInstance->getPlayHead() == this)
  1937. pluginInstance->setPlayHead (nullptr);
  1938. }
  1939. //==============================================================================
  1940. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1941. //==============================================================================
  1942. static const FUID iid;
  1943. JUCE_DECLARE_VST3_COM_REF_METHODS
  1944. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1945. {
  1946. const auto userProvidedInterface = queryAdditionalInterfaces (&getPluginInstance(),
  1947. targetIID,
  1948. &VST3ClientExtensions::queryIAudioProcessor);
  1949. const auto juceProvidedInterface = queryInterfaceInternal (targetIID);
  1950. return extractResult (userProvidedInterface, juceProvidedInterface, obj);
  1951. }
  1952. enum class CallPrepareToPlay { no, yes };
  1953. //==============================================================================
  1954. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1955. {
  1956. if (host != hostContext)
  1957. host.loadFrom (hostContext);
  1958. processContext.sampleRate = processSetup.sampleRate;
  1959. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock, CallPrepareToPlay::no);
  1960. return kResultTrue;
  1961. }
  1962. tresult PLUGIN_API terminate() override
  1963. {
  1964. getPluginInstance().releaseResources();
  1965. return kResultTrue;
  1966. }
  1967. //==============================================================================
  1968. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1969. {
  1970. if (other != nullptr && juceVST3EditController == nullptr)
  1971. juceVST3EditController.loadFrom (other);
  1972. return kResultTrue;
  1973. }
  1974. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1975. {
  1976. if (juceVST3EditController != nullptr)
  1977. juceVST3EditController->vst3IsPlaying = false;
  1978. juceVST3EditController = {};
  1979. return kResultTrue;
  1980. }
  1981. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1982. {
  1983. if (message != nullptr && juceVST3EditController == nullptr)
  1984. {
  1985. Steinberg::int64 value = 0;
  1986. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1987. {
  1988. juceVST3EditController = VSTComSmartPtr<JuceVST3EditController> { (JuceVST3EditController*) (pointer_sized_int) value };
  1989. if (juceVST3EditController != nullptr)
  1990. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1991. else
  1992. jassertfalse;
  1993. }
  1994. }
  1995. return kResultTrue;
  1996. }
  1997. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1998. {
  1999. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  2000. return kResultTrue;
  2001. }
  2002. //==============================================================================
  2003. tresult PLUGIN_API setActive (TBool state) override
  2004. {
  2005. active = (state != 0);
  2006. if (! state)
  2007. {
  2008. getPluginInstance().releaseResources();
  2009. }
  2010. else
  2011. {
  2012. auto sampleRate = getPluginInstance().getSampleRate();
  2013. auto bufferSize = getPluginInstance().getBlockSize();
  2014. sampleRate = processSetup.sampleRate > 0.0
  2015. ? processSetup.sampleRate
  2016. : sampleRate;
  2017. bufferSize = processSetup.maxSamplesPerBlock > 0
  2018. ? (int) processSetup.maxSamplesPerBlock
  2019. : bufferSize;
  2020. preparePlugin (sampleRate, bufferSize, CallPrepareToPlay::yes);
  2021. }
  2022. return kResultOk;
  2023. }
  2024. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  2025. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  2026. //==============================================================================
  2027. bool isBypassed() const
  2028. {
  2029. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  2030. return bypassParam->getValue() >= 0.5f;
  2031. return false;
  2032. }
  2033. void setBypassed (bool shouldBeBypassed)
  2034. {
  2035. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  2036. setValueAndNotifyIfChanged (*bypassParam, shouldBeBypassed ? 1.0f : 0.0f);
  2037. }
  2038. //==============================================================================
  2039. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  2040. {
  2041. if (pluginInstance->getBypassParameter() == nullptr)
  2042. {
  2043. ValueTree privateData (kJucePrivateDataIdentifier);
  2044. // for now we only store the bypass value
  2045. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  2046. privateData.writeToStream (out);
  2047. }
  2048. }
  2049. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  2050. {
  2051. if (pluginInstance->getBypassParameter() == nullptr)
  2052. {
  2053. if (comPluginInstance->getBypassParameter() != nullptr)
  2054. {
  2055. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  2056. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  2057. }
  2058. }
  2059. }
  2060. void getStateInformation (MemoryBlock& destData)
  2061. {
  2062. pluginInstance->getStateInformation (destData);
  2063. // With bypass support, JUCE now needs to store private state data.
  2064. // Put this at the end of the plug-in state and add a few null characters
  2065. // so that plug-ins built with older versions of JUCE will hopefully ignore
  2066. // this data. Additionally, we need to add some sort of magic identifier
  2067. // at the very end of the private data so that JUCE has some sort of
  2068. // way to figure out if the data was stored with a newer JUCE version.
  2069. MemoryOutputStream extraData;
  2070. extraData.writeInt64 (0);
  2071. writeJucePrivateStateInformation (extraData);
  2072. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  2073. extraData.writeInt64 (privateDataSize);
  2074. extraData << kJucePrivateDataIdentifier;
  2075. // write magic string
  2076. destData.append (extraData.getData(), extraData.getDataSize());
  2077. }
  2078. void setStateInformation (const void* data, int sizeAsInt)
  2079. {
  2080. bool unusedState = false;
  2081. auto& flagToSet = juceVST3EditController != nullptr ? juceVST3EditController->inSetState : unusedState;
  2082. const ScopedValueSetter<bool> scope (flagToSet, true);
  2083. auto size = (uint64) sizeAsInt;
  2084. // Check if this data was written with a newer JUCE version
  2085. // and if it has the JUCE private data magic code at the end
  2086. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  2087. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  2088. {
  2089. auto buffer = static_cast<const char*> (data);
  2090. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  2091. CharPointer_UTF8 (buffer + size));
  2092. if (magic == kJucePrivateDataIdentifier)
  2093. {
  2094. // found a JUCE private data section
  2095. uint64 privateDataSize;
  2096. std::memcpy (&privateDataSize,
  2097. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  2098. sizeof (uint64));
  2099. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  2100. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  2101. if (privateDataSize > 0)
  2102. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  2103. size -= sizeof (uint64);
  2104. }
  2105. }
  2106. if (size > 0)
  2107. pluginInstance->setStateInformation (data, static_cast<int> (size));
  2108. }
  2109. //==============================================================================
  2110. #if JUCE_VST3_CAN_REPLACE_VST2
  2111. bool loadVST2VstWBlock (const char* data, int size)
  2112. {
  2113. jassert (ByteOrder::bigEndianInt ("VstW") == htonl ((uint32) readUnaligned<int32> (data)));
  2114. jassert (1 == htonl ((uint32) readUnaligned<int32> (data + 8))); // version should be 1 according to Steinberg's docs
  2115. auto headerLen = (int) htonl ((uint32) readUnaligned<int32> (data + 4)) + 8;
  2116. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  2117. }
  2118. bool loadVST2CcnKBlock (const char* data, int size)
  2119. {
  2120. auto* bank = reinterpret_cast<const Vst2::fxBank*> (data);
  2121. jassert (ByteOrder::bigEndianInt ("CcnK") == htonl ((uint32) bank->chunkMagic));
  2122. jassert (ByteOrder::bigEndianInt ("FBCh") == htonl ((uint32) bank->fxMagic));
  2123. jassert (htonl ((uint32) bank->version) == 1 || htonl ((uint32) bank->version) == 2);
  2124. jassert (JucePlugin_VSTUniqueID == htonl ((uint32) bank->fxID));
  2125. setStateInformation (bank->content.data.chunk,
  2126. jmin ((int) (size - (bank->content.data.chunk - data)),
  2127. (int) htonl ((uint32) bank->content.data.size)));
  2128. return true;
  2129. }
  2130. bool loadVST3PresetFile (const char* data, int size)
  2131. {
  2132. if (size < 48)
  2133. return false;
  2134. // At offset 4 there's a little-endian version number which seems to typically be 1
  2135. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  2136. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  2137. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  2138. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  2139. jassert (entryCount > 0);
  2140. for (int i = 0; i < entryCount; ++i)
  2141. {
  2142. auto entryOffset = chunkListOffset + 8 + 20 * i;
  2143. if (entryOffset + 20 > size)
  2144. return false;
  2145. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  2146. {
  2147. // "Comp" entries seem to contain the data.
  2148. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  2149. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  2150. if (static_cast<uint64> (chunkOffset + chunkSize) > static_cast<uint64> (size))
  2151. {
  2152. jassertfalse;
  2153. return false;
  2154. }
  2155. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  2156. }
  2157. }
  2158. return true;
  2159. }
  2160. bool loadVST2CompatibleState (const char* data, int size)
  2161. {
  2162. if (size < 4)
  2163. return false;
  2164. auto header = htonl ((uint32) readUnaligned<int32> (data));
  2165. if (header == ByteOrder::bigEndianInt ("VstW"))
  2166. return loadVST2VstWBlock (data, size);
  2167. if (header == ByteOrder::bigEndianInt ("CcnK"))
  2168. return loadVST2CcnKBlock (data, size);
  2169. if (memcmp (data, "VST3", 4) == 0)
  2170. {
  2171. // In Cubase 5, when loading VST3 .vstpreset files,
  2172. // we get the whole content of the files to load.
  2173. // In Cubase 7 we get just the contents within and
  2174. // we go directly to the loadVST2VstW codepath instead.
  2175. return loadVST3PresetFile (data, size);
  2176. }
  2177. return false;
  2178. }
  2179. #endif
  2180. void loadStateData (const void* data, int size)
  2181. {
  2182. #if JUCE_VST3_CAN_REPLACE_VST2
  2183. if (loadVST2CompatibleState ((const char*) data, size))
  2184. return;
  2185. #endif
  2186. setStateInformation (data, size);
  2187. }
  2188. bool readFromMemoryStream (IBStream* state)
  2189. {
  2190. FUnknownPtr<ISizeableStream> s (state);
  2191. Steinberg::int64 size = 0;
  2192. if (s != nullptr
  2193. && s->getStreamSize (size) == kResultOk
  2194. && size > 0
  2195. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  2196. {
  2197. MemoryBlock block (static_cast<size_t> (size));
  2198. // turns out that Cubase 9 might give you the incorrect stream size :-(
  2199. Steinberg::int32 bytesRead = 1;
  2200. int len;
  2201. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  2202. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  2203. break;
  2204. if (len == 0)
  2205. return false;
  2206. block.setSize (static_cast<size_t> (len));
  2207. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  2208. if (getHostType().isAdobeAudition())
  2209. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  2210. return false;
  2211. loadStateData (block.getData(), (int) block.getSize());
  2212. return true;
  2213. }
  2214. return false;
  2215. }
  2216. bool readFromUnknownStream (IBStream* state)
  2217. {
  2218. MemoryOutputStream allData;
  2219. {
  2220. const size_t bytesPerBlock = 4096;
  2221. HeapBlock<char> buffer (bytesPerBlock);
  2222. for (;;)
  2223. {
  2224. Steinberg::int32 bytesRead = 0;
  2225. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  2226. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  2227. break;
  2228. allData.write (buffer, static_cast<size_t> (bytesRead));
  2229. }
  2230. }
  2231. const size_t dataSize = allData.getDataSize();
  2232. if (dataSize <= 0 || dataSize >= 0x7fffffff)
  2233. return false;
  2234. loadStateData (allData.getData(), (int) dataSize);
  2235. return true;
  2236. }
  2237. tresult PLUGIN_API setState (IBStream* state) override
  2238. {
  2239. // The VST3 spec requires that this function is called from the UI thread.
  2240. // If this assertion fires, your host is misbehaving!
  2241. assertHostMessageThread();
  2242. if (state == nullptr)
  2243. return kInvalidArgument;
  2244. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  2245. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  2246. {
  2247. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  2248. return kResultTrue;
  2249. if (readFromUnknownStream (state))
  2250. return kResultTrue;
  2251. }
  2252. return kResultFalse;
  2253. }
  2254. #if JUCE_VST3_CAN_REPLACE_VST2
  2255. static tresult writeVST2Header (IBStream* state, bool bypassed)
  2256. {
  2257. auto writeVST2IntToState = [state] (uint32 n)
  2258. {
  2259. auto t = (int32) htonl (n);
  2260. return state->write (&t, 4);
  2261. };
  2262. auto status = writeVST2IntToState (ByteOrder::bigEndianInt ("VstW"));
  2263. if (status == kResultOk) status = writeVST2IntToState (8); // header size
  2264. if (status == kResultOk) status = writeVST2IntToState (1); // version
  2265. if (status == kResultOk) status = writeVST2IntToState (bypassed ? 1 : 0); // bypass
  2266. return status;
  2267. }
  2268. #endif
  2269. tresult PLUGIN_API getState (IBStream* state) override
  2270. {
  2271. if (state == nullptr)
  2272. return kInvalidArgument;
  2273. MemoryBlock mem;
  2274. getStateInformation (mem);
  2275. #if JUCE_VST3_CAN_REPLACE_VST2
  2276. tresult status = writeVST2Header (state, isBypassed());
  2277. if (status != kResultOk)
  2278. return status;
  2279. const int bankBlockSize = 160;
  2280. Vst2::fxBank bank;
  2281. zerostruct (bank);
  2282. bank.chunkMagic = (int32) htonl (ByteOrder::bigEndianInt ("CcnK"));
  2283. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  2284. bank.fxMagic = (int32) htonl (ByteOrder::bigEndianInt ("FBCh"));
  2285. bank.version = (int32) htonl (2);
  2286. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  2287. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  2288. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  2289. status = state->write (&bank, bankBlockSize);
  2290. if (status != kResultOk)
  2291. return status;
  2292. #endif
  2293. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  2294. }
  2295. //==============================================================================
  2296. Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
  2297. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
  2298. Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
  2299. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
  2300. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
  2301. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  2302. Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
  2303. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
  2304. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  2305. Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
  2306. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
  2307. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  2308. Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
  2309. Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
  2310. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  2311. Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
  2312. //==============================================================================
  2313. Optional<PositionInfo> getPosition() const override
  2314. {
  2315. PositionInfo info;
  2316. info.setTimeInSamples (jmax ((juce::int64) 0, processContext.projectTimeSamples));
  2317. info.setTimeInSeconds (static_cast<double> (*info.getTimeInSamples()) / processContext.sampleRate);
  2318. info.setIsRecording ((processContext.state & Vst::ProcessContext::kRecording) != 0);
  2319. info.setIsPlaying ((processContext.state & Vst::ProcessContext::kPlaying) != 0);
  2320. info.setIsLooping ((processContext.state & Vst::ProcessContext::kCycleActive) != 0);
  2321. info.setBpm ((processContext.state & Vst::ProcessContext::kTempoValid) != 0
  2322. ? makeOptional (processContext.tempo)
  2323. : nullopt);
  2324. info.setTimeSignature ((processContext.state & Vst::ProcessContext::kTimeSigValid) != 0
  2325. ? makeOptional (TimeSignature { processContext.timeSigNumerator, processContext.timeSigDenominator })
  2326. : nullopt);
  2327. info.setLoopPoints ((processContext.state & Vst::ProcessContext::kCycleValid) != 0
  2328. ? makeOptional (LoopPoints { processContext.cycleStartMusic, processContext.cycleEndMusic })
  2329. : nullopt);
  2330. info.setPpqPosition ((processContext.state & Vst::ProcessContext::kProjectTimeMusicValid) != 0
  2331. ? makeOptional (processContext.projectTimeMusic)
  2332. : nullopt);
  2333. info.setPpqPositionOfLastBarStart ((processContext.state & Vst::ProcessContext::kBarPositionValid) != 0
  2334. ? makeOptional (processContext.barPositionMusic)
  2335. : nullopt);
  2336. info.setFrameRate ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0
  2337. ? makeOptional (FrameRate().withBaseRate ((int) processContext.frameRate.framesPerSecond)
  2338. .withDrop ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  2339. .withPullDown ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0))
  2340. : nullopt);
  2341. info.setEditOriginTime (info.getFrameRate().hasValue()
  2342. ? makeOptional ((double) processContext.smpteOffsetSubframes / (80.0 * info.getFrameRate()->getEffectiveRate()))
  2343. : nullopt);
  2344. info.setHostTimeNs ((processContext.state & Vst::ProcessContext::kSystemTimeValid) != 0
  2345. ? makeOptional ((uint64_t) processContext.systemTime)
  2346. : nullopt);
  2347. return info;
  2348. }
  2349. //==============================================================================
  2350. int getNumAudioBuses (bool isInput) const
  2351. {
  2352. int busCount = pluginInstance->getBusCount (isInput);
  2353. #ifdef JucePlugin_PreferredChannelConfigurations
  2354. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  2355. const int numConfigs = numElementsInArray (configs);
  2356. bool hasOnlyZeroChannels = true;
  2357. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  2358. if (configs[i][isInput ? 0 : 1] != 0)
  2359. hasOnlyZeroChannels = false;
  2360. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  2361. #endif
  2362. return busCount;
  2363. }
  2364. //==============================================================================
  2365. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  2366. {
  2367. if (type == Vst::kAudio)
  2368. return getNumAudioBuses (dir == Vst::kInput);
  2369. if (type == Vst::kEvent)
  2370. {
  2371. #if JucePlugin_WantsMidiInput
  2372. if (dir == Vst::kInput)
  2373. return 1;
  2374. #endif
  2375. #if JucePlugin_ProducesMidiOutput
  2376. if (dir == Vst::kOutput)
  2377. return 1;
  2378. #endif
  2379. }
  2380. return 0;
  2381. }
  2382. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  2383. Steinberg::int32 index, Vst::BusInfo& info) override
  2384. {
  2385. if (type == Vst::kAudio)
  2386. {
  2387. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  2388. return kResultFalse;
  2389. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  2390. {
  2391. info.mediaType = Vst::kAudio;
  2392. info.direction = dir;
  2393. info.channelCount = bus->getLastEnabledLayout().size();
  2394. jassert (info.channelCount == Steinberg::Vst::SpeakerArr::getChannelCount (getVst3SpeakerArrangement (bus->getLastEnabledLayout())));
  2395. toString128 (info.name, bus->getName());
  2396. info.busType = [&]
  2397. {
  2398. const auto isFirstBus = (index == 0);
  2399. if (dir == Vst::kInput)
  2400. {
  2401. if (isFirstBus)
  2402. {
  2403. if (auto* extensions = dynamic_cast<VST3ClientExtensions*> (pluginInstance))
  2404. return extensions->getPluginHasMainInput() ? Vst::kMain : Vst::kAux;
  2405. return Vst::kMain;
  2406. }
  2407. return Vst::kAux;
  2408. }
  2409. #if JucePlugin_IsSynth
  2410. return Vst::kMain;
  2411. #else
  2412. return isFirstBus ? Vst::kMain : Vst::kAux;
  2413. #endif
  2414. }();
  2415. #ifdef JucePlugin_PreferredChannelConfigurations
  2416. info.flags = Vst::BusInfo::kDefaultActive;
  2417. #else
  2418. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  2419. #endif
  2420. return kResultTrue;
  2421. }
  2422. }
  2423. if (type == Vst::kEvent)
  2424. {
  2425. info.flags = Vst::BusInfo::kDefaultActive;
  2426. #if JucePlugin_WantsMidiInput
  2427. if (dir == Vst::kInput && index == 0)
  2428. {
  2429. info.mediaType = Vst::kEvent;
  2430. info.direction = dir;
  2431. #ifdef JucePlugin_VSTNumMidiInputs
  2432. info.channelCount = JucePlugin_VSTNumMidiInputs;
  2433. #else
  2434. info.channelCount = 16;
  2435. #endif
  2436. toString128 (info.name, TRANS("MIDI Input"));
  2437. info.busType = Vst::kMain;
  2438. return kResultTrue;
  2439. }
  2440. #endif
  2441. #if JucePlugin_ProducesMidiOutput
  2442. if (dir == Vst::kOutput && index == 0)
  2443. {
  2444. info.mediaType = Vst::kEvent;
  2445. info.direction = dir;
  2446. #ifdef JucePlugin_VSTNumMidiOutputs
  2447. info.channelCount = JucePlugin_VSTNumMidiOutputs;
  2448. #else
  2449. info.channelCount = 16;
  2450. #endif
  2451. toString128 (info.name, TRANS("MIDI Output"));
  2452. info.busType = Vst::kMain;
  2453. return kResultTrue;
  2454. }
  2455. #endif
  2456. }
  2457. zerostruct (info);
  2458. return kResultFalse;
  2459. }
  2460. tresult PLUGIN_API activateBus (Vst::MediaType type,
  2461. Vst::BusDirection dir,
  2462. Steinberg::int32 index,
  2463. TBool state) override
  2464. {
  2465. // The host is misbehaving! The plugin must be deactivated before setting new arrangements.
  2466. jassert (! active);
  2467. if (type == Vst::kEvent)
  2468. {
  2469. #if JucePlugin_WantsMidiInput
  2470. if (index == 0 && dir == Vst::kInput)
  2471. {
  2472. isMidiInputBusEnabled = (state != 0);
  2473. return kResultTrue;
  2474. }
  2475. #endif
  2476. #if JucePlugin_ProducesMidiOutput
  2477. if (index == 0 && dir == Vst::kOutput)
  2478. {
  2479. isMidiOutputBusEnabled = (state != 0);
  2480. return kResultTrue;
  2481. }
  2482. #endif
  2483. return kResultFalse;
  2484. }
  2485. if (type == Vst::kAudio)
  2486. {
  2487. const auto numInputBuses = getNumAudioBuses (true);
  2488. const auto numOutputBuses = getNumAudioBuses (false);
  2489. if (! isPositiveAndBelow (index, dir == Vst::kInput ? numInputBuses : numOutputBuses))
  2490. return kResultFalse;
  2491. // The host is allowed to enable/disable buses as it sees fit, so the plugin needs to be
  2492. // able to handle any set of enabled/disabled buses, including layouts for which
  2493. // AudioProcessor::isBusesLayoutSupported would return false.
  2494. // Our strategy is to keep track of the layout that the host last requested, and to
  2495. // attempt to apply that layout directly.
  2496. // If the layout isn't supported by the processor, we'll try enabling all the buses
  2497. // instead.
  2498. // If the host enables a bus that the processor refused to enable, then we'll ignore
  2499. // that bus (and return silence for output buses). If the host disables a bus that the
  2500. // processor refuses to disable, the wrapper will provide the processor with silence for
  2501. // input buses, and ignore the contents of output buses.
  2502. // Note that some hosts (old bitwig and cakewalk) may incorrectly call this function
  2503. // when the plugin is in an activated state.
  2504. if (dir == Vst::kInput)
  2505. bufferMapper.setInputBusHostActive ((size_t) index, state != 0);
  2506. else
  2507. bufferMapper.setOutputBusHostActive ((size_t) index, state != 0);
  2508. AudioProcessor::BusesLayout desiredLayout;
  2509. for (auto i = 0; i < numInputBuses; ++i)
  2510. desiredLayout.inputBuses.add (bufferMapper.getRequestedLayoutForInputBus ((size_t) i));
  2511. for (auto i = 0; i < numOutputBuses; ++i)
  2512. desiredLayout.outputBuses.add (bufferMapper.getRequestedLayoutForOutputBus ((size_t) i));
  2513. const auto prev = pluginInstance->getBusesLayout();
  2514. const auto busesLayoutSupported = [&]
  2515. {
  2516. #ifdef JucePlugin_PreferredChannelConfigurations
  2517. struct ChannelPair
  2518. {
  2519. short ins, outs;
  2520. auto tie() const { return std::tie (ins, outs); }
  2521. bool operator== (ChannelPair x) const { return tie() == x.tie(); }
  2522. };
  2523. const auto countChannels = [] (auto& range)
  2524. {
  2525. return std::accumulate (range.begin(), range.end(), 0, [] (auto acc, auto set)
  2526. {
  2527. return acc + set.size();
  2528. });
  2529. };
  2530. const auto toShort = [] (int x)
  2531. {
  2532. jassert (0 <= x && x <= std::numeric_limits<short>::max());
  2533. return (short) x;
  2534. };
  2535. const ChannelPair requested { toShort (countChannels (desiredLayout.inputBuses)),
  2536. toShort (countChannels (desiredLayout.outputBuses)) };
  2537. const ChannelPair configs[] = { JucePlugin_PreferredChannelConfigurations };
  2538. return std::find (std::begin (configs), std::end (configs), requested) != std::end (configs);
  2539. #else
  2540. return pluginInstance->checkBusesLayoutSupported (desiredLayout);
  2541. #endif
  2542. }();
  2543. if (busesLayoutSupported)
  2544. pluginInstance->setBusesLayout (desiredLayout);
  2545. else
  2546. pluginInstance->enableAllBuses();
  2547. bufferMapper.updateActiveClientBuses (pluginInstance->getBusesLayout());
  2548. return kResultTrue;
  2549. }
  2550. return kResultFalse;
  2551. }
  2552. bool checkBusFormatsAreNotDiscrete()
  2553. {
  2554. auto numInputBuses = pluginInstance->getBusCount (true);
  2555. auto numOutputBuses = pluginInstance->getBusCount (false);
  2556. for (int i = 0; i < numInputBuses; ++i)
  2557. {
  2558. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  2559. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  2560. return false;
  2561. }
  2562. for (int i = 0; i < numOutputBuses; ++i)
  2563. {
  2564. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  2565. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  2566. return false;
  2567. }
  2568. return true;
  2569. }
  2570. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  2571. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  2572. {
  2573. if (active)
  2574. {
  2575. // The host is misbehaving! The plugin must be deactivated before setting new arrangements.
  2576. jassertfalse;
  2577. return kResultFalse;
  2578. }
  2579. auto numInputBuses = pluginInstance->getBusCount (true);
  2580. auto numOutputBuses = pluginInstance->getBusCount (false);
  2581. if (numIns > numInputBuses || numOuts > numOutputBuses)
  2582. return false;
  2583. auto requested = pluginInstance->getBusesLayout();
  2584. for (int i = 0; i < numIns; ++i)
  2585. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  2586. for (int i = 0; i < numOuts; ++i)
  2587. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  2588. #ifdef JucePlugin_PreferredChannelConfigurations
  2589. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  2590. if (! AudioProcessor::containsLayout (requested, configs))
  2591. return kResultFalse;
  2592. #endif
  2593. if (! pluginInstance->setBusesLayoutWithoutEnabling (requested))
  2594. return kResultFalse;
  2595. bufferMapper.updateFromProcessor (*pluginInstance);
  2596. return kResultTrue;
  2597. }
  2598. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  2599. {
  2600. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  2601. {
  2602. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  2603. return kResultTrue;
  2604. }
  2605. return kResultFalse;
  2606. }
  2607. //==============================================================================
  2608. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  2609. {
  2610. return (symbolicSampleSize == Vst::kSample32
  2611. || (getPluginInstance().supportsDoublePrecisionProcessing()
  2612. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  2613. }
  2614. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  2615. {
  2616. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  2617. }
  2618. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  2619. {
  2620. ScopedInSetupProcessingSetter inSetupProcessingSetter (juceVST3EditController);
  2621. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  2622. return kResultFalse;
  2623. processSetup = newSetup;
  2624. processContext.sampleRate = processSetup.sampleRate;
  2625. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  2626. ? AudioProcessor::doublePrecision
  2627. : AudioProcessor::singlePrecision);
  2628. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  2629. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock, CallPrepareToPlay::no);
  2630. return kResultTrue;
  2631. }
  2632. tresult PLUGIN_API setProcessing (TBool state) override
  2633. {
  2634. if (! state)
  2635. getPluginInstance().reset();
  2636. return kResultTrue;
  2637. }
  2638. Steinberg::uint32 PLUGIN_API getTailSamples() override
  2639. {
  2640. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  2641. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  2642. return Vst::kNoTail;
  2643. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  2644. return Vst::kInfiniteTail;
  2645. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  2646. }
  2647. //==============================================================================
  2648. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  2649. {
  2650. jassert (pluginInstance != nullptr);
  2651. auto numParamsChanged = paramChanges.getParameterCount();
  2652. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  2653. {
  2654. if (auto* paramQueue = paramChanges.getParameterData (i))
  2655. {
  2656. auto numPoints = paramQueue->getPointCount();
  2657. Steinberg::int32 offsetSamples = 0;
  2658. double value = 0.0;
  2659. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  2660. {
  2661. auto vstParamID = paramQueue->getParameterId();
  2662. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  2663. if (juceVST3EditController != nullptr && juceVST3EditController->isMidiControllerParamID (vstParamID))
  2664. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  2665. else
  2666. #endif
  2667. {
  2668. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  2669. setValueAndNotifyIfChanged (*param, (float) value);
  2670. }
  2671. }
  2672. }
  2673. }
  2674. }
  2675. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  2676. {
  2677. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  2678. int channel, ctrlNumber;
  2679. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  2680. {
  2681. if (ctrlNumber == Vst::kAfterTouch)
  2682. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  2683. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  2684. else if (ctrlNumber == Vst::kPitchBend)
  2685. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  2686. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  2687. else
  2688. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  2689. jlimit (0, 127, ctrlNumber),
  2690. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  2691. }
  2692. }
  2693. tresult PLUGIN_API process (Vst::ProcessData& data) override
  2694. {
  2695. if (pluginInstance == nullptr)
  2696. return kResultFalse;
  2697. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  2698. return kResultFalse;
  2699. if (data.processContext != nullptr)
  2700. {
  2701. processContext = *data.processContext;
  2702. if (juceVST3EditController != nullptr)
  2703. juceVST3EditController->vst3IsPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  2704. }
  2705. else
  2706. {
  2707. zerostruct (processContext);
  2708. if (juceVST3EditController != nullptr)
  2709. juceVST3EditController->vst3IsPlaying = false;
  2710. }
  2711. midiBuffer.clear();
  2712. if (data.inputParameterChanges != nullptr)
  2713. processParameterChanges (*data.inputParameterChanges);
  2714. #if JucePlugin_WantsMidiInput
  2715. if (isMidiInputBusEnabled && data.inputEvents != nullptr)
  2716. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  2717. #endif
  2718. if (getHostType().isWavelab())
  2719. {
  2720. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  2721. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  2722. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  2723. && (numInputChans + numOutputChans) == 0)
  2724. return kResultFalse;
  2725. }
  2726. // If all of these are zero, the host is attempting to flush parameters without processing audio.
  2727. if (data.numSamples != 0 || data.numInputs != 0 || data.numOutputs != 0)
  2728. {
  2729. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data);
  2730. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data);
  2731. else jassertfalse;
  2732. }
  2733. if (auto* changes = data.outputParameterChanges)
  2734. {
  2735. comPluginInstance->forAllChangedParameters ([&] (Vst::ParamID paramID, float value)
  2736. {
  2737. Steinberg::int32 queueIndex = 0;
  2738. if (auto* queue = changes->addParameterData (paramID, queueIndex))
  2739. {
  2740. Steinberg::int32 pointIndex = 0;
  2741. queue->addPoint (0, value, pointIndex);
  2742. }
  2743. });
  2744. }
  2745. #if JucePlugin_ProducesMidiOutput
  2746. if (isMidiOutputBusEnabled && data.outputEvents != nullptr)
  2747. MidiEventList::pluginToHostEventList (*data.outputEvents, midiBuffer);
  2748. #endif
  2749. return kResultTrue;
  2750. }
  2751. private:
  2752. InterfaceResultWithDeferredAddRef queryInterfaceInternal (const TUID targetIID)
  2753. {
  2754. const auto result = testForMultiple (*this,
  2755. targetIID,
  2756. UniqueBase<IPluginBase>{},
  2757. UniqueBase<JuceVST3Component>{},
  2758. UniqueBase<Vst::IComponent>{},
  2759. UniqueBase<Vst::IAudioProcessor>{},
  2760. UniqueBase<Vst::IUnitInfo>{},
  2761. UniqueBase<Vst::IConnectionPoint>{},
  2762. UniqueBase<Vst::IProcessContextRequirements>{},
  2763. #if JucePlugin_Enable_ARA
  2764. UniqueBase<ARA::IPlugInEntryPoint>{},
  2765. UniqueBase<ARA::IPlugInEntryPoint2>{},
  2766. #endif
  2767. SharedBase<FUnknown, Vst::IComponent>{});
  2768. if (result.isOk())
  2769. return result;
  2770. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  2771. return { kResultOk, comPluginInstance.get() };
  2772. return {};
  2773. }
  2774. //==============================================================================
  2775. struct ScopedInSetupProcessingSetter
  2776. {
  2777. ScopedInSetupProcessingSetter (JuceVST3EditController* c)
  2778. : controller (c)
  2779. {
  2780. if (controller != nullptr)
  2781. controller->inSetupProcessing = true;
  2782. }
  2783. ~ScopedInSetupProcessingSetter()
  2784. {
  2785. if (controller != nullptr)
  2786. controller->inSetupProcessing = false;
  2787. }
  2788. private:
  2789. JuceVST3EditController* controller = nullptr;
  2790. };
  2791. //==============================================================================
  2792. template <typename FloatType>
  2793. void processAudio (Vst::ProcessData& data)
  2794. {
  2795. ClientRemappedBuffer<FloatType> remappedBuffer { bufferMapper, data };
  2796. auto& buffer = remappedBuffer.buffer;
  2797. jassert ((int) buffer.getNumChannels() == jmax (pluginInstance->getTotalNumInputChannels(),
  2798. pluginInstance->getTotalNumOutputChannels()));
  2799. {
  2800. const ScopedLock sl (pluginInstance->getCallbackLock());
  2801. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  2802. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  2803. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  2804. #endif
  2805. if (pluginInstance->isSuspended())
  2806. {
  2807. buffer.clear();
  2808. }
  2809. else
  2810. {
  2811. // processBlockBypassed should only ever be called if the AudioProcessor doesn't
  2812. // return a valid parameter from getBypassParameter
  2813. if (pluginInstance->getBypassParameter() == nullptr && comPluginInstance->getBypassParameter()->getValue() >= 0.5f)
  2814. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  2815. else
  2816. pluginInstance->processBlock (buffer, midiBuffer);
  2817. }
  2818. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  2819. /* This assertion is caused when you've added some events to the
  2820. midiMessages array in your processBlock() method, which usually means
  2821. that you're trying to send them somewhere. But in this case they're
  2822. getting thrown away.
  2823. If your plugin does want to send MIDI messages, you'll need to set
  2824. the JucePlugin_ProducesMidiOutput macro to 1 in your
  2825. JucePluginCharacteristics.h file.
  2826. If you don't want to produce any MIDI output, then you should clear the
  2827. midiMessages array at the end of your processBlock() method, to
  2828. indicate that you don't want any of the events to be passed through
  2829. to the output.
  2830. */
  2831. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  2832. #endif
  2833. }
  2834. }
  2835. //==============================================================================
  2836. Steinberg::uint32 PLUGIN_API getProcessContextRequirements() override
  2837. {
  2838. return kNeedSystemTime
  2839. | kNeedContinousTimeSamples
  2840. | kNeedProjectTimeMusic
  2841. | kNeedBarPositionMusic
  2842. | kNeedCycleMusic
  2843. | kNeedSamplesToNextClock
  2844. | kNeedTempo
  2845. | kNeedTimeSignature
  2846. | kNeedChord
  2847. | kNeedFrameRate
  2848. | kNeedTransportState;
  2849. }
  2850. void preparePlugin (double sampleRate, int bufferSize, CallPrepareToPlay callPrepareToPlay)
  2851. {
  2852. auto& p = getPluginInstance();
  2853. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2854. if (callPrepareToPlay == CallPrepareToPlay::yes)
  2855. p.prepareToPlay (sampleRate, bufferSize);
  2856. midiBuffer.ensureSize (2048);
  2857. midiBuffer.clear();
  2858. bufferMapper.updateFromProcessor (p);
  2859. bufferMapper.prepare (bufferSize);
  2860. }
  2861. //==============================================================================
  2862. #if JucePlugin_Enable_ARA
  2863. const ARA::ARAFactory* PLUGIN_API getFactory() SMTG_OVERRIDE
  2864. {
  2865. return createARAFactory();
  2866. }
  2867. const ARA::ARAPlugInExtensionInstance* PLUGIN_API bindToDocumentController (ARA::ARADocumentControllerRef /*controllerRef*/) SMTG_OVERRIDE
  2868. {
  2869. ARA_VALIDATE_API_STATE (false && "call is deprecated in ARA 2, host must not call this");
  2870. return nullptr;
  2871. }
  2872. const ARA::ARAPlugInExtensionInstance* PLUGIN_API bindToDocumentControllerWithRoles (ARA::ARADocumentControllerRef documentControllerRef,
  2873. ARA::ARAPlugInInstanceRoleFlags knownRoles, ARA::ARAPlugInInstanceRoleFlags assignedRoles) SMTG_OVERRIDE
  2874. {
  2875. AudioProcessorARAExtension* araAudioProcessorExtension = dynamic_cast<AudioProcessorARAExtension*> (pluginInstance);
  2876. return araAudioProcessorExtension->bindToARA (documentControllerRef, knownRoles, assignedRoles);
  2877. }
  2878. #endif
  2879. //==============================================================================
  2880. ScopedJuceInitialiser_GUI libraryInitialiser;
  2881. #if JUCE_LINUX || JUCE_BSD
  2882. SharedResourcePointer<MessageThread> messageThread;
  2883. #endif
  2884. std::atomic<int> refCount { 1 };
  2885. AudioProcessor* pluginInstance = nullptr;
  2886. #if JUCE_LINUX || JUCE_BSD
  2887. template <class T>
  2888. struct LockedVSTComSmartPtr
  2889. {
  2890. LockedVSTComSmartPtr() = default;
  2891. LockedVSTComSmartPtr (const VSTComSmartPtr<T>& ptrIn) : ptr (ptrIn) {}
  2892. LockedVSTComSmartPtr (const LockedVSTComSmartPtr&) = default;
  2893. LockedVSTComSmartPtr& operator= (const LockedVSTComSmartPtr&) = default;
  2894. ~LockedVSTComSmartPtr()
  2895. {
  2896. const MessageManagerLock mmLock;
  2897. ptr = {};
  2898. }
  2899. T* operator->() const { return ptr.operator->(); }
  2900. T* get() const noexcept { return ptr.get(); }
  2901. operator T*() const noexcept { return ptr.get(); }
  2902. template <typename... Args>
  2903. bool loadFrom (Args&&... args) { return ptr.loadFrom (std::forward<Args> (args)...); }
  2904. private:
  2905. VSTComSmartPtr<T> ptr;
  2906. };
  2907. LockedVSTComSmartPtr<Vst::IHostApplication> host;
  2908. LockedVSTComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2909. LockedVSTComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2910. #else
  2911. VSTComSmartPtr<Vst::IHostApplication> host;
  2912. VSTComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2913. VSTComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2914. #endif
  2915. /**
  2916. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  2917. this object needs to be copied on every call to process() to be up-to-date...
  2918. */
  2919. Vst::ProcessContext processContext;
  2920. Vst::ProcessSetup processSetup;
  2921. MidiBuffer midiBuffer;
  2922. ClientBufferMapper bufferMapper;
  2923. bool active = false;
  2924. #if JucePlugin_WantsMidiInput
  2925. std::atomic<bool> isMidiInputBusEnabled { true };
  2926. #endif
  2927. #if JucePlugin_ProducesMidiOutput
  2928. std::atomic<bool> isMidiOutputBusEnabled { true };
  2929. #endif
  2930. static const char* kJucePrivateDataIdentifier;
  2931. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2932. };
  2933. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2934. //==============================================================================
  2935. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4310)
  2936. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wall")
  2937. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2938. DEF_CLASS_IID (JuceAudioProcessor)
  2939. #if JUCE_VST3_CAN_REPLACE_VST2
  2940. // Defined in PluginUtilities.cpp
  2941. void getUUIDForVST2ID (bool, uint8[16]);
  2942. static FUID getFUIDForVST2ID (bool forControllerUID)
  2943. {
  2944. TUID uuid;
  2945. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2946. return FUID (uuid);
  2947. }
  2948. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2949. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2950. #else
  2951. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2952. DEF_CLASS_IID (JuceVST3EditController)
  2953. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2954. DEF_CLASS_IID (JuceVST3Component)
  2955. #endif
  2956. #if JucePlugin_Enable_ARA
  2957. DECLARE_CLASS_IID (JuceARAFactory, 0xABCDEF01, 0xA1B2C3D4, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2958. DEF_CLASS_IID (JuceARAFactory)
  2959. #endif
  2960. JUCE_END_IGNORE_WARNINGS_MSVC
  2961. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  2962. //==============================================================================
  2963. bool initModule();
  2964. bool initModule()
  2965. {
  2966. #if JUCE_MAC
  2967. initialiseMacVST();
  2968. #endif
  2969. return true;
  2970. }
  2971. bool shutdownModule();
  2972. bool shutdownModule()
  2973. {
  2974. return true;
  2975. }
  2976. #undef JUCE_EXPORTED_FUNCTION
  2977. #if JUCE_WINDOWS
  2978. #define JUCE_EXPORTED_FUNCTION
  2979. #else
  2980. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility("default")))
  2981. #endif
  2982. #if JUCE_WINDOWS
  2983. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wmissing-prototypes")
  2984. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2985. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2986. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  2987. #elif JUCE_LINUX || JUCE_BSD
  2988. void* moduleHandle = nullptr;
  2989. int moduleEntryCounter = 0;
  2990. JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle);
  2991. JUCE_EXPORTED_FUNCTION bool ModuleEntry (void* sharedLibraryHandle)
  2992. {
  2993. if (++moduleEntryCounter == 1)
  2994. {
  2995. moduleHandle = sharedLibraryHandle;
  2996. return initModule();
  2997. }
  2998. return true;
  2999. }
  3000. JUCE_EXPORTED_FUNCTION bool ModuleExit();
  3001. JUCE_EXPORTED_FUNCTION bool ModuleExit()
  3002. {
  3003. if (--moduleEntryCounter == 0)
  3004. {
  3005. moduleHandle = nullptr;
  3006. return shutdownModule();
  3007. }
  3008. return true;
  3009. }
  3010. #elif JUCE_MAC
  3011. CFBundleRef globalBundleInstance = nullptr;
  3012. juce::uint32 numBundleRefs = 0;
  3013. juce::Array<CFBundleRef> bundleRefs;
  3014. enum { MaxPathLength = 2048 };
  3015. char modulePath[MaxPathLength] = { 0 };
  3016. void* moduleHandle = nullptr;
  3017. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref);
  3018. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  3019. {
  3020. if (ref != nullptr)
  3021. {
  3022. ++numBundleRefs;
  3023. CFRetain (ref);
  3024. bundleRefs.add (ref);
  3025. if (moduleHandle == nullptr)
  3026. {
  3027. globalBundleInstance = ref;
  3028. moduleHandle = ref;
  3029. CFUniquePtr<CFURLRef> tempURL (CFBundleCopyBundleURL (ref));
  3030. CFURLGetFileSystemRepresentation (tempURL.get(), true, (UInt8*) modulePath, MaxPathLength);
  3031. }
  3032. }
  3033. return initModule();
  3034. }
  3035. JUCE_EXPORTED_FUNCTION bool bundleExit();
  3036. JUCE_EXPORTED_FUNCTION bool bundleExit()
  3037. {
  3038. if (shutdownModule())
  3039. {
  3040. if (--numBundleRefs == 0)
  3041. {
  3042. for (int i = 0; i < bundleRefs.size(); ++i)
  3043. CFRelease (bundleRefs.getUnchecked (i));
  3044. bundleRefs.clear();
  3045. }
  3046. return true;
  3047. }
  3048. return false;
  3049. }
  3050. #endif
  3051. //==============================================================================
  3052. /** This typedef represents VST3's createInstance() function signature */
  3053. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  3054. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  3055. {
  3056. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  3057. }
  3058. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  3059. {
  3060. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  3061. }
  3062. #if JucePlugin_Enable_ARA
  3063. static FUnknown* createARAFactoryInstance (Vst::IHostApplication* /*host*/)
  3064. {
  3065. return static_cast<ARA::IMainFactory*> (new JuceARAFactory());
  3066. }
  3067. #endif
  3068. //==============================================================================
  3069. struct JucePluginFactory;
  3070. static JucePluginFactory* globalFactory = nullptr;
  3071. //==============================================================================
  3072. struct JucePluginFactory : public IPluginFactory3
  3073. {
  3074. JucePluginFactory()
  3075. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  3076. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  3077. {
  3078. }
  3079. virtual ~JucePluginFactory()
  3080. {
  3081. if (globalFactory == this)
  3082. globalFactory = nullptr;
  3083. }
  3084. //==============================================================================
  3085. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  3086. {
  3087. if (createFunction == nullptr)
  3088. {
  3089. jassertfalse;
  3090. return false;
  3091. }
  3092. auto entry = std::make_unique<ClassEntry> (info, createFunction);
  3093. entry->infoW.fromAscii (info);
  3094. classes.push_back (std::move (entry));
  3095. return true;
  3096. }
  3097. //==============================================================================
  3098. JUCE_DECLARE_VST3_COM_REF_METHODS
  3099. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  3100. {
  3101. const auto result = testForMultiple (*this,
  3102. targetIID,
  3103. UniqueBase<IPluginFactory3>{},
  3104. UniqueBase<IPluginFactory2>{},
  3105. UniqueBase<IPluginFactory>{},
  3106. UniqueBase<FUnknown>{});
  3107. if (result.isOk())
  3108. return result.extract (obj);
  3109. jassertfalse; // Something new?
  3110. *obj = nullptr;
  3111. return kNotImplemented;
  3112. }
  3113. //==============================================================================
  3114. Steinberg::int32 PLUGIN_API countClasses() override
  3115. {
  3116. return (Steinberg::int32) classes.size();
  3117. }
  3118. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  3119. {
  3120. if (info == nullptr)
  3121. return kInvalidArgument;
  3122. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  3123. return kResultOk;
  3124. }
  3125. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  3126. {
  3127. return getPClassInfo<PClassInfo> (index, info);
  3128. }
  3129. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  3130. {
  3131. return getPClassInfo<PClassInfo2> (index, info);
  3132. }
  3133. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  3134. {
  3135. if (info != nullptr)
  3136. {
  3137. if (auto& entry = classes[(size_t) index])
  3138. {
  3139. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  3140. return kResultOk;
  3141. }
  3142. }
  3143. return kInvalidArgument;
  3144. }
  3145. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  3146. {
  3147. ScopedJuceInitialiser_GUI libraryInitialiser;
  3148. #if JUCE_LINUX || JUCE_BSD
  3149. SharedResourcePointer<MessageThread> messageThread;
  3150. #endif
  3151. *obj = nullptr;
  3152. TUID tuid;
  3153. memcpy (tuid, sourceIid, sizeof (TUID));
  3154. #if VST_VERSION >= 0x030608
  3155. auto sourceFuid = FUID::fromTUID (tuid);
  3156. #else
  3157. FUID sourceFuid;
  3158. sourceFuid = tuid;
  3159. #endif
  3160. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  3161. {
  3162. jassertfalse; // The host you're running in has severe implementation issues!
  3163. return kInvalidArgument;
  3164. }
  3165. TUID iidToQuery;
  3166. sourceFuid.toTUID (iidToQuery);
  3167. for (auto& entry : classes)
  3168. {
  3169. if (doUIDsMatch (entry->infoW.cid, cid))
  3170. {
  3171. if (auto* instance = entry->createFunction (host))
  3172. {
  3173. const FReleaser releaser (instance);
  3174. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  3175. return kResultOk;
  3176. }
  3177. break;
  3178. }
  3179. }
  3180. return kNoInterface;
  3181. }
  3182. tresult PLUGIN_API setHostContext (FUnknown* context) override
  3183. {
  3184. host.loadFrom (context);
  3185. if (host != nullptr)
  3186. {
  3187. Vst::String128 name;
  3188. host->getName (name);
  3189. return kResultTrue;
  3190. }
  3191. return kNotImplemented;
  3192. }
  3193. private:
  3194. //==============================================================================
  3195. std::atomic<int> refCount { 1 };
  3196. const PFactoryInfo factoryInfo;
  3197. VSTComSmartPtr<Vst::IHostApplication> host;
  3198. //==============================================================================
  3199. struct ClassEntry
  3200. {
  3201. ClassEntry() noexcept {}
  3202. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  3203. : info2 (info), createFunction (fn) {}
  3204. PClassInfo2 info2;
  3205. PClassInfoW infoW;
  3206. CreateFunction createFunction = {};
  3207. bool isUnicode = false;
  3208. private:
  3209. JUCE_DECLARE_NON_COPYABLE (ClassEntry)
  3210. };
  3211. std::vector<std::unique_ptr<ClassEntry>> classes;
  3212. //==============================================================================
  3213. template <class PClassInfoType>
  3214. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  3215. {
  3216. if (info != nullptr)
  3217. {
  3218. zerostruct (*info);
  3219. if (auto& entry = classes[(size_t) index])
  3220. {
  3221. if (entry->isUnicode)
  3222. return kResultFalse;
  3223. memcpy (info, (PClassInfoType*) &entry->info2, sizeof (PClassInfoType));
  3224. return kResultOk;
  3225. }
  3226. }
  3227. jassertfalse;
  3228. return kInvalidArgument;
  3229. }
  3230. //==============================================================================
  3231. // no leak detector here to prevent it firing on shutdown when running in hosts that
  3232. // don't release the factory object correctly...
  3233. JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
  3234. };
  3235. } // namespace juce
  3236. //==============================================================================
  3237. #ifndef JucePlugin_Vst3ComponentFlags
  3238. #if JucePlugin_IsSynth
  3239. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  3240. #else
  3241. #define JucePlugin_Vst3ComponentFlags 0
  3242. #endif
  3243. #endif
  3244. #ifndef JucePlugin_Vst3Category
  3245. #if JucePlugin_IsSynth
  3246. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  3247. #else
  3248. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  3249. #endif
  3250. #endif
  3251. using namespace juce;
  3252. //==============================================================================
  3253. // The VST3 plugin entry point.
  3254. extern "C" SMTG_EXPORT_SYMBOL IPluginFactory* PLUGIN_API GetPluginFactory()
  3255. {
  3256. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  3257. #if (JUCE_MSVC || (JUCE_WINDOWS && JUCE_CLANG)) && JUCE_32BIT
  3258. // Cunning trick to force this function to be exported. Life's too short to
  3259. // faff around creating .def files for this kind of thing.
  3260. // Unnecessary for 64-bit builds because those don't use decorated function names.
  3261. #pragma comment(linker, "/EXPORT:GetPluginFactory=_GetPluginFactory@0")
  3262. #endif
  3263. if (globalFactory == nullptr)
  3264. {
  3265. globalFactory = new JucePluginFactory();
  3266. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  3267. PClassInfo::kManyInstances,
  3268. kVstAudioEffectClass,
  3269. JucePlugin_Name,
  3270. JucePlugin_Vst3ComponentFlags,
  3271. JucePlugin_Vst3Category,
  3272. JucePlugin_Manufacturer,
  3273. JucePlugin_VersionString,
  3274. kVstVersionString);
  3275. globalFactory->registerClass (componentClass, createComponentInstance);
  3276. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  3277. PClassInfo::kManyInstances,
  3278. kVstComponentControllerClass,
  3279. JucePlugin_Name,
  3280. JucePlugin_Vst3ComponentFlags,
  3281. JucePlugin_Vst3Category,
  3282. JucePlugin_Manufacturer,
  3283. JucePlugin_VersionString,
  3284. kVstVersionString);
  3285. globalFactory->registerClass (controllerClass, createControllerInstance);
  3286. #if JucePlugin_Enable_ARA
  3287. static const PClassInfo2 araFactoryClass (JuceARAFactory::iid,
  3288. PClassInfo::kManyInstances,
  3289. kARAMainFactoryClass,
  3290. JucePlugin_Name,
  3291. JucePlugin_Vst3ComponentFlags,
  3292. JucePlugin_Vst3Category,
  3293. JucePlugin_Manufacturer,
  3294. JucePlugin_VersionString,
  3295. kVstVersionString);
  3296. globalFactory->registerClass (araFactoryClass, createARAFactoryInstance);
  3297. #endif
  3298. }
  3299. else
  3300. {
  3301. globalFactory->addRef();
  3302. }
  3303. return dynamic_cast<IPluginFactory*> (globalFactory);
  3304. }
  3305. //==============================================================================
  3306. #if JUCE_WINDOWS
  3307. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wmissing-prototypes")
  3308. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  3309. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  3310. #endif
  3311. JUCE_END_NO_SANITIZE
  3312. #endif //JucePlugin_Build_VST3