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.

3216 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. #if ! JUCE_MAC
  759. float lastScaleFactorReceived = 1.0f;
  760. #endif
  761. void setupParameters()
  762. {
  763. if (auto* pluginInstance = getPluginInstance())
  764. {
  765. pluginInstance->addListener (this);
  766. // as the bypass is not part of the regular parameters
  767. // we need to listen for it explicitly
  768. if (! audioProcessor->bypassIsRegularParameter)
  769. audioProcessor->getBypassParameter()->addListener (this);
  770. if (parameters.getParameterCount() <= 0)
  771. {
  772. auto n = audioProcessor->getNumParameters();
  773. for (int i = 0; i < n; ++i)
  774. {
  775. auto vstParamID = audioProcessor->getVSTParamIDForIndex (i);
  776. auto* juceParam = audioProcessor->getParamForVSTParamID (vstParamID);
  777. auto* parameterGroup = pluginInstance->getParameterTree().getGroupsForParameter (juceParam).getLast();
  778. auto unitID = JuceAudioProcessor::getUnitID (parameterGroup);
  779. parameters.addParameter (new Param (*this, *juceParam, vstParamID, unitID,
  780. (vstParamID == audioProcessor->bypassParamID)));
  781. }
  782. if (pluginInstance->getNumPrograms() > 1)
  783. parameters.addParameter (new ProgramChangeParameter (*pluginInstance));
  784. }
  785. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  786. parameterToMidiControllerOffset = static_cast<Vst::ParamID> (audioProcessor->isUsingManagedParameters() ? JuceAudioProcessor::paramMidiControllerOffset
  787. : parameters.getParameterCount());
  788. initialiseMidiControllerMappings();
  789. #endif
  790. audioProcessorChanged (pluginInstance);
  791. }
  792. }
  793. void initialiseMidiControllerMappings()
  794. {
  795. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  796. {
  797. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  798. {
  799. midiControllerToParameter[c][i] = static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset;
  800. parameterToMidiController[p].channel = c;
  801. parameterToMidiController[p].ctrlNumber = i;
  802. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  803. static_cast<Vst::ParamID> (p) + parameterToMidiControllerOffset, nullptr, 0, 0,
  804. 0, Vst::kRootUnitId));
  805. }
  806. }
  807. }
  808. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  809. {
  810. jassert (hostContext != nullptr);
  811. if (auto* message = allocateMessage())
  812. {
  813. const FReleaser releaser (message);
  814. message->setMessageID (idTag);
  815. message->getAttributes()->setInt (idTag, value);
  816. sendMessage (message);
  817. }
  818. }
  819. //==============================================================================
  820. class JuceVST3Editor : public Vst::EditorView,
  821. public Steinberg::IPlugViewContentScaleSupport,
  822. private Timer
  823. {
  824. public:
  825. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  826. : Vst::EditorView (&ec, nullptr),
  827. owner (&ec), pluginInstance (p)
  828. {
  829. component.reset (new ContentWrapperComponent (*this, p));
  830. #if JUCE_MAC
  831. if (getHostType().type == PluginHostType::SteinbergCubase10)
  832. cubase10Workaround.reset (new Cubase10WindowResizeWorkaround (*this));
  833. #else
  834. if (! approximatelyEqual (editorScaleFactor, ec.lastScaleFactorReceived))
  835. setContentScaleFactor (ec.lastScaleFactorReceived);
  836. #endif
  837. }
  838. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  839. {
  840. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Steinberg::IPlugViewContentScaleSupport)
  841. return Vst::EditorView::queryInterface (targetIID, obj);
  842. }
  843. REFCOUNT_METHODS (Vst::EditorView)
  844. //==============================================================================
  845. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  846. {
  847. if (type != nullptr && pluginInstance.hasEditor())
  848. {
  849. #if JUCE_WINDOWS
  850. if (strcmp (type, kPlatformTypeHWND) == 0)
  851. #else
  852. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  853. #endif
  854. return kResultTrue;
  855. }
  856. return kResultFalse;
  857. }
  858. tresult PLUGIN_API attached (void* parent, FIDString type) override
  859. {
  860. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  861. return kResultFalse;
  862. if (component == nullptr)
  863. component.reset (new ContentWrapperComponent (*this, pluginInstance));
  864. #if JUCE_WINDOWS
  865. component->addToDesktop (0, parent);
  866. component->setOpaque (true);
  867. component->setVisible (true);
  868. #else
  869. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  870. macHostWindow = juce::attachComponentToWindowRefVST (component.get(), parent, isNSView);
  871. #endif
  872. component->resizeHostWindow();
  873. systemWindow = parent;
  874. attachedToParent();
  875. // Life's too short to faff around with wave lab
  876. if (getHostType().isWavelab())
  877. startTimer (200);
  878. return kResultTrue;
  879. }
  880. tresult PLUGIN_API removed() override
  881. {
  882. if (component != nullptr)
  883. {
  884. #if JUCE_WINDOWS
  885. component->removeFromDesktop();
  886. #else
  887. if (macHostWindow != nullptr)
  888. {
  889. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  890. macHostWindow = nullptr;
  891. }
  892. #endif
  893. component = nullptr;
  894. }
  895. return CPluginView::removed();
  896. }
  897. tresult PLUGIN_API onSize (ViewRect* newSize) override
  898. {
  899. if (newSize != nullptr)
  900. {
  901. rect = convertFromHostBounds (*newSize);
  902. if (component != nullptr)
  903. {
  904. auto w = rect.getWidth();
  905. auto h = rect.getHeight();
  906. component->setSize (w, h);
  907. #if JUCE_MAC
  908. if (cubase10Workaround != nullptr)
  909. {
  910. cubase10Workaround->triggerAsyncUpdate();
  911. }
  912. else
  913. #endif
  914. {
  915. if (auto* peer = component->getPeer())
  916. peer->updateBounds();
  917. }
  918. }
  919. return kResultTrue;
  920. }
  921. jassertfalse;
  922. return kResultFalse;
  923. }
  924. tresult PLUGIN_API getSize (ViewRect* size) override
  925. {
  926. if (size != nullptr && component != nullptr)
  927. {
  928. auto editorBounds = component->getSizeToContainChild();
  929. *size = convertToHostBounds ({ 0, 0, editorBounds.getWidth(), editorBounds.getHeight() });
  930. return kResultTrue;
  931. }
  932. return kResultFalse;
  933. }
  934. tresult PLUGIN_API canResize() override
  935. {
  936. if (component != nullptr)
  937. if (auto* editor = component->pluginEditor.get())
  938. if (editor->isResizable())
  939. return kResultTrue;
  940. return kResultFalse;
  941. }
  942. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  943. {
  944. if (rectToCheck != nullptr && component != nullptr)
  945. {
  946. if (auto* editor = component->pluginEditor.get())
  947. {
  948. if (auto* constrainer = editor->getConstrainer())
  949. {
  950. *rectToCheck = convertFromHostBounds (*rectToCheck);
  951. auto scale = editor->getTransform().getScaleFactor();
  952. auto minW = (double) (constrainer->getMinimumWidth() * scale);
  953. auto maxW = (double) (constrainer->getMaximumWidth() * scale);
  954. auto minH = (double) (constrainer->getMinimumHeight() * scale);
  955. auto maxH = (double) (constrainer->getMaximumHeight() * scale);
  956. auto width = (double) (rectToCheck->right - rectToCheck->left);
  957. auto height = (double) (rectToCheck->bottom - rectToCheck->top);
  958. width = jlimit (minW, maxW, width);
  959. height = jlimit (minH, maxH, height);
  960. auto aspectRatio = constrainer->getFixedAspectRatio();
  961. if (aspectRatio != 0.0)
  962. {
  963. bool adjustWidth = (width / height > aspectRatio);
  964. if (getHostType().type == PluginHostType::SteinbergCubase9)
  965. {
  966. if (editor->getWidth() == width && editor->getHeight() != height)
  967. adjustWidth = true;
  968. else if (editor->getHeight() == height && editor->getWidth() != width)
  969. adjustWidth = false;
  970. }
  971. if (adjustWidth)
  972. {
  973. width = height * aspectRatio;
  974. if (width > maxW || width < minW)
  975. {
  976. width = jlimit (minW, maxW, width);
  977. height = width / aspectRatio;
  978. }
  979. }
  980. else
  981. {
  982. height = width / aspectRatio;
  983. if (height > maxH || height < minH)
  984. {
  985. height = jlimit (minH, maxH, height);
  986. width = height * aspectRatio;
  987. }
  988. }
  989. }
  990. rectToCheck->right = rectToCheck->left + roundToInt (width);
  991. rectToCheck->bottom = rectToCheck->top + roundToInt (height);
  992. *rectToCheck = convertToHostBounds (*rectToCheck);
  993. }
  994. }
  995. return kResultTrue;
  996. }
  997. jassertfalse;
  998. return kResultFalse;
  999. }
  1000. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  1001. {
  1002. #if ! JUCE_MAC
  1003. if (! approximatelyEqual ((float) factor, editorScaleFactor))
  1004. {
  1005. editorScaleFactor = (float) factor;
  1006. if (owner != nullptr)
  1007. owner->lastScaleFactorReceived = editorScaleFactor;
  1008. if (component != nullptr)
  1009. {
  1010. if (auto* editor = component->pluginEditor.get())
  1011. {
  1012. editor->setScaleFactor (editorScaleFactor);
  1013. component->resizeHostWindow();
  1014. component->setTopLeftPosition (0, 0);
  1015. component->repaint();
  1016. }
  1017. }
  1018. }
  1019. return kResultTrue;
  1020. #else
  1021. ignoreUnused (factor);
  1022. return kResultFalse;
  1023. #endif
  1024. }
  1025. private:
  1026. void timerCallback() override
  1027. {
  1028. stopTimer();
  1029. ViewRect viewRect;
  1030. getSize (&viewRect);
  1031. onSize (&viewRect);
  1032. }
  1033. static ViewRect convertToHostBounds (ViewRect pluginRect)
  1034. {
  1035. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1036. if (approximatelyEqual (desktopScale, 1.0f))
  1037. return pluginRect;
  1038. return { roundToInt (pluginRect.left * desktopScale),
  1039. roundToInt (pluginRect.top * desktopScale),
  1040. roundToInt (pluginRect.right * desktopScale),
  1041. roundToInt (pluginRect.bottom * desktopScale) };
  1042. }
  1043. static ViewRect convertFromHostBounds (ViewRect hostRect)
  1044. {
  1045. auto desktopScale = Desktop::getInstance().getGlobalScaleFactor();
  1046. if (approximatelyEqual (desktopScale, 1.0f))
  1047. return hostRect;
  1048. return { roundToInt (hostRect.left / desktopScale),
  1049. roundToInt (hostRect.top / desktopScale),
  1050. roundToInt (hostRect.right / desktopScale),
  1051. roundToInt (hostRect.bottom / desktopScale) };
  1052. }
  1053. //==============================================================================
  1054. struct ContentWrapperComponent : public Component
  1055. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1056. , private Timer
  1057. #endif
  1058. {
  1059. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  1060. : pluginEditor (plugin.createEditorIfNeeded()),
  1061. owner (editor)
  1062. {
  1063. setOpaque (true);
  1064. setBroughtToFrontOnMouseClick (true);
  1065. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  1066. jassert (pluginEditor != nullptr);
  1067. if (pluginEditor != nullptr)
  1068. {
  1069. addAndMakeVisible (pluginEditor.get());
  1070. pluginEditor->setTopLeftPosition (0, 0);
  1071. lastBounds = getSizeToContainChild();
  1072. {
  1073. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1074. setBounds (lastBounds);
  1075. }
  1076. resizeHostWindow();
  1077. }
  1078. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1079. startTimer (500);
  1080. #endif
  1081. ignoreUnused (fakeMouseGenerator);
  1082. }
  1083. ~ContentWrapperComponent() override
  1084. {
  1085. if (pluginEditor != nullptr)
  1086. {
  1087. PopupMenu::dismissAllActiveMenus();
  1088. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  1089. }
  1090. }
  1091. void paint (Graphics& g) override
  1092. {
  1093. g.fillAll (Colours::black);
  1094. }
  1095. juce::Rectangle<int> getSizeToContainChild()
  1096. {
  1097. if (pluginEditor != nullptr)
  1098. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  1099. return {};
  1100. }
  1101. void childBoundsChanged (Component*) override
  1102. {
  1103. if (resizingChild)
  1104. return;
  1105. auto b = getSizeToContainChild();
  1106. if (lastBounds != b)
  1107. {
  1108. lastBounds = b;
  1109. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1110. resizeHostWindow();
  1111. }
  1112. }
  1113. void resized() override
  1114. {
  1115. if (pluginEditor != nullptr)
  1116. {
  1117. if (! resizingParent)
  1118. {
  1119. auto newBounds = getLocalBounds();
  1120. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1121. if (! lastBounds.isEmpty() && isWithin (newBounds.toDouble().getAspectRatio(), lastBounds.toDouble().getAspectRatio(), 0.1))
  1122. return;
  1123. #endif
  1124. lastBounds = newBounds;
  1125. const ScopedValueSetter<bool> resizingChildSetter (resizingChild, true);
  1126. if (auto* constrainer = pluginEditor->getConstrainer())
  1127. {
  1128. auto aspectRatio = constrainer->getFixedAspectRatio();
  1129. if (aspectRatio != 0)
  1130. {
  1131. auto width = (double) lastBounds.getWidth();
  1132. auto height = (double) lastBounds.getHeight();
  1133. if (width / height > aspectRatio)
  1134. setBounds ({ 0, 0, roundToInt (height * aspectRatio), lastBounds.getHeight() });
  1135. else
  1136. setBounds ({ 0, 0, lastBounds.getWidth(), roundToInt (width / aspectRatio) });
  1137. }
  1138. }
  1139. pluginEditor->setTopLeftPosition (0, 0);
  1140. pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
  1141. }
  1142. }
  1143. }
  1144. void resizeHostWindow()
  1145. {
  1146. if (pluginEditor != nullptr)
  1147. {
  1148. auto b = getSizeToContainChild();
  1149. auto w = b.getWidth();
  1150. auto h = b.getHeight();
  1151. auto host = getHostType();
  1152. #if JUCE_WINDOWS
  1153. setSize (w, h);
  1154. #endif
  1155. if (owner.plugFrame != nullptr)
  1156. {
  1157. auto newSize = convertToHostBounds ({ 0, 0, b.getWidth(), b.getHeight() });
  1158. {
  1159. const ScopedValueSetter<bool> resizingParentSetter (resizingParent, true);
  1160. owner.plugFrame->resizeView (&owner, &newSize);
  1161. }
  1162. #if JUCE_MAC
  1163. if (host.isWavelab() || host.isReaper())
  1164. #else
  1165. if (host.isWavelab() || host.isAbletonLive())
  1166. #endif
  1167. setBounds (0, 0, w, h);
  1168. }
  1169. }
  1170. }
  1171. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  1172. private:
  1173. #if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
  1174. void timerCallback() override
  1175. {
  1176. auto hostWindowScale = (float) getScaleFactorForWindow ((HWND) owner.systemWindow);
  1177. if (hostWindowScale > 0.0 && ! approximatelyEqual (hostWindowScale, owner.editorScaleFactor))
  1178. owner.setContentScaleFactor (hostWindowScale);
  1179. }
  1180. #endif
  1181. JuceVST3Editor& owner;
  1182. FakeMouseMoveGenerator fakeMouseGenerator;
  1183. Rectangle<int> lastBounds;
  1184. bool resizingChild = false, resizingParent = false;
  1185. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  1186. };
  1187. //==============================================================================
  1188. ComSmartPtr<JuceVST3EditController> owner;
  1189. AudioProcessor& pluginInstance;
  1190. std::unique_ptr<ContentWrapperComponent> component;
  1191. friend struct ContentWrapperComponent;
  1192. #if JUCE_MAC
  1193. void* macHostWindow = nullptr;
  1194. bool isNSView = false;
  1195. // On macOS Cubase 10 resizes the host window after calling onSize() resulting in the peer
  1196. // bounds being a step behind the plug-in. Calling updateBounds() asynchronously seems to fix things...
  1197. struct Cubase10WindowResizeWorkaround : public AsyncUpdater
  1198. {
  1199. Cubase10WindowResizeWorkaround (JuceVST3Editor& o) : owner (o) {}
  1200. void handleAsyncUpdate() override
  1201. {
  1202. if (owner.component != nullptr)
  1203. if (auto* peer = owner.component->getPeer())
  1204. peer->updateBounds();
  1205. }
  1206. JuceVST3Editor& owner;
  1207. };
  1208. std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
  1209. #else
  1210. float editorScaleFactor = 1.0f;
  1211. #if JUCE_WINDOWS
  1212. WindowsHooks hooks;
  1213. #endif
  1214. #endif
  1215. //==============================================================================
  1216. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  1217. };
  1218. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  1219. };
  1220. namespace
  1221. {
  1222. template <typename FloatType> struct AudioBusPointerHelper {};
  1223. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  1224. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  1225. template <typename FloatType> struct ChooseBufferHelper {};
  1226. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  1227. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  1228. }
  1229. //==============================================================================
  1230. class JuceVST3Component : public Vst::IComponent,
  1231. public Vst::IAudioProcessor,
  1232. public Vst::IUnitInfo,
  1233. public Vst::IConnectionPoint,
  1234. public AudioPlayHead
  1235. {
  1236. public:
  1237. JuceVST3Component (Vst::IHostApplication* h)
  1238. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  1239. host (h)
  1240. {
  1241. inParameterChangedCallback = false;
  1242. #ifdef JucePlugin_PreferredChannelConfigurations
  1243. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1244. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1245. ignoreUnused (numConfigs);
  1246. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1247. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1248. #endif
  1249. // VST-3 requires your default layout to be non-discrete!
  1250. // For example, your default layout must be mono, stereo, quadrophonic
  1251. // and not AudioChannelSet::discreteChannels (2) etc.
  1252. jassert (checkBusFormatsAreNotDiscrete());
  1253. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  1254. zerostruct (processContext);
  1255. processSetup.maxSamplesPerBlock = 1024;
  1256. processSetup.processMode = Vst::kRealtime;
  1257. processSetup.sampleRate = 44100.0;
  1258. processSetup.symbolicSampleSize = Vst::kSample32;
  1259. pluginInstance->setPlayHead (this);
  1260. }
  1261. ~JuceVST3Component() override
  1262. {
  1263. if (juceVST3EditController != nullptr)
  1264. juceVST3EditController->vst3IsPlaying = false;
  1265. if (pluginInstance != nullptr)
  1266. if (pluginInstance->getPlayHead() == this)
  1267. pluginInstance->setPlayHead (nullptr);
  1268. }
  1269. //==============================================================================
  1270. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1271. //==============================================================================
  1272. static const FUID iid;
  1273. JUCE_DECLARE_VST3_COM_REF_METHODS
  1274. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1275. {
  1276. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  1277. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  1278. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  1279. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  1280. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  1281. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  1282. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  1283. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  1284. {
  1285. comPluginInstance->addRef();
  1286. *obj = comPluginInstance;
  1287. return kResultOk;
  1288. }
  1289. *obj = nullptr;
  1290. return kNoInterface;
  1291. }
  1292. //==============================================================================
  1293. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1294. {
  1295. if (host != hostContext)
  1296. host.loadFrom (hostContext);
  1297. processContext.sampleRate = processSetup.sampleRate;
  1298. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  1299. return kResultTrue;
  1300. }
  1301. tresult PLUGIN_API terminate() override
  1302. {
  1303. getPluginInstance().releaseResources();
  1304. return kResultTrue;
  1305. }
  1306. //==============================================================================
  1307. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1308. {
  1309. if (other != nullptr && juceVST3EditController == nullptr)
  1310. juceVST3EditController.loadFrom (other);
  1311. return kResultTrue;
  1312. }
  1313. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1314. {
  1315. if (juceVST3EditController != nullptr)
  1316. juceVST3EditController->vst3IsPlaying = false;
  1317. juceVST3EditController = nullptr;
  1318. return kResultTrue;
  1319. }
  1320. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1321. {
  1322. if (message != nullptr && juceVST3EditController == nullptr)
  1323. {
  1324. Steinberg::int64 value = 0;
  1325. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1326. {
  1327. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  1328. if (juceVST3EditController != nullptr)
  1329. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1330. else
  1331. jassertfalse;
  1332. }
  1333. }
  1334. return kResultTrue;
  1335. }
  1336. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1337. {
  1338. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1339. return kResultTrue;
  1340. }
  1341. //==============================================================================
  1342. tresult PLUGIN_API setActive (TBool state) override
  1343. {
  1344. if (! state)
  1345. {
  1346. getPluginInstance().releaseResources();
  1347. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1348. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1349. }
  1350. else
  1351. {
  1352. auto sampleRate = getPluginInstance().getSampleRate();
  1353. auto bufferSize = getPluginInstance().getBlockSize();
  1354. sampleRate = processSetup.sampleRate > 0.0
  1355. ? processSetup.sampleRate
  1356. : sampleRate;
  1357. bufferSize = processSetup.maxSamplesPerBlock > 0
  1358. ? (int) processSetup.maxSamplesPerBlock
  1359. : bufferSize;
  1360. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1361. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1362. preparePlugin (sampleRate, bufferSize);
  1363. }
  1364. return kResultOk;
  1365. }
  1366. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1367. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1368. //==============================================================================
  1369. bool isBypassed()
  1370. {
  1371. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1372. return (bypassParam->getValue() != 0.0f);
  1373. return false;
  1374. }
  1375. void setBypassed (bool shouldBeBypassed)
  1376. {
  1377. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1378. {
  1379. auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
  1380. bypassParam->setValue (floatValue);
  1381. inParameterChangedCallback = true;
  1382. bypassParam->sendValueChangedMessageToListeners (floatValue);
  1383. }
  1384. }
  1385. //==============================================================================
  1386. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1387. {
  1388. if (pluginInstance->getBypassParameter() == nullptr)
  1389. {
  1390. ValueTree privateData (kJucePrivateDataIdentifier);
  1391. // for now we only store the bypass value
  1392. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1393. privateData.writeToStream (out);
  1394. }
  1395. }
  1396. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1397. {
  1398. if (pluginInstance->getBypassParameter() == nullptr)
  1399. {
  1400. if (comPluginInstance->getBypassParameter() != nullptr)
  1401. {
  1402. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1403. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1404. }
  1405. }
  1406. }
  1407. void getStateInformation (MemoryBlock& destData)
  1408. {
  1409. pluginInstance->getStateInformation (destData);
  1410. // With bypass support, JUCE now needs to store private state data.
  1411. // Put this at the end of the plug-in state and add a few null characters
  1412. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1413. // this data. Additionally, we need to add some sort of magic identifier
  1414. // at the very end of the private data so that JUCE has some sort of
  1415. // way to figure out if the data was stored with a newer JUCE version.
  1416. MemoryOutputStream extraData;
  1417. extraData.writeInt64 (0);
  1418. writeJucePrivateStateInformation (extraData);
  1419. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1420. extraData.writeInt64 (privateDataSize);
  1421. extraData << kJucePrivateDataIdentifier;
  1422. // write magic string
  1423. destData.append (extraData.getData(), extraData.getDataSize());
  1424. }
  1425. void setStateInformation (const void* data, int sizeAsInt)
  1426. {
  1427. int64 size = sizeAsInt;
  1428. // Check if this data was written with a newer JUCE version
  1429. // and if it has the JUCE private data magic code at the end
  1430. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1431. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1432. {
  1433. auto buffer = static_cast<const char*> (data);
  1434. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1435. CharPointer_UTF8 (buffer + size));
  1436. if (magic == kJucePrivateDataIdentifier)
  1437. {
  1438. // found a JUCE private data section
  1439. uint64 privateDataSize;
  1440. std::memcpy (&privateDataSize,
  1441. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1442. sizeof (uint64));
  1443. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1444. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1445. if (privateDataSize > 0)
  1446. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1447. size -= sizeof (uint64);
  1448. }
  1449. }
  1450. if (size >= 0)
  1451. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1452. }
  1453. //==============================================================================
  1454. #if JUCE_VST3_CAN_REPLACE_VST2
  1455. bool loadVST2VstWBlock (const char* data, int size)
  1456. {
  1457. jassert ('VstW' == htonl (*(juce::int32*) data));
  1458. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1459. auto headerLen = (int) htonl (*(juce::int32*) (data + 4)) + 8;
  1460. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1461. }
  1462. bool loadVST2CcnKBlock (const char* data, int size)
  1463. {
  1464. auto bank = (const Vst2::fxBank*) data;
  1465. jassert ('CcnK' == htonl (bank->chunkMagic));
  1466. jassert ('FBCh' == htonl (bank->fxMagic));
  1467. jassert (htonl (bank->version) == 1 || htonl (bank->version) == 2);
  1468. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1469. setStateInformation (bank->content.data.chunk,
  1470. jmin ((int) (size - (bank->content.data.chunk - data)),
  1471. (int) htonl (bank->content.data.size)));
  1472. return true;
  1473. }
  1474. bool loadVST3PresetFile (const char* data, int size)
  1475. {
  1476. if (size < 48)
  1477. return false;
  1478. // At offset 4 there's a little-endian version number which seems to typically be 1
  1479. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1480. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1481. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1482. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1483. jassert (entryCount > 0);
  1484. for (int i = 0; i < entryCount; ++i)
  1485. {
  1486. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1487. if (entryOffset + 20 > size)
  1488. return false;
  1489. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1490. {
  1491. // "Comp" entries seem to contain the data.
  1492. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1493. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1494. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1495. {
  1496. jassertfalse;
  1497. return false;
  1498. }
  1499. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1500. }
  1501. }
  1502. return true;
  1503. }
  1504. bool loadVST2CompatibleState (const char* data, int size)
  1505. {
  1506. if (size < 4)
  1507. return false;
  1508. auto header = htonl (*(juce::int32*) data);
  1509. if (header == 'VstW')
  1510. return loadVST2VstWBlock (data, size);
  1511. if (header == 'CcnK')
  1512. return loadVST2CcnKBlock (data, size);
  1513. if (memcmp (data, "VST3", 4) == 0)
  1514. {
  1515. // In Cubase 5, when loading VST3 .vstpreset files,
  1516. // we get the whole content of the files to load.
  1517. // In Cubase 7 we get just the contents within and
  1518. // we go directly to the loadVST2VstW codepath instead.
  1519. return loadVST3PresetFile (data, size);
  1520. }
  1521. return false;
  1522. }
  1523. #endif
  1524. void loadStateData (const void* data, int size)
  1525. {
  1526. #if JUCE_VST3_CAN_REPLACE_VST2
  1527. if (loadVST2CompatibleState ((const char*) data, size))
  1528. return;
  1529. #endif
  1530. setStateInformation (data, size);
  1531. }
  1532. bool readFromMemoryStream (IBStream* state)
  1533. {
  1534. FUnknownPtr<ISizeableStream> s (state);
  1535. Steinberg::int64 size = 0;
  1536. if (s != nullptr
  1537. && s->getStreamSize (size) == kResultOk
  1538. && size > 0
  1539. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1540. {
  1541. MemoryBlock block (static_cast<size_t> (size));
  1542. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1543. Steinberg::int32 bytesRead = 1;
  1544. int len;
  1545. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1546. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1547. break;
  1548. if (len == 0)
  1549. return false;
  1550. block.setSize (static_cast<size_t> (len));
  1551. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1552. if (getHostType().isAdobeAudition())
  1553. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1554. return false;
  1555. loadStateData (block.getData(), (int) block.getSize());
  1556. return true;
  1557. }
  1558. return false;
  1559. }
  1560. bool readFromUnknownStream (IBStream* state)
  1561. {
  1562. MemoryOutputStream allData;
  1563. {
  1564. const size_t bytesPerBlock = 4096;
  1565. HeapBlock<char> buffer (bytesPerBlock);
  1566. for (;;)
  1567. {
  1568. Steinberg::int32 bytesRead = 0;
  1569. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1570. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1571. break;
  1572. allData.write (buffer, static_cast<size_t> (bytesRead));
  1573. }
  1574. }
  1575. const size_t dataSize = allData.getDataSize();
  1576. if (dataSize <= 0 || dataSize >= 0x7fffffff)
  1577. return false;
  1578. loadStateData (allData.getData(), (int) dataSize);
  1579. return true;
  1580. }
  1581. tresult PLUGIN_API setState (IBStream* state) override
  1582. {
  1583. if (state == nullptr)
  1584. return kInvalidArgument;
  1585. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1586. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1587. {
  1588. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1589. return kResultTrue;
  1590. if (readFromUnknownStream (state))
  1591. return kResultTrue;
  1592. }
  1593. return kResultFalse;
  1594. }
  1595. #if JUCE_VST3_CAN_REPLACE_VST2
  1596. static tresult writeVST2Int (IBStream* state, int n)
  1597. {
  1598. juce::int32 t = (juce::int32) htonl (n);
  1599. return state->write (&t, 4);
  1600. }
  1601. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1602. {
  1603. tresult status = writeVST2Int (state, 'VstW');
  1604. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1605. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1606. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1607. return status;
  1608. }
  1609. #endif
  1610. tresult PLUGIN_API getState (IBStream* state) override
  1611. {
  1612. if (state == nullptr)
  1613. return kInvalidArgument;
  1614. juce::MemoryBlock mem;
  1615. getStateInformation (mem);
  1616. #if JUCE_VST3_CAN_REPLACE_VST2
  1617. tresult status = writeVST2Header (state, isBypassed());
  1618. if (status != kResultOk)
  1619. return status;
  1620. const int bankBlockSize = 160;
  1621. Vst2::fxBank bank;
  1622. zerostruct (bank);
  1623. bank.chunkMagic = (int32) htonl ('CcnK');
  1624. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1625. bank.fxMagic = (int32) htonl ('FBCh');
  1626. bank.version = (int32) htonl (2);
  1627. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1628. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  1629. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  1630. status = state->write (&bank, bankBlockSize);
  1631. if (status != kResultOk)
  1632. return status;
  1633. #endif
  1634. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1635. }
  1636. //==============================================================================
  1637. Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
  1638. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
  1639. Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
  1640. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
  1641. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
  1642. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1643. Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
  1644. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
  1645. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1646. Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
  1647. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
  1648. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  1649. Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
  1650. Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
  1651. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  1652. Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
  1653. //==============================================================================
  1654. bool getCurrentPosition (CurrentPositionInfo& info) override
  1655. {
  1656. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1657. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  1658. info.bpm = jmax (1.0, processContext.tempo);
  1659. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1660. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1661. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1662. info.ppqPosition = processContext.projectTimeMusic;
  1663. info.ppqLoopStart = processContext.cycleStartMusic;
  1664. info.ppqLoopEnd = processContext.cycleEndMusic;
  1665. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1666. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1667. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1668. info.editOriginTime = 0.0;
  1669. info.frameRate = AudioPlayHead::fpsUnknown;
  1670. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1671. {
  1672. switch (processContext.frameRate.framesPerSecond)
  1673. {
  1674. case 24:
  1675. {
  1676. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1677. info.frameRate = AudioPlayHead::fps23976;
  1678. else
  1679. info.frameRate = AudioPlayHead::fps24;
  1680. }
  1681. break;
  1682. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1683. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1684. case 30:
  1685. {
  1686. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1687. info.frameRate = AudioPlayHead::fps30drop;
  1688. else
  1689. info.frameRate = AudioPlayHead::fps30;
  1690. }
  1691. break;
  1692. default: break;
  1693. }
  1694. }
  1695. return true;
  1696. }
  1697. //==============================================================================
  1698. int getNumAudioBuses (bool isInput) const
  1699. {
  1700. int busCount = pluginInstance->getBusCount (isInput);
  1701. #ifdef JucePlugin_PreferredChannelConfigurations
  1702. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1703. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1704. bool hasOnlyZeroChannels = true;
  1705. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1706. if (configs[i][isInput ? 0 : 1] != 0)
  1707. hasOnlyZeroChannels = false;
  1708. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1709. #endif
  1710. return busCount;
  1711. }
  1712. //==============================================================================
  1713. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1714. {
  1715. if (type == Vst::kAudio)
  1716. return getNumAudioBuses (dir == Vst::kInput);
  1717. if (type == Vst::kEvent)
  1718. {
  1719. if (dir == Vst::kInput)
  1720. return isMidiInputBusEnabled ? 1 : 0;
  1721. if (dir == Vst::kOutput)
  1722. return isMidiOutputBusEnabled ? 1 : 0;
  1723. }
  1724. return 0;
  1725. }
  1726. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1727. Steinberg::int32 index, Vst::BusInfo& info) override
  1728. {
  1729. if (type == Vst::kAudio)
  1730. {
  1731. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1732. return kResultFalse;
  1733. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1734. {
  1735. info.mediaType = Vst::kAudio;
  1736. info.direction = dir;
  1737. info.channelCount = bus->getLastEnabledLayout().size();
  1738. toString128 (info.name, bus->getName());
  1739. #if JucePlugin_IsSynth
  1740. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1741. #else
  1742. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1743. #endif
  1744. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1745. return kResultTrue;
  1746. }
  1747. }
  1748. if (type == Vst::kEvent)
  1749. {
  1750. info.flags = Vst::BusInfo::kDefaultActive;
  1751. #if JucePlugin_WantsMidiInput
  1752. if (dir == Vst::kInput && index == 0)
  1753. {
  1754. info.mediaType = Vst::kEvent;
  1755. info.direction = dir;
  1756. #ifdef JucePlugin_VSTNumMidiInputs
  1757. info.channelCount = JucePlugin_VSTNumMidiInputs;
  1758. #else
  1759. info.channelCount = 16;
  1760. #endif
  1761. toString128 (info.name, TRANS("MIDI Input"));
  1762. info.busType = Vst::kMain;
  1763. return kResultTrue;
  1764. }
  1765. #endif
  1766. #if JucePlugin_ProducesMidiOutput
  1767. if (dir == Vst::kOutput && index == 0)
  1768. {
  1769. info.mediaType = Vst::kEvent;
  1770. info.direction = dir;
  1771. #ifdef JucePlugin_VSTNumMidiOutputs
  1772. info.channelCount = JucePlugin_VSTNumMidiOutputs;
  1773. #else
  1774. info.channelCount = 16;
  1775. #endif
  1776. toString128 (info.name, TRANS("MIDI Output"));
  1777. info.busType = Vst::kMain;
  1778. return kResultTrue;
  1779. }
  1780. #endif
  1781. }
  1782. zerostruct (info);
  1783. return kResultFalse;
  1784. }
  1785. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1786. {
  1787. if (type == Vst::kEvent)
  1788. {
  1789. if (index != 0)
  1790. return kResultFalse;
  1791. if (dir == Vst::kInput)
  1792. isMidiInputBusEnabled = (state != 0);
  1793. else
  1794. isMidiOutputBusEnabled = (state != 0);
  1795. return kResultTrue;
  1796. }
  1797. if (type == Vst::kAudio)
  1798. {
  1799. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1800. return kResultFalse;
  1801. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1802. {
  1803. #ifdef JucePlugin_PreferredChannelConfigurations
  1804. auto newLayout = pluginInstance->getBusesLayout();
  1805. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1806. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1807. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1808. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1809. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1810. return kResultFalse;
  1811. #endif
  1812. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1813. }
  1814. }
  1815. return kResultFalse;
  1816. }
  1817. bool checkBusFormatsAreNotDiscrete()
  1818. {
  1819. auto numInputBuses = pluginInstance->getBusCount (true);
  1820. auto numOutputBuses = pluginInstance->getBusCount (false);
  1821. for (int i = 0; i < numInputBuses; ++i)
  1822. {
  1823. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  1824. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1825. return false;
  1826. }
  1827. for (int i = 0; i < numOutputBuses; ++i)
  1828. {
  1829. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  1830. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1831. return false;
  1832. }
  1833. return true;
  1834. }
  1835. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1836. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1837. {
  1838. auto numInputBuses = pluginInstance->getBusCount (true);
  1839. auto numOutputBuses = pluginInstance->getBusCount (false);
  1840. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1841. return false;
  1842. auto requested = pluginInstance->getBusesLayout();
  1843. for (int i = 0; i < numIns; ++i)
  1844. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1845. for (int i = 0; i < numOuts; ++i)
  1846. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1847. #ifdef JucePlugin_PreferredChannelConfigurations
  1848. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1849. if (! AudioProcessor::containsLayout (requested, configs))
  1850. return kResultFalse;
  1851. #endif
  1852. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1853. }
  1854. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1855. {
  1856. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1857. {
  1858. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1859. return kResultTrue;
  1860. }
  1861. return kResultFalse;
  1862. }
  1863. //==============================================================================
  1864. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1865. {
  1866. return (symbolicSampleSize == Vst::kSample32
  1867. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1868. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1869. }
  1870. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1871. {
  1872. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1873. }
  1874. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1875. {
  1876. ScopedInSetupProcessingSetter inSetupProcessingSetter (juceVST3EditController);
  1877. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1878. return kResultFalse;
  1879. processSetup = newSetup;
  1880. processContext.sampleRate = processSetup.sampleRate;
  1881. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1882. ? AudioProcessor::doublePrecision
  1883. : AudioProcessor::singlePrecision);
  1884. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  1885. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1886. return kResultTrue;
  1887. }
  1888. tresult PLUGIN_API setProcessing (TBool state) override
  1889. {
  1890. if (! state)
  1891. getPluginInstance().reset();
  1892. return kResultTrue;
  1893. }
  1894. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1895. {
  1896. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1897. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  1898. return Vst::kNoTail;
  1899. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  1900. return Vst::kInfiniteTail;
  1901. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1902. }
  1903. //==============================================================================
  1904. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1905. {
  1906. jassert (pluginInstance != nullptr);
  1907. auto numParamsChanged = paramChanges.getParameterCount();
  1908. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1909. {
  1910. if (auto* paramQueue = paramChanges.getParameterData (i))
  1911. {
  1912. auto numPoints = paramQueue->getPointCount();
  1913. Steinberg::int32 offsetSamples = 0;
  1914. double value = 0.0;
  1915. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1916. {
  1917. auto vstParamID = paramQueue->getParameterId();
  1918. if (vstParamID == JuceAudioProcessor::paramPreset)
  1919. {
  1920. auto numPrograms = pluginInstance->getNumPrograms();
  1921. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1922. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1923. && programValue != pluginInstance->getCurrentProgram())
  1924. pluginInstance->setCurrentProgram (programValue);
  1925. }
  1926. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1927. else if (juceVST3EditController != nullptr && juceVST3EditController->isMidiControllerParamID (vstParamID))
  1928. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1929. #endif
  1930. else
  1931. {
  1932. auto floatValue = static_cast<float> (value);
  1933. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  1934. {
  1935. param->setValue (floatValue);
  1936. inParameterChangedCallback = true;
  1937. param->sendValueChangedMessageToListeners (floatValue);
  1938. }
  1939. }
  1940. }
  1941. }
  1942. }
  1943. }
  1944. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1945. {
  1946. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1947. int channel, ctrlNumber;
  1948. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1949. {
  1950. if (ctrlNumber == Vst::kAfterTouch)
  1951. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1952. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1953. else if (ctrlNumber == Vst::kPitchBend)
  1954. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1955. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1956. else
  1957. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1958. jlimit (0, 127, ctrlNumber),
  1959. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1960. }
  1961. }
  1962. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1963. {
  1964. if (pluginInstance == nullptr)
  1965. return kResultFalse;
  1966. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1967. return kResultFalse;
  1968. if (data.processContext != nullptr)
  1969. {
  1970. processContext = *data.processContext;
  1971. if (juceVST3EditController != nullptr)
  1972. juceVST3EditController->vst3IsPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1973. }
  1974. else
  1975. {
  1976. zerostruct (processContext);
  1977. if (juceVST3EditController != nullptr)
  1978. juceVST3EditController->vst3IsPlaying = false;
  1979. }
  1980. midiBuffer.clear();
  1981. if (data.inputParameterChanges != nullptr)
  1982. processParameterChanges (*data.inputParameterChanges);
  1983. #if JucePlugin_WantsMidiInput
  1984. if (data.inputEvents != nullptr)
  1985. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1986. #endif
  1987. if (getHostType().isWavelab())
  1988. {
  1989. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1990. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1991. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1992. && (numInputChans + numOutputChans) == 0)
  1993. return kResultFalse;
  1994. }
  1995. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1996. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1997. else jassertfalse;
  1998. #if JucePlugin_ProducesMidiOutput
  1999. if (data.outputEvents != nullptr)
  2000. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  2001. #endif
  2002. return kResultTrue;
  2003. }
  2004. private:
  2005. //==============================================================================
  2006. struct ScopedInSetupProcessingSetter
  2007. {
  2008. ScopedInSetupProcessingSetter (JuceVST3EditController* c)
  2009. : controller (c)
  2010. {
  2011. if (controller != nullptr)
  2012. controller->inSetupProcessing = true;
  2013. }
  2014. ~ScopedInSetupProcessingSetter()
  2015. {
  2016. if (controller != nullptr)
  2017. controller->inSetupProcessing = false;
  2018. }
  2019. private:
  2020. JuceVST3EditController* controller = nullptr;
  2021. };
  2022. //==============================================================================
  2023. template <typename FloatType>
  2024. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  2025. {
  2026. int totalInputChans = 0, totalOutputChans = 0;
  2027. bool tmpBufferNeedsClearing = false;
  2028. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  2029. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  2030. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  2031. int vstInputs;
  2032. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  2033. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  2034. && data.inputs[vstInputs].numChannels > 0)
  2035. break;
  2036. int vstOutputs;
  2037. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  2038. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  2039. && data.outputs[vstOutputs].numChannels > 0)
  2040. break;
  2041. {
  2042. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  2043. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  2044. {
  2045. if (auto* busObject = pluginInstance->getBus (false, bus))
  2046. if (! busObject->isEnabled())
  2047. continue;
  2048. if (bus < vstOutputs)
  2049. {
  2050. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  2051. {
  2052. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  2053. for (int i = 0; i < numChans; ++i)
  2054. {
  2055. if (auto dst = busChannels[i])
  2056. {
  2057. if (totalOutputChans >= plugInInputChannels)
  2058. FloatVectorOperations::clear (dst, (int) data.numSamples);
  2059. channelList.set (totalOutputChans++, busChannels[i]);
  2060. }
  2061. }
  2062. }
  2063. }
  2064. else
  2065. {
  2066. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  2067. for (int i = 0; i < numChans; ++i)
  2068. {
  2069. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  2070. {
  2071. tmpBufferNeedsClearing = true;
  2072. channelList.set (totalOutputChans++, tmpBuffer);
  2073. }
  2074. else
  2075. return;
  2076. }
  2077. }
  2078. }
  2079. }
  2080. {
  2081. auto n = jmax (vstInputs, getNumAudioBuses (true));
  2082. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  2083. {
  2084. if (auto* busObject = pluginInstance->getBus (true, bus))
  2085. if (! busObject->isEnabled())
  2086. continue;
  2087. if (bus < vstInputs)
  2088. {
  2089. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  2090. {
  2091. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  2092. for (int i = 0; i < numChans; ++i)
  2093. {
  2094. if (busChannels[i] != nullptr)
  2095. {
  2096. if (totalInputChans >= totalOutputChans)
  2097. channelList.set (totalInputChans, busChannels[i]);
  2098. else
  2099. {
  2100. auto* dst = channelList.getReference (totalInputChans);
  2101. auto* src = busChannels[i];
  2102. if (dst != src)
  2103. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  2104. }
  2105. }
  2106. ++totalInputChans;
  2107. }
  2108. }
  2109. }
  2110. else
  2111. {
  2112. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  2113. for (int i = 0; i < numChans; ++i)
  2114. {
  2115. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  2116. {
  2117. tmpBufferNeedsClearing = true;
  2118. channelList.set (totalInputChans++, tmpBuffer);
  2119. }
  2120. else
  2121. return;
  2122. }
  2123. }
  2124. }
  2125. }
  2126. if (tmpBufferNeedsClearing)
  2127. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  2128. AudioBuffer<FloatType> buffer;
  2129. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  2130. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  2131. {
  2132. const ScopedLock sl (pluginInstance->getCallbackLock());
  2133. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  2134. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  2135. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  2136. #endif
  2137. if (pluginInstance->isSuspended())
  2138. {
  2139. buffer.clear();
  2140. }
  2141. else
  2142. {
  2143. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  2144. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  2145. {
  2146. if (isBypassed())
  2147. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  2148. else
  2149. pluginInstance->processBlock (buffer, midiBuffer);
  2150. }
  2151. }
  2152. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  2153. /* This assertion is caused when you've added some events to the
  2154. midiMessages array in your processBlock() method, which usually means
  2155. that you're trying to send them somewhere. But in this case they're
  2156. getting thrown away.
  2157. If your plugin does want to send MIDI messages, you'll need to set
  2158. the JucePlugin_ProducesMidiOutput macro to 1 in your
  2159. JucePluginCharacteristics.h file.
  2160. If you don't want to produce any MIDI output, then you should clear the
  2161. midiMessages array at the end of your processBlock() method, to
  2162. indicate that you don't want any of the events to be passed through
  2163. to the output.
  2164. */
  2165. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  2166. #endif
  2167. }
  2168. }
  2169. //==============================================================================
  2170. template <typename FloatType>
  2171. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2172. {
  2173. channelList.clearQuick();
  2174. channelList.insertMultiple (0, nullptr, 128);
  2175. auto& p = getPluginInstance();
  2176. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  2177. buffer.clear();
  2178. }
  2179. template <typename FloatType>
  2180. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2181. {
  2182. channelList.clearQuick();
  2183. channelList.resize (0);
  2184. buffer.setSize (0, 0);
  2185. }
  2186. template <typename FloatType>
  2187. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  2188. {
  2189. return AudioBusPointerHelper<FloatType>::impl (data);
  2190. }
  2191. template <typename FloatType>
  2192. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  2193. {
  2194. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  2195. // we can't do anything if the host requests to render many more samples than the
  2196. // block size, we need to bail out
  2197. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  2198. return nullptr;
  2199. return buffer.getWritePointer (channel);
  2200. }
  2201. void preparePlugin (double sampleRate, int bufferSize)
  2202. {
  2203. auto& p = getPluginInstance();
  2204. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2205. p.prepareToPlay (sampleRate, bufferSize);
  2206. midiBuffer.ensureSize (2048);
  2207. midiBuffer.clear();
  2208. }
  2209. //==============================================================================
  2210. ScopedJuceInitialiser_GUI libraryInitialiser;
  2211. std::atomic<int> refCount { 1 };
  2212. AudioProcessor* pluginInstance;
  2213. ComSmartPtr<Vst::IHostApplication> host;
  2214. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2215. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2216. /**
  2217. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  2218. this object needs to be copied on every call to process() to be up-to-date...
  2219. */
  2220. Vst::ProcessContext processContext;
  2221. Vst::ProcessSetup processSetup;
  2222. MidiBuffer midiBuffer;
  2223. Array<float*> channelListFloat;
  2224. Array<double*> channelListDouble;
  2225. AudioBuffer<float> emptyBufferFloat;
  2226. AudioBuffer<double> emptyBufferDouble;
  2227. #if JucePlugin_WantsMidiInput
  2228. bool isMidiInputBusEnabled = true;
  2229. #else
  2230. bool isMidiInputBusEnabled = false;
  2231. #endif
  2232. #if JucePlugin_ProducesMidiOutput
  2233. bool isMidiOutputBusEnabled = true;
  2234. #else
  2235. bool isMidiOutputBusEnabled = false;
  2236. #endif
  2237. static const char* kJucePrivateDataIdentifier;
  2238. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2239. };
  2240. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2241. //==============================================================================
  2242. #if JUCE_MSVC
  2243. #pragma warning (push, 0)
  2244. #pragma warning (disable: 4310)
  2245. #elif JUCE_CLANG
  2246. #pragma clang diagnostic push
  2247. #pragma clang diagnostic ignored "-Wall"
  2248. #endif
  2249. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2250. DEF_CLASS_IID (JuceAudioProcessor)
  2251. #if JUCE_VST3_CAN_REPLACE_VST2
  2252. FUID getFUIDForVST2ID (bool forControllerUID)
  2253. {
  2254. TUID uuid;
  2255. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  2256. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2257. return FUID (uuid);
  2258. }
  2259. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2260. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2261. #else
  2262. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2263. DEF_CLASS_IID (JuceVST3EditController)
  2264. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2265. DEF_CLASS_IID (JuceVST3Component)
  2266. #endif
  2267. #if JUCE_MSVC
  2268. #pragma warning (pop)
  2269. #elif JUCE_CLANG
  2270. #pragma clang diagnostic pop
  2271. #endif
  2272. //==============================================================================
  2273. bool initModule()
  2274. {
  2275. #if JUCE_MAC
  2276. initialiseMacVST();
  2277. #endif
  2278. return true;
  2279. }
  2280. bool shutdownModule()
  2281. {
  2282. return true;
  2283. }
  2284. #undef JUCE_EXPORTED_FUNCTION
  2285. #if JUCE_WINDOWS
  2286. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2287. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2288. #define JUCE_EXPORTED_FUNCTION
  2289. #else
  2290. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  2291. CFBundleRef globalBundleInstance = nullptr;
  2292. juce::uint32 numBundleRefs = 0;
  2293. juce::Array<CFBundleRef> bundleRefs;
  2294. enum { MaxPathLength = 2048 };
  2295. char modulePath[MaxPathLength] = { 0 };
  2296. void* moduleHandle = nullptr;
  2297. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  2298. {
  2299. if (ref != nullptr)
  2300. {
  2301. ++numBundleRefs;
  2302. CFRetain (ref);
  2303. bundleRefs.add (ref);
  2304. if (moduleHandle == nullptr)
  2305. {
  2306. globalBundleInstance = ref;
  2307. moduleHandle = ref;
  2308. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  2309. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  2310. CFRelease (tempURL);
  2311. }
  2312. }
  2313. return initModule();
  2314. }
  2315. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2316. {
  2317. if (shutdownModule())
  2318. {
  2319. if (--numBundleRefs == 0)
  2320. {
  2321. for (int i = 0; i < bundleRefs.size(); ++i)
  2322. CFRelease (bundleRefs.getUnchecked (i));
  2323. bundleRefs.clear();
  2324. }
  2325. return true;
  2326. }
  2327. return false;
  2328. }
  2329. #endif
  2330. //==============================================================================
  2331. /** This typedef represents VST3's createInstance() function signature */
  2332. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2333. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2334. {
  2335. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2336. }
  2337. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2338. {
  2339. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2340. }
  2341. //==============================================================================
  2342. struct JucePluginFactory;
  2343. static JucePluginFactory* globalFactory = nullptr;
  2344. //==============================================================================
  2345. struct JucePluginFactory : public IPluginFactory3
  2346. {
  2347. JucePluginFactory()
  2348. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2349. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2350. {
  2351. }
  2352. virtual ~JucePluginFactory()
  2353. {
  2354. if (globalFactory == this)
  2355. globalFactory = nullptr;
  2356. }
  2357. //==============================================================================
  2358. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2359. {
  2360. if (createFunction == nullptr)
  2361. {
  2362. jassertfalse;
  2363. return false;
  2364. }
  2365. auto entry = std::make_unique<ClassEntry> (info, createFunction);
  2366. entry->infoW.fromAscii (info);
  2367. classes.push_back (std::move (entry));
  2368. return true;
  2369. }
  2370. //==============================================================================
  2371. JUCE_DECLARE_VST3_COM_REF_METHODS
  2372. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2373. {
  2374. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2375. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2376. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2377. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2378. jassertfalse; // Something new?
  2379. *obj = nullptr;
  2380. return kNotImplemented;
  2381. }
  2382. //==============================================================================
  2383. Steinberg::int32 PLUGIN_API countClasses() override
  2384. {
  2385. return (Steinberg::int32) classes.size();
  2386. }
  2387. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2388. {
  2389. if (info == nullptr)
  2390. return kInvalidArgument;
  2391. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2392. return kResultOk;
  2393. }
  2394. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2395. {
  2396. return getPClassInfo<PClassInfo> (index, info);
  2397. }
  2398. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2399. {
  2400. return getPClassInfo<PClassInfo2> (index, info);
  2401. }
  2402. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2403. {
  2404. if (info != nullptr)
  2405. {
  2406. if (auto& entry = classes[(size_t) index])
  2407. {
  2408. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2409. return kResultOk;
  2410. }
  2411. }
  2412. return kInvalidArgument;
  2413. }
  2414. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2415. {
  2416. ScopedJuceInitialiser_GUI libraryInitialiser;
  2417. *obj = nullptr;
  2418. TUID tuid;
  2419. memcpy (tuid, sourceIid, sizeof (TUID));
  2420. #if VST_VERSION >= 0x030608
  2421. auto sourceFuid = FUID::fromTUID (tuid);
  2422. #else
  2423. FUID sourceFuid;
  2424. sourceFuid = tuid;
  2425. #endif
  2426. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2427. {
  2428. jassertfalse; // The host you're running in has severe implementation issues!
  2429. return kInvalidArgument;
  2430. }
  2431. TUID iidToQuery;
  2432. sourceFuid.toTUID (iidToQuery);
  2433. for (auto& entry : classes)
  2434. {
  2435. if (doUIDsMatch (entry->infoW.cid, cid))
  2436. {
  2437. if (auto* instance = entry->createFunction (host))
  2438. {
  2439. const FReleaser releaser (instance);
  2440. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2441. return kResultOk;
  2442. }
  2443. break;
  2444. }
  2445. }
  2446. return kNoInterface;
  2447. }
  2448. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2449. {
  2450. host.loadFrom (context);
  2451. if (host != nullptr)
  2452. {
  2453. Vst::String128 name;
  2454. host->getName (name);
  2455. return kResultTrue;
  2456. }
  2457. return kNotImplemented;
  2458. }
  2459. private:
  2460. //==============================================================================
  2461. std::atomic<int> refCount { 1 };
  2462. const PFactoryInfo factoryInfo;
  2463. ComSmartPtr<Vst::IHostApplication> host;
  2464. //==============================================================================
  2465. struct ClassEntry
  2466. {
  2467. ClassEntry() noexcept {}
  2468. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2469. : info2 (info), createFunction (fn) {}
  2470. PClassInfo2 info2;
  2471. PClassInfoW infoW;
  2472. CreateFunction createFunction = {};
  2473. bool isUnicode = false;
  2474. private:
  2475. JUCE_DECLARE_NON_COPYABLE (ClassEntry)
  2476. };
  2477. std::vector<std::unique_ptr<ClassEntry>> classes;
  2478. //==============================================================================
  2479. template<class PClassInfoType>
  2480. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2481. {
  2482. if (info != nullptr)
  2483. {
  2484. zerostruct (*info);
  2485. if (auto& entry = classes[(size_t) index])
  2486. {
  2487. if (entry->isUnicode)
  2488. return kResultFalse;
  2489. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2490. return kResultOk;
  2491. }
  2492. }
  2493. jassertfalse;
  2494. return kInvalidArgument;
  2495. }
  2496. //==============================================================================
  2497. // no leak detector here to prevent it firing on shutdown when running in hosts that
  2498. // don't release the factory object correctly...
  2499. JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
  2500. };
  2501. } // juce namespace
  2502. //==============================================================================
  2503. #ifndef JucePlugin_Vst3ComponentFlags
  2504. #if JucePlugin_IsSynth
  2505. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2506. #else
  2507. #define JucePlugin_Vst3ComponentFlags 0
  2508. #endif
  2509. #endif
  2510. #ifndef JucePlugin_Vst3Category
  2511. #if JucePlugin_IsSynth
  2512. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2513. #else
  2514. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2515. #endif
  2516. #endif
  2517. using namespace juce;
  2518. //==============================================================================
  2519. // The VST3 plugin entry point.
  2520. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2521. {
  2522. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2523. #if JUCE_MSVC
  2524. // Cunning trick to force this function to be exported. Life's too short to
  2525. // faff around creating .def files for this kind of thing.
  2526. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2527. #endif
  2528. if (globalFactory == nullptr)
  2529. {
  2530. globalFactory = new JucePluginFactory();
  2531. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2532. PClassInfo::kManyInstances,
  2533. kVstAudioEffectClass,
  2534. JucePlugin_Name,
  2535. JucePlugin_Vst3ComponentFlags,
  2536. JucePlugin_Vst3Category,
  2537. JucePlugin_Manufacturer,
  2538. JucePlugin_VersionString,
  2539. kVstVersionString);
  2540. globalFactory->registerClass (componentClass, createComponentInstance);
  2541. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2542. PClassInfo::kManyInstances,
  2543. kVstComponentControllerClass,
  2544. JucePlugin_Name,
  2545. JucePlugin_Vst3ComponentFlags,
  2546. JucePlugin_Vst3Category,
  2547. JucePlugin_Manufacturer,
  2548. JucePlugin_VersionString,
  2549. kVstVersionString);
  2550. globalFactory->registerClass (controllerClass, createControllerInstance);
  2551. }
  2552. else
  2553. {
  2554. globalFactory->addRef();
  2555. }
  2556. return dynamic_cast<IPluginFactory*> (globalFactory);
  2557. }
  2558. //==============================================================================
  2559. #if _MSC_VER || JUCE_MINGW
  2560. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2561. #endif
  2562. #endif //JucePlugin_Build_VST3