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.

4110 lines
154KB

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