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.

3185 lines
119KB

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