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.

2904 lines
106KB

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