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.

2683 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. #if JUCE_VST3_CAN_REPLACE_VST2
  43. #include "../../juce_audio_processors/format_types/juce_VSTInterface.h"
  44. #endif
  45. #ifndef JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  46. #define JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS 1
  47. #endif
  48. #if JUCE_VST3_CAN_REPLACE_VST2
  49. #if JUCE_MSVC
  50. #pragma warning (push)
  51. #pragma warning (disable: 4514 4996)
  52. #endif
  53. #if JUCE_MSVC
  54. #pragma warning (pop)
  55. #endif
  56. #endif
  57. namespace juce
  58. {
  59. using namespace Steinberg;
  60. //==============================================================================
  61. #if JUCE_MAC
  62. extern void initialiseMacVST();
  63. #if ! JUCE_64BIT
  64. extern void updateEditorCompBoundsVST (Component*);
  65. #endif
  66. extern JUCE_API void* attachComponentToWindowRefVST (Component*, void* parentWindowOrView, bool isNSView);
  67. extern JUCE_API void detachComponentFromWindowRefVST (Component*, void* nsWindow, bool isNSView);
  68. extern JUCE_API void setNativeHostWindowSizeVST (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  69. #endif
  70. //==============================================================================
  71. class JuceAudioProcessor : public FUnknown
  72. {
  73. public:
  74. JuceAudioProcessor (AudioProcessor* source) noexcept
  75. : isBypassed (false), refCount (0), audioProcessor (source) {}
  76. virtual ~JuceAudioProcessor() {}
  77. AudioProcessor* get() const noexcept { return audioProcessor; }
  78. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  79. JUCE_DECLARE_VST3_COM_REF_METHODS
  80. static const FUID iid;
  81. bool isBypassed;
  82. private:
  83. Atomic<int> refCount;
  84. ScopedPointer<AudioProcessor> audioProcessor;
  85. ScopedJuceInitialiser_GUI libraryInitialiser;
  86. JuceAudioProcessor() JUCE_DELETED_FUNCTION;
  87. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  88. };
  89. class JuceVST3Component;
  90. //==============================================================================
  91. class JuceVST3EditController : public Vst::EditController,
  92. public Vst::IMidiMapping,
  93. public AudioProcessorListener
  94. {
  95. public:
  96. JuceVST3EditController (Vst::IHostApplication* host)
  97. #if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
  98. : usingManagedParameter (false)
  99. #endif
  100. {
  101. if (host != nullptr)
  102. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  103. }
  104. //==============================================================================
  105. static const FUID iid;
  106. //==============================================================================
  107. #if JUCE_CLANG
  108. #pragma clang diagnostic push
  109. #pragma clang diagnostic ignored "-Winconsistent-missing-override"
  110. #endif
  111. REFCOUNT_METHODS (ComponentBase)
  112. #if JUCE_CLANG
  113. #pragma clang diagnostic pop
  114. #endif
  115. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  116. {
  117. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  118. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  119. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  120. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  121. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  122. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  123. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  124. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  125. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  126. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  127. {
  128. audioProcessor->addRef();
  129. *obj = audioProcessor;
  130. return kResultOk;
  131. }
  132. *obj = nullptr;
  133. return kNoInterface;
  134. }
  135. //==============================================================================
  136. tresult PLUGIN_API initialize (FUnknown* context) override
  137. {
  138. if (hostContext != context)
  139. {
  140. if (hostContext != nullptr)
  141. hostContext->release();
  142. hostContext = context;
  143. if (hostContext != nullptr)
  144. hostContext->addRef();
  145. }
  146. return kResultTrue;
  147. }
  148. tresult PLUGIN_API terminate() override
  149. {
  150. if (AudioProcessor* const pluginInstance = getPluginInstance())
  151. pluginInstance->removeListener (this);
  152. audioProcessor = nullptr;
  153. return EditController::terminate();
  154. }
  155. //==============================================================================
  156. enum InternalParameters
  157. {
  158. paramPreset = 0x70727374, // 'prst'
  159. paramBypass = 0x62797073, // 'byps'
  160. paramMidiControllerOffset = 0x6d636d00 // 'mdm*'
  161. };
  162. struct Param : public Vst::Parameter
  163. {
  164. Param (AudioProcessor& p, int index, Vst::ParamID paramID) : owner (p), paramIndex (index)
  165. {
  166. info.id = paramID;
  167. toString128 (info.title, p.getParameterName (index));
  168. toString128 (info.shortTitle, p.getParameterName (index, 8));
  169. toString128 (info.units, p.getParameterLabel (index));
  170. const int numSteps = p.getParameterNumSteps (index);
  171. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  172. info.defaultNormalizedValue = p.getParameterDefaultValue (index);
  173. jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
  174. info.unitId = Vst::kRootUnitId;
  175. // is this a meter?
  176. if (((p.getParameterCategory (index) & 0xffff0000) >> 16) == 2)
  177. info.flags = Vst::ParameterInfo::kIsReadOnly;
  178. else
  179. info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
  180. }
  181. virtual ~Param() {}
  182. bool setNormalized (Vst::ParamValue v) override
  183. {
  184. v = jlimit (0.0, 1.0, v);
  185. if (v != valueNormalized)
  186. {
  187. valueNormalized = v;
  188. owner.setParameter (paramIndex, static_cast<float> (v));
  189. changed();
  190. return true;
  191. }
  192. return false;
  193. }
  194. void toString (Vst::ParamValue value, Vst::String128 result) const override
  195. {
  196. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  197. toString128 (result, p->getText ((float) value, 128));
  198. else
  199. // remain backward-compatible with old JUCE code
  200. toString128 (result, owner.getParameterText (paramIndex, 128));
  201. }
  202. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  203. {
  204. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  205. {
  206. outValueNormalized = p->getValueForText (getStringFromVstTChars (text));
  207. return true;
  208. }
  209. return false;
  210. }
  211. static String getStringFromVstTChars (const Vst::TChar* text)
  212. {
  213. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  214. }
  215. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  216. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  217. private:
  218. AudioProcessor& owner;
  219. int paramIndex;
  220. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  221. };
  222. //==============================================================================
  223. struct BypassParam : public Vst::Parameter
  224. {
  225. BypassParam (Vst::ParamID vstParamID)
  226. {
  227. info.id = vstParamID;
  228. toString128 (info.title, "Bypass");
  229. toString128 (info.shortTitle, "Bypass");
  230. toString128 (info.units, "");
  231. info.stepCount = 1;
  232. info.defaultNormalizedValue = 0.0f;
  233. info.unitId = Vst::kRootUnitId;
  234. info.flags = Vst::ParameterInfo::kIsBypass | Vst::ParameterInfo::kCanAutomate;
  235. }
  236. virtual ~BypassParam() {}
  237. bool setNormalized (Vst::ParamValue v) override
  238. {
  239. bool bypass = (v != 0.0f);
  240. v = (bypass ? 1.0f : 0.0f);
  241. if (valueNormalized != v)
  242. {
  243. valueNormalized = v;
  244. changed();
  245. return true;
  246. }
  247. return false;
  248. }
  249. void toString (Vst::ParamValue value, Vst::String128 result) const override
  250. {
  251. bool bypass = (value != 0.0f);
  252. toString128 (result, bypass ? "On" : "Off");
  253. }
  254. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  255. {
  256. const String paramValueString (getStringFromVstTChars (text));
  257. if (paramValueString.equalsIgnoreCase ("on")
  258. || paramValueString.equalsIgnoreCase ("yes")
  259. || paramValueString.equalsIgnoreCase ("true"))
  260. {
  261. outValueNormalized = 1.0f;
  262. return true;
  263. }
  264. if (paramValueString.equalsIgnoreCase ("off")
  265. || paramValueString.equalsIgnoreCase ("no")
  266. || paramValueString.equalsIgnoreCase ("false"))
  267. {
  268. outValueNormalized = 0.0f;
  269. return true;
  270. }
  271. var varValue = JSON::fromString (paramValueString);
  272. if (varValue.isDouble() || varValue.isInt()
  273. || varValue.isInt64() || varValue.isBool())
  274. {
  275. double value = varValue;
  276. outValueNormalized = (value != 0.0) ? 1.0f : 0.0f;
  277. return true;
  278. }
  279. return false;
  280. }
  281. static String getStringFromVstTChars (const Vst::TChar* text)
  282. {
  283. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  284. }
  285. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  286. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  287. 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 (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 vst2FxBank* bank = (const vst2FxBank*) (data + (8 + headerLen));
  1016. const int version = static_cast<int> (htonl (bank->version1)); 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 ('CcnK' == htonl (bank->magic1));
  1020. jassert ('FBCh' == htonl (bank->magic2));
  1021. jassert (version == 1 || version == 2);
  1022. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  1023. setStateInformation (bank->chunk,
  1024. jmin ((int) (size - (bank->chunk - data)),
  1025. (int) htonl (bank->chunkSize)));
  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<ISizeableStream> s (state);
  1089. Steinberg::int64 size = 0;
  1090. if (s != nullptr
  1091. && s->getStreamSize (size) == kResultOk
  1092. && size > 0
  1093. && size < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  1094. {
  1095. MemoryBlock block (static_cast<size_t> (size));
  1096. // turns out that Cubase 9 might give you the incorrect stream size :-(
  1097. Steinberg::int32 bytesRead = 1;
  1098. int len;
  1099. for (len = 0; bytesRead > 0 && len < static_cast<int> (block.getSize()); len += bytesRead)
  1100. if (state->read (block.getData(), static_cast<int32> (block.getSize()), &bytesRead) != kResultOk)
  1101. break;
  1102. if (len == 0)
  1103. return false;
  1104. block.setSize (static_cast<size_t> (len));
  1105. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  1106. if (getHostType().isAdobeAudition())
  1107. if (block.getSize() >= 5 && memcmp (block.getData(), "VC2!E", 5) == 0)
  1108. return false;
  1109. return loadStateData (block.getData(), (int) block.getSize());
  1110. }
  1111. return false;
  1112. }
  1113. bool readFromUnknownStream (IBStream* state)
  1114. {
  1115. MemoryOutputStream allData;
  1116. {
  1117. const size_t bytesPerBlock = 4096;
  1118. HeapBlock<char> buffer (bytesPerBlock);
  1119. for (;;)
  1120. {
  1121. Steinberg::int32 bytesRead = 0;
  1122. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  1123. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  1124. break;
  1125. allData.write (buffer, static_cast<size_t> (bytesRead));
  1126. }
  1127. }
  1128. const size_t dataSize = allData.getDataSize();
  1129. return dataSize > 0 && dataSize < 0x7fffffff
  1130. && loadStateData (allData.getData(), (int) dataSize);
  1131. }
  1132. tresult PLUGIN_API setState (IBStream* state) override
  1133. {
  1134. if (state == nullptr)
  1135. return kInvalidArgument;
  1136. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  1137. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  1138. {
  1139. if (! getHostType().isFruityLoops() && readFromMemoryStream (state))
  1140. return kResultTrue;
  1141. if (readFromUnknownStream (state))
  1142. return kResultTrue;
  1143. }
  1144. return kResultFalse;
  1145. }
  1146. #if JUCE_VST3_CAN_REPLACE_VST2
  1147. static tresult writeVST2Int (IBStream* state, int n)
  1148. {
  1149. juce::int32 t = (juce::int32) htonl (n);
  1150. return state->write (&t, 4);
  1151. }
  1152. static tresult writeVST2Header (IBStream* state, bool bypassed)
  1153. {
  1154. tresult status = writeVST2Int (state, 'VstW');
  1155. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  1156. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  1157. if (status == kResultOk) status = writeVST2Int (state, bypassed ? 1 : 0); // bypass
  1158. return status;
  1159. }
  1160. #endif
  1161. tresult PLUGIN_API getState (IBStream* state) override
  1162. {
  1163. if (state == nullptr)
  1164. return kInvalidArgument;
  1165. juce::MemoryBlock mem;
  1166. getStateInformation (mem);
  1167. #if JUCE_VST3_CAN_REPLACE_VST2
  1168. tresult status = writeVST2Header (state, isBypassed());
  1169. if (status != kResultOk)
  1170. return status;
  1171. const int bankBlockSize = 160;
  1172. vst2FxBank bank;
  1173. zerostruct (bank);
  1174. bank.magic1 = (int32) htonl ('CcnK');
  1175. bank.size = (int32) htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  1176. bank.magic1 = (int32) htonl ('FBCh');
  1177. bank.version1 = (int32) htonl (2);
  1178. bank.fxID = (int32) htonl (JucePlugin_VSTUniqueID);
  1179. bank.version2 = (int32) htonl (JucePlugin_VersionCode);
  1180. bank.chunkSize = (int32) htonl ((unsigned int) mem.getSize());
  1181. status = state->write (&bank, bankBlockSize);
  1182. if (status != kResultOk)
  1183. return status;
  1184. #endif
  1185. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  1186. }
  1187. //==============================================================================
  1188. Steinberg::int32 PLUGIN_API getUnitCount() override
  1189. {
  1190. return 1;
  1191. }
  1192. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  1193. {
  1194. if (unitIndex == 0)
  1195. {
  1196. info.id = Vst::kRootUnitId;
  1197. info.parentUnitId = Vst::kNoParentUnitId;
  1198. info.programListId = Vst::kNoProgramListId;
  1199. toString128 (info.name, TRANS("Root Unit"));
  1200. return kResultTrue;
  1201. }
  1202. zerostruct (info);
  1203. return kResultFalse;
  1204. }
  1205. Steinberg::int32 PLUGIN_API getProgramListCount() override
  1206. {
  1207. if (getPluginInstance().getNumPrograms() > 0)
  1208. return 1;
  1209. return 0;
  1210. }
  1211. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  1212. {
  1213. if (listIndex == 0)
  1214. {
  1215. info.id = JuceVST3EditController::paramPreset;
  1216. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  1217. toString128 (info.name, TRANS("Factory Presets"));
  1218. return kResultTrue;
  1219. }
  1220. jassertfalse;
  1221. zerostruct (info);
  1222. return kResultFalse;
  1223. }
  1224. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  1225. {
  1226. if (listId == JuceVST3EditController::paramPreset
  1227. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  1228. {
  1229. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  1230. return kResultTrue;
  1231. }
  1232. jassertfalse;
  1233. toString128 (name, juce::String());
  1234. return kResultFalse;
  1235. }
  1236. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  1237. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  1238. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  1239. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  1240. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  1241. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  1242. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection, Steinberg::int32, Steinberg::int32, Vst::UnitID& unitId) override
  1243. {
  1244. zerostruct (unitId);
  1245. return kNotImplemented;
  1246. }
  1247. //==============================================================================
  1248. bool getCurrentPosition (CurrentPositionInfo& info) override
  1249. {
  1250. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  1251. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  1252. info.bpm = jmax (1.0, processContext.tempo);
  1253. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  1254. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  1255. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  1256. info.ppqPosition = processContext.projectTimeMusic;
  1257. info.ppqLoopStart = processContext.cycleStartMusic;
  1258. info.ppqLoopEnd = processContext.cycleEndMusic;
  1259. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  1260. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  1261. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  1262. info.editOriginTime = 0.0;
  1263. info.frameRate = AudioPlayHead::fpsUnknown;
  1264. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  1265. {
  1266. switch (processContext.frameRate.framesPerSecond)
  1267. {
  1268. case 24: info.frameRate = AudioPlayHead::fps24; break;
  1269. case 25: info.frameRate = AudioPlayHead::fps25; break;
  1270. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  1271. case 30:
  1272. {
  1273. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  1274. info.frameRate = AudioPlayHead::fps30drop;
  1275. else
  1276. info.frameRate = AudioPlayHead::fps30;
  1277. }
  1278. break;
  1279. default: break;
  1280. }
  1281. }
  1282. return true;
  1283. }
  1284. //==============================================================================
  1285. int getNumAudioBuses (bool isInput) const
  1286. {
  1287. int busCount = pluginInstance->getBusCount (isInput);
  1288. #ifdef JucePlugin_PreferredChannelConfigurations
  1289. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1290. const int numConfigs = sizeof (configs) / sizeof (short[2]);
  1291. bool hasOnlyZeroChannels = true;
  1292. for (int i = 0; i < numConfigs && hasOnlyZeroChannels == true; ++i)
  1293. if (configs[i][isInput ? 0 : 1] != 0)
  1294. hasOnlyZeroChannels = false;
  1295. busCount = jmin (busCount, hasOnlyZeroChannels ? 0 : 1);
  1296. #endif
  1297. return busCount;
  1298. }
  1299. //==============================================================================
  1300. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  1301. {
  1302. if (type == Vst::kAudio)
  1303. return getNumAudioBuses (dir == Vst::kInput);
  1304. if (type == Vst::kEvent)
  1305. {
  1306. if (dir == Vst::kInput)
  1307. return isMidiInputBusEnabled ? 1 : 0;
  1308. if (dir == Vst::kOutput)
  1309. return isMidiOutputBusEnabled ? 1 : 0;
  1310. }
  1311. return 0;
  1312. }
  1313. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  1314. Steinberg::int32 index, Vst::BusInfo& info) override
  1315. {
  1316. if (type == Vst::kAudio)
  1317. {
  1318. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1319. return kResultFalse;
  1320. if (const AudioProcessor::Bus* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1321. {
  1322. info.mediaType = Vst::kAudio;
  1323. info.direction = dir;
  1324. info.channelCount = bus->getLastEnabledLayout().size();
  1325. toString128 (info.name, bus->getName());
  1326. #if JucePlugin_IsSynth
  1327. info.busType = (dir == Vst::kInput && index > 0 ? Vst::kAux : Vst::kMain);
  1328. #else
  1329. info.busType = (index == 0 ? Vst::kMain : Vst::kAux);
  1330. #endif
  1331. info.flags = (bus->isEnabledByDefault()) ? Vst::BusInfo::kDefaultActive : 0;
  1332. return kResultTrue;
  1333. }
  1334. }
  1335. if (type == Vst::kEvent)
  1336. {
  1337. info.flags = Vst::BusInfo::kDefaultActive;
  1338. #if JucePlugin_WantsMidiInput
  1339. if (dir == Vst::kInput && index == 0)
  1340. {
  1341. info.mediaType = Vst::kEvent;
  1342. info.direction = dir;
  1343. info.channelCount = 16;
  1344. toString128 (info.name, TRANS("MIDI Input"));
  1345. info.busType = Vst::kMain;
  1346. return kResultTrue;
  1347. }
  1348. #endif
  1349. #if JucePlugin_ProducesMidiOutput
  1350. if (dir == Vst::kOutput && index == 0)
  1351. {
  1352. info.mediaType = Vst::kEvent;
  1353. info.direction = dir;
  1354. info.channelCount = 16;
  1355. toString128 (info.name, TRANS("MIDI Output"));
  1356. info.busType = Vst::kMain;
  1357. return kResultTrue;
  1358. }
  1359. #endif
  1360. }
  1361. zerostruct (info);
  1362. return kResultFalse;
  1363. }
  1364. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir, Steinberg::int32 index, TBool state) override
  1365. {
  1366. if (type == Vst::kEvent)
  1367. {
  1368. if (index != 0)
  1369. return kResultFalse;
  1370. if (dir == Vst::kInput)
  1371. isMidiInputBusEnabled = (state != 0);
  1372. else
  1373. isMidiOutputBusEnabled = (state != 0);
  1374. return kResultTrue;
  1375. }
  1376. if (type == Vst::kAudio)
  1377. {
  1378. if (index < 0 || index >= getNumAudioBuses (dir == Vst::kInput))
  1379. return kResultFalse;
  1380. if (AudioProcessor::Bus* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1381. {
  1382. #ifdef JucePlugin_PreferredChannelConfigurations
  1383. AudioProcessor::BusesLayout newLayout = pluginInstance->getBusesLayout();
  1384. AudioChannelSet targetLayout
  1385. = (state != 0 ? bus->getLastEnabledLayout() : AudioChannelSet::disabled());
  1386. (dir == Vst::kInput ? newLayout.inputBuses : newLayout.outputBuses).getReference (index) = targetLayout;
  1387. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1388. AudioProcessor::BusesLayout compLayout
  1389. = pluginInstance->getNextBestLayoutInLayoutList (newLayout, configs);
  1390. if ((dir == Vst::kInput ? compLayout.inputBuses : compLayout.outputBuses).getReference (index) != targetLayout)
  1391. return kResultFalse;
  1392. #endif
  1393. return (bus->enable (state != 0) ? kResultTrue : kResultFalse);
  1394. }
  1395. }
  1396. return kResultFalse;
  1397. }
  1398. bool checkBusFormatsAreNotDiscrete()
  1399. {
  1400. const int numInputBuses = pluginInstance->getBusCount (true);
  1401. const int numOutputBuses = pluginInstance->getBusCount (false);
  1402. for (int i = 0; i < numInputBuses; ++i)
  1403. if (pluginInstance->getChannelLayoutOfBus (true, i).isDiscreteLayout())
  1404. return false;
  1405. for (int i = 0; i < numOutputBuses; ++i)
  1406. if (pluginInstance->getChannelLayoutOfBus (false, i).isDiscreteLayout())
  1407. return false;
  1408. return true;
  1409. }
  1410. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  1411. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  1412. {
  1413. const int numInputBuses = pluginInstance->getBusCount (true);
  1414. const int numOutputBuses = pluginInstance->getBusCount (false);
  1415. if (numIns > numInputBuses || numOuts > numOutputBuses)
  1416. return false;
  1417. AudioProcessor::BusesLayout requested = pluginInstance->getBusesLayout();
  1418. for (int i = 0; i < numIns; ++i)
  1419. requested.getChannelSet (true, i) = getChannelSetForSpeakerArrangement (inputs[i]);
  1420. for (int i = 0; i < numOuts; ++i)
  1421. requested.getChannelSet (false, i) = getChannelSetForSpeakerArrangement (outputs[i]);
  1422. #ifdef JucePlugin_PreferredChannelConfigurations
  1423. short configs[][2] = {JucePlugin_PreferredChannelConfigurations};
  1424. if (! AudioProcessor::containsLayout (requested, configs))
  1425. return kResultFalse;
  1426. #endif
  1427. return (pluginInstance->setBusesLayoutWithoutEnabling (requested) ? kResultTrue : kResultFalse);
  1428. }
  1429. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  1430. {
  1431. if (AudioProcessor::Bus* bus = pluginInstance->getBus (dir == Vst::kInput, index))
  1432. {
  1433. arr = getVst3SpeakerArrangement (bus->getLastEnabledLayout());
  1434. return kResultTrue;
  1435. }
  1436. return kResultFalse;
  1437. }
  1438. //==============================================================================
  1439. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1440. {
  1441. return (symbolicSampleSize == Vst::kSample32
  1442. || (getPluginInstance().supportsDoublePrecisionProcessing()
  1443. && symbolicSampleSize == Vst::kSample64)) ? kResultTrue : kResultFalse;
  1444. }
  1445. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1446. {
  1447. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1448. }
  1449. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1450. {
  1451. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1452. return kResultFalse;
  1453. processSetup = newSetup;
  1454. processContext.sampleRate = processSetup.sampleRate;
  1455. getPluginInstance().setProcessingPrecision (newSetup.symbolicSampleSize == Vst::kSample64
  1456. ? AudioProcessor::doublePrecision
  1457. : AudioProcessor::singlePrecision);
  1458. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1459. return kResultTrue;
  1460. }
  1461. tresult PLUGIN_API setProcessing (TBool state) override
  1462. {
  1463. if (! state)
  1464. getPluginInstance().reset();
  1465. return kResultTrue;
  1466. }
  1467. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1468. {
  1469. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1470. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1471. return Vst::kNoTail;
  1472. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1473. }
  1474. //==============================================================================
  1475. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1476. {
  1477. jassert (pluginInstance != nullptr);
  1478. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  1479. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1480. {
  1481. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  1482. {
  1483. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  1484. Steinberg::int32 offsetSamples;
  1485. double value = 0.0;
  1486. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1487. {
  1488. const Vst::ParamID vstParamID = paramQueue->getParameterId();
  1489. if (vstParamID == vstBypassParameterId)
  1490. setBypassed (static_cast<float> (value) != 0.0f);
  1491. #if JUCE_VST3_EMULATE_MIDI_CC_WITH_PARAMETERS
  1492. else if (juceVST3EditController->isMidiControllerParamID (vstParamID))
  1493. addParameterChangeToMidiBuffer (offsetSamples, vstParamID, value);
  1494. #endif
  1495. else if (vstParamID == JuceVST3EditController::paramPreset)
  1496. {
  1497. const int numPrograms = pluginInstance->getNumPrograms();
  1498. const int programValue = roundToInt (value * numPrograms);
  1499. if (numPrograms > 1 && isPositiveAndBelow (programValue, numPrograms)
  1500. && programValue != pluginInstance->getCurrentProgram())
  1501. pluginInstance->setCurrentProgram (programValue);
  1502. }
  1503. else
  1504. {
  1505. const int index = getJuceIndexForVSTParamID (vstParamID);
  1506. if (isPositiveAndBelow (index, pluginInstance->getNumParameters()))
  1507. pluginInstance->setParameter (index, static_cast<float> (value));
  1508. }
  1509. }
  1510. }
  1511. }
  1512. }
  1513. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const Vst::ParamID id, const double value)
  1514. {
  1515. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1516. int channel, ctrlNumber;
  1517. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1518. {
  1519. if (ctrlNumber == Vst::kAfterTouch)
  1520. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1521. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1522. else if (ctrlNumber == Vst::kPitchBend)
  1523. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1524. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1525. else
  1526. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1527. jlimit (0, 127, ctrlNumber),
  1528. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1529. }
  1530. }
  1531. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1532. {
  1533. if (pluginInstance == nullptr)
  1534. return kResultFalse;
  1535. if ((processSetup.symbolicSampleSize == Vst::kSample64) != pluginInstance->isUsingDoublePrecision())
  1536. return kResultFalse;
  1537. if (data.processContext != nullptr)
  1538. processContext = *data.processContext;
  1539. else
  1540. zerostruct (processContext);
  1541. midiBuffer.clear();
  1542. #if JucePlugin_WantsMidiInput
  1543. if (data.inputEvents != nullptr)
  1544. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1545. #endif
  1546. if (getHostType().isWavelab())
  1547. {
  1548. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1549. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1550. if ((pluginInstance->getTotalNumInputChannels() + pluginInstance->getTotalNumOutputChannels()) > 0
  1551. && (numInputChans + numOutputChans) == 0)
  1552. return kResultFalse;
  1553. }
  1554. if (processSetup.symbolicSampleSize == Vst::kSample32) processAudio<float> (data, channelListFloat);
  1555. else if (processSetup.symbolicSampleSize == Vst::kSample64) processAudio<double> (data, channelListDouble);
  1556. else jassertfalse;
  1557. #if JucePlugin_ProducesMidiOutput
  1558. if (data.outputEvents != nullptr)
  1559. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1560. #endif
  1561. return kResultTrue;
  1562. }
  1563. private:
  1564. //==============================================================================
  1565. Atomic<int> refCount;
  1566. AudioProcessor* pluginInstance;
  1567. ComSmartPtr<Vst::IHostApplication> host;
  1568. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1569. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1570. /**
  1571. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1572. this object needs to be copied on every call to process() to be up-to-date...
  1573. */
  1574. Vst::ProcessContext processContext;
  1575. Vst::ProcessSetup processSetup;
  1576. MidiBuffer midiBuffer;
  1577. Array<float*> channelListFloat;
  1578. Array<double*> channelListDouble;
  1579. AudioBuffer<float> emptyBufferFloat;
  1580. AudioBuffer<double> emptyBufferDouble;
  1581. bool isMidiInputBusEnabled, isMidiOutputBusEnabled;
  1582. ScopedJuceInitialiser_GUI libraryInitialiser;
  1583. #if ! JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1584. bool usingManagedParameter;
  1585. Array<Vst::ParamID> vstParamIDs;
  1586. HashMap<int32, int> paramMap;
  1587. #endif
  1588. Vst::ParamID vstBypassParameterId;
  1589. static const char* kJucePrivateDataIdentifier;
  1590. //==============================================================================
  1591. template <typename FloatType>
  1592. void processAudio (Vst::ProcessData& data, Array<FloatType*>& channelList)
  1593. {
  1594. int totalInputChans = 0;
  1595. bool tmpBufferNeedsClearing = false;
  1596. const int plugInInputChannels = pluginInstance->getTotalNumInputChannels();
  1597. const int plugInOutputChannels = pluginInstance->getTotalNumOutputChannels();
  1598. // Wavelab workaround: wave-lab lies on the number of inputs/outputs so re-count here
  1599. int vstInputs;
  1600. for (vstInputs = 0; vstInputs < data.numInputs; ++vstInputs)
  1601. if (getPointerForAudioBus<FloatType> (data.inputs[vstInputs]) == nullptr
  1602. && data.inputs[vstInputs].numChannels > 0)
  1603. break;
  1604. int vstOutputs;
  1605. for (vstOutputs = 0; vstOutputs < data.numOutputs; ++vstOutputs)
  1606. if (getPointerForAudioBus<FloatType> (data.outputs[vstOutputs]) == nullptr
  1607. && data.outputs[vstOutputs].numChannels > 0)
  1608. break;
  1609. {
  1610. const int n = jmax (vstInputs, getNumAudioBuses (true));
  1611. for (int bus = 0; bus < n && totalInputChans < plugInInputChannels; ++bus)
  1612. {
  1613. if (bus < vstInputs)
  1614. {
  1615. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.inputs[bus]))
  1616. {
  1617. const int numChans = jmin ((int) data.inputs[bus].numChannels, plugInInputChannels - totalInputChans);
  1618. for (int i = 0; i < numChans; ++i)
  1619. if (busChannels[i] != nullptr)
  1620. channelList.set (totalInputChans++, busChannels[i]);
  1621. }
  1622. }
  1623. else
  1624. {
  1625. const int numChans = jmin (pluginInstance->getChannelCountOfBus (true, bus), plugInInputChannels - totalInputChans);
  1626. for (int i = 0; i < numChans; ++i)
  1627. {
  1628. if (FloatType* tmpBuffer = getTmpBufferForChannel<FloatType> (totalInputChans, data.numSamples))
  1629. {
  1630. tmpBufferNeedsClearing = true;
  1631. channelList.set (totalInputChans++, tmpBuffer);
  1632. }
  1633. else
  1634. return;
  1635. }
  1636. }
  1637. }
  1638. }
  1639. int totalOutputChans = 0;
  1640. {
  1641. const int n = jmax (vstOutputs, getNumAudioBuses (false));
  1642. for (int bus = 0; bus < n && totalOutputChans < plugInOutputChannels; ++bus)
  1643. {
  1644. if (bus < vstOutputs)
  1645. {
  1646. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1647. {
  1648. const int numChans = jmin ((int) data.outputs[bus].numChannels, plugInOutputChannels - totalOutputChans);
  1649. for (int i = 0; i < numChans; ++i)
  1650. {
  1651. if (busChannels[i] != nullptr)
  1652. {
  1653. if (totalOutputChans >= totalInputChans)
  1654. {
  1655. FloatVectorOperations::clear (busChannels[i], data.numSamples);
  1656. channelList.set (totalOutputChans, busChannels[i]);
  1657. }
  1658. ++totalOutputChans;
  1659. }
  1660. }
  1661. }
  1662. }
  1663. else
  1664. {
  1665. const int numChans = jmin (pluginInstance->getChannelCountOfBus (false, bus), plugInOutputChannels - totalOutputChans);
  1666. for (int i = 0; i < numChans; ++i)
  1667. {
  1668. if (FloatType* tmpBuffer = getTmpBufferForChannel<FloatType> (totalOutputChans, data.numSamples))
  1669. {
  1670. if (totalOutputChans >= totalInputChans)
  1671. {
  1672. tmpBufferNeedsClearing = true;
  1673. channelList.set (totalOutputChans, tmpBuffer);
  1674. }
  1675. ++totalOutputChans;
  1676. }
  1677. else
  1678. return;
  1679. }
  1680. }
  1681. }
  1682. }
  1683. if (tmpBufferNeedsClearing)
  1684. ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble).clear();
  1685. AudioBuffer<FloatType> buffer;
  1686. if (int totalChans = jmax (totalOutputChans, totalInputChans))
  1687. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1688. {
  1689. const ScopedLock sl (pluginInstance->getCallbackLock());
  1690. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1691. if (data.inputParameterChanges != nullptr)
  1692. processParameterChanges (*data.inputParameterChanges);
  1693. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1694. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1695. #endif
  1696. if (pluginInstance->isSuspended())
  1697. {
  1698. buffer.clear();
  1699. }
  1700. else
  1701. {
  1702. if (totalInputChans == pluginInstance->getTotalNumInputChannels()
  1703. && totalOutputChans == pluginInstance->getTotalNumOutputChannels())
  1704. {
  1705. if (isBypassed())
  1706. pluginInstance->processBlockBypassed (buffer, midiBuffer);
  1707. else
  1708. pluginInstance->processBlock (buffer, midiBuffer);
  1709. }
  1710. }
  1711. #if JUCE_DEBUG && (! JucePlugin_ProducesMidiOutput)
  1712. /* This assertion is caused when you've added some events to the
  1713. midiMessages array in your processBlock() method, which usually means
  1714. that you're trying to send them somewhere. But in this case they're
  1715. getting thrown away.
  1716. If your plugin does want to send MIDI messages, you'll need to set
  1717. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1718. JucePluginCharacteristics.h file.
  1719. If you don't want to produce any MIDI output, then you should clear the
  1720. midiMessages array at the end of your processBlock() method, to
  1721. indicate that you don't want any of the events to be passed through
  1722. to the output.
  1723. */
  1724. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1725. #endif
  1726. }
  1727. if (data.outputs != nullptr)
  1728. {
  1729. int outChanIndex = 0;
  1730. for (int bus = 0; bus < data.numOutputs; ++bus)
  1731. {
  1732. if (FloatType** const busChannels = getPointerForAudioBus<FloatType> (data.outputs[bus]))
  1733. {
  1734. const int numChans = (int) data.outputs[bus].numChannels;
  1735. for (int i = 0; i < numChans; ++i)
  1736. {
  1737. if (outChanIndex < totalInputChans && busChannels[i] != nullptr)
  1738. FloatVectorOperations::copy (busChannels[i], buffer.getReadPointer (outChanIndex), (int) data.numSamples);
  1739. else if (outChanIndex >= totalOutputChans && busChannels[i] != nullptr)
  1740. FloatVectorOperations::clear (busChannels[i], (int) data.numSamples);
  1741. ++outChanIndex;
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747. //==============================================================================
  1748. template <typename FloatType>
  1749. void allocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1750. {
  1751. channelList.clearQuick();
  1752. channelList.insertMultiple (0, nullptr, 128);
  1753. const AudioProcessor& p = getPluginInstance();
  1754. buffer.setSize (jmax (p.getTotalNumInputChannels(), p.getTotalNumOutputChannels()), p.getBlockSize() * 4);
  1755. buffer.clear();
  1756. }
  1757. template <typename FloatType>
  1758. void deallocateChannelListAndBuffers (Array<FloatType*>& channelList, AudioBuffer<FloatType>& buffer)
  1759. {
  1760. channelList.clearQuick();
  1761. channelList.resize (0);
  1762. buffer.setSize (0, 0);
  1763. }
  1764. template <typename FloatType>
  1765. static FloatType** getPointerForAudioBus (Vst::AudioBusBuffers& data) noexcept
  1766. {
  1767. return AudioBusPointerHelper<FloatType>::impl (data);
  1768. }
  1769. template <typename FloatType>
  1770. FloatType* getTmpBufferForChannel (int channel, int numSamples) noexcept
  1771. {
  1772. AudioBuffer<FloatType>& buffer = ChooseBufferHelper<FloatType>::impl (emptyBufferFloat, emptyBufferDouble);
  1773. // we can't do anything if the host requests to render many more samples than the
  1774. // block size, we need to bail out
  1775. if (numSamples > buffer.getNumSamples() || channel >= buffer.getNumChannels())
  1776. return nullptr;
  1777. return buffer.getWritePointer (channel);
  1778. }
  1779. void preparePlugin (double sampleRate, int bufferSize)
  1780. {
  1781. AudioProcessor& p = getPluginInstance();
  1782. p.setRateAndBufferSizeDetails (sampleRate, bufferSize);
  1783. p.prepareToPlay (sampleRate, bufferSize);
  1784. }
  1785. //==============================================================================
  1786. #if JUCE_FORCE_USE_LEGACY_PARAM_IDS
  1787. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept { return static_cast<Vst::ParamID> (paramIndex); }
  1788. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept { return static_cast<int> (paramID); }
  1789. #else
  1790. void cacheParameterIDs()
  1791. {
  1792. const int numParameters = pluginInstance->getNumParameters();
  1793. usingManagedParameter = (pluginInstance->getParameters().size() == numParameters);
  1794. vstBypassParameterId = static_cast<Vst::ParamID> (usingManagedParameter ? JuceVST3EditController::paramBypass : numParameters);
  1795. for (int i = 0; i < numParameters; ++i)
  1796. {
  1797. const Vst::ParamID paramID = JuceVST3EditController::generateVSTParamIDForIndex (pluginInstance, i);
  1798. // Consider yourself very unlucky if you hit this assertion. The hash code of your
  1799. // parameter ids are not unique.
  1800. jassert (! vstParamIDs.contains (static_cast<Vst::ParamID> (paramID)));
  1801. vstParamIDs.add (paramID);
  1802. paramMap.set (static_cast<int32> (paramID), i);
  1803. }
  1804. }
  1805. inline Vst::ParamID getVSTParamIDForIndex (int paramIndex) const noexcept
  1806. {
  1807. return usingManagedParameter ? vstParamIDs.getReference (paramIndex)
  1808. : static_cast<Vst::ParamID> (paramIndex);
  1809. }
  1810. inline int getJuceIndexForVSTParamID (Vst::ParamID paramID) const noexcept
  1811. {
  1812. return usingManagedParameter ? paramMap[static_cast<int32> (paramID)]
  1813. : static_cast<int> (paramID);
  1814. }
  1815. #endif
  1816. //==============================================================================
  1817. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1818. };
  1819. const char* JuceVST3Component::kJucePrivateDataIdentifier = "JUCEPrivateData";
  1820. //==============================================================================
  1821. #if JUCE_MSVC
  1822. #pragma warning (push, 0)
  1823. #pragma warning (disable: 4310)
  1824. #elif JUCE_CLANG
  1825. #pragma clang diagnostic push
  1826. #pragma clang diagnostic ignored "-Wall"
  1827. #endif
  1828. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1829. DEF_CLASS_IID (JuceAudioProcessor)
  1830. #if JUCE_VST3_CAN_REPLACE_VST2
  1831. FUID getFUIDForVST2ID (bool forControllerUID)
  1832. {
  1833. TUID uuid;
  1834. extern JUCE_API void getUUIDForVST2ID (bool, uint8[16]);
  1835. getUUIDForVST2ID (forControllerUID, (uint8*) uuid);
  1836. return FUID (uuid);
  1837. }
  1838. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1839. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1840. #else
  1841. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1842. DEF_CLASS_IID (JuceVST3EditController)
  1843. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1844. DEF_CLASS_IID (JuceVST3Component)
  1845. #endif
  1846. #if JUCE_MSVC
  1847. #pragma warning (pop)
  1848. #elif JUCE_CLANG
  1849. #pragma clang diagnostic pop
  1850. #endif
  1851. //==============================================================================
  1852. bool initModule()
  1853. {
  1854. #if JUCE_MAC
  1855. initialiseMacVST();
  1856. #endif
  1857. return true;
  1858. }
  1859. bool shutdownModule()
  1860. {
  1861. return true;
  1862. }
  1863. #undef JUCE_EXPORTED_FUNCTION
  1864. #if JUCE_WINDOWS
  1865. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1866. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1867. #define JUCE_EXPORTED_FUNCTION
  1868. #else
  1869. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1870. CFBundleRef globalBundleInstance = nullptr;
  1871. juce::uint32 numBundleRefs = 0;
  1872. juce::Array<CFBundleRef> bundleRefs;
  1873. enum { MaxPathLength = 2048 };
  1874. char modulePath[MaxPathLength] = { 0 };
  1875. void* moduleHandle = nullptr;
  1876. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1877. {
  1878. if (ref != nullptr)
  1879. {
  1880. ++numBundleRefs;
  1881. CFRetain (ref);
  1882. bundleRefs.add (ref);
  1883. if (moduleHandle == nullptr)
  1884. {
  1885. globalBundleInstance = ref;
  1886. moduleHandle = ref;
  1887. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1888. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1889. CFRelease (tempURL);
  1890. }
  1891. }
  1892. return initModule();
  1893. }
  1894. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1895. {
  1896. if (shutdownModule())
  1897. {
  1898. if (--numBundleRefs == 0)
  1899. {
  1900. for (int i = 0; i < bundleRefs.size(); ++i)
  1901. CFRelease (bundleRefs.getUnchecked (i));
  1902. bundleRefs.clear();
  1903. }
  1904. return true;
  1905. }
  1906. return false;
  1907. }
  1908. #endif
  1909. //==============================================================================
  1910. /** This typedef represents VST3's createInstance() function signature */
  1911. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1912. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1913. {
  1914. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1915. }
  1916. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1917. {
  1918. return (Vst::IEditController*) new JuceVST3EditController (host);
  1919. }
  1920. //==============================================================================
  1921. class JucePluginFactory;
  1922. static JucePluginFactory* globalFactory = nullptr;
  1923. //==============================================================================
  1924. class JucePluginFactory : public IPluginFactory3
  1925. {
  1926. public:
  1927. JucePluginFactory()
  1928. : refCount (1),
  1929. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1930. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1931. {
  1932. }
  1933. virtual ~JucePluginFactory()
  1934. {
  1935. if (globalFactory == this)
  1936. globalFactory = nullptr;
  1937. }
  1938. //==============================================================================
  1939. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1940. {
  1941. if (createFunction == nullptr)
  1942. {
  1943. jassertfalse;
  1944. return false;
  1945. }
  1946. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1947. entry->infoW.fromAscii (info);
  1948. return true;
  1949. }
  1950. bool isClassRegistered (const FUID& cid) const
  1951. {
  1952. for (int i = 0; i < classes.size(); ++i)
  1953. if (classes.getUnchecked (i)->infoW.cid == cid)
  1954. return true;
  1955. return false;
  1956. }
  1957. //==============================================================================
  1958. JUCE_DECLARE_VST3_COM_REF_METHODS
  1959. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1960. {
  1961. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1962. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1963. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1964. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1965. jassertfalse; // Something new?
  1966. *obj = nullptr;
  1967. return kNotImplemented;
  1968. }
  1969. //==============================================================================
  1970. Steinberg::int32 PLUGIN_API countClasses() override
  1971. {
  1972. return (Steinberg::int32) classes.size();
  1973. }
  1974. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1975. {
  1976. if (info == nullptr)
  1977. return kInvalidArgument;
  1978. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1979. return kResultOk;
  1980. }
  1981. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1982. {
  1983. return getPClassInfo<PClassInfo> (index, info);
  1984. }
  1985. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1986. {
  1987. return getPClassInfo<PClassInfo2> (index, info);
  1988. }
  1989. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1990. {
  1991. if (info != nullptr)
  1992. {
  1993. if (ClassEntry* entry = classes[(int) index])
  1994. {
  1995. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1996. return kResultOk;
  1997. }
  1998. }
  1999. return kInvalidArgument;
  2000. }
  2001. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  2002. {
  2003. *obj = nullptr;
  2004. FUID sourceFuid = sourceIid;
  2005. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  2006. {
  2007. jassertfalse; // The host you're running in has severe implementation issues!
  2008. return kInvalidArgument;
  2009. }
  2010. TUID iidToQuery;
  2011. sourceFuid.toTUID (iidToQuery);
  2012. for (int i = 0; i < classes.size(); ++i)
  2013. {
  2014. const ClassEntry& entry = *classes.getUnchecked (i);
  2015. if (doUIDsMatch (entry.infoW.cid, cid))
  2016. {
  2017. if (FUnknown* const instance = entry.createFunction (host))
  2018. {
  2019. const FReleaser releaser (instance);
  2020. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  2021. return kResultOk;
  2022. }
  2023. break;
  2024. }
  2025. }
  2026. return kNoInterface;
  2027. }
  2028. tresult PLUGIN_API setHostContext (FUnknown* context) override
  2029. {
  2030. host.loadFrom (context);
  2031. if (host != nullptr)
  2032. {
  2033. Vst::String128 name;
  2034. host->getName (name);
  2035. return kResultTrue;
  2036. }
  2037. return kNotImplemented;
  2038. }
  2039. private:
  2040. //==============================================================================
  2041. ScopedJuceInitialiser_GUI libraryInitialiser;
  2042. Atomic<int> refCount;
  2043. const PFactoryInfo factoryInfo;
  2044. ComSmartPtr<Vst::IHostApplication> host;
  2045. //==============================================================================
  2046. struct ClassEntry
  2047. {
  2048. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  2049. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  2050. : info2 (info), createFunction (fn), isUnicode (false) {}
  2051. PClassInfo2 info2;
  2052. PClassInfoW infoW;
  2053. CreateFunction createFunction;
  2054. bool isUnicode;
  2055. private:
  2056. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  2057. };
  2058. OwnedArray<ClassEntry> classes;
  2059. //==============================================================================
  2060. template<class PClassInfoType>
  2061. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  2062. {
  2063. if (info != nullptr)
  2064. {
  2065. zerostruct (*info);
  2066. if (ClassEntry* entry = classes[(int) index])
  2067. {
  2068. if (entry->isUnicode)
  2069. return kResultFalse;
  2070. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  2071. return kResultOk;
  2072. }
  2073. }
  2074. jassertfalse;
  2075. return kInvalidArgument;
  2076. }
  2077. //==============================================================================
  2078. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  2079. };
  2080. } // juce namespace
  2081. //==============================================================================
  2082. #ifndef JucePlugin_Vst3ComponentFlags
  2083. #if JucePlugin_IsSynth
  2084. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  2085. #else
  2086. #define JucePlugin_Vst3ComponentFlags 0
  2087. #endif
  2088. #endif
  2089. #ifndef JucePlugin_Vst3Category
  2090. #if JucePlugin_IsSynth
  2091. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  2092. #else
  2093. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  2094. #endif
  2095. #endif
  2096. //==============================================================================
  2097. // The VST3 plugin entry point.
  2098. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  2099. {
  2100. PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_VST3;
  2101. #if JUCE_WINDOWS
  2102. // Cunning trick to force this function to be exported. Life's too short to
  2103. // faff around creating .def files for this kind of thing.
  2104. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  2105. #endif
  2106. if (globalFactory == nullptr)
  2107. {
  2108. globalFactory = new JucePluginFactory();
  2109. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  2110. PClassInfo::kManyInstances,
  2111. kVstAudioEffectClass,
  2112. JucePlugin_Name,
  2113. JucePlugin_Vst3ComponentFlags,
  2114. JucePlugin_Vst3Category,
  2115. JucePlugin_Manufacturer,
  2116. JucePlugin_VersionString,
  2117. kVstVersionString);
  2118. globalFactory->registerClass (componentClass, createComponentInstance);
  2119. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  2120. PClassInfo::kManyInstances,
  2121. kVstComponentControllerClass,
  2122. JucePlugin_Name,
  2123. JucePlugin_Vst3ComponentFlags,
  2124. JucePlugin_Vst3Category,
  2125. JucePlugin_Manufacturer,
  2126. JucePlugin_VersionString,
  2127. kVstVersionString);
  2128. globalFactory->registerClass (controllerClass, createControllerInstance);
  2129. }
  2130. else
  2131. {
  2132. globalFactory->addRef();
  2133. }
  2134. return dynamic_cast<IPluginFactory*> (globalFactory);
  2135. }
  2136. //==============================================================================
  2137. #if _MSC_VER || JUCE_MINGW
  2138. extern "C" BOOL WINAPI DllMain (HINSTANCE instance, DWORD reason, LPVOID) { if (reason == DLL_PROCESS_ATTACH) Process::setCurrentModuleInstanceHandle (instance); return true; }
  2139. #endif
  2140. #endif //JucePlugin_Build_VST3