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.

2960 lines
108KB

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