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.

3214 lines
119KB

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