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.

2553 lines
94KB

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