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.

2831 lines
104KB

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