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.

2934 lines
107KB

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