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.

2666 lines
98KB

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