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.

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