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.

3173 lines
118KB

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