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.

3202 lines
119KB

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