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.

3875 lines
144KB

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