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.

2687 lines
98KB

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