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.

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