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.

3261 lines
121KB

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