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.

3907 lines
145KB

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