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.

4053 lines
151KB

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