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.

3207 lines
119KB

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