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.

3225 lines
119KB

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