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.

2650 lines
97KB

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