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.

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