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.

3208 lines
119KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  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. //==============================================================================
  15. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  16. #if JUCE_PLUGINHOST_VST3 && (JUCE_MAC || JUCE_WINDOWS)
  17. #undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
  18. #define JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY 1
  19. #endif
  20. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  21. #undef JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY
  22. #include "../utility/juce_CheckSettingMacros.h"
  23. #include "../utility/juce_IncludeModuleHeaders.h"
  24. #include "../utility/juce_WindowsHooks.h"
  25. #include "../utility/juce_FakeMouseMoveGenerator.h"
  26. #include "../../juce_audio_processors/format_types/juce_LegacyAudioParameter.cpp"
  27. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  28. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  29. #define JUCE_VST3_CAN_REPLACE_VST2 1
  30. #endif
  31. #if JUCE_VST3_CAN_REPLACE_VST2
  32. namespace Vst2
  33. {
  34. #include "pluginterfaces/vst2.x/vstfxstore.h"
  35. }
  36. #endif
  37. #ifndef JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  38. #if JucePlugin_WantsMidiInput
  39. #define JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS 1
  40. #endif
  41. #endif
  42. #if JUCE_VST3_CAN_REPLACE_VST2
  43. #if JUCE_MSVC
  44. #pragma warning (push)
  45. #pragma warning (disable: 4514 4996)
  46. #endif
  47. #if JUCE_MSVC
  48. #pragma warning (pop)
  49. #endif
  50. #endif
  51. namespace juce
  52. {
  53. using namespace Steinberg;
  54. //==============================================================================
  55. #if JUCE_MAC
  56. extern void initialiseMacVST();
  57. #if ! JUCE_64BIT
  58. extern void updateEditorCompBoundsVST (Component*);
  59. #endif
  60. extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
  61. extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
  62. #endif
  63. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  64. extern JUCE_API double getScaleFactorForWindow (HWND);
  65. #endif
  66. //==============================================================================
  67. class JuceAudioProcessor : public Vst::IUnitInfo
  68. {
  69. public:
  70. JuceAudioProcessor (AudioProcessor* source) noexcept
  71. : audioProcessor (source)
  72. {
  73. setupParameters();
  74. }
  75. virtual ~JuceAudioProcessor() {}
  76. AudioProcessor* get() const noexcept { return audioProcessor.get(); }
  77. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  78. JUCE_DECLARE_VST3_COM_REF_METHODS
  79. //==============================================================================
  80. enum InternalParameters
  81. {
  82. paramPreset = 0x70727374, // 'prst'
  83. paramMidiControllerOffset = 0x6d636d00, // 'mdm*'
  84. paramBypass = 0x62797073 // 'byps'
  85. };
  86. //==============================================================================
  87. Steinberg::int32 PLUGIN_API getUnitCount() override
  88. {
  89. return parameterGroups.size() + 1;
  90. }
  91. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  92. {
  93. if (unitIndex == 0)
  94. {
  95. info.id = Vst::kRootUnitId;
  96. info.parentUnitId = Vst::kNoParentUnitId;
  97. info.programListId = Vst::kNoProgramListId;
  98. toString128 (info.name, TRANS("Root Unit"));
  99. return kResultTrue;
  100. }
  101. if (auto* group = parameterGroups[unitIndex - 1])
  102. {
  103. info.id = JuceAudioProcessor::getUnitID (group);
  104. info.parentUnitId = JuceAudioProcessor::getUnitID (group->getParent());
  105. info.programListId = Vst::kNoProgramListId;
  106. toString128 (info.name, group->getName());
  107. return kResultTrue;
  108. }
  109. return kResultFalse;
  110. }
  111. Steinberg::int32 PLUGIN_API getProgramListCount() override
  112. {
  113. if (audioProcessor->getNumPrograms() > 0)
  114. return 1;
  115. return 0;
  116. }
  117. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  118. {
  119. if (listIndex == 0)
  120. {
  121. info.id = paramPreset;
  122. info.programCount = (Steinberg::int32) audioProcessor->getNumPrograms();
  123. toString128 (info.name, TRANS("Factory Presets"));
  124. return kResultTrue;
  125. }
  126. jassertfalse;
  127. zerostruct (info);
  128. return kResultFalse;
  129. }
  130. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  131. {
  132. if (listId == paramPreset
  133. && isPositiveAndBelow ((int) programIndex, audioProcessor->getNumPrograms()))
  134. {
  135. toString128 (name, audioProcessor->getProgramName ((int) programIndex));
  136. return kResultTrue;
  137. }
  138. jassertfalse;
  139. toString128 (name, juce::String());
  140. return kResultFalse;
  141. }
  142. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  143. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  144. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  145. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  146. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  147. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  148. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  149. {
  150. zerostruct (unitId);
  151. return kNotImplemented;
  152. }
  153. //==============================================================================
  154. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
  155. {
  156. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  157. return static_cast<Vst::ParamID> (paramIndex);
  158. #else
  159. return vstParamIDs.getReference (paramIndex);
  160. #endif
  161. }
  162. AudioProcessorParameter* getParamForVSTParamID (Vst::ParamID paramID) const noexcept
  163. {
  164. return paramMap[static_cast<int32> (paramID)];
  165. }
  166. AudioProcessorParameter* getBypassParameter() const noexcept
  167. {
  168. return getParamForVSTParamID (bypassParamID);
  169. }
  170. static Vst::UnitID getUnitID (const AudioProcessorParameterGroup* group)
  171. {
  172. return group == nullptr ? Vst::kRootUnitId : group->getID().hashCode();
  173. }
  174. int getNumParameters() const noexcept { return vstParamIDs.size(); }
  175. bool isUsingManagedParameters() const noexcept { return juceParameters.isUsingManagedParameters(); }
  176. //==============================================================================
  177. static const FUID iid;
  178. Array<Vst::ParamID> vstParamIDs;
  179. Vst::ParamID bypassParamID = 0;
  180. bool bypassIsRegularParameter = false;
  181. private:
  182. //==============================================================================
  183. bool isBypassPartOfRegularParemeters() const
  184. {
  185. int n = juceParameters.getNumParameters();
  186. if (auto* bypassParam = audioProcessor->getBypassParameter())
  187. for (int i = 0; i < n; ++i)
  188. if (juceParameters.getParamForIndex (i) == bypassParam)
  189. return true;
  190. return false;
  191. }
  192. void setupParameters()
  193. {
  194. parameterGroups = audioProcessor->getParameterTree().getSubgroups (true);
  195. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  196. const bool forceLegacyParamIDs = true;
  197. #else
  198. const bool forceLegacyParamIDs = false;
  199. #endif
  200. juceParameters.update (*audioProcessor, forceLegacyParamIDs);
  201. auto numParameters = juceParameters.getNumParameters();
  202. bool vst3WrapperProvidedBypassParam = false;
  203. auto* bypassParameter = audioProcessor->getBypassParameter();
  204. if (bypassParameter == nullptr)
  205. {
  206. vst3WrapperProvidedBypassParam = true;
  207. ownedBypassParameter.reset (new AudioParameterBool ("byps", "Bypass", false, {}, {}, {}));
  208. bypassParameter = ownedBypassParameter.get();
  209. }
  210. // if the bypass parameter is not part of the exported parameters that the plug-in supports
  211. // then add it to the end of the list as VST3 requires the bypass parameter to be exported!
  212. bypassIsRegularParameter = isBypassPartOfRegularParemeters();
  213. if (! bypassIsRegularParameter)
  214. juceParameters.params.add (bypassParameter);
  215. int i = 0;
  216. for (auto* juceParam : juceParameters.params)
  217. {
  218. bool isBypassParameter = (juceParam == bypassParameter);
  219. Vst::ParamID vstParamID = forceLegacyParamIDs ? static_cast<Vst::ParamID> (i++)
  220. : generateVSTParamIDForParam (juceParam);
  221. if (isBypassParameter)
  222. {
  223. // we need to remain backward compatible with the old bypass id
  224. if (vst3WrapperProvidedBypassParam)
  225. vstParamID = static_cast<Vst::ParamID> ((isUsingManagedParameters() && ! forceLegacyParamIDs) ? paramBypass : numParameters);
  226. bypassParamID = vstParamID;
  227. }
  228. vstParamIDs.add (vstParamID);
  229. paramMap.set (static_cast<int32> (vstParamID), juceParam);
  230. }
  231. }
  232. Vst::ParamID generateVSTParamIDForParam (AudioProcessorParameter* param)
  233. {
  234. auto juceParamID = LegacyAudioParameter::getParamID (param, false);
  235. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  236. return static_cast<Vst::ParamID> (juceParamID.getIntValue());
  237. #else
  238. auto paramHash = static_cast<Vst::ParamID> (juceParamID.hashCode());
  239. #if JUCE_USE_STUDIO_ONE_COMPATIBLE_PARAMETERS
  240. // studio one doesn't like negative parameters
  241. paramHash &= ~(((Vst::ParamID) 1) << (sizeof (Vst::ParamID) * 8 - 1));
  242. #endif
  243. return paramHash;
  244. #endif
  245. }
  246. //==============================================================================
  247. std::atomic<int> refCount { 0 };
  248. std::unique_ptr<AudioProcessor> audioProcessor;
  249. //==============================================================================
  250. LegacyAudioParametersWrapper juceParameters;
  251. HashMap<int32, AudioProcessorParameter*> paramMap;
  252. std::unique_ptr<AudioProcessorParameter> ownedBypassParameter;
  253. Array<const AudioProcessorParameterGroup*> parameterGroups;
  254. JuceAudioProcessor() = delete;
  255. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  256. };
  257. class JuceVST3Component;
  258. static ThreadLocalValue<bool> inParameterChangedCallback;
  259. //==============================================================================
  260. class JuceVST3EditController : public Vst::EditController,
  261. public Vst::IMidiMapping,
  262. public Vst::IUnitInfo,
  263. public Vst::ChannelContext::IInfoListener,
  264. public AudioProcessorListener,
  265. private AudioProcessorParameter::Listener
  266. {
  267. public:
  268. JuceVST3EditController (Vst::IHostApplication* host)
  269. {
  270. if (host != nullptr)
  271. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  272. }
  273. //==============================================================================
  274. static const FUID iid;
  275. //==============================================================================
  276. #if JUCE_CLANG
  277. #pragma clang diagnostic push
  278. #pragma clang diagnostic ignored "-Winconsistent-missing-override"
  279. #endif
  280. REFCOUNT_METHODS (ComponentBase)
  281. #if JUCE_CLANG
  282. #pragma clang diagnostic pop
  283. #endif
  284. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  285. {
  286. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  287. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  288. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  289. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  290. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  291. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  292. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  293. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::ChannelContext::IInfoListener)
  294. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  295. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  296. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  297. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  298. {
  299. audioProcessor->addRef();
  300. *obj = audioProcessor;
  301. return kResultOk;
  302. }
  303. *obj = nullptr;
  304. return kNoInterface;
  305. }
  306. //==============================================================================
  307. tresult PLUGIN_API initialize (FUnknown* context) override
  308. {
  309. if (hostContext != context)
  310. {
  311. if (hostContext != nullptr)
  312. hostContext->release();
  313. hostContext = context;
  314. if (hostContext != nullptr)
  315. hostContext->addRef();
  316. }
  317. return kResultTrue;
  318. }
  319. tresult PLUGIN_API terminate() override
  320. {
  321. if (auto* pluginInstance = getPluginInstance())
  322. pluginInstance->removeListener (this);
  323. audioProcessor = nullptr;
  324. return EditController::terminate();
  325. }
  326. //==============================================================================
  327. struct Param : public Vst::Parameter
  328. {
  329. Param (JuceVST3EditController& editController, AudioProcessorParameter& p,
  330. Vst::ParamID vstParamID, Vst::UnitID vstUnitID,
  331. bool isBypassParameter)
  332. : owner (editController), param (p)
  333. {
  334. info.id = vstParamID;
  335. info.unitId = vstUnitID;
  336. updateParameterInfo();
  337. info.stepCount = (Steinberg::int32) 0;
  338. #if ! JUCE_FORCE_LEGACY_PARAMETER_AUTOMATION_TYPE
  339. if (param.isDiscrete())
  340. #endif
  341. {
  342. const int numSteps = param.getNumSteps();
  343. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  344. }
  345. info.defaultNormalizedValue = param.getDefaultValue();
  346. jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
  347. // Is this a meter?
  348. if (((param.getCategory() & 0xffff0000) >> 16) == 2)
  349. info.flags = Vst::ParameterInfo::kIsReadOnly;
  350. else
  351. info.flags = param.isAutomatable() ? Vst::ParameterInfo::kCanAutomate : 0;
  352. if (isBypassParameter)
  353. info.flags |= Vst::ParameterInfo::kIsBypass;
  354. valueNormalized = info.defaultNormalizedValue;
  355. }
  356. virtual ~Param() override = default;
  357. void updateParameterInfo()
  358. {
  359. toString128 (info.title, param.getName (128));
  360. toString128 (info.shortTitle, param.getName (8));
  361. toString128 (info.units, param.getLabel());
  362. }
  363. bool setNormalized (Vst::ParamValue v) override
  364. {
  365. v = jlimit (0.0, 1.0, v);
  366. if (v != valueNormalized)
  367. {
  368. valueNormalized = v;
  369. // Only update the AudioProcessor here if we're not playing,
  370. // otherwise we get parallel streams of parameter value updates
  371. // during playback
  372. if (! owner.vst3IsPlaying)
  373. {
  374. auto value = static_cast<float> (v);
  375. param.setValue (value);
  376. inParameterChangedCallback = true;
  377. param.sendValueChangedMessageToListeners (value);
  378. }
  379. changed();
  380. return true;
  381. }
  382. return false;
  383. }
  384. void toString (Vst::ParamValue value, Vst::String128 result) const override
  385. {
  386. if (LegacyAudioParameter::isLegacy (&param))
  387. // remain backward-compatible with old JUCE code
  388. toString128 (result, param.getCurrentValueAsText());
  389. else
  390. toString128 (result, param.getText ((float) value, 128));
  391. }
  392. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  393. {
  394. if (! LegacyAudioParameter::isLegacy (&param))
  395. {
  396. outValueNormalized = param.getValueForText (getStringFromVstTChars (text));
  397. return true;
  398. }
  399. return false;
  400. }
  401. static String getStringFromVstTChars (const Vst::TChar* text)
  402. {
  403. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  404. }
  405. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  406. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  407. private:
  408. JuceVST3EditController& owner;
  409. AudioProcessorParameter& param;
  410. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  411. };
  412. //==============================================================================
  413. struct ProgramChangeParameter : public Vst::Parameter
  414. {
  415. ProgramChangeParameter (AudioProcessor& p) : owner (p)
  416. {
  417. jassert (owner.getNumPrograms() > 1);
  418. info.id = JuceAudioProcessor::paramPreset;
  419. toString128 (info.title, "Program");
  420. toString128 (info.shortTitle, "Program");
  421. toString128 (info.units, "");
  422. info.stepCount = owner.getNumPrograms() - 1;
  423. info.defaultNormalizedValue = static_cast<Vst::ParamValue> (owner.getCurrentProgram())
  424. / static_cast<Vst::ParamValue> (info.stepCount);
  425. info.unitId = Vst::kRootUnitId;
  426. info.flags = Vst::ParameterInfo::kIsProgramChange | Vst::ParameterInfo::kCanAutomate;
  427. }
  428. virtual ~ProgramChangeParameter() override = default;
  429. bool setNormalized (Vst::ParamValue v) override
  430. {
  431. Vst::ParamValue program = v * info.stepCount;
  432. if (! isPositiveAndBelow ((int) program, owner.getNumPrograms()))
  433. return false;
  434. if (valueNormalized != v)
  435. {
  436. valueNormalized = v;
  437. changed();
  438. return true;
  439. }
  440. return false;
  441. }
  442. void toString (Vst::ParamValue value, Vst::String128 result) const override
  443. {
  444. toString128 (result, owner.getProgramName (roundToInt (value * info.stepCount)));
  445. }
  446. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  447. {
  448. auto paramValueString = getStringFromVstTChars (text);
  449. auto n = owner.getNumPrograms();
  450. for (int i = 0; i < n; ++i)
  451. {
  452. if (paramValueString == owner.getProgramName (i))
  453. {
  454. outValueNormalized = static_cast<Vst::ParamValue> (i) / info.stepCount;
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. static String getStringFromVstTChars (const Vst::TChar* text)
  461. {
  462. return String (CharPointer_UTF16 (reinterpret_cast<const CharPointer_UTF16::CharType*> (text)));
  463. }
  464. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v * info.stepCount; }
  465. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v / info.stepCount; }
  466. private:
  467. AudioProcessor& owner;
  468. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProgramChangeParameter)
  469. };
  470. //==============================================================================
  471. tresult PLUGIN_API setChannelContextInfos (Vst::IAttributeList* list) override
  472. {
  473. if (auto* instance = getPluginInstance())
  474. {
  475. if (list != nullptr)
  476. {
  477. AudioProcessor::TrackProperties trackProperties;
  478. {
  479. Vst::String128 channelName;
  480. if (list->getString (Vst::ChannelContext::kChannelNameKey, channelName, sizeof (channelName)) == kResultTrue)
  481. trackProperties.name = toString (channelName);
  482. }
  483. {
  484. int64 colour;
  485. if (list->getInt (Vst::ChannelContext::kChannelColorKey, colour) == kResultTrue)
  486. trackProperties.colour = Colour (Vst::ChannelContext::GetRed ((uint32) colour), Vst::ChannelContext::GetGreen ((uint32) colour),
  487. Vst::ChannelContext::GetBlue ((uint32) colour), Vst::ChannelContext::GetAlpha ((uint32) colour));
  488. }
  489. if (MessageManager::getInstance()->isThisTheMessageThread())
  490. instance->updateTrackProperties (trackProperties);
  491. else
  492. MessageManager::callAsync ([trackProperties, instance]
  493. { instance->updateTrackProperties (trackProperties); });
  494. }
  495. }
  496. return kResultOk;
  497. }
  498. //==============================================================================
  499. tresult PLUGIN_API setComponentState (IBStream* stream) override
  500. {
  501. // Cubase and Nuendo need to inform the host of the current parameter values
  502. if (auto* pluginInstance = getPluginInstance())
  503. {
  504. for (auto vstParamId : audioProcessor->vstParamIDs)
  505. setParamNormalized (vstParamId, audioProcessor->getParamForVSTParamID (vstParamId)->getValue());
  506. auto numPrograms = pluginInstance->getNumPrograms();
  507. if (numPrograms > 1)
  508. setParamNormalized (JuceAudioProcessor::paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
  509. / static_cast<Vst::ParamValue> (numPrograms - 1));
  510. }
  511. if (auto* handler = getComponentHandler())
  512. handler->restartComponent (Vst::kParamValuesChanged);
  513. return Vst::EditController::setComponentState (stream);
  514. }
  515. void setAudioProcessor (JuceAudioProcessor* audioProc)
  516. {
  517. if (audioProcessor != audioProc)
  518. {
  519. audioProcessor = audioProc;
  520. setupParameters();
  521. }
  522. }
  523. tresult PLUGIN_API connect (IConnectionPoint* other) override
  524. {
  525. if (other != nullptr && audioProcessor == nullptr)
  526. {
  527. auto result = ComponentBase::connect (other);
  528. if (! audioProcessor.loadFrom (other))
  529. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  530. else
  531. setupParameters();
  532. return result;
  533. }
  534. jassertfalse;
  535. return kResultFalse;
  536. }
  537. //==============================================================================
  538. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
  539. Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
  540. {
  541. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  542. resultID = midiControllerToParameter[channel][midiControllerNumber];
  543. return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
  544. #else
  545. ignoreUnused (channel, midiControllerNumber, resultID);
  546. return kResultFalse;
  547. #endif
  548. }
  549. // Converts an incoming parameter index to a MIDI controller:
  550. bool getMidiControllerForParameter (Vst::ParamID index, int& channel, int& ctrlNumber)
  551. {
  552. auto mappedIndex = static_cast<int> (index - parameterToMidiControllerOffset);
  553. if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
  554. {
  555. auto& mc = parameterToMidiController[mappedIndex];
  556. if (mc.channel != -1 && mc.ctrlNumber != -1)
  557. {
  558. channel = jlimit (1, 16, mc.channel + 1);
  559. ctrlNumber = mc.ctrlNumber;
  560. return true;
  561. }
  562. }
  563. return false;
  564. }
  565. inline bool isMidiControllerParamID (Vst::ParamID paramID) const noexcept
  566. {
  567. return (paramID >= parameterToMidiControllerOffset
  568. && isPositiveAndBelow (paramID - parameterToMidiControllerOffset,
  569. static_cast<Vst::ParamID> (numElementsInArray (parameterToMidiController))));
  570. }
  571. //==============================================================================
  572. Steinberg::int32 PLUGIN_API getUnitCount() override
  573. {
  574. if (audioProcessor != nullptr)
  575. return audioProcessor->getUnitCount();
  576. jassertfalse;
  577. return 1;
  578. }
  579. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  580. {
  581. if (audioProcessor != nullptr)
  582. return audioProcessor->getUnitInfo (unitIndex, info);
  583. if (unitIndex == 0)
  584. {
  585. info.id = Vst::kRootUnitId;
  586. info.parentUnitId = Vst::kNoParentUnitId;
  587. info.programListId = Vst::kNoProgramListId;
  588. toString128 (info.name, TRANS("Root Unit"));
  589. return kResultTrue;
  590. }
  591. jassertfalse;
  592. zerostruct (info);
  593. return kResultFalse;
  594. }
  595. Steinberg::int32 PLUGIN_API getProgramListCount() override
  596. {
  597. if (audioProcessor != nullptr)
  598. return audioProcessor->getProgramListCount();
  599. jassertfalse;
  600. return 0;
  601. }
  602. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  603. {
  604. if (audioProcessor != nullptr)
  605. return audioProcessor->getProgramListInfo (listIndex, info);
  606. jassertfalse;
  607. zerostruct (info);
  608. return kResultFalse;
  609. }
  610. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  611. {
  612. if (audioProcessor != nullptr)
  613. return audioProcessor->getProgramName (listId, programIndex, name);
  614. jassertfalse;
  615. toString128 (name, juce::String());
  616. return kResultFalse;
  617. }
  618. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  619. Vst::CString attributeId, Vst::String128 attributeValue) override
  620. {
  621. if (audioProcessor != nullptr)
  622. return audioProcessor->getProgramInfo (listId, programIndex, attributeId, attributeValue);
  623. jassertfalse;
  624. return kResultFalse;
  625. }
  626. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override
  627. {
  628. if (audioProcessor != nullptr)
  629. return audioProcessor->hasProgramPitchNames (listId, programIndex);
  630. jassertfalse;
  631. return kResultFalse;
  632. }
  633. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  634. Steinberg::int16 midiPitch, Vst::String128 name) override
  635. {
  636. if (audioProcessor != nullptr)
  637. return audioProcessor->getProgramPitchName (listId, programIndex, midiPitch, name);
  638. jassertfalse;
  639. return kResultFalse;
  640. }
  641. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override
  642. {
  643. if (audioProcessor != nullptr)
  644. return audioProcessor->selectUnit (unitId);
  645. jassertfalse;
  646. return kResultFalse;
  647. }
  648. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  649. Steinberg::IBStream* data) override
  650. {
  651. if (audioProcessor != nullptr)
  652. return audioProcessor->setUnitProgramData (listOrUnitId, programIndex, data);
  653. jassertfalse;
  654. return kResultFalse;
  655. }
  656. Vst::UnitID PLUGIN_API getSelectedUnit() override
  657. {
  658. if (audioProcessor != nullptr)
  659. return audioProcessor->getSelectedUnit();
  660. jassertfalse;
  661. return kResultFalse;
  662. }
  663. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  664. Steinberg::int32 channel, Vst::UnitID& unitId) override
  665. {
  666. if (audioProcessor != nullptr)
  667. return audioProcessor->getUnitByBus (type, dir, busIndex, channel, unitId);
  668. jassertfalse;
  669. return kResultFalse;
  670. }
  671. //==============================================================================
  672. IPlugView* PLUGIN_API createView (const char* name) override
  673. {
  674. if (auto* pluginInstance = getPluginInstance())
  675. {
  676. if (pluginInstance->hasEditor() && name != nullptr
  677. && strcmp (name, Vst::ViewType::kEditor) == 0)
  678. {
  679. return new JuceVST3Editor (*this, *pluginInstance);
  680. }
  681. }
  682. return nullptr;
  683. }
  684. //==============================================================================
  685. void paramChanged (Vst::ParamID vstParamId, float newValue)
  686. {
  687. if (inParameterChangedCallback.get())
  688. {
  689. inParameterChangedCallback = false;
  690. return;
  691. }
  692. // NB: Cubase has problems if performEdit is called without setParamNormalized
  693. EditController::setParamNormalized (vstParamId, (double) newValue);
  694. performEdit (vstParamId, (double) newValue);
  695. }
  696. //==============================================================================
  697. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit (audioProcessor->getVSTParamIDForIndex (index)); }
  698. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit (audioProcessor->getVSTParamIDForIndex (index)); }
  699. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  700. {
  701. paramChanged (audioProcessor->getVSTParamIDForIndex (index), newValue);
  702. }
  703. void audioProcessorChanged (AudioProcessor*) override
  704. {
  705. auto numParameters = parameters.getParameterCount();
  706. for (int32 i = 0; i < numParameters; ++i)
  707. if (auto* param = dynamic_cast<Param*> (parameters.getParameterByIndex (i)))
  708. param->updateParameterInfo();
  709. if (auto* pluginInstance = getPluginInstance())
  710. {
  711. if (pluginInstance->getNumPrograms() > 1)
  712. EditController::setParamNormalized (JuceAudioProcessor::paramPreset, static_cast<Vst::ParamValue> (pluginInstance->getCurrentProgram())
  713. / static_cast<Vst::ParamValue> (pluginInstance->getNumPrograms() - 1));
  714. }
  715. if (componentHandler != nullptr && ! inSetupProcessing)
  716. componentHandler->restartComponent (Vst::kLatencyChanged | Vst::kParamValuesChanged | Vst::kParamTitlesChanged);
  717. }
  718. void parameterValueChanged (int, float newValue) override
  719. {
  720. // this can only come from the bypass parameter
  721. paramChanged (audioProcessor->bypassParamID, newValue);
  722. }
  723. void parameterGestureChanged (int, bool gestureIsStarting) override
  724. {
  725. // this can only come from the bypass parameter
  726. if (gestureIsStarting) beginEdit (audioProcessor->bypassParamID);
  727. else endEdit (audioProcessor->bypassParamID);
  728. }
  729. //==============================================================================
  730. AudioProcessor* getPluginInstance() const noexcept
  731. {
  732. if (audioProcessor != nullptr)
  733. return audioProcessor->get();
  734. return nullptr;
  735. }
  736. private:
  737. friend class JuceVST3Component;
  738. friend struct Param;
  739. //==============================================================================
  740. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  741. struct MidiController
  742. {
  743. int channel = -1, ctrlNumber = -1;
  744. };
  745. enum { numMIDIChannels = 16 };
  746. Vst::ParamID parameterToMidiControllerOffset;
  747. MidiController parameterToMidiController[(int) numMIDIChannels * (int) Vst::kCountCtrlNumber];
  748. Vst::ParamID midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
  749. //==============================================================================
  750. std::atomic<bool> vst3IsPlaying { false },
  751. inSetupProcessing { false };
  752. #if ! JUCE_MAC
  753. float lastScaleFactorReceived = 1.0f;
  754. #endif
  755. void setupParameters()
  756. {
  757. if (auto* pluginInstance = getPluginInstance())
  758. {
  759. pluginInstance->addListener (this);
  760. // as the bypass is not part of the regular parameters
  761. // we need to listen for it explicitly
  762. if (! audioProcessor->bypassIsRegularParameter)
  763. audioProcessor->getBypassParameter()->addListener (this);
  764. if (parameters.getParameterCount() <= 0)
  765. {
  766. auto n = audioProcessor->getNumParameters();
  767. for (int i = 0; i < n; ++i)
  768. {
  769. auto vstParamID = audioProcessor->getVSTParamIDForIndex (i);
  770. auto* juceParam = audioProcessor->getParamForVSTParamID (vstParamID);
  771. auto* parameterGroup = pluginInstance->getParameterTree().getGroupsForParameter (juceParam).getLast();
  772. auto unitID = JuceAudioProcessor::getUnitID (parameterGroup);
  773. parameters.addParameter (new Param (*this, *juceParam, vstParamID, unitID,
  774. (vstParamID == audioProcessor->bypassParamID)));
  775. }
  776. if (pluginInstance->getNumPrograms() > 1)
  777. parameters.addParameter (new ProgramChangeParameter (*pluginInstance));
  778. }
  779. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  780. parameterToMidiControllerOffset = static_cast<Vst::ParamID> (audioProcessor->isUsingManagedParameters() ? JuceAudioProcessor::paramMidiControllerOffset
  781. : parameters.getParameterCount());
  782. initialiseMidiControllerMappings();
  783. #endif
  784. audioProcessorChanged (pluginInstance);
  785. }
  786. }
  787. void initialiseMidiControllerMappings()
  788. {
  789. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  790. {
  791. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  792. {
  793. midiControllerToParameter[c][i] = static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset;
  794. parameterToMidiController[p].channel = c;
  795. parameterToMidiController[p].ctrlNumber = i;
  796. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  797. static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset, nullptr, 0, 0,
  798. 0, Vst::kRootUnitId));
  799. }
  800. }
  801. }
  802. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  803. {
  804. jassert (hostContext != nullptr);
  805. if (auto* message = allocateMessage())
  806. {
  807. const FReleaser releaser (message);
  808. message->setMessageID (idTag);
  809. message->getAttributes()->setInt (idTag, value);
  810. sendMessage (message);
  811. }
  812. }
  813. //==============================================================================
  814. class JuceVST3Editor : public Vst::EditorView,
  815. public Steinberg::IPlugViewContentScaleSupport,
  816. private Timer
  817. {
  818. public:
  819. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  820. : Vst::EditorView (&ec, nullptr),
  821. owner (&ec), pluginInstance (p)
  822. {
  823. component.reset (new ContentWrapperComponent (*this, p));
  824. #if JUCE_MAC
  825. if (getHostType().type == PluginHostType::SteinbergCubase10)
  826. cubase10Workaround.reset (new Cubase10WindowResizeWorkaround (*this));
  827. #else
  828. if (! approximatelyEqual (editorScaleFactor, ec.lastScaleFactorReceived))
  829. setContentScaleFactor (ec.lastScaleFactorReceived);
  830. #endif
  831. }
  832. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  833. {
  834. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Steinberg::IPlugViewContentScaleSupport)
  835. return Vst::EditorView::queryInterface (targetIID, obj);
  836. }
  837. REFCOUNT_METHODS (Vst::EditorView)
  838. //==============================================================================
  839. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  840. {
  841. if (type != nullptr && pluginInstance.hasEditor())
  842. {
  843. #if JUCE_WINDOWS
  844. if (strcmp (type, kPlatformTypeHWND) == 0)
  845. #else
  846. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  847. #endif
  848. return kResultTrue;
  849. }
  850. return kResultFalse;
  851. }
  852. tresult PLUGIN_API attached (void* parent, FIDString type) override
  853. {
  854. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  855. return kResultFalse;
  856. if (component == nullptr)
  857. component.reset (new ContentWrapperComponent (*this, pluginInstance));
  858. #if JUCE_WINDOWS
  859. component->addToDesktop (0, parent);
  860. component->setOpaque (true);
  861. component->setVisible (true);
  862. #else
  863. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  864. macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
  865. #endif
  866. component->resizeHostWindow();
  867. systemWindow = parent;
  868. attachedToParent();
  869. // Life's too short to faff around with wave lab
  870. if (getHostType().isWavelab())
  871. startTimer (200);
  872. return kResultTrue;
  873. }
  874. tresult PLUGIN_API removed() override
  875. {
  876. if (component != nullptr)
  877. {
  878. #if JUCE_WINDOWS
  879. component->removeFromDesktop();
  880. #else
  881. if (macHostWindow != nullptr)
  882. {
  883. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  884. macHostWindow = nullptr;
  885. }
  886. #endif
  887. component = nullptr;
  888. }
  889. return CPluginView::removed();
  890. }
  891. tresult PLUGIN_API onSize (ViewRect* newSize) override
  892. {
  893. if (newSize != nullptr)
  894. {
  895. rect = convertFromHostBounds (*newSize);
  896. if (component != nullptr)
  897. {
  898. auto w = rect.getWidth();
  899. auto h = rect.getHeight();
  900. component->setSize (w, h);
  901. #if JUCE_MAC
  902. if (cubase10Workaround != nullptr)
  903. {
  904. cubase10Workaround->triggerAsyncUpdate();
  905. }
  906. else
  907. #endif
  908. {
  909. if (auto* peer = component->getPeer())
  910. peer->updateBounds();
  911. }
  912. }
  913. return kResultTrue;
  914. }
  915. jassertfalse;
  916. return kResultFalse;
  917. }
  918. tresult PLUGIN_API getSize (ViewRect* size) override
  919. {
  920. if (size != nullptr && component != nullptr)
  921. {
  922. auto editorBounds = component->getSizeToContainChild();
  923. *size = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  924. return kResultTrue;
  925. }
  926. return kResultFalse;
  927. }
  928. tresult PLUGIN_API canResize() override
  929. {
  930. if (component != nullptr)
  931. if (auto* editor = component->pluginEditor.get())
  932. if (editor->isResizable())
  933. return kResultTrue;
  934. return kResultFalse;
  935. }
  936. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  937. {
  938. if (rectToCheck != nullptr && component != nullptr)
  939. {
  940. if (auto* editor = component->pluginEditor.get())
  941. {
  942. if (auto* constrainer = editor->getConstrainer())
  943. {
  944. *rectToCheck = convertFromHostBounds (*rectToCheck);
  945. auto transformScale = std::sqrt (std::abs (editor->getTransform().getDeterminant()));
  946. auto minW = (double) (constrainer->getMinimumWidth() * transformScale);
  947. auto maxW = (double) (constrainer->getMaximumWidth() * transformScale);
  948. auto minH = (double) (constrainer->getMinimumHeight() * transformScale);
  949. auto maxH = (double) (constrainer->getMaximumHeight() * transformScale);
  950. auto width = (double) (rectToCheck->right - rectToCheck->left);
  951. auto height = (double) (rectToCheck->bottom - rectToCheck->top);
  952. width = jlimit (minW, maxW, width);
  953. height = jlimit (minH, maxH, height);
  954. auto aspectRatio = constrainer->getFixedAspectRatio();
  955. if (aspectRatio != 0.0)
  956. {
  957. bool adjustWidth = (width / height > aspectRatio);
  958. if (getHostType().type == PluginHostType::SteinbergCubase9)
  959. {
  960. if (editor->getWidth() == width && editor->getHeight() != height)
  961. adjustWidth = true;
  962. else if (editor->getHeight() == height && editor->getWidth() != width)
  963. adjustWidth = false;
  964. }
  965. if (adjustWidth)
  966. {
  967. width = height * aspectRatio;
  968. if (width > maxW || width < minW)
  969. {
  970. width = jlimit (minW, maxW, width);
  971. height = width / aspectRatio;
  972. }
  973. }
  974. else
  975. {
  976. height = width / aspectRatio;
  977. if (height > maxH || height < minH)
  978. {
  979. height = jlimit (minH, maxH, height);
  980. width = height * aspectRatio;
  981. }
  982. }
  983. }
  984. rectToCheck->right = rectToCheck->left + roundToInt (width);
  985. rectToCheck->bottom = rectToCheck->top + roundToInt (height);
  986. *rectToCheck = convertToHostBounds (*rectToCheck);
  987. }
  988. }
  989. return kResultTrue;
  990. }
  991. jassertfalse;
  992. return kResultFalse;
  993. }
  994. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  995. {
  996. #if ! JUCE_MAC
  997. if (! approximatelyEqual ((float) factor, editorScaleFactor))
  998. {
  999. editorScaleFactor = (float) factor;
  1000. if (owner != nullptr)
  1001. owner->lastScaleFactorReceived = editorScaleFactor;
  1002. if (component != nullptr)
  1003. {
  1004. if (auto* editor = component->pluginEditor.get())
  1005. {
  1006. editor->setScaleFactor (editorScaleFactor);
  1007. component->resizeHostWindow();
  1008. component->setTopLeftPosition (0, 0);
  1009. component->repaint();
  1010. }
  1011. }
  1012. }
  1013. return kResultTrue;
  1014. #else
  1015. ignoreUnused (factor);
  1016. return kResultFalse;
  1017. #endif
  1018. }
  1019. private:
  1020. void timerCallback() override
  1021. {
  1022. stopTimer();
  1023. ViewRect viewRect;
  1024. getSize (&viewRect);
  1025. onSize (&viewRect);
  1026. }
  1027. static ViewRect convertToHostBounds (ViewRect pluginRect)
  1028. {
  1029. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1030. if (approximatelyEqual (desktopScale, 1.0f))
  1031. return pluginRect;
  1032. return { roundToInt (pluginRect.left * desktopScale),
  1033. roundToInt (pluginRect.top * desktopScale),
  1034. roundToInt (pluginRect.right * desktopScale),
  1035. roundToInt (pluginRect.bottom * desktopScale) };
  1036. }
  1037. static ViewRect convertFromHostBounds (ViewRect hostRect)
  1038. {
  1039. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1040. if (approximatelyEqual (desktopScale, 1.0f))
  1041. return hostRect;
  1042. return { roundToInt (hostRect.left / desktopScale),
  1043. roundToInt (hostRect.top / desktopScale),
  1044. roundToInt (hostRect.right / desktopScale),
  1045. roundToInt (hostRect.bottom / desktopScale) };
  1046. }
  1047. //==============================================================================
  1048. struct ContentWrapperComponent : public Component
  1049. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1050. , private Timer
  1051. #endif
  1052. {
  1053. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  1054. : pluginEditor (plugin.createEditorIfNeeded()),
  1055. owner (editor)
  1056. {
  1057. setOpaque (true);
  1058. setBroughtToFrontOnMouseClick (true);
  1059. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  1060. jassert (pluginEditor != nullptr);
  1061. if (pluginEditor != nullptr)
  1062. {
  1063. addAndMakeVisible (pluginEditor.get());
  1064. pluginEditor->setTopLeftPosition (0, 0);
  1065. lastBounds = getSizeToContainChild();
  1066. {
  1067. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1068. setBounds (lastBounds);
  1069. }
  1070. resizeHostWindow();
  1071. }
  1072. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1073. startTimer (500);
  1074. #endif
  1075. ignoreUnused (fakeMouseGenerator);
  1076. }
  1077. ~ContentWrapperComponent() override
  1078. {
  1079. if (pluginEditor != nullptr)
  1080. {
  1081. PopupMenu::dismissAllActiveMenus();
  1082. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  1083. }
  1084. }
  1085. void paint (Graphics& g) override
  1086. {
  1087. g.fillAll (Colours::black);
  1088. }
  1089. juce::Rectangle<int> getSizeToContainChild()
  1090. {
  1091. if (pluginEditor != nullptr)
  1092. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  1093. return {};
  1094. }
  1095. void childBoundsChanged (Component*) override
  1096. {
  1097. if (resizingChild)
  1098. return;
  1099. auto b = getSizeToContainChild();
  1100. if (lastBounds != b)
  1101. {
  1102. lastBounds = b;
  1103. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1104. resizeHostWindow();
  1105. }
  1106. }
  1107. void resized() override
  1108. {
  1109. if (pluginEditor != nullptr)
  1110. {
  1111. if (! resizingParent)
  1112. {
  1113. auto newBounds = getLocalBounds();
  1114. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1115. if (! lastBounds.isEmpty() && isWithin (newBounds.toDouble().getAspectRatio(), lastBounds.toDouble().getAspectRatio(), 0.1))
  1116. return;
  1117. #endif
  1118. lastBounds = newBounds;
  1119. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1120. if (auto* constrainer = pluginEditor->getConstrainer())
  1121. {
  1122. auto aspectRatio = constrainer->getFixedAspectRatio();
  1123. if (aspectRatio != 0)
  1124. {
  1125. auto width = (double) lastBounds.getWidth();
  1126. auto height = (double) lastBounds.getHeight();
  1127. if (width / height > aspectRatio)
  1128. setBounds ({ 0, 0, roundToInt (height * aspectRatio), lastBounds.getHeight() });
  1129. else
  1130. setBounds ({ 0, 0, lastBounds.getWidth(), roundToInt (width / aspectRatio) });
  1131. }
  1132. }
  1133. pluginEditor->setTopLeftPosition (0, 0);
  1134. pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
  1135. }
  1136. }
  1137. }
  1138. void resizeHostWindow()
  1139. {
  1140. if (pluginEditor != nullptr)
  1141. {
  1142. auto b = getSizeToContainChild();
  1143. auto w = b.getWidth();
  1144. auto h = b.getHeight();
  1145. auto host = getHostType();
  1146. #if JUCE_WINDOWS
  1147. setSize (w, h);
  1148. #endif
  1149. if (owner.plugFrame != nullptr)
  1150. {
  1151. auto newSize = convertToHostBounds ({ 0, 0, b.getWidth(), b.getHeight() });
  1152. {
  1153. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1154. owner.plugFrame->resizeView (&owner, &newSize);
  1155. }
  1156. #if JUCE_MAC
  1157. if (host.isWavelab() || host.isReaper())
  1158. #else
  1159. if (host.isWavelab() || host.isAbletonLive())
  1160. #endif
  1161. setBounds (0, 0, w, h);
  1162. }
  1163. }
  1164. }
  1165. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  1166. private:
  1167. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1168. void timerCallback() override
  1169. {
  1170. auto hostWindowScale = (float) getScaleFactorForWindow ((HWND) owner.systemWindow);
  1171. if (hostWindowScale > 0.0 && ! approximatelyEqual (hostWindowScale, owner.editorScaleFactor))
  1172. owner.setContentScaleFactor (hostWindowScale);
  1173. }
  1174. #endif
  1175. JuceVST3Editor& owner;
  1176. FakeMouseMoveGenerator fakeMouseGenerator;
  1177. Rectangle<int> lastBounds;
  1178. bool resizingChild = false, resizingParent = false;
  1179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  1180. };
  1181. //==============================================================================
  1182. ComSmartPtr<JuceVST3EditController> owner;
  1183. AudioProcessor& pluginInstance;
  1184. std::unique_ptr<ContentWrapperComponent> component;
  1185. friend struct ContentWrapperComponent;
  1186. #if JUCE_MAC
  1187. void* macHostWindow = nullptr;
  1188. bool isNSView = false;
  1189. // On macOS Cubase 10 resizes the host window after calling onSize() resulting in the peer
  1190. // bounds being a step behind the plug-in. Calling updateBounds() asynchronously seems to fix things...
  1191. struct Cubase10WindowResizeWorkaround : public AsyncUpdater
  1192. {
  1193. Cubase10WindowResizeWorkaround (JuceVST3Editor& o) : owner (o) {}
  1194. void handleAsyncUpdate() override
  1195. {
  1196. if (owner.component != nullptr)
  1197. if (auto* peer = owner.component->getPeer())
  1198. peer->updateBounds();
  1199. }
  1200. JuceVST3Editor& owner;
  1201. };
  1202. std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
  1203. #else
  1204. float editorScaleFactor = 1.0f;
  1205. #if JUCE_WINDOWS
  1206. WindowsHooks hooks;
  1207. #endif
  1208. #endif
  1209. //==============================================================================
  1210. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  1211. };
  1212. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  1213. };
  1214. namespace
  1215. {
  1216. template <typename FloatType> struct AudioBusPointerHelper {};
  1217. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  1218. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  1219. template <typename FloatType> struct ChooseBufferHelper {};
  1220. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  1221. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  1222. }
  1223. //==============================================================================
  1224. class JuceVST3Component : public Vst::IComponent,
  1225. public Vst::IAudioProcessor,
  1226. public Vst::IUnitInfo,
  1227. public Vst::IConnectionPoint,
  1228. public AudioPlayHead
  1229. {
  1230. public:
  1231. JuceVST3Component (Vst::IHostApplication* h)
  1232. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  1233. host (h)
  1234. {
  1235. inParameterChangedCallback = false;
  1236. #ifdef JucePlugin_PreferredChannelConfigurations
  1237. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1238. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1239. ignoreUnused (numConfigs);
  1240. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1241. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1242. #endif
  1243. // VST-3 requires your default layout to be non-discrete!
  1244. // For example, your default layout must be mono, stereo, quadrophonic
  1245. // and not AudioChannelSet::discreteChannels (2) etc.
  1246. jassert (checkBusFormatsAreNotDiscrete());
  1247. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  1248. zerostruct (processContext);
  1249. processSetup.maxSamplesPerBlock = 1024;
  1250. processSetup.processMode = Vst::kRealtime;
  1251. processSetup.sampleRate = 44100.0;
  1252. processSetup.symbolicSampleSize = Vst::kSample32;
  1253. pluginInstance->setPlayHead (this);
  1254. }
  1255. ~JuceVST3Component() override
  1256. {
  1257. if (juceVST3EditController != nullptr)
  1258. juceVST3EditController->vst3IsPlaying = false;
  1259. if (pluginInstance != nullptr)
  1260. if (pluginInstance->getPlayHead() == this)
  1261. pluginInstance->setPlayHead (nullptr);
  1262. }
  1263. //==============================================================================
  1264. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1265. //==============================================================================
  1266. static const FUID iid;
  1267. JUCE_DECLARE_VST3_COM_REF_METHODS
  1268. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1269. {
  1270. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  1271. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  1272. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  1273. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  1274. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  1275. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  1276. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  1277. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  1278. {
  1279. comPluginInstance->addRef();
  1280. *obj = comPluginInstance;
  1281. return kResultOk;
  1282. }
  1283. *obj = nullptr;
  1284. return kNoInterface;
  1285. }
  1286. //==============================================================================
  1287. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1288. {
  1289. if (host != hostContext)
  1290. host.loadFrom (hostContext);
  1291. processContext.sampleRate = processSetup.sampleRate;
  1292. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  1293. return kResultTrue;
  1294. }
  1295. tresult PLUGIN_API terminate() override
  1296. {
  1297. getPluginInstance().releaseResources();
  1298. return kResultTrue;
  1299. }
  1300. //==============================================================================
  1301. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1302. {
  1303. if (other != nullptr && juceVST3EditController == nullptr)
  1304. juceVST3EditController.loadFrom (other);
  1305. return kResultTrue;
  1306. }
  1307. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1308. {
  1309. if (juceVST3EditController != nullptr)
  1310. juceVST3EditController->vst3IsPlaying = false;
  1311. juceVST3EditController = nullptr;
  1312. return kResultTrue;
  1313. }
  1314. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1315. {
  1316. if (message != nullptr && juceVST3EditController == nullptr)
  1317. {
  1318. Steinberg::int64 value = 0;
  1319. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1320. {
  1321. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  1322. if (juceVST3EditController != nullptr)
  1323. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1324. else
  1325. jassertfalse;
  1326. }
  1327. }
  1328. return kResultTrue;
  1329. }
  1330. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1331. {
  1332. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1333. return kResultTrue;
  1334. }
  1335. //==============================================================================
  1336. tresult PLUGIN_API setActive (TBool state) override
  1337. {
  1338. if (! state)
  1339. {
  1340. getPluginInstance().releaseResources();
  1341. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1342. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1343. }
  1344. else
  1345. {
  1346. auto sampleRate = getPluginInstance().getSampleRate();
  1347. auto bufferSize = getPluginInstance().getBlockSize();
  1348. sampleRate = processSetup.sampleRate > 0.0
  1349. ? processSetup.sampleRate
  1350. : sampleRate;
  1351. bufferSize = processSetup.maxSamplesPerBlock > 0
  1352. ? (int) processSetup.maxSamplesPerBlock
  1353. : bufferSize;
  1354. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1355. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1356. preparePlugin (sampleRate, bufferSize);
  1357. }
  1358. return kResultOk;
  1359. }
  1360. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1361. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1362. //==============================================================================
  1363. bool isBypassed()
  1364. {
  1365. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1366. return (bypassParam->getValue() != 0.0f);
  1367. return false;
  1368. }
  1369. void setBypassed (bool shouldBeBypassed)
  1370. {
  1371. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1372. {
  1373. auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
  1374. bypassParam->setValue (floatValue);
  1375. inParameterChangedCallback = true;
  1376. bypassParam->sendValueChangedMessageToListeners (floatValue);
  1377. }
  1378. }
  1379. //==============================================================================
  1380. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1381. {
  1382. if (pluginInstance->getBypassParameter() == nullptr)
  1383. {
  1384. ValueTree privateData (kJucePrivateDataIdentifier);
  1385. // for now we only store the bypass value
  1386. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1387. privateData.writeToStream (out);
  1388. }
  1389. }
  1390. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1391. {
  1392. if (pluginInstance->getBypassParameter() == nullptr)
  1393. {
  1394. if (comPluginInstance->getBypassParameter() != nullptr)
  1395. {
  1396. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1397. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1398. }
  1399. }
  1400. }
  1401. void getStateInformation (MemoryBlock& destData)
  1402. {
  1403. pluginInstance->getStateInformation (destData);
  1404. // With bypass support, JUCE now needs to store private state data.
  1405. // Put this at the end of the plug-in state and add a few null characters
  1406. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1407. // this data. Additionally, we need to add some sort of magic identifier
  1408. // at the very end of the private data so that JUCE has some sort of
  1409. // way to figure out if the data was stored with a newer JUCE version.
  1410. MemoryOutputStream extraData;
  1411. extraData.writeInt64 (0);
  1412. writeJucePrivateStateInformation (extraData);
  1413. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1414. extraData.writeInt64 (privateDataSize);
  1415. extraData << kJucePrivateDataIdentifier;
  1416. // write magic string
  1417. destData.append (extraData.getData(), extraData.getDataSize());
  1418. }
  1419. void setStateInformation (const void* data, int sizeAsInt)
  1420. {
  1421. int64 size = sizeAsInt;
  1422. // Check if this data was written with a newer JUCE version
  1423. // and if it has the JUCE private data magic code at the end
  1424. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1425. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1426. {
  1427. auto buffer = static_cast<const char*> (data);
  1428. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1429. CharPointer_UTF8 (buffer + size));
  1430. if (magic == kJucePrivateDataIdentifier)
  1431. {
  1432. // found a JUCE private data section
  1433. uint64 privateDataSize;
  1434. std::memcpy (&privateDataSize,
  1435. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1436. sizeof (uint64));
  1437. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1438. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1439. if (privateDataSize > 0)
  1440. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1441. size -= sizeof (uint64);
  1442. }
  1443. }
  1444. if (size >= 0)
  1445. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1446. }
  1447. //==============================================================================
  1448. #if JUCE_VST3_CAN_REPLACE_VST2
  1449. bool loadVST2VstWBlock (const char* data, int size)
  1450. {
  1451. jassert ('VstW' == htonl (*(juce::int32*) data));
  1452. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1453. auto headerLen = (int) htonl (*(juce::int32*) (data + 4)) + 8;
  1454. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1455. }
  1456. bool loadVST2CcnKBlock (const char* data, int size)
  1457. {
  1458. auto bank = (const Vst2::fxBank*) data;
  1459. jassert ('CcnK' == htonl (bank->chunkMagic));
  1460. jassert ('FBCh' == htonl (bank->fxMagic));
  1461. jassert (htonl (bank->version) == 1 || htonl (bank->version) == 2);
  1462. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1463. setStateInformation (bank->content.data.chunk,
  1464. jmin ((int) (size - (bank->content.data.chunk - data)),
  1465. (int) htonl (bank->content.data.size)));
  1466. return true;
  1467. }
  1468. bool loadVST3PresetFile (const char* data, int size)
  1469. {
  1470. if (size < 48)
  1471. return false;
  1472. // At offset 4 there's a little-endian version number which seems to typically be 1
  1473. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1474. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1475. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1476. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1477. jassert (entryCount > 0);
  1478. for (int i = 0; i < entryCount; ++i)
  1479. {
  1480. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1481. if (entryOffset + 20 > size)
  1482. return false;
  1483. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1484. {
  1485. // "Comp" entries seem to contain the data.
  1486. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1487. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1488. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1489. {
  1490. jassertfalse;
  1491. return false;
  1492. }
  1493. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1494. }
  1495. }
  1496. return true;
  1497. }
  1498. bool loadVST2CompatibleState (const char* data, int size)
  1499. {
  1500. if (size < 4)
  1501. return false;
  1502. auto header = htonl (*(juce::int32*) data);
  1503. if (header == 'VstW')
  1504. return loadVST2VstWBlock (data, size);
  1505. if (header == 'CcnK')
  1506. return loadVST2CcnKBlock (data, size);
  1507. if (memcmp (data, "VST3", 4) == 0)
  1508. {
  1509. // In Cubase 5, when loading VST3 .vstpreset files,
  1510. // we get the whole content of the files to load.
  1511. // In Cubase 7 we get just the contents within and
  1512. // we go directly to the loadVST2VstW codepath instead.
  1513. return loadVST3PresetFile (data, size);
  1514. }
  1515. return false;
  1516. }
  1517. #endif
  1518. void loadStateData (const void* data, int size)
  1519. {
  1520. #if JUCE_VST3_CAN_REPLACE_VST2
  1521. if (loadVST2CompatibleState ((const char*) data, size))
  1522. return;
  1523. #endif
  1524. setStateInformation (data, size);
  1525. }
  1526. bool readFromMemoryStream (IBStream* state)
  1527. {
  1528. FUnknownPtr<ISizeableStream> s (state);
  1529. Steinberg::int64 size = 0;
  1530. if (s != nullptr
  1531. && s->getStreamSize (size) == kResultOk
  1532. && size > 0
  1533. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1534. {
  1535. MemoryBlock block (static_cast<size_t> (size));
  1536. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1537. Steinberg::int32 bytesRead = 1;
  1538. int len;
  1539. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1540. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1541. break;
  1542. if (len == 0)
  1543. return false;
  1544. block.setSize (static_cast<size_t> (len));
  1545. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1546. if (getHostType().isAdobeAudition())
  1547. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1548. return false;
  1549. loadStateData (block.getData(), (int) block.getSize());
  1550. return true;
  1551. }
  1552. return false;
  1553. }
  1554. bool readFromUnknownStream (IBStream* state)
  1555. {
  1556. MemoryOutputStream allData;
  1557. {
  1558. const size_t bytesPerBlock = 4096;
  1559. HeapBlock<char> buffer (bytesPerBlock);
  1560. for (;;)
  1561. {
  1562. Steinberg::int32 bytesRead = 0;
  1563. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1564. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1565. break;
  1566. allData.write (buffer, static_cast<size_t> (bytesRead));
  1567. }
  1568. }
  1569. const size_t dataSize = allData.getDataSize();
  1570. if (dataSize <= 0 || dataSize >= 0x7fffffff)
  1571. return false;
  1572. loadStateData (allData.getData(), (int) dataSize);
  1573. return true;
  1574. }
  1575. tresult PLUGIN_API setState (IBStream* state) override
  1576. {
  1577. if (state == nullptr)
  1578. return kInvalidArgument;
  1579. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1580. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1581. {
  1582. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1583. return kResultTrue;
  1584. if (readFromUnknownStream (state))
  1585. return kResultTrue;
  1586. }
  1587. return kResultFalse;
  1588. }
  1589. #if JUCE_VST3_CAN_REPLACE_VST2
  1590. static tresult writeVST2Int (IBStream* state, int n)
  1591. {
  1592. juce::int32 t = (juce::int32) htonl (n);
  1593. return state->write (&t, 4);
  1594. }
  1595. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1596. {
  1597. tresult status = writeVST2Int (state, 'VstW');
  1598. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1599. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1600. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1601. return status;
  1602. }
  1603. #endif
  1604. tresult PLUGIN_API getState (IBStream* state) override
  1605. {
  1606. if (state == nullptr)
  1607. return kInvalidArgument;
  1608. juce::MemoryBlock mem;
  1609. getStateInformation (mem);
  1610. #if JUCE_VST3_CAN_REPLACE_VST2
  1611. tresult status = writeVST2Header (state, isBypassed());
  1612. if (status != kResultOk)
  1613. return status;
  1614. const int bankBlockSize = 160;
  1615. Vst2::fxBank bank;
  1616. zerostruct (bank);
  1617. bank.chunkMagic = (int32) htonl ('CcnK');
  1618. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1619. bank.fxMagic = (int32) htonl ('FBCh');
  1620. bank.version = (int32) htonl (2);
  1621. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1622. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  1623. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  1624. status = state->write (&bank, bankBlockSize);
  1625. if (status != kResultOk)
  1626. return status;
  1627. #endif
  1628. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1629. }
  1630. //==============================================================================
  1631. Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
  1632. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
  1633. Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
  1634. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
  1635. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
  1636. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1637. Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
  1638. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
  1639. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1640. Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
  1641. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
  1642. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  1643. Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
  1644. Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
  1645. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  1646. Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
  1647. //==============================================================================
  1648. bool getCurrentPosition (CurrentPositionInfo& info) override
  1649. {
  1650. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1651. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  1652. info.bpm = jmax (1.0, processContext.tempo);
  1653. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1654. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1655. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1656. info.ppqPosition = processContext.projectTimeMusic;
  1657. info.ppqLoopStart = processContext.cycleStartMusic;
  1658. info.ppqLoopEnd = processContext.cycleEndMusic;
  1659. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1660. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1661. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1662. info.editOriginTime = 0.0;
  1663. info.frameRate = AudioPlayHead::fpsUnknown;
  1664. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1665. {
  1666. switch (processContext.frameRate.framesPerSecond)
  1667. {
  1668. case 24:
  1669. {
  1670. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1671. info.frameRate = AudioPlayHead::fps23976;
  1672. else
  1673. info.frameRate = AudioPlayHead::fps24;
  1674. }
  1675. break;
  1676. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1677. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1678. case 30:
  1679. {
  1680. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1681. info.frameRate = AudioPlayHead::fps30drop;
  1682. else
  1683. info.frameRate = AudioPlayHead::fps30;
  1684. }
  1685. break;
  1686. default: break;
  1687. }
  1688. }
  1689. return true;
  1690. }
  1691. //==============================================================================
  1692. int getNumAudioBuses (bool isInput) const
  1693. {
  1694. int busCount = pluginInstance->getBusCount (isInput);
  1695. #ifdef JucePlugin_PreferredChannelConfigurations
  1696. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1697. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1698. bool hasOnlyZeroChannels = true;
  1699. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1700. if (configs[i][isInput ? 0 : 1] != 0)
  1701. hasOnlyZeroChannels = false;
  1702. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1703. #endif
  1704. return busCount;
  1705. }
  1706. //==============================================================================
  1707. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1708. {
  1709. if (type == Vst::kAudio)
  1710. return getNumAudioBuses (dir == Vst::kInput);
  1711. if (type == Vst::kEvent)
  1712. {
  1713. if (dir == Vst::kInput)
  1714. return isMidiInputBusEnabled ? 1 : 0;
  1715. if (dir == Vst::kOutput)
  1716. return isMidiOutputBusEnabled ? 1 : 0;
  1717. }
  1718. return 0;
  1719. }
  1720. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1721. Steinberg::int32 index, Vst::BusInfo& info) override
  1722. {
  1723. if (type == Vst::kAudio)
  1724. {
  1725. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1726. return kResultFalse;
  1727. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1728. {
  1729. info.mediaType = Vst::kAudio;
  1730. info.direction = dir;
  1731. info.channelCount = bus->getLastEnabledLayout().size();
  1732. toString128 (info.name, bus->getName());
  1733. #if JucePlugin_IsSynth
  1734. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1735. #else
  1736. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1737. #endif
  1738. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1739. return kResultTrue;
  1740. }
  1741. }
  1742. if (type == Vst::kEvent)
  1743. {
  1744. info.flags = Vst::BusInfo::kDefaultActive;
  1745. #if JucePlugin_WantsMidiInput
  1746. if (dir == Vst::kInput && index == 0)
  1747. {
  1748. info.mediaType = Vst::kEvent;
  1749. info.direction = dir;
  1750. #ifdef JucePlugin_VSTNumMidiInputs
  1751. info.channelCount = JucePlugin_VSTNumMidiInputs;
  1752. #else
  1753. info.channelCount = 16;
  1754. #endif
  1755. toString128 (info.name, TRANS("MIDI Input"));
  1756. info.busType = Vst::kMain;
  1757. return kResultTrue;
  1758. }
  1759. #endif
  1760. #if JucePlugin_ProducesMidiOutput
  1761. if (dir == Vst::kOutput && index == 0)
  1762. {
  1763. info.mediaType = Vst::kEvent;
  1764. info.direction = dir;
  1765. #ifdef JucePlugin_VSTNumMidiOutputs
  1766. info.channelCount = JucePlugin_VSTNumMidiOutputs;
  1767. #else
  1768. info.channelCount = 16;
  1769. #endif
  1770. toString128 (info.name, TRANS("MIDI Output"));
  1771. info.busType = Vst::kMain;
  1772. return kResultTrue;
  1773. }
  1774. #endif
  1775. }
  1776. zerostruct (info);
  1777. return kResultFalse;
  1778. }
  1779. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1780. {
  1781. if (type == Vst::kEvent)
  1782. {
  1783. if (index != 0)
  1784. return kResultFalse;
  1785. if (dir == Vst::kInput)
  1786. isMidiInputBusEnabled = (state != 0);
  1787. else
  1788. isMidiOutputBusEnabled = (state != 0);
  1789. return kResultTrue;
  1790. }
  1791. if (type == Vst::kAudio)
  1792. {
  1793. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1794. return kResultFalse;
  1795. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1796. {
  1797. #ifdef JucePlugin_PreferredChannelConfigurations
  1798. auto newLayout = pluginInstance->getBusesLayout();
  1799. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1800. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1801. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1802. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1803. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1804. return kResultFalse;
  1805. #endif
  1806. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1807. }
  1808. }
  1809. return kResultFalse;
  1810. }
  1811. bool checkBusFormatsAreNotDiscrete()
  1812. {
  1813. auto numInputBuses = pluginInstance->getBusCount (true);
  1814. auto numOutputBuses = pluginInstance->getBusCount (false);
  1815. for (int i = 0; i < numInputBuses; ++i)
  1816. {
  1817. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  1818. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1819. return false;
  1820. }
  1821. for (int i = 0; i < numOutputBuses; ++i)
  1822. {
  1823. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  1824. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1825. return false;
  1826. }
  1827. return true;
  1828. }
  1829. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1830. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1831. {
  1832. auto numInputBuses = pluginInstance->getBusCount (true);
  1833. auto numOutputBuses = pluginInstance->getBusCount (false);
  1834. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1835. return false;
  1836. auto requested = pluginInstance->getBusesLayout();
  1837. for (int i = 0; i < numIns; ++i)
  1838. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1839. for (int i = 0; i < numOuts; ++i)
  1840. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1841. #ifdef JucePlugin_PreferredChannelConfigurations
  1842. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1843. if (! AudioProcessor::containsLayout (requested, configs))
  1844. return kResultFalse;
  1845. #endif
  1846. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1847. }
  1848. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1849. {
  1850. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1851. {
  1852. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1853. return kResultTrue;
  1854. }
  1855. return kResultFalse;
  1856. }
  1857. //==============================================================================
  1858. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1859. {
  1860. return (symbolicSampleSize == Vst::kSample32
  1861. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1862. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1863. }
  1864. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1865. {
  1866. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1867. }
  1868. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1869. {
  1870. ScopedInSetupProcessingSetter inSetupProcessingSetter (juceVST3EditController);
  1871. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1872. return kResultFalse;
  1873. processSetup = newSetup;
  1874. processContext.sampleRate = processSetup.sampleRate;
  1875. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1876. ? AudioProcessor::doublePrecision
  1877. : AudioProcessor::singlePrecision);
  1878. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  1879. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1880. return kResultTrue;
  1881. }
  1882. tresult PLUGIN_API setProcessing (TBool state) override
  1883. {
  1884. if (! state)
  1885. getPluginInstance().reset();
  1886. return kResultTrue;
  1887. }
  1888. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1889. {
  1890. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1891. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  1892. return Vst::kNoTail;
  1893. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  1894. return Vst::kInfiniteTail;
  1895. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1896. }
  1897. //==============================================================================
  1898. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1899. {
  1900. jassert (pluginInstance != nullptr);
  1901. auto numParamsChanged = paramChanges.getParameterCount();
  1902. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1903. {
  1904. if (auto* paramQueue = paramChanges.getParameterData (i))
  1905. {
  1906. auto numPoints = paramQueue->getPointCount();
  1907. Steinberg::int32 offsetSamples = 0;
  1908. double value = 0.0;
  1909. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1910. {
  1911. auto vstParamID = paramQueue->getParameterId();
  1912. if (vstParamID == JuceAudioProcessor::paramPreset)
  1913. {
  1914. auto numPrograms = pluginInstance->getNumPrograms();
  1915. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1916. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1917. && programValue != pluginInstance->getCurrentProgram())
  1918. pluginInstance->setCurrentProgram (programValue);
  1919. }
  1920. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1921. else if (juceVST3EditController != nullptr && juceVST3EditController->isMidiControllerParamID (vstParamID))
  1922. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1923. #endif
  1924. else
  1925. {
  1926. auto floatValue = static_cast<float> (value);
  1927. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  1928. {
  1929. param->setValue (floatValue);
  1930. inParameterChangedCallback = true;
  1931. param->sendValueChangedMessageToListeners (floatValue);
  1932. }
  1933. }
  1934. }
  1935. }
  1936. }
  1937. }
  1938. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1939. {
  1940. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1941. int channel, ctrlNumber;
  1942. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1943. {
  1944. if (ctrlNumber == Vst::kAfterTouch)
  1945. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1946. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1947. else if (ctrlNumber == Vst::kPitchBend)
  1948. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1949. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1950. else
  1951. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1952. jlimit (0, 127, ctrlNumber),
  1953. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1954. }
  1955. }
  1956. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1957. {
  1958. if (pluginInstance == nullptr)
  1959. return kResultFalse;
  1960. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1961. return kResultFalse;
  1962. if (data.processContext != nullptr)
  1963. {
  1964. processContext = *data.processContext;
  1965. if (juceVST3EditController != nullptr)
  1966. juceVST3EditController->vst3IsPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1967. }
  1968. else
  1969. {
  1970. zerostruct (processContext);
  1971. if (juceVST3EditController != nullptr)
  1972. juceVST3EditController->vst3IsPlaying = false;
  1973. }
  1974. midiBuffer.clear();
  1975. if (data.inputParameterChanges != nullptr)
  1976. processParameterChanges (*data.inputParameterChanges);
  1977. #if JucePlugin_WantsMidiInput
  1978. if (data.inputEvents != nullptr)
  1979. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1980. #endif
  1981. if (getHostType().isWavelab())
  1982. {
  1983. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1984. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1985. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1986. && (numInputChans + numOutputChans) == 0)
  1987. return kResultFalse;
  1988. }
  1989. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1990. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1991. else jassertfalse;
  1992. #if JucePlugin_ProducesMidiOutput
  1993. if (data.outputEvents != nullptr)
  1994. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1995. #endif
  1996. return kResultTrue;
  1997. }
  1998. private:
  1999. //==============================================================================
  2000. struct ScopedInSetupProcessingSetter
  2001. {
  2002. ScopedInSetupProcessingSetter (JuceVST3EditController* c)
  2003. : controller (c)
  2004. {
  2005. if (controller != nullptr)
  2006. controller->inSetupProcessing = true;
  2007. }
  2008. ~ScopedInSetupProcessingSetter()
  2009. {
  2010. if (controller != nullptr)
  2011. controller->inSetupProcessing = false;
  2012. }
  2013. private:
  2014. JuceVST3EditController* controller = nullptr;
  2015. };
  2016. //==============================================================================
  2017. template <typename FloatType>
  2018. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  2019. {
  2020. int totalInputChans = 0, totalOutputChans = 0;
  2021. bool tmpBufferNeedsClearing = false;
  2022. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  2023. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  2024. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  2025. int vstInputs;
  2026. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  2027. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  2028. && data.inputs[vstInputs].numChannels > 0)
  2029. break;
  2030. int vstOutputs;
  2031. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  2032. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  2033. && data.outputs[vstOutputs].numChannels > 0)
  2034. break;
  2035. {
  2036. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  2037. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  2038. {
  2039. if (auto* busObject = pluginInstance->getBus (false, bus))
  2040. if (! busObject->isEnabled())
  2041. continue;
  2042. if (bus < vstOutputs)
  2043. {
  2044. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  2045. {
  2046. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  2047. for (int i = 0; i < numChans; ++i)
  2048. {
  2049. if (auto dst = busChannels[i])
  2050. {
  2051. if (totalOutputChans >= plugInInputChannels)
  2052. FloatVectorOperations::clear (dst, (int) data.numSamples);
  2053. channelList.set (totalOutputChans++, busChannels[i]);
  2054. }
  2055. }
  2056. }
  2057. }
  2058. else
  2059. {
  2060. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  2061. for (int i = 0; i < numChans; ++i)
  2062. {
  2063. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  2064. {
  2065. tmpBufferNeedsClearing = true;
  2066. channelList.set (totalOutputChans++, tmpBuffer);
  2067. }
  2068. else
  2069. return;
  2070. }
  2071. }
  2072. }
  2073. }
  2074. {
  2075. auto n = jmax (vstInputs, getNumAudioBuses (true));
  2076. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  2077. {
  2078. if (auto* busObject = pluginInstance->getBus (true, bus))
  2079. if (! busObject->isEnabled())
  2080. continue;
  2081. if (bus < vstInputs)
  2082. {
  2083. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  2084. {
  2085. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  2086. for (int i = 0; i < numChans; ++i)
  2087. {
  2088. if (busChannels[i] != nullptr)
  2089. {
  2090. if (totalInputChans >= totalOutputChans)
  2091. channelList.set (totalInputChans, busChannels[i]);
  2092. else
  2093. {
  2094. auto* dst = channelList.getReference (totalInputChans);
  2095. auto* src = busChannels[i];
  2096. if (dst != src)
  2097. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  2098. }
  2099. }
  2100. ++totalInputChans;
  2101. }
  2102. }
  2103. }
  2104. else
  2105. {
  2106. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  2107. for (int i = 0; i < numChans; ++i)
  2108. {
  2109. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  2110. {
  2111. tmpBufferNeedsClearing = true;
  2112. channelList.set (totalInputChans++, tmpBuffer);
  2113. }
  2114. else
  2115. return;
  2116. }
  2117. }
  2118. }
  2119. }
  2120. if (tmpBufferNeedsClearing)
  2121. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  2122. AudioBuffer<FloatType> buffer;
  2123. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  2124. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  2125. {
  2126. const ScopedLock sl (pluginInstance->getCallbackLock());
  2127. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  2128. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  2129. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  2130. #endif
  2131. if (pluginInstance->isSuspended())
  2132. {
  2133. buffer.clear();
  2134. }
  2135. else
  2136. {
  2137. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  2138. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  2139. {
  2140. if (isBypassed())
  2141. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  2142. else
  2143. pluginInstance->processBlock (buffer, midiBuffer);
  2144. }
  2145. }
  2146. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  2147. /* This assertion is caused when you've added some events to the
  2148. midiMessages array in your processBlock() method, which usually means
  2149. that you're trying to send them somewhere. But in this case they're
  2150. getting thrown away.
  2151. If your plugin does want to send MIDI messages, you'll need to set
  2152. the JucePlugin_ProducesMidiOutput macro to 1 in your
  2153. JucePluginCharacteristics.h file.
  2154. If you don't want to produce any MIDI output, then you should clear the
  2155. midiMessages array at the end of your processBlock() method, to
  2156. indicate that you don't want any of the events to be passed through
  2157. to the output.
  2158. */
  2159. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  2160. #endif
  2161. }
  2162. }
  2163. //==============================================================================
  2164. template <typename FloatType>
  2165. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2166. {
  2167. channelList.clearQuick();
  2168. channelList.insertMultiple (0, nullptr, 128);
  2169. auto& p = getPluginInstance();
  2170. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  2171. buffer.clear();
  2172. }
  2173. template <typename FloatType>
  2174. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2175. {
  2176. channelList.clearQuick();
  2177. channelList.resize (0);
  2178. buffer.setSize (0, 0);
  2179. }
  2180. template <typename FloatType>
  2181. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  2182. {
  2183. return AudioBusPointerHelper<FloatType>::impl (data);
  2184. }
  2185. template <typename FloatType>
  2186. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  2187. {
  2188. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  2189. // we can't do anything if the host requests to render many more samples than the
  2190. // block size, we need to bail out
  2191. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  2192. return nullptr;
  2193. return buffer.getWritePointer (channel);
  2194. }
  2195. void preparePlugin (double sampleRate, int bufferSize)
  2196. {
  2197. auto& p = getPluginInstance();
  2198. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2199. p.prepareToPlay (sampleRate, bufferSize);
  2200. midiBuffer.ensureSize (2048);
  2201. midiBuffer.clear();
  2202. }
  2203. //==============================================================================
  2204. ScopedJuceInitialiser_GUI libraryInitialiser;
  2205. std::atomic<int> refCount { 1 };
  2206. AudioProcessor* pluginInstance;
  2207. ComSmartPtr<Vst::IHostApplication> host;
  2208. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2209. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2210. /**
  2211. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  2212. this object needs to be copied on every call to process() to be up-to-date...
  2213. */
  2214. Vst::ProcessContext processContext;
  2215. Vst::ProcessSetup processSetup;
  2216. MidiBuffer midiBuffer;
  2217. Array<float*> channelListFloat;
  2218. Array<double*> channelListDouble;
  2219. AudioBuffer<float> emptyBufferFloat;
  2220. AudioBuffer<double> emptyBufferDouble;
  2221. #if JucePlugin_WantsMidiInput
  2222. bool isMidiInputBusEnabled = true;
  2223. #else
  2224. bool isMidiInputBusEnabled = false;
  2225. #endif
  2226. #if JucePlugin_ProducesMidiOutput
  2227. bool isMidiOutputBusEnabled = true;
  2228. #else
  2229. bool isMidiOutputBusEnabled = false;
  2230. #endif
  2231. static const char* kJucePrivateDataIdentifier;
  2232. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2233. };
  2234. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2235. //==============================================================================
  2236. #if JUCE_MSVC
  2237. #pragma warning (push, 0)
  2238. #pragma warning (disable: 4310)
  2239. #elif JUCE_CLANG
  2240. #pragma clang diagnostic push
  2241. #pragma clang diagnostic ignored "-Wall"
  2242. #endif
  2243. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2244. DEF_CLASS_IID (JuceAudioProcessor)
  2245. #if JUCE_VST3_CAN_REPLACE_VST2
  2246. FUID getFUIDForVST2ID (bool forControllerUID)
  2247. {
  2248. TUID uuid;
  2249. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  2250. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2251. return FUID (uuid);
  2252. }
  2253. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2254. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2255. #else
  2256. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2257. DEF_CLASS_IID (JuceVST3EditController)
  2258. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2259. DEF_CLASS_IID (JuceVST3Component)
  2260. #endif
  2261. #if JUCE_MSVC
  2262. #pragma warning (pop)
  2263. #elif JUCE_CLANG
  2264. #pragma clang diagnostic pop
  2265. #endif
  2266. //==============================================================================
  2267. bool initModule()
  2268. {
  2269. #if JUCE_MAC
  2270. initialiseMacVST();
  2271. #endif
  2272. return true;
  2273. }
  2274. bool shutdownModule()
  2275. {
  2276. return true;
  2277. }
  2278. #undef JUCE_EXPORTED_FUNCTION
  2279. #if JUCE_WINDOWS
  2280. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2281. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2282. #define JUCE_EXPORTED_FUNCTION
  2283. #else
  2284. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  2285. CFBundleRef globalBundleInstance = nullptr;
  2286. juce::uint32 numBundleRefs = 0;
  2287. juce::Array<CFBundleRef> bundleRefs;
  2288. enum { MaxPathLength = 2048 };
  2289. char modulePath[MaxPathLength] = { 0 };
  2290. void* moduleHandle = nullptr;
  2291. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  2292. {
  2293. if (ref != nullptr)
  2294. {
  2295. ++numBundleRefs;
  2296. CFRetain (ref);
  2297. bundleRefs.add (ref);
  2298. if (moduleHandle == nullptr)
  2299. {
  2300. globalBundleInstance = ref;
  2301. moduleHandle = ref;
  2302. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  2303. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  2304. CFRelease (tempURL);
  2305. }
  2306. }
  2307. return initModule();
  2308. }
  2309. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2310. {
  2311. if (shutdownModule())
  2312. {
  2313. if (--numBundleRefs == 0)
  2314. {
  2315. for (int i = 0; i < bundleRefs.size(); ++i)
  2316. CFRelease (bundleRefs.getUnchecked (i));
  2317. bundleRefs.clear();
  2318. }
  2319. return true;
  2320. }
  2321. return false;
  2322. }
  2323. #endif
  2324. //==============================================================================
  2325. /** This typedef represents VST3's createInstance() function signature */
  2326. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2327. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2328. {
  2329. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2330. }
  2331. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2332. {
  2333. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2334. }
  2335. //==============================================================================
  2336. struct JucePluginFactory;
  2337. static JucePluginFactory* globalFactory = nullptr;
  2338. //==============================================================================
  2339. struct JucePluginFactory : public IPluginFactory3
  2340. {
  2341. JucePluginFactory()
  2342. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2343. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2344. {
  2345. }
  2346. virtual ~JucePluginFactory()
  2347. {
  2348. if (globalFactory == this)
  2349. globalFactory = nullptr;
  2350. }
  2351. //==============================================================================
  2352. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2353. {
  2354. if (createFunction == nullptr)
  2355. {
  2356. jassertfalse;
  2357. return false;
  2358. }
  2359. auto entry = std::make_unique<ClassEntry> (info, createFunction);
  2360. entry->infoW.fromAscii (info);
  2361. classes.push_back (std::move (entry));
  2362. return true;
  2363. }
  2364. //==============================================================================
  2365. JUCE_DECLARE_VST3_COM_REF_METHODS
  2366. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2367. {
  2368. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2369. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2370. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2371. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2372. jassertfalse; // Something new?
  2373. *obj = nullptr;
  2374. return kNotImplemented;
  2375. }
  2376. //==============================================================================
  2377. Steinberg::int32 PLUGIN_API countClasses() override
  2378. {
  2379. return (Steinberg::int32) classes.size();
  2380. }
  2381. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2382. {
  2383. if (info == nullptr)
  2384. return kInvalidArgument;
  2385. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2386. return kResultOk;
  2387. }
  2388. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2389. {
  2390. return getPClassInfo<PClassInfo> (index, info);
  2391. }
  2392. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2393. {
  2394. return getPClassInfo<PClassInfo2> (index, info);
  2395. }
  2396. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2397. {
  2398. if (info != nullptr)
  2399. {
  2400. if (auto& entry = classes[(size_t) index])
  2401. {
  2402. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2403. return kResultOk;
  2404. }
  2405. }
  2406. return kInvalidArgument;
  2407. }
  2408. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2409. {
  2410. ScopedJuceInitialiser_GUI libraryInitialiser;
  2411. *obj = nullptr;
  2412. TUID tuid;
  2413. memcpy (tuid, sourceIid, sizeof (TUID));
  2414. #if VST_VERSION >= 0x030608
  2415. auto sourceFuid = FUID::fromTUID (tuid);
  2416. #else
  2417. FUID sourceFuid;
  2418. sourceFuid = tuid;
  2419. #endif
  2420. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2421. {
  2422. jassertfalse; // The host you're running in has severe implementation issues!
  2423. return kInvalidArgument;
  2424. }
  2425. TUID iidToQuery;
  2426. sourceFuid.toTUID (iidToQuery);
  2427. for (auto& entry : classes)
  2428. {
  2429. if (doUIDsMatch (entry->infoW.cid, cid))
  2430. {
  2431. if (auto* instance = entry->createFunction (host))
  2432. {
  2433. const FReleaser releaser (instance);
  2434. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2435. return kResultOk;
  2436. }
  2437. break;
  2438. }
  2439. }
  2440. return kNoInterface;
  2441. }
  2442. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2443. {
  2444. host.loadFrom (context);
  2445. if (host != nullptr)
  2446. {
  2447. Vst::String128 name;
  2448. host->getName (name);
  2449. return kResultTrue;
  2450. }
  2451. return kNotImplemented;
  2452. }
  2453. private:
  2454. //==============================================================================
  2455. std::atomic<int> refCount { 1 };
  2456. const PFactoryInfo factoryInfo;
  2457. ComSmartPtr<Vst::IHostApplication> host;
  2458. //==============================================================================
  2459. struct ClassEntry
  2460. {
  2461. ClassEntry() noexcept {}
  2462. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2463. : info2 (info), createFunction (fn) {}
  2464. PClassInfo2 info2;
  2465. PClassInfoW infoW;
  2466. CreateFunction createFunction = {};
  2467. bool isUnicode = false;
  2468. private:
  2469. JUCE_DECLARE_NON_COPYABLE (ClassEntry)
  2470. };
  2471. std::vector<std::unique_ptr<ClassEntry>> classes;
  2472. //==============================================================================
  2473. template<class PClassInfoType>
  2474. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2475. {
  2476. if (info != nullptr)
  2477. {
  2478. zerostruct (*info);
  2479. if (auto& entry = classes[(size_t) index])
  2480. {
  2481. if (entry->isUnicode)
  2482. return kResultFalse;
  2483. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2484. return kResultOk;
  2485. }
  2486. }
  2487. jassertfalse;
  2488. return kInvalidArgument;
  2489. }
  2490. //==============================================================================
  2491. // no leak detector here to prevent it firing on shutdown when running in hosts that
  2492. // don't release the factory object correctly...
  2493. JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
  2494. };
  2495. } // juce namespace
  2496. //==============================================================================
  2497. #ifndef JucePlugin_Vst3ComponentFlags
  2498. #if JucePlugin_IsSynth
  2499. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2500. #else
  2501. #define JucePlugin_Vst3ComponentFlags 0
  2502. #endif
  2503. #endif
  2504. #ifndef JucePlugin_Vst3Category
  2505. #if JucePlugin_IsSynth
  2506. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2507. #else
  2508. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2509. #endif
  2510. #endif
  2511. using namespace juce;
  2512. //==============================================================================
  2513. // The VST3 plugin entry point.
  2514. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2515. {
  2516. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2517. #if JUCE_MSVC
  2518. // Cunning trick to force this function to be exported. Life's too short to
  2519. // faff around creating .def files for this kind of thing.
  2520. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2521. #endif
  2522. if (globalFactory == nullptr)
  2523. {
  2524. globalFactory = new JucePluginFactory();
  2525. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2526. PClassInfo::kManyInstances,
  2527. kVstAudioEffectClass,
  2528. JucePlugin_Name,
  2529. JucePlugin_Vst3ComponentFlags,
  2530. JucePlugin_Vst3Category,
  2531. JucePlugin_Manufacturer,
  2532. JucePlugin_VersionString,
  2533. kVstVersionString);
  2534. globalFactory->registerClass (componentClass, createComponentInstance);
  2535. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2536. PClassInfo::kManyInstances,
  2537. kVstComponentControllerClass,
  2538. JucePlugin_Name,
  2539. JucePlugin_Vst3ComponentFlags,
  2540. JucePlugin_Vst3Category,
  2541. JucePlugin_Manufacturer,
  2542. JucePlugin_VersionString,
  2543. kVstVersionString);
  2544. globalFactory->registerClass (controllerClass, createControllerInstance);
  2545. }
  2546. else
  2547. {
  2548. globalFactory->addRef();
  2549. }
  2550. return dynamic_cast<IPluginFactory*> (globalFactory);
  2551. }
  2552. //==============================================================================
  2553. #if _MSC_VER || JUCE_MINGW
  2554. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2555. #endif
  2556. #endif //JucePlugin_Build_VST3