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.

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