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.

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