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.

2915 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. #if ! JUCE_MAC
  674. setContentScaleFactor ((Steinberg::IPlugViewContentScaleSupport::ScaleFactor) scaleFactor);
  675. #endif
  676. component->resizeHostWindow();
  677. systemWindow = parent;
  678. attachedToParent();
  679. // Life's too short to faff around with wave lab
  680. if (getHostType().isWavelab())
  681. startTimer (200);
  682. return kResultTrue;
  683. }
  684. tresult PLUGIN_API removed() override
  685. {
  686. if (component != nullptr)
  687. {
  688. #if JUCE_WINDOWS
  689. component->removeFromDesktop();
  690. #else
  691. if (macHostWindow != nullptr)
  692. {
  693. juce::detachComponentFromWindowRefVST (component.get(), macHostWindow, isNSView);
  694. macHostWindow = nullptr;
  695. }
  696. #endif
  697. component = nullptr;
  698. }
  699. return CPluginView::removed();
  700. }
  701. tresult PLUGIN_API onSize (ViewRect* newSize) override
  702. {
  703. if (newSize != nullptr)
  704. {
  705. rect = *newSize;
  706. if (component != nullptr)
  707. {
  708. auto scale = component->getNativeEditorScaleFactor();
  709. component->setSize (roundToInt (rect.getWidth() / scale),
  710. roundToInt (rect.getHeight() / scale));
  711. if (auto* peer = component->getPeer())
  712. peer->updateBounds();
  713. }
  714. return kResultTrue;
  715. }
  716. jassertfalse;
  717. return kResultFalse;
  718. }
  719. tresult PLUGIN_API getSize (ViewRect* size) override
  720. {
  721. if (size != nullptr && component != nullptr)
  722. {
  723. auto scale = component->getNativeEditorScaleFactor();
  724. *size = ViewRect (0, 0,
  725. roundToInt (component->getWidth() * scale),
  726. roundToInt (component->getHeight() * scale));
  727. return kResultTrue;
  728. }
  729. return kResultFalse;
  730. }
  731. tresult PLUGIN_API canResize() override
  732. {
  733. if (component != nullptr)
  734. if (auto* editor = component->pluginEditor.get())
  735. return editor->isResizable() ? kResultTrue : kResultFalse;
  736. return kResultFalse;
  737. }
  738. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  739. {
  740. if (rectToCheck != nullptr && component != nullptr)
  741. {
  742. if (auto* editor = component->pluginEditor.get())
  743. {
  744. // checkSizeConstraint
  745. auto scale = component->getNativeEditorScaleFactor();
  746. auto scaledRect = (Rectangle<int>::leftTopRightBottom (rectToCheck->left, rectToCheck->top,
  747. rectToCheck->right, rectToCheck->bottom).toFloat() / scale).toNearestInt();
  748. auto juceRect = editor->getLocalArea (component.get(), scaledRect);
  749. if (auto* constrainer = editor->getConstrainer())
  750. {
  751. Rectangle<int> limits (0, 0, constrainer->getMaximumWidth(), constrainer->getMaximumHeight());
  752. constrainer->checkBounds (juceRect, editor->getBounds(), limits, false, false, false, false);
  753. juceRect = component->getLocalArea (editor, juceRect);
  754. rectToCheck->right = rectToCheck->left + roundToInt (juceRect.getWidth() * scale);
  755. rectToCheck->bottom = rectToCheck->top + roundToInt (juceRect.getHeight() * scale);
  756. }
  757. }
  758. return kResultTrue;
  759. }
  760. jassertfalse;
  761. return kResultFalse;
  762. }
  763. tresult PLUGIN_API setContentScaleFactor (Steinberg::IPlugViewContentScaleSupport::ScaleFactor factor) override
  764. {
  765. #if ! JUCE_MAC
  766. scaleFactor = static_cast<float> (factor);
  767. if (component == nullptr)
  768. return kResultFalse;
  769. #if JUCE_WINDOWS && ! JUCE_WIN_PER_MONITOR_DPI_AWARE
  770. if (auto* ed = component->pluginEditor.get())
  771. ed->setScaleFactor (scaleFactor);
  772. #else
  773. if (! approximatelyEqual (component->getNativeEditorScaleFactor(), scaleFactor))
  774. component->nativeScaleFactorChanged ((double) scaleFactor);
  775. #endif
  776. component->resizeHostWindow();
  777. return kResultTrue;
  778. #else
  779. ignoreUnused (factor);
  780. return kResultFalse;
  781. #endif
  782. }
  783. private:
  784. void timerCallback() override
  785. {
  786. stopTimer();
  787. ViewRect viewRect;
  788. getSize (&viewRect);
  789. onSize (&viewRect);
  790. }
  791. //==============================================================================
  792. struct ContentWrapperComponent : public Component
  793. #if ! JUCE_MAC
  794. , public ComponentPeer::ScaleFactorListener,
  795. public ComponentMovementWatcher
  796. #endif
  797. {
  798. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  799. :
  800. #if ! JUCE_MAC
  801. ComponentMovementWatcher (this),
  802. #endif
  803. pluginEditor (plugin.createEditorIfNeeded()),
  804. owner (editor)
  805. {
  806. setOpaque (true);
  807. setBroughtToFrontOnMouseClick (true);
  808. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  809. jassert (pluginEditor != nullptr);
  810. if (pluginEditor != nullptr)
  811. {
  812. addAndMakeVisible (pluginEditor.get());
  813. pluginEditor->setTopLeftPosition (0, 0);
  814. lastBounds = getSizeToContainChild();
  815. isResizingParentToFitChild = true;
  816. setBounds (lastBounds);
  817. isResizingParentToFitChild = false;
  818. resizeHostWindow();
  819. }
  820. ignoreUnused (fakeMouseGenerator);
  821. }
  822. ~ContentWrapperComponent()
  823. {
  824. if (pluginEditor != nullptr)
  825. {
  826. PopupMenu::dismissAllActiveMenus();
  827. pluginEditor->processor.editorBeingDeleted (pluginEditor.get());
  828. }
  829. #if ! JUCE_MAC
  830. for (int i = 0; i < ComponentPeer::getNumPeers(); ++i)
  831. if (auto* p = ComponentPeer::getPeer (i))
  832. p->removeScaleFactorListener (this);
  833. #endif
  834. }
  835. void paint (Graphics& g) override
  836. {
  837. g.fillAll (Colours::black);
  838. }
  839. juce::Rectangle<int> getSizeToContainChild()
  840. {
  841. if (pluginEditor != nullptr)
  842. return getLocalArea (pluginEditor.get(), pluginEditor->getLocalBounds());
  843. return {};
  844. }
  845. void childBoundsChanged (Component*) override
  846. {
  847. if (isResizingChildToFitParent)
  848. return;
  849. auto b = getSizeToContainChild();
  850. if (lastBounds != b)
  851. {
  852. lastBounds = b;
  853. isResizingParentToFitChild = true;
  854. resizeHostWindow();
  855. isResizingParentToFitChild = false;
  856. }
  857. }
  858. void resized() override
  859. {
  860. if (pluginEditor != nullptr)
  861. {
  862. if (! isResizingParentToFitChild)
  863. {
  864. lastBounds = getLocalBounds();
  865. isResizingChildToFitParent = true;
  866. if (auto* constrainer = pluginEditor->getConstrainer())
  867. {
  868. auto aspectRatio = constrainer->getFixedAspectRatio();
  869. auto width = (double) lastBounds.getWidth();
  870. auto height = (double) lastBounds.getHeight();
  871. if (aspectRatio != 0)
  872. {
  873. if (width / height > aspectRatio)
  874. setBounds ({ 0, 0, roundToInt (height * aspectRatio), lastBounds.getHeight() });
  875. else
  876. setBounds ({ 0, 0, lastBounds.getWidth(), roundToInt (width / aspectRatio) });
  877. }
  878. }
  879. pluginEditor->setTopLeftPosition (0, 0);
  880. pluginEditor->setBounds (pluginEditor->getLocalArea (this, getLocalBounds()));
  881. isResizingChildToFitParent = false;
  882. }
  883. }
  884. }
  885. void resizeHostWindow()
  886. {
  887. if (pluginEditor != nullptr)
  888. {
  889. auto b = getSizeToContainChild();
  890. auto w = b.getWidth();
  891. auto h = b.getHeight();
  892. auto host = getHostType();
  893. #if JUCE_WINDOWS
  894. setSize (w, h);
  895. #else
  896. if (owner.macHostWindow != nullptr && ! (host.isWavelab() || host.isReaper() || host.isBitwigStudio()))
  897. juce::setNativeHostWindowSizeVST (owner.macHostWindow, this, w, h, owner.isNSView);
  898. #endif
  899. if (owner.plugFrame != nullptr)
  900. {
  901. ViewRect newSize (0, 0, roundToInt (w * nativeScaleFactor), roundToInt (h * nativeScaleFactor));
  902. isResizingParentToFitChild = true;
  903. owner.plugFrame->resizeView (&owner, &newSize);
  904. isResizingParentToFitChild = false;
  905. #if JUCE_MAC
  906. if (host.isWavelab() || host.isReaper())
  907. #else
  908. if (host.isWavelab())
  909. #endif
  910. setBounds (0, 0, w, h);
  911. }
  912. }
  913. }
  914. float getNativeEditorScaleFactor() const noexcept { return nativeScaleFactor; }
  915. #if ! JUCE_MAC
  916. void componentMovedOrResized (bool, bool) override {}
  917. void componentPeerChanged() override
  918. {
  919. if (auto* peer = getTopLevelComponent()->getPeer())
  920. peer->addScaleFactorListener (this);
  921. }
  922. void componentVisibilityChanged() override
  923. {
  924. if (auto* peer = getTopLevelComponent()->getPeer())
  925. nativeScaleFactor = (float) peer->getPlatformScaleFactor();
  926. }
  927. void nativeScaleFactorChanged (double newScaleFactor) override
  928. {
  929. nativeScaleFactor = (float) newScaleFactor;
  930. auto host = getHostType();
  931. if (host.isWavelab())
  932. {
  933. Timer::callAfterDelay (250, [this] {
  934. if (auto* peer = getPeer())
  935. {
  936. peer->updateBounds();
  937. repaint();
  938. }
  939. resizeHostWindow();
  940. });
  941. }
  942. else if (host.isBitwigStudio())
  943. {
  944. resizeHostWindow();
  945. setTopLeftPosition (0, 0);
  946. }
  947. }
  948. #endif
  949. std::unique_ptr<AudioProcessorEditor> pluginEditor;
  950. private:
  951. JuceVST3Editor& owner;
  952. FakeMouseMoveGenerator fakeMouseGenerator;
  953. Rectangle<int> lastBounds;
  954. bool isResizingChildToFitParent = false;
  955. bool isResizingParentToFitChild = false;
  956. float nativeScaleFactor = 1.0f;
  957. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  958. };
  959. //==============================================================================
  960. ComSmartPtr<JuceVST3EditController> owner;
  961. AudioProcessor& pluginInstance;
  962. std::unique_ptr<ContentWrapperComponent> component;
  963. friend struct ContentWrapperComponent;
  964. #if JUCE_MAC
  965. void* macHostWindow = nullptr;
  966. bool isNSView = false;
  967. #else
  968. float scaleFactor = 1.0f;
  969. #endif
  970. #if JUCE_WINDOWS
  971. WindowsHooks hooks;
  972. #endif
  973. ScopedJuceInitialiser_GUI libraryInitialiser;
  974. //==============================================================================
  975. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  976. };
  977. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  978. };
  979. namespace
  980. {
  981. template <typename FloatType> struct AudioBusPointerHelper {};
  982. template <> struct AudioBusPointerHelper<float> { static inline float** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers32; } };
  983. template <> struct AudioBusPointerHelper<double> { static inline double** impl (Vst::AudioBusBuffers& data) noexcept { return data.channelBuffers64; } };
  984. template <typename FloatType> struct ChooseBufferHelper {};
  985. template <> struct ChooseBufferHelper<float> { static inline AudioBuffer<float>& impl (AudioBuffer<float>& f, AudioBuffer<double>& ) noexcept { return f; } };
  986. template <> struct ChooseBufferHelper<double> { static inline AudioBuffer<double>& impl (AudioBuffer<float>& , AudioBuffer<double>& d) noexcept { return d; } };
  987. }
  988. //==============================================================================
  989. class JuceVST3Component : public Vst::IComponent,
  990. public Vst::IAudioProcessor,
  991. public Vst::IUnitInfo,
  992. public Vst::IConnectionPoint,
  993. public AudioPlayHead
  994. {
  995. public:
  996. JuceVST3Component (Vst::IHostApplication* h)
  997. : pluginInstance (createPluginFilterOfType (AudioProcessor::wrapperType_VST3)),
  998. host (h)
  999. {
  1000. inParameterChangedCallback = false;
  1001. #ifdef JucePlugin_PreferredChannelConfigurations
  1002. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1003. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1004. jassert (numConfigs > 0 && (configs[0][0] > 0 || configs[0][1] > 0));
  1005. pluginInstance->setPlayConfigDetails (configs[0][0], configs[0][1], 44100.0, 1024);
  1006. #endif
  1007. // VST-3 requires your default layout to be non-discrete!
  1008. // For example, your default layout must be mono, stereo, quadrophonic
  1009. // and not AudioChannelSet::discreteChannels (2) etc.
  1010. jassert (checkBusFormatsAreNotDiscrete());
  1011. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  1012. zerostruct (processContext);
  1013. processSetup.maxSamplesPerBlock = 1024;
  1014. processSetup.processMode = Vst::kRealtime;
  1015. processSetup.sampleRate = 44100.0;
  1016. processSetup.symbolicSampleSize = Vst::kSample32;
  1017. pluginInstance->setPlayHead (this);
  1018. }
  1019. ~JuceVST3Component()
  1020. {
  1021. if (juceVST3EditController != nullptr)
  1022. juceVST3EditController->vst3IsPlaying = 0;
  1023. if (pluginInstance != nullptr)
  1024. if (pluginInstance->getPlayHead() == this)
  1025. pluginInstance->setPlayHead (nullptr);
  1026. }
  1027. //==============================================================================
  1028. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  1029. //==============================================================================
  1030. static const FUID iid;
  1031. JUCE_DECLARE_VST3_COM_REF_METHODS
  1032. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1033. {
  1034. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  1035. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  1036. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  1037. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  1038. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  1039. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  1040. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  1041. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  1042. {
  1043. comPluginInstance->addRef();
  1044. *obj = comPluginInstance;
  1045. return kResultOk;
  1046. }
  1047. *obj = nullptr;
  1048. return kNoInterface;
  1049. }
  1050. //==============================================================================
  1051. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  1052. {
  1053. if (host != hostContext)
  1054. host.loadFrom (hostContext);
  1055. processContext.sampleRate = processSetup.sampleRate;
  1056. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  1057. return kResultTrue;
  1058. }
  1059. tresult PLUGIN_API terminate() override
  1060. {
  1061. getPluginInstance().releaseResources();
  1062. return kResultTrue;
  1063. }
  1064. //==============================================================================
  1065. tresult PLUGIN_API connect (IConnectionPoint* other) override
  1066. {
  1067. if (other != nullptr && juceVST3EditController == nullptr)
  1068. juceVST3EditController.loadFrom (other);
  1069. return kResultTrue;
  1070. }
  1071. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  1072. {
  1073. if (juceVST3EditController != nullptr)
  1074. juceVST3EditController->vst3IsPlaying = 0;
  1075. juceVST3EditController = nullptr;
  1076. return kResultTrue;
  1077. }
  1078. tresult PLUGIN_API notify (Vst::IMessage* message) override
  1079. {
  1080. if (message != nullptr && juceVST3EditController == nullptr)
  1081. {
  1082. Steinberg::int64 value = 0;
  1083. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  1084. {
  1085. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  1086. if (juceVST3EditController != nullptr)
  1087. juceVST3EditController->setAudioProcessor (comPluginInstance);
  1088. else
  1089. jassertfalse;
  1090. }
  1091. }
  1092. return kResultTrue;
  1093. }
  1094. tresult PLUGIN_API getControllerClassId (TUID classID) override
  1095. {
  1096. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  1097. return kResultTrue;
  1098. }
  1099. //==============================================================================
  1100. tresult PLUGIN_API setActive (TBool state) override
  1101. {
  1102. if (! state)
  1103. {
  1104. getPluginInstance().releaseResources();
  1105. deallocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1106. deallocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1107. }
  1108. else
  1109. {
  1110. auto sampleRate = getPluginInstance().getSampleRate();
  1111. auto bufferSize = getPluginInstance().getBlockSize();
  1112. sampleRate = processSetup.sampleRate > 0.0
  1113. ? processSetup.sampleRate
  1114. : sampleRate;
  1115. bufferSize = processSetup.maxSamplesPerBlock > 0
  1116. ? (int) processSetup.maxSamplesPerBlock
  1117. : bufferSize;
  1118. allocateChannelListAndBuffers (channelListFloat, emptyBufferFloat);
  1119. allocateChannelListAndBuffers (channelListDouble, emptyBufferDouble);
  1120. preparePlugin (sampleRate, bufferSize);
  1121. }
  1122. return kResultOk;
  1123. }
  1124. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  1125. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  1126. //==============================================================================
  1127. bool isBypassed()
  1128. {
  1129. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1130. return (bypassParam->getValue() != 0.0f);
  1131. return false;
  1132. }
  1133. void setBypassed (bool shouldBeBypassed)
  1134. {
  1135. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1136. {
  1137. auto floatValue = (shouldBeBypassed ? 1.0f : 0.0f);
  1138. bypassParam->setValue (floatValue);
  1139. inParameterChangedCallback = true;
  1140. bypassParam->sendValueChangedMessageToListeners (floatValue);
  1141. }
  1142. }
  1143. //==============================================================================
  1144. void writeJucePrivateStateInformation (MemoryOutputStream& out)
  1145. {
  1146. if (pluginInstance->getBypassParameter() == nullptr)
  1147. {
  1148. ValueTree privateData (kJucePrivateDataIdentifier);
  1149. // for now we only store the bypass value
  1150. privateData.setProperty ("Bypass", var (isBypassed()), nullptr);
  1151. privateData.writeToStream (out);
  1152. }
  1153. }
  1154. void setJucePrivateStateInformation (const void* data, int sizeInBytes)
  1155. {
  1156. if (pluginInstance->getBypassParameter() == nullptr)
  1157. {
  1158. if (auto* bypassParam = comPluginInstance->getBypassParameter())
  1159. {
  1160. auto privateData = ValueTree::readFromData (data, static_cast<size_t> (sizeInBytes));
  1161. setBypassed (static_cast<bool> (privateData.getProperty ("Bypass", var (false))));
  1162. }
  1163. }
  1164. }
  1165. void getStateInformation (MemoryBlock& destData)
  1166. {
  1167. pluginInstance->getStateInformation (destData);
  1168. // With bypass support, JUCE now needs to store private state data.
  1169. // Put this at the end of the plug-in state and add a few null characters
  1170. // so that plug-ins built with older versions of JUCE will hopefully ignore
  1171. // this data. Additionally, we need to add some sort of magic identifier
  1172. // at the very end of the private data so that JUCE has some sort of
  1173. // way to figure out if the data was stored with a newer JUCE version.
  1174. MemoryOutputStream extraData;
  1175. extraData.writeInt64 (0);
  1176. writeJucePrivateStateInformation (extraData);
  1177. auto privateDataSize = (int64) (extraData.getDataSize() - sizeof (int64));
  1178. extraData.writeInt64 (privateDataSize);
  1179. extraData << kJucePrivateDataIdentifier;
  1180. // write magic string
  1181. destData.append (extraData.getData(), extraData.getDataSize());
  1182. }
  1183. void setStateInformation (const void* data, int sizeAsInt)
  1184. {
  1185. int64 size = sizeAsInt;
  1186. // Check if this data was written with a newer JUCE version
  1187. // and if it has the JUCE private data magic code at the end
  1188. auto jucePrivDataIdentifierSize = std::strlen (kJucePrivateDataIdentifier);
  1189. if ((size_t) size >= jucePrivDataIdentifierSize + sizeof (int64))
  1190. {
  1191. auto buffer = static_cast<const char*> (data);
  1192. String magic (CharPointer_UTF8 (buffer + size - jucePrivDataIdentifierSize),
  1193. CharPointer_UTF8 (buffer + size));
  1194. if (magic == kJucePrivateDataIdentifier)
  1195. {
  1196. // found a JUCE private data section
  1197. uint64 privateDataSize;
  1198. std::memcpy (&privateDataSize,
  1199. buffer + ((size_t) size - jucePrivDataIdentifierSize - sizeof (uint64)),
  1200. sizeof (uint64));
  1201. privateDataSize = ByteOrder::swapIfBigEndian (privateDataSize);
  1202. size -= privateDataSize + jucePrivDataIdentifierSize + sizeof (uint64);
  1203. if (privateDataSize > 0)
  1204. setJucePrivateStateInformation (buffer + size, static_cast<int> (privateDataSize));
  1205. size -= sizeof (uint64);
  1206. }
  1207. }
  1208. if (size >= 0)
  1209. pluginInstance->setStateInformation (data, static_cast<int> (size));
  1210. }
  1211. //==============================================================================
  1212. #if JUCE_VST3_CAN_REPLACE_VST2
  1213. bool loadVST2VstWBlock (const char* data, int size)
  1214. {
  1215. jassert ('VstW' == htonl (*(juce::int32*) data));
  1216. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  1217. auto headerLen = (int) htonl (*(juce::int32*) (data + 4)) + 8;
  1218. return loadVST2CcnKBlock (data + headerLen, size - headerLen);
  1219. }
  1220. bool loadVST2CcnKBlock (const char* data, int size)
  1221. {
  1222. auto bank = (const Vst2::fxBank*) data;
  1223. jassert ('CcnK' == htonl (bank->chunkMagic));
  1224. jassert ('FBCh' == htonl (bank->fxMagic));
  1225. jassert (htonl (bank->version) == 1 || htonl (bank->version) == 2);
  1226. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1227. setStateInformation (bank->content.data.chunk,
  1228. jmin ((int) (size - (bank->content.data.chunk - data)),
  1229. (int) htonl (bank->content.data.size)));
  1230. return true;
  1231. }
  1232. bool loadVST3PresetFile (const char* data, int size)
  1233. {
  1234. if (size < 48)
  1235. return false;
  1236. // At offset 4 there's a little-endian version number which seems to typically be 1
  1237. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  1238. auto chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  1239. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  1240. auto entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  1241. jassert (entryCount > 0);
  1242. for (int i = 0; i < entryCount; ++i)
  1243. {
  1244. auto entryOffset = chunkListOffset + 8 + 20 * i;
  1245. if (entryOffset + 20 > size)
  1246. return false;
  1247. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  1248. {
  1249. // "Comp" entries seem to contain the data.
  1250. auto chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  1251. auto chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  1252. if (chunkOffset + chunkSize > static_cast<juce::uint64> (size))
  1253. {
  1254. jassertfalse;
  1255. return false;
  1256. }
  1257. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  1258. }
  1259. }
  1260. return true;
  1261. }
  1262. bool loadVST2CompatibleState (const char* data, int size)
  1263. {
  1264. if (size < 4)
  1265. return false;
  1266. auto header = htonl (*(juce::int32*) data);
  1267. if (header == 'VstW')
  1268. return loadVST2VstWBlock (data, size);
  1269. if (header == 'CcnK')
  1270. return loadVST2CcnKBlock (data, size);
  1271. if (memcmp (data, "VST3", 4) == 0)
  1272. {
  1273. // In Cubase 5, when loading VST3 .vstpreset files,
  1274. // we get the whole content of the files to load.
  1275. // In Cubase 7 we get just the contents within and
  1276. // we go directly to the loadVST2VstW codepath instead.
  1277. return loadVST3PresetFile (data, size);
  1278. }
  1279. return false;
  1280. }
  1281. #endif
  1282. bool loadStateData (const void* data, int size)
  1283. {
  1284. #if JUCE_VST3_CAN_REPLACE_VST2
  1285. return loadVST2CompatibleState ((const char*) data, size);
  1286. #else
  1287. setStateInformation (data, size);
  1288. return true;
  1289. #endif
  1290. }
  1291. bool readFromMemoryStream (IBStream* state)
  1292. {
  1293. FUnknownPtr<ISizeableStream> s (state);
  1294. Steinberg::int64 size = 0;
  1295. if (s != nullptr
  1296. && s->getStreamSize (size) == kResultOk
  1297. && size > 0
  1298. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1299. {
  1300. MemoryBlock block (static_cast<size_t> (size));
  1301. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1302. Steinberg::int32 bytesRead = 1;
  1303. int len;
  1304. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1305. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1306. break;
  1307. if (len == 0)
  1308. return false;
  1309. block.setSize (static_cast<size_t> (len));
  1310. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1311. if (getHostType().isAdobeAudition())
  1312. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1313. return false;
  1314. return loadStateData (block.getData(), (int) block.getSize());
  1315. }
  1316. return false;
  1317. }
  1318. bool readFromUnknownStream (IBStream* state)
  1319. {
  1320. MemoryOutputStream allData;
  1321. {
  1322. const size_t bytesPerBlock = 4096;
  1323. HeapBlock<char> buffer (bytesPerBlock);
  1324. for (;;)
  1325. {
  1326. Steinberg::int32 bytesRead = 0;
  1327. auto status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1328. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1329. break;
  1330. allData.write (buffer, static_cast<size_t> (bytesRead));
  1331. }
  1332. }
  1333. const size_t dataSize = allData.getDataSize();
  1334. return dataSize > 0 && dataSize < 0x7fffffff
  1335. && loadStateData (allData.getData(), (int) dataSize);
  1336. }
  1337. tresult PLUGIN_API setState (IBStream* state) override
  1338. {
  1339. if (state == nullptr)
  1340. return kInvalidArgument;
  1341. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1342. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1343. {
  1344. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1345. return kResultTrue;
  1346. if (readFromUnknownStream (state))
  1347. return kResultTrue;
  1348. }
  1349. return kResultFalse;
  1350. }
  1351. #if JUCE_VST3_CAN_REPLACE_VST2
  1352. static tresult writeVST2Int (IBStream* state, int n)
  1353. {
  1354. juce::int32 t = (juce::int32) htonl (n);
  1355. return state->write (&t, 4);
  1356. }
  1357. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1358. {
  1359. tresult status = writeVST2Int (state, 'VstW');
  1360. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1361. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1362. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1363. return status;
  1364. }
  1365. #endif
  1366. tresult PLUGIN_API getState (IBStream* state) override
  1367. {
  1368. if (state == nullptr)
  1369. return kInvalidArgument;
  1370. juce::MemoryBlock mem;
  1371. getStateInformation (mem);
  1372. #if JUCE_VST3_CAN_REPLACE_VST2
  1373. tresult status = writeVST2Header (state, isBypassed());
  1374. if (status != kResultOk)
  1375. return status;
  1376. const int bankBlockSize = 160;
  1377. Vst2::fxBank bank;
  1378. zerostruct (bank);
  1379. bank.chunkMagic = (int32) htonl ('CcnK');
  1380. bank.byteSize = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1381. bank.fxMagic = (int32) htonl ('FBCh');
  1382. bank.version = (int32) htonl (2);
  1383. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1384. bank.fxVersion = (int32) htonl (JucePlugin_VersionCode);
  1385. bank.content.data.size = (int32) htonl ((unsigned int) mem.getSize());
  1386. status = state->write (&bank, bankBlockSize);
  1387. if (status != kResultOk)
  1388. return status;
  1389. #endif
  1390. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1391. }
  1392. //==============================================================================
  1393. Steinberg::int32 PLUGIN_API getUnitCount() override
  1394. {
  1395. return 1;
  1396. }
  1397. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  1398. {
  1399. if (unitIndex == 0)
  1400. {
  1401. info.id = Vst::kRootUnitId;
  1402. info.parentUnitId = Vst::kNoParentUnitId;
  1403. info.programListId = Vst::kNoProgramListId;
  1404. toString128 (info.name, TRANS("Root Unit"));
  1405. return kResultTrue;
  1406. }
  1407. zerostruct (info);
  1408. return kResultFalse;
  1409. }
  1410. Steinberg::int32 PLUGIN_API getProgramListCount() override
  1411. {
  1412. if (getPluginInstance().getNumPrograms() > 0)
  1413. return 1;
  1414. return 0;
  1415. }
  1416. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  1417. {
  1418. if (listIndex == 0)
  1419. {
  1420. info.id = JuceVST3EditController::paramPreset;
  1421. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1422. toString128 (info.name, TRANS("Factory Presets"));
  1423. return kResultTrue;
  1424. }
  1425. jassertfalse;
  1426. zerostruct (info);
  1427. return kResultFalse;
  1428. }
  1429. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1430. {
  1431. if (listId == JuceVST3EditController::paramPreset
  1432. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1433. {
  1434. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1435. return kResultTrue;
  1436. }
  1437. jassertfalse;
  1438. toString128 (name, juce::String());
  1439. return kResultFalse;
  1440. }
  1441. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1442. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1443. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1444. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1445. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1446. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1447. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1448. {
  1449. zerostruct (unitId);
  1450. return kNotImplemented;
  1451. }
  1452. //==============================================================================
  1453. bool getCurrentPosition (CurrentPositionInfo& info) override
  1454. {
  1455. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1456. info.timeInSeconds = static_cast<double> (info.timeInSamples) / processContext.sampleRate;
  1457. info.bpm = jmax (1.0, processContext.tempo);
  1458. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1459. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1460. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1461. info.ppqPosition = processContext.projectTimeMusic;
  1462. info.ppqLoopStart = processContext.cycleStartMusic;
  1463. info.ppqLoopEnd = processContext.cycleEndMusic;
  1464. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1465. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1466. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1467. info.editOriginTime = 0.0;
  1468. info.frameRate = AudioPlayHead::fpsUnknown;
  1469. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1470. {
  1471. switch (processContext.frameRate.framesPerSecond)
  1472. {
  1473. case 24:
  1474. {
  1475. if ((processContext.frameRate.flags & Vst::FrameRate::kPullDownRate) != 0)
  1476. info.frameRate = AudioPlayHead::fps23976;
  1477. else
  1478. info.frameRate = AudioPlayHead::fps24;
  1479. }
  1480. break;
  1481. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1482. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1483. case 30:
  1484. {
  1485. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1486. info.frameRate = AudioPlayHead::fps30drop;
  1487. else
  1488. info.frameRate = AudioPlayHead::fps30;
  1489. }
  1490. break;
  1491. default: break;
  1492. }
  1493. }
  1494. return true;
  1495. }
  1496. //==============================================================================
  1497. int getNumAudioBuses (bool isInput) const
  1498. {
  1499. int busCount = pluginInstance->getBusCount (isInput);
  1500. #ifdef JucePlugin_PreferredChannelConfigurations
  1501. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1502. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1503. bool hasOnlyZeroChannels = true;
  1504. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1505. if (configs[i][isInput ? 0 : 1] != 0)
  1506. hasOnlyZeroChannels = false;
  1507. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1508. #endif
  1509. return busCount;
  1510. }
  1511. //==============================================================================
  1512. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1513. {
  1514. if (type == Vst::kAudio)
  1515. return getNumAudioBuses (dir == Vst::kInput);
  1516. if (type == Vst::kEvent)
  1517. {
  1518. if (dir == Vst::kInput)
  1519. return isMidiInputBusEnabled ? 1 : 0;
  1520. if (dir == Vst::kOutput)
  1521. return isMidiOutputBusEnabled ? 1 : 0;
  1522. }
  1523. return 0;
  1524. }
  1525. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1526. Steinberg::int32 index, Vst::BusInfo& info) override
  1527. {
  1528. if (type == Vst::kAudio)
  1529. {
  1530. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1531. return kResultFalse;
  1532. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1533. {
  1534. info.mediaType = Vst::kAudio;
  1535. info.direction = dir;
  1536. info.channelCount = bus->getLastEnabledLayout().size();
  1537. toString128 (info.name, bus->getName());
  1538. #if JucePlugin_IsSynth
  1539. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1540. #else
  1541. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1542. #endif
  1543. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1544. return kResultTrue;
  1545. }
  1546. }
  1547. if (type == Vst::kEvent)
  1548. {
  1549. info.flags = Vst::BusInfo::kDefaultActive;
  1550. #if JucePlugin_WantsMidiInput
  1551. if (dir == Vst::kInput && index == 0)
  1552. {
  1553. info.mediaType = Vst::kEvent;
  1554. info.direction = dir;
  1555. info.channelCount = 16;
  1556. toString128 (info.name, TRANS("MIDI Input"));
  1557. info.busType = Vst::kMain;
  1558. return kResultTrue;
  1559. }
  1560. #endif
  1561. #if JucePlugin_ProducesMidiOutput
  1562. if (dir == Vst::kOutput && index == 0)
  1563. {
  1564. info.mediaType = Vst::kEvent;
  1565. info.direction = dir;
  1566. info.channelCount = 16;
  1567. toString128 (info.name, TRANS("MIDI Output"));
  1568. info.busType = Vst::kMain;
  1569. return kResultTrue;
  1570. }
  1571. #endif
  1572. }
  1573. zerostruct (info);
  1574. return kResultFalse;
  1575. }
  1576. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1577. {
  1578. if (type == Vst::kEvent)
  1579. {
  1580. if (index != 0)
  1581. return kResultFalse;
  1582. if (dir == Vst::kInput)
  1583. isMidiInputBusEnabled = (state != 0);
  1584. else
  1585. isMidiOutputBusEnabled = (state != 0);
  1586. return kResultTrue;
  1587. }
  1588. if (type == Vst::kAudio)
  1589. {
  1590. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1591. return kResultFalse;
  1592. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1593. {
  1594. #ifdef JucePlugin_PreferredChannelConfigurations
  1595. auto newLayout = pluginInstance->getBusesLayout();
  1596. auto targetLayout = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1597. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1598. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1599. auto compLayout = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1600. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1601. return kResultFalse;
  1602. #endif
  1603. return bus->enable (state != 0) ? kResultTrue : kResultFalse;
  1604. }
  1605. }
  1606. return kResultFalse;
  1607. }
  1608. bool checkBusFormatsAreNotDiscrete()
  1609. {
  1610. auto numInputBuses = pluginInstance->getBusCount (true);
  1611. auto numOutputBuses = pluginInstance->getBusCount (false);
  1612. for (int i = 0; i < numInputBuses; ++i)
  1613. {
  1614. auto layout = pluginInstance->getChannelLayoutOfBus (true, i);
  1615. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1616. return false;
  1617. }
  1618. for (int i = 0; i < numOutputBuses; ++i)
  1619. {
  1620. auto layout = pluginInstance->getChannelLayoutOfBus (false, i);
  1621. if (layout.isDiscreteLayout() && ! layout.isDisabled())
  1622. return false;
  1623. }
  1624. return true;
  1625. }
  1626. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1627. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1628. {
  1629. auto numInputBuses = pluginInstance->getBusCount (true);
  1630. auto numOutputBuses = pluginInstance->getBusCount (false);
  1631. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1632. return false;
  1633. auto requested = pluginInstance->getBusesLayout();
  1634. for (int i = 0; i < numIns; ++i)
  1635. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1636. for (int i = 0; i < numOuts; ++i)
  1637. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1638. #ifdef JucePlugin_PreferredChannelConfigurations
  1639. short configs[][2] = { JucePlugin_PreferredChannelConfigurations };
  1640. if (! AudioProcessor::containsLayout (requested, configs))
  1641. return kResultFalse;
  1642. #endif
  1643. return pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse;
  1644. }
  1645. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1646. {
  1647. if (auto* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1648. {
  1649. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1650. return kResultTrue;
  1651. }
  1652. return kResultFalse;
  1653. }
  1654. //==============================================================================
  1655. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1656. {
  1657. return (symbolicSampleSize == Vst::kSample32
  1658. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1659. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1660. }
  1661. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1662. {
  1663. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1664. }
  1665. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1666. {
  1667. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1668. return kResultFalse;
  1669. processSetup = newSetup;
  1670. processContext.sampleRate = processSetup.sampleRate;
  1671. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1672. ? AudioProcessor::doublePrecision
  1673. : AudioProcessor::singlePrecision);
  1674. getPluginInstance().setNonRealtime (newSetup.processMode == Vst::kOffline);
  1675. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1676. return kResultTrue;
  1677. }
  1678. tresult PLUGIN_API setProcessing (TBool state) override
  1679. {
  1680. if (! state)
  1681. getPluginInstance().reset();
  1682. return kResultTrue;
  1683. }
  1684. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1685. {
  1686. auto tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1687. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate <= 0.0)
  1688. return Vst::kNoTail;
  1689. if (tailLengthSeconds == std::numeric_limits<double>::infinity())
  1690. return Vst::kInfiniteTail;
  1691. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1692. }
  1693. //==============================================================================
  1694. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1695. {
  1696. jassert (pluginInstance != nullptr);
  1697. auto numParamsChanged = paramChanges.getParameterCount();
  1698. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1699. {
  1700. if (auto* paramQueue = paramChanges.getParameterData (i))
  1701. {
  1702. auto numPoints = paramQueue->getPointCount();
  1703. Steinberg::int32 offsetSamples = 0;
  1704. double value = 0.0;
  1705. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1706. {
  1707. auto vstParamID = paramQueue->getParameterId();
  1708. if (vstParamID == JuceVST3EditController::paramPreset)
  1709. {
  1710. auto numPrograms = pluginInstance->getNumPrograms();
  1711. auto programValue = roundToInt (value * (jmax (0, numPrograms - 1)));
  1712. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1713. && programValue != pluginInstance->getCurrentProgram())
  1714. pluginInstance->setCurrentProgram (programValue);
  1715. }
  1716. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1717. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1718. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1719. #endif
  1720. else
  1721. {
  1722. auto floatValue = static_cast<float> (value);
  1723. if (auto* param = comPluginInstance->getParamForVSTParamID (vstParamID))
  1724. {
  1725. param->setValue (floatValue);
  1726. inParameterChangedCallback = true;
  1727. param->sendValueChangedMessageToListeners (floatValue);
  1728. }
  1729. }
  1730. }
  1731. }
  1732. }
  1733. }
  1734. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1735. {
  1736. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1737. int channel, ctrlNumber;
  1738. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1739. {
  1740. if (ctrlNumber == Vst::kAfterTouch)
  1741. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1742. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1743. else if (ctrlNumber == Vst::kPitchBend)
  1744. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1745. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1746. else
  1747. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1748. jlimit (0, 127, ctrlNumber),
  1749. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1750. }
  1751. }
  1752. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1753. {
  1754. if (pluginInstance == nullptr)
  1755. return kResultFalse;
  1756. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1757. return kResultFalse;
  1758. if (data.processContext != nullptr)
  1759. {
  1760. processContext = *data.processContext;
  1761. if (juceVST3EditController != nullptr)
  1762. juceVST3EditController->vst3IsPlaying = processContext.state & Vst::ProcessContext::kPlaying;
  1763. }
  1764. else
  1765. {
  1766. zerostruct (processContext);
  1767. if (juceVST3EditController != nullptr)
  1768. juceVST3EditController->vst3IsPlaying = 0;
  1769. }
  1770. midiBuffer.clear();
  1771. if (data.inputParameterChanges != nullptr)
  1772. processParameterChanges (*data.inputParameterChanges);
  1773. #if JucePlugin_WantsMidiInput
  1774. if (data.inputEvents != nullptr)
  1775. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1776. #endif
  1777. if (getHostType().isWavelab())
  1778. {
  1779. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1780. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1781. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1782. && (numInputChans + numOutputChans) == 0)
  1783. return kResultFalse;
  1784. }
  1785. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1786. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1787. else jassertfalse;
  1788. #if JucePlugin_ProducesMidiOutput
  1789. if (data.outputEvents != nullptr)
  1790. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1791. #endif
  1792. return kResultTrue;
  1793. }
  1794. private:
  1795. //==============================================================================
  1796. Atomic<int> refCount { 1 };
  1797. AudioProcessor* pluginInstance;
  1798. ComSmartPtr<Vst::IHostApplication> host;
  1799. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1800. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1801. /**
  1802. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1803. this object needs to be copied on every call to process() to be up-to-date...
  1804. */
  1805. Vst::ProcessContext processContext;
  1806. Vst::ProcessSetup processSetup;
  1807. MidiBuffer midiBuffer;
  1808. Array<float*> channelListFloat;
  1809. Array<double*> channelListDouble;
  1810. AudioBuffer<float> emptyBufferFloat;
  1811. AudioBuffer<double> emptyBufferDouble;
  1812. #if JucePlugin_WantsMidiInput
  1813. bool isMidiInputBusEnabled = true;
  1814. #else
  1815. bool isMidiInputBusEnabled = false;
  1816. #endif
  1817. #if JucePlugin_ProducesMidiOutput
  1818. bool isMidiOutputBusEnabled = true;
  1819. #else
  1820. bool isMidiOutputBusEnabled = false;
  1821. #endif
  1822. ScopedJuceInitialiser_GUI libraryInitialiser;
  1823. static const char* kJucePrivateDataIdentifier;
  1824. //==============================================================================
  1825. template <typename FloatType>
  1826. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1827. {
  1828. int totalInputChans = 0, totalOutputChans = 0;
  1829. bool tmpBufferNeedsClearing = false;
  1830. auto plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1831. auto plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1832. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  1833. int vstInputs;
  1834. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  1835. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  1836. && data.inputs[vstInputs].numChannels > 0)
  1837. break;
  1838. int vstOutputs;
  1839. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  1840. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  1841. && data.outputs[vstOutputs].numChannels > 0)
  1842. break;
  1843. {
  1844. auto n = jmax (vstOutputs, getNumAudioBuses (false));
  1845. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  1846. {
  1847. if (bus < vstOutputs)
  1848. {
  1849. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1850. {
  1851. auto numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1852. for (int i = 0; i < numChans; ++i)
  1853. {
  1854. if (auto dst = busChannels[i])
  1855. {
  1856. if (totalOutputChans >= plugInInputChannels)
  1857. FloatVectorOperations::clear (dst, (int) data.numSamples);
  1858. channelList.set (totalOutputChans++, busChannels[i]);
  1859. }
  1860. }
  1861. }
  1862. }
  1863. else
  1864. {
  1865. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  1866. for (int i = 0; i < numChans; ++i)
  1867. {
  1868. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))\
  1869. {
  1870. tmpBufferNeedsClearing = true;
  1871. channelList.set (totalOutputChans++, tmpBuffer);
  1872. }
  1873. else
  1874. return;
  1875. }
  1876. }
  1877. }
  1878. }
  1879. {
  1880. auto n = jmax (vstInputs, getNumAudioBuses (true));
  1881. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  1882. {
  1883. if (bus < vstInputs)
  1884. {
  1885. if (auto** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1886. {
  1887. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1888. for (int i = 0; i < numChans; ++i)
  1889. {
  1890. if (busChannels[i] != nullptr)
  1891. {
  1892. if (totalInputChans >= totalOutputChans)
  1893. channelList.set (totalInputChans, busChannels[i]);
  1894. else
  1895. {
  1896. auto* dst = channelList.getReference (totalInputChans);
  1897. auto* src = busChannels[i];
  1898. if (dst != src)
  1899. FloatVectorOperations::copy (dst, src, (int) data.numSamples);
  1900. }
  1901. }
  1902. ++totalInputChans;
  1903. }
  1904. }
  1905. }
  1906. else
  1907. {
  1908. auto numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  1909. for (int i = 0; i < numChans; ++i)
  1910. {
  1911. if (auto* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  1912. {
  1913. tmpBufferNeedsClearing = true;
  1914. channelList.set (totalInputChans++, tmpBuffer);
  1915. }
  1916. else
  1917. return;
  1918. }
  1919. }
  1920. }
  1921. }
  1922. if (tmpBufferNeedsClearing)
  1923. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  1924. AudioBuffer<FloatType> buffer;
  1925. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1926. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1927. {
  1928. const ScopedLock sl (pluginInstance->getCallbackLock());
  1929. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1930. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1931. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1932. #endif
  1933. if (pluginInstance->isSuspended())
  1934. {
  1935. buffer.clear();
  1936. }
  1937. else
  1938. {
  1939. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1940. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1941. {
  1942. if (isBypassed())
  1943. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1944. else
  1945. pluginInstance->processBlock (buffer, midiBuffer);
  1946. }
  1947. }
  1948. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  1949. /* This assertion is caused when you've added some events to the
  1950. midiMessages array in your processBlock() method, which usually means
  1951. that you're trying to send them somewhere. But in this case they're
  1952. getting thrown away.
  1953. If your plugin does want to send MIDI messages, you'll need to set
  1954. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1955. JucePluginCharacteristics.h file.
  1956. If you don't want to produce any MIDI output, then you should clear the
  1957. midiMessages array at the end of your processBlock() method, to
  1958. indicate that you don't want any of the events to be passed through
  1959. to the output.
  1960. */
  1961. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1962. #endif
  1963. }
  1964. }
  1965. //==============================================================================
  1966. template <typename FloatType>
  1967. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1968. {
  1969. channelList.clearQuick();
  1970. channelList.insertMultiple (0, nullptr, 128);
  1971. auto& p = getPluginInstance();
  1972. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  1973. buffer.clear();
  1974. }
  1975. template <typename FloatType>
  1976. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1977. {
  1978. channelList.clearQuick();
  1979. channelList.resize (0);
  1980. buffer.setSize (0, 0);
  1981. }
  1982. template <typename FloatType>
  1983. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1984. {
  1985. return AudioBusPointerHelper<FloatType>::impl (data);
  1986. }
  1987. template <typename FloatType>
  1988. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  1989. {
  1990. auto& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  1991. // we can't do anything if the host requests to render many more samples than the
  1992. // block size, we need to bail out
  1993. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  1994. return nullptr;
  1995. return buffer.getWritePointer (channel);
  1996. }
  1997. void preparePlugin (double sampleRate, int bufferSize)
  1998. {
  1999. auto& p = getPluginInstance();
  2000. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  2001. p.prepareToPlay (sampleRate, bufferSize);
  2002. midiBuffer.ensureSize (2048);
  2003. midiBuffer.clear();
  2004. }
  2005. //==============================================================================
  2006. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  2007. };
  2008. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  2009. //==============================================================================
  2010. #if JUCE_MSVC
  2011. #pragma warning (push, 0)
  2012. #pragma warning (disable: 4310)
  2013. #elif JUCE_CLANG
  2014. #pragma clang diagnostic push
  2015. #pragma clang diagnostic ignored "-Wall"
  2016. #endif
  2017. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2018. DEF_CLASS_IID (JuceAudioProcessor)
  2019. #if JUCE_VST3_CAN_REPLACE_VST2
  2020. FUID getFUIDForVST2ID (bool forControllerUID)
  2021. {
  2022. TUID uuid;
  2023. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  2024. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  2025. return FUID (uuid);
  2026. }
  2027. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  2028. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  2029. #else
  2030. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2031. DEF_CLASS_IID (JuceVST3EditController)
  2032. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  2033. DEF_CLASS_IID (JuceVST3Component)
  2034. #endif
  2035. #if JUCE_MSVC
  2036. #pragma warning (pop)
  2037. #elif JUCE_CLANG
  2038. #pragma clang diagnostic pop
  2039. #endif
  2040. //==============================================================================
  2041. bool initModule()
  2042. {
  2043. #if JUCE_MAC
  2044. initialiseMacVST();
  2045. #endif
  2046. return true;
  2047. }
  2048. bool shutdownModule()
  2049. {
  2050. return true;
  2051. }
  2052. #undef JUCE_EXPORTED_FUNCTION
  2053. #if JUCE_WINDOWS
  2054. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  2055. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  2056. #define JUCE_EXPORTED_FUNCTION
  2057. #else
  2058. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  2059. CFBundleRef globalBundleInstance = nullptr;
  2060. juce::uint32 numBundleRefs = 0;
  2061. juce::Array<CFBundleRef> bundleRefs;
  2062. enum { MaxPathLength = 2048 };
  2063. char modulePath[MaxPathLength] = { 0 };
  2064. void* moduleHandle = nullptr;
  2065. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  2066. {
  2067. if (ref != nullptr)
  2068. {
  2069. ++numBundleRefs;
  2070. CFRetain (ref);
  2071. bundleRefs.add (ref);
  2072. if (moduleHandle == nullptr)
  2073. {
  2074. globalBundleInstance = ref;
  2075. moduleHandle = ref;
  2076. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  2077. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  2078. CFRelease (tempURL);
  2079. }
  2080. }
  2081. return initModule();
  2082. }
  2083. JUCE_EXPORTED_FUNCTION bool bundleExit()
  2084. {
  2085. if (shutdownModule())
  2086. {
  2087. if (--numBundleRefs == 0)
  2088. {
  2089. for (int i = 0; i < bundleRefs.size(); ++i)
  2090. CFRelease (bundleRefs.getUnchecked (i));
  2091. bundleRefs.clear();
  2092. }
  2093. return true;
  2094. }
  2095. return false;
  2096. }
  2097. #endif
  2098. //==============================================================================
  2099. /** This typedef represents VST3's createInstance() function signature */
  2100. using CreateFunction = FUnknown* (*)(Vst::IHostApplication*);
  2101. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  2102. {
  2103. return static_cast<Vst::IAudioProcessor*> (new JuceVST3Component (host));
  2104. }
  2105. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  2106. {
  2107. return static_cast<Vst::IEditController*> (new JuceVST3EditController (host));
  2108. }
  2109. //==============================================================================
  2110. struct JucePluginFactory;
  2111. static JucePluginFactory* globalFactory = nullptr;
  2112. //==============================================================================
  2113. struct JucePluginFactory : public IPluginFactory3
  2114. {
  2115. JucePluginFactory()
  2116. : factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  2117. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  2118. {
  2119. }
  2120. virtual ~JucePluginFactory()
  2121. {
  2122. if (globalFactory == this)
  2123. globalFactory = nullptr;
  2124. }
  2125. //==============================================================================
  2126. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  2127. {
  2128. if (createFunction == nullptr)
  2129. {
  2130. jassertfalse;
  2131. return false;
  2132. }
  2133. auto* entry = classes.add (new ClassEntry (info, createFunction));
  2134. entry->infoW.fromAscii (info);
  2135. return true;
  2136. }
  2137. //==============================================================================
  2138. JUCE_DECLARE_VST3_COM_REF_METHODS
  2139. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  2140. {
  2141. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  2142. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  2143. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  2144. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  2145. jassertfalse; // Something new?
  2146. *obj = nullptr;
  2147. return kNotImplemented;
  2148. }
  2149. //==============================================================================
  2150. Steinberg::int32 PLUGIN_API countClasses() override
  2151. {
  2152. return (Steinberg::int32) classes.size();
  2153. }
  2154. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  2155. {
  2156. if (info == nullptr)
  2157. return kInvalidArgument;
  2158. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  2159. return kResultOk;
  2160. }
  2161. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  2162. {
  2163. return getPClassInfo<PClassInfo> (index, info);
  2164. }
  2165. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  2166. {
  2167. return getPClassInfo<PClassInfo2> (index, info);
  2168. }
  2169. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  2170. {
  2171. if (info != nullptr)
  2172. {
  2173. if (auto* entry = classes[(int) index])
  2174. {
  2175. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  2176. return kResultOk;
  2177. }
  2178. }
  2179. return kInvalidArgument;
  2180. }
  2181. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2182. {
  2183. *obj = nullptr;
  2184. TUID tuid;
  2185. memcpy (tuid, sourceIid, sizeof (TUID));
  2186. #if VST_VERSION >= 0x030608
  2187. auto sourceFuid = FUID::fromTUID (tuid);
  2188. #else
  2189. FUID sourceFuid;
  2190. sourceFuid = tuid;
  2191. #endif
  2192. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2193. {
  2194. jassertfalse; // The host you're running in has severe implementation issues!
  2195. return kInvalidArgument;
  2196. }
  2197. TUID iidToQuery;
  2198. sourceFuid.toTUID (iidToQuery);
  2199. for (auto* entry : classes)
  2200. {
  2201. if (doUIDsMatch (entry->infoW.cid, cid))
  2202. {
  2203. if (auto* instance = entry->createFunction (host))
  2204. {
  2205. const FReleaser releaser (instance);
  2206. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2207. return kResultOk;
  2208. }
  2209. break;
  2210. }
  2211. }
  2212. return kNoInterface;
  2213. }
  2214. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2215. {
  2216. host.loadFrom (context);
  2217. if (host != nullptr)
  2218. {
  2219. Vst::String128 name;
  2220. host->getName (name);
  2221. return kResultTrue;
  2222. }
  2223. return kNotImplemented;
  2224. }
  2225. private:
  2226. //==============================================================================
  2227. ScopedJuceInitialiser_GUI libraryInitialiser;
  2228. Atomic<int> refCount { 1 };
  2229. const PFactoryInfo factoryInfo;
  2230. ComSmartPtr<Vst::IHostApplication> host;
  2231. //==============================================================================
  2232. struct ClassEntry
  2233. {
  2234. ClassEntry() noexcept {}
  2235. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2236. : info2 (info), createFunction (fn) {}
  2237. PClassInfo2 info2;
  2238. PClassInfoW infoW;
  2239. CreateFunction createFunction = {};
  2240. bool isUnicode = false;
  2241. private:
  2242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  2243. };
  2244. OwnedArray<ClassEntry> classes;
  2245. //==============================================================================
  2246. template<class PClassInfoType>
  2247. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2248. {
  2249. if (info != nullptr)
  2250. {
  2251. zerostruct (*info);
  2252. if (auto* entry = classes[(int) index])
  2253. {
  2254. if (entry->isUnicode)
  2255. return kResultFalse;
  2256. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2257. return kResultOk;
  2258. }
  2259. }
  2260. jassertfalse;
  2261. return kInvalidArgument;
  2262. }
  2263. //==============================================================================
  2264. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  2265. };
  2266. } // juce namespace
  2267. //==============================================================================
  2268. #ifndef JucePlugin_Vst3ComponentFlags
  2269. #if JucePlugin_IsSynth
  2270. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2271. #else
  2272. #define JucePlugin_Vst3ComponentFlags 0
  2273. #endif
  2274. #endif
  2275. #ifndef JucePlugin_Vst3Category
  2276. #if JucePlugin_IsSynth
  2277. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2278. #else
  2279. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2280. #endif
  2281. #endif
  2282. using namespace juce;
  2283. //==============================================================================
  2284. // The VST3 plugin entry point.
  2285. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2286. {
  2287. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2288. #if JUCE_WINDOWS
  2289. // Cunning trick to force this function to be exported. Life's too short to
  2290. // faff around creating .def files for this kind of thing.
  2291. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2292. #endif
  2293. if (globalFactory == nullptr)
  2294. {
  2295. globalFactory = new JucePluginFactory();
  2296. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2297. PClassInfo::kManyInstances,
  2298. kVstAudioEffectClass,
  2299. JucePlugin_Name,
  2300. JucePlugin_Vst3ComponentFlags,
  2301. JucePlugin_Vst3Category,
  2302. JucePlugin_Manufacturer,
  2303. JucePlugin_VersionString,
  2304. kVstVersionString);
  2305. globalFactory->registerClass (componentClass, createComponentInstance);
  2306. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2307. PClassInfo::kManyInstances,
  2308. kVstComponentControllerClass,
  2309. JucePlugin_Name,
  2310. JucePlugin_Vst3ComponentFlags,
  2311. JucePlugin_Vst3Category,
  2312. JucePlugin_Manufacturer,
  2313. JucePlugin_VersionString,
  2314. kVstVersionString);
  2315. globalFactory->registerClass (controllerClass, createControllerInstance);
  2316. }
  2317. else
  2318. {
  2319. globalFactory->addRef();
  2320. }
  2321. return dynamic_cast<IPluginFactory*> (globalFactory);
  2322. }
  2323. //==============================================================================
  2324. #if _MSC_VER || JUCE_MINGW
  2325. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2326. #endif
  2327. #endif //JucePlugin_Build_VST3