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.

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