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.

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