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.

2937 lines
108KB

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