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.

3226 lines
120KB

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