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.

3876 lines
144KB

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