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.

3176 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 &= ~(((Vst::ParamID) 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() override = default;
  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() override = default;
  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->getParameterTree().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, nullptr, 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. auto hostType = getHostType().type;
  1011. if (hostType == PluginHostType::SteinbergCubase10 || hostType == PluginHostType::FruityLoops)
  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() override
  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 (owner.component != nullptr)
  1197. if (auto* peer = owner.component->getPeer())
  1198. peer->updateBounds();
  1199. }
  1200. JuceVST3Editor& owner;
  1201. };
  1202. std::unique_ptr<Cubase10WindowResizeWorkaround> cubase10Workaround;
  1203. #endif
  1204. float editorScaleFactor = 1.0f;
  1205. #if JUCE_WINDOWS
  1206. WindowsHooks hooks;
  1207. #endif
  1208. //==============================================================================
  1209. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  1210. };
  1211. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  1212. };
  1213. namespace
  1214. {
  1215. template <typename FloatType> struct AudioBusPointerHelper {};
  1216. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  1217. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  1218. template <typename FloatType> struct ChooseBufferHelper {};
  1219. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  1220. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  1221. }
  1222. //==============================================================================
  1223. class JuceVST3Component : public Vst::IComponent,
  1224. public Vst::IAudioProcessor,
  1225. public Vst::IUnitInfo,
  1226. public Vst::IConnectionPoint,
  1227. public AudioPlayHead
  1228. {
  1229. public:
  1230. JuceVST3Component (Vst::IHostApplication* h)
  1231. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  1232. host (h)
  1233. {
  1234. inParameterChangedCallback = false;
  1235. #ifdef JucePlugin_PreferredChannelConfigurations
  1236. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1237. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1238. ignoreUnused (numConfigs);
  1239. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1240. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1241. #endif
  1242. // VST-3 requires your default layout to be non-discrete!
  1243. // For example, your default layout must be mono, stereo, quadrophonic
  1244. // and not AudioChannelSet::discreteChannels (2) etc.
  1245. jassert (checkBusFormatsAreNotDiscrete());
  1246. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  1247. zerostruct (processContext);
  1248. processSetup.maxSamplesPerBlock = 1024;
  1249. processSetup.processMode = Vst::kRealtime;
  1250. processSetup.sampleRate = 44100.0;
  1251. processSetup.symbolicSampleSize = Vst::kSample32;
  1252. pluginInstance->setPlayHead (this);
  1253. }
  1254. ~JuceVST3Component() override
  1255. {
  1256. if (juceVST3EditController != nullptr)
  1257. juceVST3EditController->vst3IsPlaying = 0;
  1258. if (pluginInstance != nullptr)
  1259. if (pluginInstance->getPlayHead() == this)
  1260. pluginInstance->setPlayHead (nullptr);
  1261. }
  1262. //==============================================================================
  1263. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1264. //==============================================================================
  1265. static const FUID iid;
  1266. JUCE_DECLARE_VST3_COM_REF_METHODS
  1267. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1268. {
  1269. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  1270. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  1271. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  1272. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  1273. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  1274. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  1275. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  1276. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  1277. {
  1278. comPluginInstance->addRef();
  1279. *obj = comPluginInstance;
  1280. return kResultOk;
  1281. }
  1282. *obj = nullptr;
  1283. return kNoInterface;
  1284. }
  1285. //==============================================================================
  1286. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1287. {
  1288. if (host != hostContext)
  1289. host.loadFrom (hostContext);
  1290. processContext.sampleRate = processSetup.sampleRate;
  1291. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  1292. return kResultTrue;
  1293. }
  1294. tresult PLUGIN_API terminate() override
  1295. {
  1296. getPluginInstance().releaseResources();
  1297. return kResultTrue;
  1298. }
  1299. //==============================================================================
  1300. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1301. {
  1302. if (other != nullptr && juceVST3EditController == nullptr)
  1303. juceVST3EditController.loadFrom (other);
  1304. return kResultTrue;
  1305. }
  1306. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1307. {
  1308. if (juceVST3EditController != nullptr)
  1309. juceVST3EditController->vst3IsPlaying = 0;
  1310. juceVST3EditController = nullptr;
  1311. return kResultTrue;
  1312. }
  1313. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1314. {
  1315. if (message != nullptr && juceVST3EditController == nullptr)
  1316. {
  1317. Steinberg::int64 value = 0;
  1318. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1319. {
  1320. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  1321. if (juceVST3EditController != nullptr)
  1322. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1323. else
  1324. jassertfalse;
  1325. }
  1326. }
  1327. return kResultTrue;
  1328. }
  1329. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1330. {
  1331. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1332. return kResultTrue;
  1333. }
  1334. //==============================================================================
  1335. tresult PLUGIN_API setActive (TBool state) override
  1336. {
  1337. if (! state)
  1338. {
  1339. getPluginInstance().releaseResources();
  1340. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1341. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1342. }
  1343. else
  1344. {
  1345. auto sampleRate = getPluginInstance().getSampleRate();
  1346. auto bufferSize = getPluginInstance().getBlockSize();
  1347. sampleRate = processSetup.sampleRate > 0.0
  1348. ? processSetup.sampleRate
  1349. : sampleRate;
  1350. bufferSize = processSetup.maxSamplesPerBlock > 0
  1351. ? (int) processSetup.maxSamplesPerBlock
  1352. : bufferSize;
  1353. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1354. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1355. preparePlugin (sampleRate, bufferSize);
  1356. }
  1357. return kResultOk;
  1358. }
  1359. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1360. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1361. //==============================================================================
  1362. bool isBypassed()
  1363. {
  1364. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1365. return (bypassParam->getValue() != 0.0f);
  1366. return false;
  1367. }
  1368. void setBypassed (bool shouldBeBypassed)
  1369. {
  1370. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1371. {
  1372. auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
  1373. bypassParam->setValue (floatValue);
  1374. inParameterChangedCallback = true;
  1375. bypassParam->sendValueChangedMessageToListeners (floatValue);
  1376. }
  1377. }
  1378. //==============================================================================
  1379. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1380. {
  1381. if (pluginInstance->getBypassParameter() == nullptr)
  1382. {
  1383. ValueTree privateData (kJucePrivateDataIdentifier);
  1384. // for now we only store the bypass value
  1385. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1386. privateData.writeToStream (out);
  1387. }
  1388. }
  1389. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1390. {
  1391. if (pluginInstance->getBypassParameter() == nullptr)
  1392. {
  1393. if (comPluginInstance->getBypassParameter() != nullptr)
  1394. {
  1395. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1396. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1397. }
  1398. }
  1399. }
  1400. void getStateInformation (MemoryBlock& destData)
  1401. {
  1402. pluginInstance->getStateInformation (destData);
  1403. // With bypass support, JUCE now needs to store private state data.
  1404. // Put this at the end of the plug-in state and add a few null characters
  1405. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1406. // this data. Additionally, we need to add some sort of magic identifier
  1407. // at the very end of the private data so that JUCE has some sort of
  1408. // way to figure out if the data was stored with a newer JUCE version.
  1409. MemoryOutputStream extraData;
  1410. extraData.writeInt64 (0);
  1411. writeJucePrivateStateInformation (extraData);
  1412. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1413. extraData.writeInt64 (privateDataSize);
  1414. extraData << kJucePrivateDataIdentifier;
  1415. // write magic string
  1416. destData.append (extraData.getData(), extraData.getDataSize());
  1417. }
  1418. void setStateInformation (const void* data, int sizeAsInt)
  1419. {
  1420. int64 size = sizeAsInt;
  1421. // Check if this data was written with a newer JUCE version
  1422. // and if it has the JUCE private data magic code at the end
  1423. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1424. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1425. {
  1426. auto buffer = static_cast<const char*> (data);
  1427. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1428. CharPointer_UTF8 (buffer + size));
  1429. if (magic == kJucePrivateDataIdentifier)
  1430. {
  1431. // found a JUCE private data section
  1432. uint64 privateDataSize;
  1433. std::memcpy (&privateDataSize,
  1434. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1435. sizeof (uint64));
  1436. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1437. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1438. if (privateDataSize > 0)
  1439. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1440. size -= sizeof (uint64);
  1441. }
  1442. }
  1443. if (size >= 0)
  1444. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1445. }
  1446. //==============================================================================
  1447. #if JUCE_VST3_CAN_REPLACE_VST2
  1448. bool loadVST2VstWBlock (const char* data, int size)
  1449. {
  1450. jassert ('VstW' == htonl (*(juce::int32*) data));
  1451. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1452. auto headerLen = (int) htonl (*(juce::int32*) (data + 4)) + 8;
  1453. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1454. }
  1455. bool loadVST2CcnKBlock (const char* data, int size)
  1456. {
  1457. auto bank = (const Vst2::fxBank*) data;
  1458. jassert ('CcnK' == htonl (bank->chunkMagic));
  1459. jassert ('FBCh' == htonl (bank->fxMagic));
  1460. jassert (htonl (bank->version) == 1 || htonl (bank->version) == 2);
  1461. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1462. setStateInformation (bank->content.data.chunk,
  1463. jmin ((int) (size - (bank->content.data.chunk - data)),
  1464. (int) htonl (bank->content.data.size)));
  1465. return true;
  1466. }
  1467. bool loadVST3PresetFile (const char* data, int size)
  1468. {
  1469. if (size < 48)
  1470. return false;
  1471. // At offset 4 there's a little-endian version number which seems to typically be 1
  1472. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1473. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1474. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1475. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1476. jassert (entryCount > 0);
  1477. for (int i = 0; i < entryCount; ++i)
  1478. {
  1479. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1480. if (entryOffset + 20 > size)
  1481. return false;
  1482. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1483. {
  1484. // "Comp" entries seem to contain the data.
  1485. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1486. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1487. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1488. {
  1489. jassertfalse;
  1490. return false;
  1491. }
  1492. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1493. }
  1494. }
  1495. return true;
  1496. }
  1497. bool loadVST2CompatibleState (const char* data, int size)
  1498. {
  1499. if (size < 4)
  1500. return false;
  1501. auto header = htonl (*(juce::int32*) data);
  1502. if (header == 'VstW')
  1503. return loadVST2VstWBlock (data, size);
  1504. if (header == 'CcnK')
  1505. return loadVST2CcnKBlock (data, size);
  1506. if (memcmp (data, "VST3", 4) == 0)
  1507. {
  1508. // In Cubase 5, when loading VST3 .vstpreset files,
  1509. // we get the whole content of the files to load.
  1510. // In Cubase 7 we get just the contents within and
  1511. // we go directly to the loadVST2VstW codepath instead.
  1512. return loadVST3PresetFile (data, size);
  1513. }
  1514. return false;
  1515. }
  1516. #endif
  1517. void loadStateData (const void* data, int size)
  1518. {
  1519. #if JUCE_VST3_CAN_REPLACE_VST2
  1520. if (loadVST2CompatibleState ((const char*) data, size))
  1521. return;
  1522. #endif
  1523. setStateInformation (data, size);
  1524. }
  1525. bool readFromMemoryStream (IBStream* state)
  1526. {
  1527. FUnknownPtr<ISizeableStream> s (state);
  1528. Steinberg::int64 size = 0;
  1529. if (s != nullptr
  1530. && s->getStreamSize (size) == kResultOk
  1531. && size > 0
  1532. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1533. {
  1534. MemoryBlock block (static_cast<size_t> (size));
  1535. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1536. Steinberg::int32 bytesRead = 1;
  1537. int len;
  1538. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1539. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1540. break;
  1541. if (len == 0)
  1542. return false;
  1543. block.setSize (static_cast<size_t> (len));
  1544. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1545. if (getHostType().isAdobeAudition())
  1546. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1547. return false;
  1548. loadStateData (block.getData(), (int) block.getSize());
  1549. return true;
  1550. }
  1551. return false;
  1552. }
  1553. bool readFromUnknownStream (IBStream* state)
  1554. {
  1555. MemoryOutputStream allData;
  1556. {
  1557. const size_t bytesPerBlock = 4096;
  1558. HeapBlock<char> buffer (bytesPerBlock);
  1559. for (;;)
  1560. {
  1561. Steinberg::int32 bytesRead = 0;
  1562. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1563. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1564. break;
  1565. allData.write (buffer, static_cast<size_t> (bytesRead));
  1566. }
  1567. }
  1568. const size_t dataSize = allData.getDataSize();
  1569. if (dataSize <= 0 || dataSize >= 0x7fffffff)
  1570. return false;
  1571. loadStateData (allData.getData(), (int) dataSize);
  1572. return true;
  1573. }
  1574. tresult PLUGIN_API setState (IBStream* state) override
  1575. {
  1576. if (state == nullptr)
  1577. return kInvalidArgument;
  1578. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1579. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1580. {
  1581. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1582. return kResultTrue;
  1583. if (readFromUnknownStream (state))
  1584. return kResultTrue;
  1585. }
  1586. return kResultFalse;
  1587. }
  1588. #if JUCE_VST3_CAN_REPLACE_VST2
  1589. static tresult writeVST2Int (IBStream* state, int n)
  1590. {
  1591. juce::int32 t = (juce::int32) htonl (n);
  1592. return state->write (&t, 4);
  1593. }
  1594. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1595. {
  1596. tresult status = writeVST2Int (state, 'VstW');
  1597. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1598. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1599. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1600. return status;
  1601. }
  1602. #endif
  1603. tresult PLUGIN_API getState (IBStream* state) override
  1604. {
  1605. if (state == nullptr)
  1606. return kInvalidArgument;
  1607. juce::MemoryBlock mem;
  1608. getStateInformation (mem);
  1609. #if JUCE_VST3_CAN_REPLACE_VST2
  1610. tresult status = writeVST2Header (state, isBypassed());
  1611. if (status != kResultOk)
  1612. return status;
  1613. const int bankBlockSize = 160;
  1614. Vst2::fxBank bank;
  1615. zerostruct (bank);
  1616. bank.chunkMagic = (int32) htonl ('CcnK');
  1617. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1618. bank.fxMagic = (int32) htonl ('FBCh');
  1619. bank.version = (int32) htonl (2);
  1620. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1621. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  1622. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  1623. status = state->write (&bank, bankBlockSize);
  1624. if (status != kResultOk)
  1625. return status;
  1626. #endif
  1627. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1628. }
  1629. //==============================================================================
  1630. Steinberg::int32 PLUGIN_API getUnitCount() override { return comPluginInstance->getUnitCount(); }
  1631. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override { return comPluginInstance->getUnitInfo (unitIndex, info); }
  1632. Steinberg::int32 PLUGIN_API getProgramListCount() override { return comPluginInstance->getProgramListCount(); }
  1633. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override { return comPluginInstance->getProgramListInfo (listIndex, info); }
  1634. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override { return comPluginInstance->getProgramName (listId, programIndex, name); }
  1635. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1636. Vst::CString attributeId, Vst::String128 attributeValue) override { return comPluginInstance->getProgramInfo (listId, programIndex, attributeId, attributeValue); }
  1637. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID listId, Steinberg::int32 programIndex) override { return comPluginInstance->hasProgramPitchNames (listId, programIndex); }
  1638. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID listId, Steinberg::int32 programIndex,
  1639. Steinberg::int16 midiPitch, Vst::String128 name) override { return comPluginInstance->getProgramPitchName (listId, programIndex, midiPitch, name); }
  1640. tresult PLUGIN_API selectUnit (Vst::UnitID unitId) override { return comPluginInstance->selectUnit (unitId); }
  1641. tresult PLUGIN_API setUnitProgramData (Steinberg::int32 listOrUnitId, Steinberg::int32 programIndex,
  1642. Steinberg::IBStream* data) override { return comPluginInstance->setUnitProgramData (listOrUnitId, programIndex, data); }
  1643. Vst::UnitID PLUGIN_API getSelectedUnit() override { return comPluginInstance->getSelectedUnit(); }
  1644. tresult PLUGIN_API getUnitByBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 busIndex,
  1645. Steinberg::int32 channel, Vst::UnitID& unitId) override { return comPluginInstance->getUnitByBus (type, dir, busIndex, channel, unitId); }
  1646. //==============================================================================
  1647. bool getCurrentPosition (CurrentPositionInfo& info) override
  1648. {
  1649. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1650. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  1651. info.bpm = jmax (1.0, processContext.tempo);
  1652. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1653. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1654. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1655. info.ppqPosition = processContext.projectTimeMusic;
  1656. info.ppqLoopStart = processContext.cycleStartMusic;
  1657. info.ppqLoopEnd = processContext.cycleEndMusic;
  1658. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1659. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1660. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1661. info.editOriginTime = 0.0;
  1662. info.frameRate = AudioPlayHead::fpsUnknown;
  1663. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1664. {
  1665. switch (processContext.frameRate.framesPerSecond)
  1666. {
  1667. case 24:
  1668. {
  1669. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1670. info.frameRate = AudioPlayHead::fps23976;
  1671. else
  1672. info.frameRate = AudioPlayHead::fps24;
  1673. }
  1674. break;
  1675. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1676. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1677. case 30:
  1678. {
  1679. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1680. info.frameRate = AudioPlayHead::fps30drop;
  1681. else
  1682. info.frameRate = AudioPlayHead::fps30;
  1683. }
  1684. break;
  1685. default: break;
  1686. }
  1687. }
  1688. return true;
  1689. }
  1690. //==============================================================================
  1691. int getNumAudioBuses (bool isInput) const
  1692. {
  1693. int busCount = pluginInstance->getBusCount (isInput);
  1694. #ifdef JucePlugin_PreferredChannelConfigurations
  1695. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1696. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1697. bool hasOnlyZeroChannels = true;
  1698. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1699. if (configs[i][isInput ? 0 : 1] != 0)
  1700. hasOnlyZeroChannels = false;
  1701. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1702. #endif
  1703. return busCount;
  1704. }
  1705. //==============================================================================
  1706. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1707. {
  1708. if (type == Vst::kAudio)
  1709. return getNumAudioBuses (dir == Vst::kInput);
  1710. if (type == Vst::kEvent)
  1711. {
  1712. if (dir == Vst::kInput)
  1713. return isMidiInputBusEnabled ? 1 : 0;
  1714. if (dir == Vst::kOutput)
  1715. return isMidiOutputBusEnabled ? 1 : 0;
  1716. }
  1717. return 0;
  1718. }
  1719. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1720. Steinberg::int32 index, Vst::BusInfo& info) override
  1721. {
  1722. if (type == Vst::kAudio)
  1723. {
  1724. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1725. return kResultFalse;
  1726. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1727. {
  1728. info.mediaType = Vst::kAudio;
  1729. info.direction = dir;
  1730. info.channelCount = bus->getLastEnabledLayout().size();
  1731. toString128 (info.name, bus->getName());
  1732. #if JucePlugin_IsSynth
  1733. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1734. #else
  1735. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1736. #endif
  1737. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1738. return kResultTrue;
  1739. }
  1740. }
  1741. if (type == Vst::kEvent)
  1742. {
  1743. info.flags = Vst::BusInfo::kDefaultActive;
  1744. #if JucePlugin_WantsMidiInput
  1745. if (dir == Vst::kInput && index == 0)
  1746. {
  1747. info.mediaType = Vst::kEvent;
  1748. info.direction = dir;
  1749. #ifdef JucePlugin_VSTNumMidiInputs
  1750. info.channelCount = JucePlugin_VSTNumMidiInputs;
  1751. #else
  1752. info.channelCount = 16;
  1753. #endif
  1754. toString128 (info.name, TRANS("MIDI Input"));
  1755. info.busType = Vst::kMain;
  1756. return kResultTrue;
  1757. }
  1758. #endif
  1759. #if JucePlugin_ProducesMidiOutput
  1760. if (dir == Vst::kOutput && index == 0)
  1761. {
  1762. info.mediaType = Vst::kEvent;
  1763. info.direction = dir;
  1764. #ifdef JucePlugin_VSTNumMidiOutputs
  1765. info.channelCount = JucePlugin_VSTNumMidiOutputs;
  1766. #else
  1767. info.channelCount = 16;
  1768. #endif
  1769. toString128 (info.name, TRANS("MIDI Output"));
  1770. info.busType = Vst::kMain;
  1771. return kResultTrue;
  1772. }
  1773. #endif
  1774. }
  1775. zerostruct (info);
  1776. return kResultFalse;
  1777. }
  1778. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1779. {
  1780. if (type == Vst::kEvent)
  1781. {
  1782. if (index != 0)
  1783. return kResultFalse;
  1784. if (dir == Vst::kInput)
  1785. isMidiInputBusEnabled = (state != 0);
  1786. else
  1787. isMidiOutputBusEnabled = (state != 0);
  1788. return kResultTrue;
  1789. }
  1790. if (type == Vst::kAudio)
  1791. {
  1792. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1793. return kResultFalse;
  1794. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1795. {
  1796. #ifdef JucePlugin_PreferredChannelConfigurations
  1797. auto newLayout = pluginInstance->getBusesLayout();
  1798. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1799. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1800. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1801. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1802. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1803. return kResultFalse;
  1804. #endif
  1805. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1806. }
  1807. }
  1808. return kResultFalse;
  1809. }
  1810. bool checkBusFormatsAreNotDiscrete()
  1811. {
  1812. auto numInputBuses = pluginInstance->getBusCount (true);
  1813. auto numOutputBuses = pluginInstance->getBusCount (false);
  1814. for (int i = 0; i < numInputBuses; ++i)
  1815. {
  1816. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  1817. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1818. return false;
  1819. }
  1820. for (int i = 0; i < numOutputBuses; ++i)
  1821. {
  1822. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  1823. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1824. return false;
  1825. }
  1826. return true;
  1827. }
  1828. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1829. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1830. {
  1831. auto numInputBuses = pluginInstance->getBusCount (true);
  1832. auto numOutputBuses = pluginInstance->getBusCount (false);
  1833. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1834. return false;
  1835. auto requested = pluginInstance->getBusesLayout();
  1836. for (int i = 0; i < numIns; ++i)
  1837. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1838. for (int i = 0; i < numOuts; ++i)
  1839. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1840. #ifdef JucePlugin_PreferredChannelConfigurations
  1841. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1842. if (! AudioProcessor::containsLayout (requested, configs))
  1843. return kResultFalse;
  1844. #endif
  1845. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1846. }
  1847. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1848. {
  1849. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1850. {
  1851. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1852. return kResultTrue;
  1853. }
  1854. return kResultFalse;
  1855. }
  1856. //==============================================================================
  1857. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1858. {
  1859. return (symbolicSampleSize == Vst::kSample32
  1860. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1861. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1862. }
  1863. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1864. {
  1865. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1866. }
  1867. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1868. {
  1869. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1870. return kResultFalse;
  1871. processSetup = newSetup;
  1872. processContext.sampleRate = processSetup.sampleRate;
  1873. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1874. ? AudioProcessor::doublePrecision
  1875. : AudioProcessor::singlePrecision);
  1876. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  1877. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1878. return kResultTrue;
  1879. }
  1880. tresult PLUGIN_API setProcessing (TBool state) override
  1881. {
  1882. if (! state)
  1883. getPluginInstance().reset();
  1884. return kResultTrue;
  1885. }
  1886. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1887. {
  1888. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1889. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  1890. return Vst::kNoTail;
  1891. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  1892. return Vst::kInfiniteTail;
  1893. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1894. }
  1895. //==============================================================================
  1896. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1897. {
  1898. jassert (pluginInstance != nullptr);
  1899. auto numParamsChanged = paramChanges.getParameterCount();
  1900. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1901. {
  1902. if (auto* paramQueue = paramChanges.getParameterData (i))
  1903. {
  1904. auto numPoints = paramQueue->getPointCount();
  1905. Steinberg::int32 offsetSamples = 0;
  1906. double value = 0.0;
  1907. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1908. {
  1909. auto vstParamID = paramQueue->getParameterId();
  1910. if (vstParamID == JuceAudioProcessor::paramPreset)
  1911. {
  1912. auto numPrograms = pluginInstance->getNumPrograms();
  1913. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1914. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1915. && programValue != pluginInstance->getCurrentProgram())
  1916. pluginInstance->setCurrentProgram (programValue);
  1917. }
  1918. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1919. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1920. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1921. #endif
  1922. else
  1923. {
  1924. auto floatValue = static_cast<float> (value);
  1925. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  1926. {
  1927. param->setValue (floatValue);
  1928. inParameterChangedCallback = true;
  1929. param->sendValueChangedMessageToListeners (floatValue);
  1930. }
  1931. }
  1932. }
  1933. }
  1934. }
  1935. }
  1936. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1937. {
  1938. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1939. int channel, ctrlNumber;
  1940. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1941. {
  1942. if (ctrlNumber == Vst::kAfterTouch)
  1943. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1944. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1945. else if (ctrlNumber == Vst::kPitchBend)
  1946. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1947. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1948. else
  1949. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1950. jlimit (0, 127, ctrlNumber),
  1951. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1952. }
  1953. }
  1954. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1955. {
  1956. if (pluginInstance == nullptr)
  1957. return kResultFalse;
  1958. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1959. return kResultFalse;
  1960. if (data.processContext != nullptr)
  1961. {
  1962. processContext = *data.processContext;
  1963. if (juceVST3EditController != nullptr)
  1964. juceVST3EditController->vst3IsPlaying = processContext.state & Vst::ProcessContext::kPlaying;
  1965. }
  1966. else
  1967. {
  1968. zerostruct (processContext);
  1969. if (juceVST3EditController != nullptr)
  1970. juceVST3EditController->vst3IsPlaying = 0;
  1971. }
  1972. midiBuffer.clear();
  1973. if (data.inputParameterChanges != nullptr)
  1974. processParameterChanges (*data.inputParameterChanges);
  1975. #if JucePlugin_WantsMidiInput
  1976. if (data.inputEvents != nullptr)
  1977. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1978. #endif
  1979. if (getHostType().isWavelab())
  1980. {
  1981. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1982. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1983. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1984. && (numInputChans + numOutputChans) == 0)
  1985. return kResultFalse;
  1986. }
  1987. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1988. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1989. else jassertfalse;
  1990. #if JucePlugin_ProducesMidiOutput
  1991. if (data.outputEvents != nullptr)
  1992. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1993. #endif
  1994. return kResultTrue;
  1995. }
  1996. private:
  1997. //==============================================================================
  1998. template <typename FloatType>
  1999. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  2000. {
  2001. int totalInputChans = 0, totalOutputChans = 0;
  2002. bool tmpBufferNeedsClearing = false;
  2003. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  2004. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  2005. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  2006. int vstInputs;
  2007. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  2008. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  2009. && data.inputs[vstInputs].numChannels > 0)
  2010. break;
  2011. int vstOutputs;
  2012. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  2013. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  2014. && data.outputs[vstOutputs].numChannels > 0)
  2015. break;
  2016. {
  2017. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  2018. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  2019. {
  2020. if (bus < vstOutputs)
  2021. {
  2022. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  2023. {
  2024. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  2025. for (int i = 0; i < numChans; ++i)
  2026. {
  2027. if (auto dst = busChannels[i])
  2028. {
  2029. if (totalOutputChans >= plugInInputChannels)
  2030. FloatVectorOperations::clear (dst, (int) data.numSamples);
  2031. channelList.set (totalOutputChans++, busChannels[i]);
  2032. }
  2033. }
  2034. }
  2035. }
  2036. else
  2037. {
  2038. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  2039. for (int i = 0; i < numChans; ++i)
  2040. {
  2041. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  2042. {
  2043. tmpBufferNeedsClearing = true;
  2044. channelList.set (totalOutputChans++, tmpBuffer);
  2045. }
  2046. else
  2047. return;
  2048. }
  2049. }
  2050. }
  2051. }
  2052. {
  2053. auto n = jmax (vstInputs, getNumAudioBuses (true));
  2054. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  2055. {
  2056. if (bus < vstInputs)
  2057. {
  2058. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  2059. {
  2060. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  2061. for (int i = 0; i < numChans; ++i)
  2062. {
  2063. if (busChannels[i] != nullptr)
  2064. {
  2065. if (totalInputChans >= totalOutputChans)
  2066. channelList.set (totalInputChans, busChannels[i]);
  2067. else
  2068. {
  2069. auto* dst = channelList.getReference (totalInputChans);
  2070. auto* src = busChannels[i];
  2071. if (dst != src)
  2072. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  2073. }
  2074. }
  2075. ++totalInputChans;
  2076. }
  2077. }
  2078. }
  2079. else
  2080. {
  2081. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  2082. for (int i = 0; i < numChans; ++i)
  2083. {
  2084. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  2085. {
  2086. tmpBufferNeedsClearing = true;
  2087. channelList.set (totalInputChans++, tmpBuffer);
  2088. }
  2089. else
  2090. return;
  2091. }
  2092. }
  2093. }
  2094. }
  2095. if (tmpBufferNeedsClearing)
  2096. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  2097. AudioBuffer<FloatType> buffer;
  2098. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  2099. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  2100. {
  2101. const ScopedLock sl (pluginInstance->getCallbackLock());
  2102. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  2103. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  2104. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  2105. #endif
  2106. if (pluginInstance->isSuspended())
  2107. {
  2108. buffer.clear();
  2109. }
  2110. else
  2111. {
  2112. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  2113. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  2114. {
  2115. if (isBypassed())
  2116. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  2117. else
  2118. pluginInstance->processBlock (buffer, midiBuffer);
  2119. }
  2120. }
  2121. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  2122. /* This assertion is caused when you've added some events to the
  2123. midiMessages array in your processBlock() method, which usually means
  2124. that you're trying to send them somewhere. But in this case they're
  2125. getting thrown away.
  2126. If your plugin does want to send MIDI messages, you'll need to set
  2127. the JucePlugin_ProducesMidiOutput macro to 1 in your
  2128. JucePluginCharacteristics.h file.
  2129. If you don't want to produce any MIDI output, then you should clear the
  2130. midiMessages array at the end of your processBlock() method, to
  2131. indicate that you don't want any of the events to be passed through
  2132. to the output.
  2133. */
  2134. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  2135. #endif
  2136. }
  2137. }
  2138. //==============================================================================
  2139. template <typename FloatType>
  2140. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2141. {
  2142. channelList.clearQuick();
  2143. channelList.insertMultiple (0, nullptr, 128);
  2144. auto& p = getPluginInstance();
  2145. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  2146. buffer.clear();
  2147. }
  2148. template <typename FloatType>
  2149. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  2150. {
  2151. channelList.clearQuick();
  2152. channelList.resize (0);
  2153. buffer.setSize (0, 0);
  2154. }
  2155. template <typename FloatType>
  2156. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  2157. {
  2158. return AudioBusPointerHelper<FloatType>::impl (data);
  2159. }
  2160. template <typename FloatType>
  2161. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  2162. {
  2163. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  2164. // we can't do anything if the host requests to render many more samples than the
  2165. // block size, we need to bail out
  2166. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  2167. return nullptr;
  2168. return buffer.getWritePointer (channel);
  2169. }
  2170. void preparePlugin (double sampleRate, int bufferSize)
  2171. {
  2172. auto& p = getPluginInstance();
  2173. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2174. p.prepareToPlay (sampleRate, bufferSize);
  2175. midiBuffer.ensureSize (2048);
  2176. midiBuffer.clear();
  2177. }
  2178. //==============================================================================
  2179. ScopedJuceInitialiser_GUI libraryInitialiser;
  2180. Atomic<int> refCount { 1 };
  2181. AudioProcessor* pluginInstance;
  2182. ComSmartPtr<Vst::IHostApplication> host;
  2183. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  2184. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  2185. /**
  2186. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  2187. this object needs to be copied on every call to process() to be up-to-date...
  2188. */
  2189. Vst::ProcessContext processContext;
  2190. Vst::ProcessSetup processSetup;
  2191. MidiBuffer midiBuffer;
  2192. Array<float*> channelListFloat;
  2193. Array<double*> channelListDouble;
  2194. AudioBuffer<float> emptyBufferFloat;
  2195. AudioBuffer<double> emptyBufferDouble;
  2196. #if JucePlugin_WantsMidiInput
  2197. bool isMidiInputBusEnabled = true;
  2198. #else
  2199. bool isMidiInputBusEnabled = false;
  2200. #endif
  2201. #if JucePlugin_ProducesMidiOutput
  2202. bool isMidiOutputBusEnabled = true;
  2203. #else
  2204. bool isMidiOutputBusEnabled = false;
  2205. #endif
  2206. static const char* kJucePrivateDataIdentifier;
  2207. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2208. };
  2209. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2210. //==============================================================================
  2211. #if JUCE_MSVC
  2212. #pragma warning (push, 0)
  2213. #pragma warning (disable: 4310)
  2214. #elif JUCE_CLANG
  2215. #pragma clang diagnostic push
  2216. #pragma clang diagnostic ignored "-Wall"
  2217. #endif
  2218. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2219. DEF_CLASS_IID (JuceAudioProcessor)
  2220. #if JUCE_VST3_CAN_REPLACE_VST2
  2221. FUID getFUIDForVST2ID (bool forControllerUID)
  2222. {
  2223. TUID uuid;
  2224. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  2225. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2226. return FUID (uuid);
  2227. }
  2228. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2229. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2230. #else
  2231. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2232. DEF_CLASS_IID (JuceVST3EditController)
  2233. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2234. DEF_CLASS_IID (JuceVST3Component)
  2235. #endif
  2236. #if JUCE_MSVC
  2237. #pragma warning (pop)
  2238. #elif JUCE_CLANG
  2239. #pragma clang diagnostic pop
  2240. #endif
  2241. //==============================================================================
  2242. bool initModule()
  2243. {
  2244. #if JUCE_MAC
  2245. initialiseMacVST();
  2246. #endif
  2247. return true;
  2248. }
  2249. bool shutdownModule()
  2250. {
  2251. return true;
  2252. }
  2253. #undef JUCE_EXPORTED_FUNCTION
  2254. #if JUCE_WINDOWS
  2255. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2256. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2257. #define JUCE_EXPORTED_FUNCTION
  2258. #else
  2259. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  2260. CFBundleRef globalBundleInstance = nullptr;
  2261. juce::uint32 numBundleRefs = 0;
  2262. juce::Array<CFBundleRef> bundleRefs;
  2263. enum { MaxPathLength = 2048 };
  2264. char modulePath[MaxPathLength] = { 0 };
  2265. void* moduleHandle = nullptr;
  2266. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  2267. {
  2268. if (ref != nullptr)
  2269. {
  2270. ++numBundleRefs;
  2271. CFRetain (ref);
  2272. bundleRefs.add (ref);
  2273. if (moduleHandle == nullptr)
  2274. {
  2275. globalBundleInstance = ref;
  2276. moduleHandle = ref;
  2277. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  2278. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  2279. CFRelease (tempURL);
  2280. }
  2281. }
  2282. return initModule();
  2283. }
  2284. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2285. {
  2286. if (shutdownModule())
  2287. {
  2288. if (--numBundleRefs == 0)
  2289. {
  2290. for (int i = 0; i < bundleRefs.size(); ++i)
  2291. CFRelease (bundleRefs.getUnchecked (i));
  2292. bundleRefs.clear();
  2293. }
  2294. return true;
  2295. }
  2296. return false;
  2297. }
  2298. #endif
  2299. //==============================================================================
  2300. /** This typedef represents VST3's createInstance() function signature */
  2301. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2302. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2303. {
  2304. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2305. }
  2306. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2307. {
  2308. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2309. }
  2310. //==============================================================================
  2311. struct JucePluginFactory;
  2312. static JucePluginFactory* globalFactory = nullptr;
  2313. //==============================================================================
  2314. struct JucePluginFactory : public IPluginFactory3
  2315. {
  2316. JucePluginFactory()
  2317. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2318. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2319. {
  2320. }
  2321. virtual ~JucePluginFactory()
  2322. {
  2323. if (globalFactory == this)
  2324. globalFactory = nullptr;
  2325. }
  2326. //==============================================================================
  2327. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2328. {
  2329. if (createFunction == nullptr)
  2330. {
  2331. jassertfalse;
  2332. return false;
  2333. }
  2334. auto entry = std::make_unique<ClassEntry> (info, createFunction);
  2335. entry->infoW.fromAscii (info);
  2336. classes.push_back (std::move (entry));
  2337. return true;
  2338. }
  2339. //==============================================================================
  2340. JUCE_DECLARE_VST3_COM_REF_METHODS
  2341. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2342. {
  2343. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2344. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2345. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2346. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2347. jassertfalse; // Something new?
  2348. *obj = nullptr;
  2349. return kNotImplemented;
  2350. }
  2351. //==============================================================================
  2352. Steinberg::int32 PLUGIN_API countClasses() override
  2353. {
  2354. return (Steinberg::int32) classes.size();
  2355. }
  2356. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2357. {
  2358. if (info == nullptr)
  2359. return kInvalidArgument;
  2360. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2361. return kResultOk;
  2362. }
  2363. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2364. {
  2365. return getPClassInfo<PClassInfo> (index, info);
  2366. }
  2367. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2368. {
  2369. return getPClassInfo<PClassInfo2> (index, info);
  2370. }
  2371. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2372. {
  2373. if (info != nullptr)
  2374. {
  2375. if (auto& entry = classes[(size_t) index])
  2376. {
  2377. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2378. return kResultOk;
  2379. }
  2380. }
  2381. return kInvalidArgument;
  2382. }
  2383. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2384. {
  2385. ScopedJuceInitialiser_GUI libraryInitialiser;
  2386. *obj = nullptr;
  2387. TUID tuid;
  2388. memcpy (tuid, sourceIid, sizeof (TUID));
  2389. #if VST_VERSION >= 0x030608
  2390. auto sourceFuid = FUID::fromTUID (tuid);
  2391. #else
  2392. FUID sourceFuid;
  2393. sourceFuid = tuid;
  2394. #endif
  2395. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2396. {
  2397. jassertfalse; // The host you're running in has severe implementation issues!
  2398. return kInvalidArgument;
  2399. }
  2400. TUID iidToQuery;
  2401. sourceFuid.toTUID (iidToQuery);
  2402. for (auto& entry : classes)
  2403. {
  2404. if (doUIDsMatch (entry->infoW.cid, cid))
  2405. {
  2406. if (auto* instance = entry->createFunction (host))
  2407. {
  2408. const FReleaser releaser (instance);
  2409. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2410. return kResultOk;
  2411. }
  2412. break;
  2413. }
  2414. }
  2415. return kNoInterface;
  2416. }
  2417. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2418. {
  2419. host.loadFrom (context);
  2420. if (host != nullptr)
  2421. {
  2422. Vst::String128 name;
  2423. host->getName (name);
  2424. return kResultTrue;
  2425. }
  2426. return kNotImplemented;
  2427. }
  2428. private:
  2429. //==============================================================================
  2430. Atomic<int> refCount { 1 };
  2431. const PFactoryInfo factoryInfo;
  2432. ComSmartPtr<Vst::IHostApplication> host;
  2433. //==============================================================================
  2434. struct ClassEntry
  2435. {
  2436. ClassEntry() noexcept {}
  2437. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2438. : info2 (info), createFunction (fn) {}
  2439. PClassInfo2 info2;
  2440. PClassInfoW infoW;
  2441. CreateFunction createFunction = {};
  2442. bool isUnicode = false;
  2443. private:
  2444. JUCE_DECLARE_NON_COPYABLE (ClassEntry)
  2445. };
  2446. std::vector<std::unique_ptr<ClassEntry>> classes;
  2447. //==============================================================================
  2448. template<class PClassInfoType>
  2449. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2450. {
  2451. if (info != nullptr)
  2452. {
  2453. zerostruct (*info);
  2454. if (auto& entry = classes[(size_t) index])
  2455. {
  2456. if (entry->isUnicode)
  2457. return kResultFalse;
  2458. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2459. return kResultOk;
  2460. }
  2461. }
  2462. jassertfalse;
  2463. return kInvalidArgument;
  2464. }
  2465. //==============================================================================
  2466. // no leak detector here to prevent it firing on shutdown when running in hosts that
  2467. // don't release the factory object correctly...
  2468. JUCE_DECLARE_NON_COPYABLE (JucePluginFactory)
  2469. };
  2470. } // juce namespace
  2471. //==============================================================================
  2472. #ifndef JucePlugin_Vst3ComponentFlags
  2473. #if JucePlugin_IsSynth
  2474. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2475. #else
  2476. #define JucePlugin_Vst3ComponentFlags 0
  2477. #endif
  2478. #endif
  2479. #ifndef JucePlugin_Vst3Category
  2480. #if JucePlugin_IsSynth
  2481. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2482. #else
  2483. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2484. #endif
  2485. #endif
  2486. using namespace juce;
  2487. //==============================================================================
  2488. // The VST3 plugin entry point.
  2489. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2490. {
  2491. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2492. #if JUCE_WINDOWS
  2493. // Cunning trick to force this function to be exported. Life's too short to
  2494. // faff around creating .def files for this kind of thing.
  2495. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2496. #endif
  2497. if (globalFactory == nullptr)
  2498. {
  2499. globalFactory = new JucePluginFactory();
  2500. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2501. PClassInfo::kManyInstances,
  2502. kVstAudioEffectClass,
  2503. JucePlugin_Name,
  2504. JucePlugin_Vst3ComponentFlags,
  2505. JucePlugin_Vst3Category,
  2506. JucePlugin_Manufacturer,
  2507. JucePlugin_VersionString,
  2508. kVstVersionString);
  2509. globalFactory->registerClass (componentClass, createComponentInstance);
  2510. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2511. PClassInfo::kManyInstances,
  2512. kVstComponentControllerClass,
  2513. JucePlugin_Name,
  2514. JucePlugin_Vst3ComponentFlags,
  2515. JucePlugin_Vst3Category,
  2516. JucePlugin_Manufacturer,
  2517. JucePlugin_VersionString,
  2518. kVstVersionString);
  2519. globalFactory->registerClass (controllerClass, createControllerInstance);
  2520. }
  2521. else
  2522. {
  2523. globalFactory->addRef();
  2524. }
  2525. return dynamic_cast<IPluginFactory*> (globalFactory);
  2526. }
  2527. //==============================================================================
  2528. #if _MSC_VER || JUCE_MINGW
  2529. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2530. #endif
  2531. #endif //JucePlugin_Build_VST3