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.

1928 lines
67KB

  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. // Your project must contain an AppConfig.h file with your project-specific settings in it,
  18. // and your header search path must make it accessible to the module's files.
  19. #include "AppConfig.h"
  20. //==============================================================================
  21. #if JucePlugin_Build_VST3 && (__APPLE_CPP__ || __APPLE_CC__ || _WIN32 || _WIN64)
  22. #include "../../juce_audio_processors/format_types/juce_VST3Headers.h"
  23. #include "../utility/juce_CheckSettingMacros.h"
  24. #include "../utility/juce_IncludeModuleHeaders.h"
  25. #include "../utility/juce_WindowsHooks.h"
  26. #include "../../juce_audio_processors/format_types/juce_VST3Common.h"
  27. #ifndef JUCE_VST3_CAN_REPLACE_VST2
  28. #define JUCE_VST3_CAN_REPLACE_VST2 1
  29. #endif
  30. #if JUCE_VST3_CAN_REPLACE_VST2
  31. #if JUCE_MSVC
  32. #pragma warning (push)
  33. #pragma warning (disable: 4514 4996)
  34. #endif
  35. #include <pluginterfaces/vst2.x/vstfxstore.h>
  36. #if JUCE_MSVC
  37. #pragma warning (pop)
  38. #endif
  39. #endif
  40. #undef Point
  41. #undef Component
  42. namespace juce
  43. {
  44. using namespace Steinberg;
  45. //==============================================================================
  46. #if JUCE_MAC
  47. extern void initialiseMac();
  48. extern void* attachComponentToWindowRef (Component*, void* parent, bool isNSView);
  49. extern void detachComponentFromWindowRef (Component*, void* window, bool isNSView);
  50. extern void setNativeHostWindowSize (void* window, Component*, int newWidth, int newHeight, bool isNSView);
  51. #endif
  52. //==============================================================================
  53. class JuceAudioProcessor : public FUnknown
  54. {
  55. public:
  56. JuceAudioProcessor (AudioProcessor* source) noexcept
  57. : refCount (0), audioProcessor (source) {}
  58. virtual ~JuceAudioProcessor() {}
  59. AudioProcessor* get() const noexcept { return audioProcessor; }
  60. JUCE_DECLARE_VST3_COM_QUERY_METHODS
  61. JUCE_DECLARE_VST3_COM_REF_METHODS
  62. static const FUID iid;
  63. private:
  64. Atomic<int> refCount;
  65. ScopedPointer<AudioProcessor> audioProcessor;
  66. ScopedJuceInitialiser_GUI libraryInitialiser;
  67. JuceAudioProcessor() JUCE_DELETED_FUNCTION;
  68. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceAudioProcessor)
  69. };
  70. //==============================================================================
  71. class JuceVST3EditController : public Vst::EditController,
  72. public Vst::IMidiMapping,
  73. public AudioProcessorListener
  74. {
  75. public:
  76. JuceVST3EditController (Vst::IHostApplication* host)
  77. {
  78. if (host != nullptr)
  79. host->queryInterface (FUnknown::iid, (void**) &hostContext);
  80. }
  81. //==============================================================================
  82. static const FUID iid;
  83. //==============================================================================
  84. REFCOUNT_METHODS (ComponentBase)
  85. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  86. {
  87. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FObject)
  88. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3EditController)
  89. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController)
  90. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IEditController2)
  91. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  92. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IMidiMapping)
  93. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IPluginBase, Vst::IEditController)
  94. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, IDependent, Vst::IEditController)
  95. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IEditController)
  96. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  97. {
  98. audioProcessor->addRef();
  99. *obj = audioProcessor;
  100. return kResultOk;
  101. }
  102. *obj = nullptr;
  103. return kNoInterface;
  104. }
  105. //==============================================================================
  106. tresult PLUGIN_API initialize (FUnknown* context) override
  107. {
  108. if (hostContext != context)
  109. {
  110. if (hostContext != nullptr)
  111. hostContext->release();
  112. hostContext = context;
  113. if (hostContext != nullptr)
  114. hostContext->addRef();
  115. }
  116. return kResultTrue;
  117. }
  118. tresult PLUGIN_API terminate() override
  119. {
  120. if (AudioProcessor* const pluginInstance = getPluginInstance())
  121. pluginInstance->removeListener (this);
  122. audioProcessor = nullptr;
  123. return EditController::terminate();
  124. }
  125. //==============================================================================
  126. struct Param : public Vst::Parameter
  127. {
  128. Param (AudioProcessor& p, int index) : owner (p), paramIndex (index)
  129. {
  130. info.id = (Vst::ParamID) index;
  131. toString128 (info.title, p.getParameterName (index));
  132. toString128 (info.shortTitle, p.getParameterName (index, 8));
  133. toString128 (info.units, p.getParameterLabel (index));
  134. const int numSteps = p.getParameterNumSteps (index);
  135. info.stepCount = (Steinberg::int32) (numSteps > 0 && numSteps < 0x7fffffff ? numSteps - 1 : 0);
  136. info.defaultNormalizedValue = p.getParameterDefaultValue (index);
  137. jassert (info.defaultNormalizedValue >= 0 && info.defaultNormalizedValue <= 1.0f);
  138. info.unitId = Vst::kRootUnitId;
  139. info.flags = p.isParameterAutomatable (index) ? Vst::ParameterInfo::kCanAutomate : 0;
  140. }
  141. virtual ~Param() {}
  142. bool setNormalized (Vst::ParamValue v) override
  143. {
  144. v = jlimit (0.0, 1.0, v);
  145. if (v != valueNormalized)
  146. {
  147. valueNormalized = v;
  148. changed();
  149. return true;
  150. }
  151. return false;
  152. }
  153. void toString (Vst::ParamValue value, Vst::String128 result) const override
  154. {
  155. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  156. toString128 (result, p->getText ((float) value, 128));
  157. else
  158. // remain backward-compatible with old JUCE code
  159. toString128 (result, owner.getParameterText (paramIndex, 128));
  160. }
  161. bool fromString (const Vst::TChar* text, Vst::ParamValue& outValueNormalized) const override
  162. {
  163. if (AudioProcessorParameter* p = owner.getParameters()[paramIndex])
  164. {
  165. outValueNormalized = p->getValueForText (getStringFromVstTChars (text));
  166. return true;
  167. }
  168. return false;
  169. }
  170. static String getStringFromVstTChars (const Vst::TChar* text)
  171. {
  172. return juce::String (juce::CharPointer_UTF16 (reinterpret_cast<const juce::CharPointer_UTF16::CharType*> (text)));
  173. }
  174. Vst::ParamValue toPlain (Vst::ParamValue v) const override { return v; }
  175. Vst::ParamValue toNormalized (Vst::ParamValue v) const override { return v; }
  176. private:
  177. AudioProcessor& owner;
  178. int paramIndex;
  179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Param)
  180. };
  181. //==============================================================================
  182. tresult PLUGIN_API setComponentState (IBStream* stream) override
  183. {
  184. // Cubase and Nuendo need to inform the host of the current parameter values
  185. if (AudioProcessor* const pluginInstance = getPluginInstance())
  186. {
  187. for (int i = 0; i < pluginInstance->getNumParameters(); ++i)
  188. setParamNormalized ((Vst::ParamID) i, (double) pluginInstance->getParameter (i));
  189. }
  190. return Vst::EditController::setComponentState (stream);
  191. }
  192. void setAudioProcessor (JuceAudioProcessor* audioProc)
  193. {
  194. if (audioProcessor != audioProc)
  195. {
  196. audioProcessor = audioProc;
  197. setupParameters();
  198. }
  199. }
  200. tresult PLUGIN_API connect (IConnectionPoint* other) override
  201. {
  202. if (other != nullptr && audioProcessor == nullptr)
  203. {
  204. const tresult result = ComponentBase::connect (other);
  205. if (! audioProcessor.loadFrom (other))
  206. sendIntMessage ("JuceVST3EditController", (Steinberg::int64) (pointer_sized_int) this);
  207. else
  208. setupParameters();
  209. return result;
  210. }
  211. jassertfalse;
  212. return kResultFalse;
  213. }
  214. //==============================================================================
  215. tresult PLUGIN_API getMidiControllerAssignment (Steinberg::int32 /*busIndex*/, Steinberg::int16 channel,
  216. Vst::CtrlNumber midiControllerNumber, Vst::ParamID& resultID) override
  217. {
  218. resultID = midiControllerToParameter[channel][midiControllerNumber];
  219. return kResultTrue; // Returning false makes some hosts stop asking for further MIDI Controller Assignments
  220. }
  221. // Converts an incoming parameter index to a MIDI controller:
  222. bool getMidiControllerForParameter (int index, int& channel, int& ctrlNumber)
  223. {
  224. const int mappedIndex = index - parameterToMidiControllerOffset;
  225. if (isPositiveAndBelow (mappedIndex, numElementsInArray (parameterToMidiController)))
  226. {
  227. const MidiController& mc = parameterToMidiController[mappedIndex];
  228. if (mc.channel != -1 && mc.ctrlNumber != -1)
  229. {
  230. channel = jlimit (1, 16, mc.channel + 1);
  231. ctrlNumber = mc.ctrlNumber;
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. //==============================================================================
  238. IPlugView* PLUGIN_API createView (const char* name) override
  239. {
  240. if (AudioProcessor* const pluginInstance = getPluginInstance())
  241. {
  242. if (pluginInstance->hasEditor() && name != nullptr
  243. && strcmp (name, Vst::ViewType::kEditor) == 0)
  244. {
  245. return new JuceVST3Editor (*this, *pluginInstance);
  246. }
  247. }
  248. return nullptr;
  249. }
  250. //==============================================================================
  251. void audioProcessorParameterChangeGestureBegin (AudioProcessor*, int index) override { beginEdit ((Vst::ParamID) index); }
  252. void audioProcessorParameterChanged (AudioProcessor*, int index, float newValue) override
  253. {
  254. // NB: Cubase has problems if performEdit is called without setParamNormalized
  255. EditController::setParamNormalized ((Vst::ParamID) index, (double) newValue);
  256. performEdit ((Vst::ParamID) index, (double) newValue);
  257. }
  258. void audioProcessorParameterChangeGestureEnd (AudioProcessor*, int index) override { endEdit ((Vst::ParamID) index); }
  259. void audioProcessorChanged (AudioProcessor*) override
  260. {
  261. if (componentHandler != nullptr)
  262. componentHandler->restartComponent (Vst::kLatencyChanged | Vst::kParamValuesChanged);
  263. }
  264. //==============================================================================
  265. AudioProcessor* getPluginInstance() const noexcept
  266. {
  267. if (audioProcessor != nullptr)
  268. return audioProcessor->get();
  269. return nullptr;
  270. }
  271. private:
  272. //==============================================================================
  273. ComSmartPtr<JuceAudioProcessor> audioProcessor;
  274. ScopedJuceInitialiser_GUI libraryInitialiser;
  275. struct MidiController
  276. {
  277. MidiController() noexcept : channel (-1), ctrlNumber (-1) {}
  278. int channel, ctrlNumber;
  279. };
  280. enum { numMIDIChannels = 16 };
  281. int parameterToMidiControllerOffset;
  282. MidiController parameterToMidiController[numMIDIChannels * Vst::kCountCtrlNumber];
  283. int midiControllerToParameter[numMIDIChannels][Vst::kCountCtrlNumber];
  284. //==============================================================================
  285. void setupParameters()
  286. {
  287. if (AudioProcessor* const pluginInstance = getPluginInstance())
  288. {
  289. pluginInstance->addListener (this);
  290. if (parameters.getParameterCount() <= 0)
  291. for (int i = 0; i < pluginInstance->getNumParameters(); ++i)
  292. parameters.addParameter (new Param (*pluginInstance, i));
  293. initialiseMidiControllerMappings (pluginInstance->getNumParameters());
  294. audioProcessorChanged (pluginInstance);
  295. }
  296. }
  297. void initialiseMidiControllerMappings (const int numParameters)
  298. {
  299. parameterToMidiControllerOffset = numParameters;
  300. for (int c = 0, p = 0; c < numMIDIChannels; ++c)
  301. {
  302. for (int i = 0; i < Vst::kCountCtrlNumber; ++i, ++p)
  303. {
  304. midiControllerToParameter[c][i] = p + parameterToMidiControllerOffset;
  305. parameterToMidiController[p].channel = c;
  306. parameterToMidiController[p].ctrlNumber = i;
  307. parameters.addParameter (new Vst::Parameter (toString ("MIDI CC " + String (c) + "|" + String (i)),
  308. p + parameterToMidiControllerOffset, 0, 0, 0,
  309. Vst::ParameterInfo::kCanAutomate, Vst::kRootUnitId));
  310. }
  311. }
  312. }
  313. void sendIntMessage (const char* idTag, const Steinberg::int64 value)
  314. {
  315. jassert (hostContext != nullptr);
  316. if (Vst::IMessage* message = allocateMessage())
  317. {
  318. const FReleaser releaser (message);
  319. message->setMessageID (idTag);
  320. message->getAttributes()->setInt (idTag, value);
  321. sendMessage (message);
  322. }
  323. }
  324. //==============================================================================
  325. class JuceVST3Editor : public Vst::EditorView
  326. {
  327. public:
  328. JuceVST3Editor (JuceVST3EditController& ec, AudioProcessor& p)
  329. : Vst::EditorView (&ec, nullptr),
  330. owner (&ec), pluginInstance (p)
  331. {
  332. #if JUCE_MAC
  333. macHostWindow = nullptr;
  334. isNSView = false;
  335. #endif
  336. component = new ContentWrapperComponent (*this, p);
  337. }
  338. //==============================================================================
  339. tresult PLUGIN_API isPlatformTypeSupported (FIDString type) override
  340. {
  341. if (type != nullptr && pluginInstance.hasEditor())
  342. {
  343. #if JUCE_WINDOWS
  344. if (strcmp (type, kPlatformTypeHWND) == 0)
  345. #else
  346. if (strcmp (type, kPlatformTypeNSView) == 0 || strcmp (type, kPlatformTypeHIView) == 0)
  347. #endif
  348. return kResultTrue;
  349. }
  350. return kResultFalse;
  351. }
  352. tresult PLUGIN_API attached (void* parent, FIDString type) override
  353. {
  354. if (parent == nullptr || isPlatformTypeSupported (type) == kResultFalse)
  355. return kResultFalse;
  356. if (component == nullptr)
  357. component = new ContentWrapperComponent (*this, pluginInstance);
  358. #if JUCE_WINDOWS
  359. component->addToDesktop (0, parent);
  360. component->setOpaque (true);
  361. component->setVisible (true);
  362. #else
  363. isNSView = (strcmp (type, kPlatformTypeNSView) == 0);
  364. macHostWindow = juce::attachComponentToWindowRef (component, parent, isNSView);
  365. #endif
  366. component->resizeHostWindow();
  367. systemWindow = parent;
  368. attachedToParent();
  369. return kResultTrue;
  370. }
  371. tresult PLUGIN_API removed() override
  372. {
  373. if (component != nullptr)
  374. {
  375. #if JUCE_WINDOWS
  376. component->removeFromDesktop();
  377. #else
  378. if (macHostWindow != nullptr)
  379. {
  380. juce::detachComponentFromWindowRef (component, macHostWindow, isNSView);
  381. macHostWindow = nullptr;
  382. }
  383. #endif
  384. component = nullptr;
  385. }
  386. return CPluginView::removed();
  387. }
  388. tresult PLUGIN_API onSize (ViewRect* newSize) override
  389. {
  390. if (newSize != nullptr)
  391. {
  392. rect = *newSize;
  393. if (component != nullptr)
  394. component->setSize (rect.getWidth(), rect.getHeight());
  395. return kResultTrue;
  396. }
  397. jassertfalse;
  398. return kResultFalse;
  399. }
  400. tresult PLUGIN_API getSize (ViewRect* size) override
  401. {
  402. if (size != nullptr && component != nullptr)
  403. {
  404. *size = ViewRect (0, 0, component->getWidth(), component->getHeight());
  405. return kResultTrue;
  406. }
  407. return kResultFalse;
  408. }
  409. tresult PLUGIN_API canResize() override { return kResultTrue; }
  410. tresult PLUGIN_API checkSizeConstraint (ViewRect* rectToCheck) override
  411. {
  412. if (rectToCheck != nullptr && component != nullptr)
  413. {
  414. rectToCheck->right = rectToCheck->left + component->getWidth();
  415. rectToCheck->bottom = rectToCheck->top + component->getHeight();
  416. return kResultTrue;
  417. }
  418. jassertfalse;
  419. return kResultFalse;
  420. }
  421. private:
  422. //==============================================================================
  423. class ContentWrapperComponent : public juce::Component
  424. {
  425. public:
  426. ContentWrapperComponent (JuceVST3Editor& editor, AudioProcessor& plugin)
  427. : owner (editor),
  428. pluginEditor (plugin.createEditorIfNeeded())
  429. {
  430. setOpaque (true);
  431. setBroughtToFrontOnMouseClick (true);
  432. // if hasEditor() returns true then createEditorIfNeeded has to return a valid editor
  433. jassert (pluginEditor != nullptr);
  434. if (pluginEditor != nullptr)
  435. {
  436. addAndMakeVisible (pluginEditor);
  437. setBounds (pluginEditor->getLocalBounds());
  438. resizeHostWindow();
  439. }
  440. }
  441. ~ContentWrapperComponent()
  442. {
  443. if (pluginEditor != nullptr)
  444. {
  445. PopupMenu::dismissAllActiveMenus();
  446. pluginEditor->processor.editorBeingDeleted (pluginEditor);
  447. }
  448. }
  449. void paint (Graphics& g) override
  450. {
  451. g.fillAll (Colours::black);
  452. }
  453. void childBoundsChanged (Component*) override
  454. {
  455. resizeHostWindow();
  456. }
  457. void resized() override
  458. {
  459. if (pluginEditor != nullptr)
  460. pluginEditor->setBounds (getLocalBounds());
  461. }
  462. void resizeHostWindow()
  463. {
  464. if (pluginEditor != nullptr)
  465. {
  466. const int w = pluginEditor->getWidth();
  467. const int h = pluginEditor->getHeight();
  468. #if JUCE_WINDOWS
  469. setSize (w, h);
  470. #else
  471. if (owner.macHostWindow != nullptr && ! getHostType().isWavelab())
  472. juce::setNativeHostWindowSize (owner.macHostWindow, this, w, h, owner.isNSView);
  473. #endif
  474. if (owner.plugFrame != nullptr)
  475. {
  476. ViewRect newSize (0, 0, w, h);
  477. owner.plugFrame->resizeView (&owner, &newSize);
  478. if (getHostType().isWavelab())
  479. setBounds (0, 0, w, h);
  480. }
  481. }
  482. }
  483. private:
  484. JuceVST3Editor& owner;
  485. ScopedPointer<AudioProcessorEditor> pluginEditor;
  486. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContentWrapperComponent)
  487. };
  488. //==============================================================================
  489. ComSmartPtr<JuceVST3EditController> owner;
  490. AudioProcessor& pluginInstance;
  491. ScopedPointer<ContentWrapperComponent> component;
  492. friend class ContentWrapperComponent;
  493. #if JUCE_MAC
  494. void* macHostWindow;
  495. bool isNSView;
  496. #endif
  497. #if JUCE_WINDOWS
  498. WindowsHooks hooks;
  499. #endif
  500. ScopedJuceInitialiser_GUI libraryInitialiser;
  501. //==============================================================================
  502. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Editor)
  503. };
  504. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3EditController)
  505. };
  506. //==============================================================================
  507. class JuceVST3Component : public Vst::IComponent,
  508. public Vst::IAudioProcessor,
  509. public Vst::IUnitInfo,
  510. public Vst::IConnectionPoint,
  511. public AudioPlayHead
  512. {
  513. public:
  514. JuceVST3Component (Vst::IHostApplication* h)
  515. : refCount (1),
  516. host (h),
  517. audioInputs (Vst::kAudio, Vst::kInput),
  518. audioOutputs (Vst::kAudio, Vst::kOutput),
  519. eventInputs (Vst::kEvent, Vst::kInput),
  520. eventOutputs (Vst::kEvent, Vst::kOutput)
  521. {
  522. pluginInstance = createPluginFilterOfType (AudioProcessor::wrapperType_VST3);
  523. comPluginInstance = new JuceAudioProcessor (pluginInstance);
  524. zerostruct (processContext);
  525. processSetup.maxSamplesPerBlock = 1024;
  526. processSetup.processMode = Vst::kRealtime;
  527. processSetup.sampleRate = 44100.0;
  528. processSetup.symbolicSampleSize = Vst::kSample32;
  529. pluginInstance->setPlayHead (this);
  530. }
  531. ~JuceVST3Component()
  532. {
  533. if (pluginInstance != nullptr)
  534. if (pluginInstance->getPlayHead() == this)
  535. pluginInstance->setPlayHead (nullptr);
  536. audioInputs.removeAll();
  537. audioOutputs.removeAll();
  538. eventInputs.removeAll();
  539. eventOutputs.removeAll();
  540. }
  541. //==============================================================================
  542. AudioProcessor& getPluginInstance() const noexcept { return *pluginInstance; }
  543. //==============================================================================
  544. static const FUID iid;
  545. JUCE_DECLARE_VST3_COM_REF_METHODS
  546. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  547. {
  548. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginBase)
  549. TEST_FOR_AND_RETURN_IF_VALID (targetIID, JuceVST3Component)
  550. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IComponent)
  551. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IAudioProcessor)
  552. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IUnitInfo)
  553. TEST_FOR_AND_RETURN_IF_VALID (targetIID, Vst::IConnectionPoint)
  554. TEST_FOR_COMMON_BASE_AND_RETURN_IF_VALID (targetIID, FUnknown, Vst::IComponent)
  555. if (doUIDsMatch (targetIID, JuceAudioProcessor::iid))
  556. {
  557. comPluginInstance->addRef();
  558. *obj = comPluginInstance;
  559. return kResultOk;
  560. }
  561. *obj = nullptr;
  562. return kNoInterface;
  563. }
  564. //==============================================================================
  565. tresult PLUGIN_API initialize (FUnknown* hostContext) override
  566. {
  567. if (host != hostContext)
  568. host.loadFrom (hostContext);
  569. #if JucePlugin_MaxNumInputChannels > 0
  570. addAudioBusTo (audioInputs, TRANS("Audio Input"),
  571. getArrangementForNumChannels (JucePlugin_MaxNumInputChannels));
  572. #endif
  573. #if JucePlugin_MaxNumOutputChannels > 0
  574. addAudioBusTo (audioOutputs, TRANS("Audio Output"),
  575. getArrangementForNumChannels (JucePlugin_MaxNumOutputChannels));
  576. #endif
  577. #if JucePlugin_WantsMidiInput
  578. addEventBusTo (eventInputs, TRANS("MIDI Input"));
  579. #endif
  580. #if JucePlugin_ProducesMidiOutput
  581. addEventBusTo (eventOutputs, TRANS("MIDI Output"));
  582. #endif
  583. processContext.sampleRate = processSetup.sampleRate;
  584. preparePlugin (processSetup.sampleRate, (int) processSetup.maxSamplesPerBlock);
  585. return kResultTrue;
  586. }
  587. tresult PLUGIN_API terminate() override
  588. {
  589. getPluginInstance().releaseResources();
  590. return kResultTrue;
  591. }
  592. //==============================================================================
  593. tresult PLUGIN_API connect (IConnectionPoint* other) override
  594. {
  595. if (other != nullptr && juceVST3EditController == nullptr)
  596. juceVST3EditController.loadFrom (other);
  597. return kResultTrue;
  598. }
  599. tresult PLUGIN_API disconnect (IConnectionPoint*) override
  600. {
  601. juceVST3EditController = nullptr;
  602. return kResultTrue;
  603. }
  604. tresult PLUGIN_API notify (Vst::IMessage* message) override
  605. {
  606. if (message != nullptr && juceVST3EditController == nullptr)
  607. {
  608. Steinberg::int64 value = 0;
  609. if (message->getAttributes()->getInt ("JuceVST3EditController", value) == kResultTrue)
  610. {
  611. juceVST3EditController = (JuceVST3EditController*) (pointer_sized_int) value;
  612. if (juceVST3EditController != nullptr)
  613. juceVST3EditController->setAudioProcessor (comPluginInstance);
  614. else
  615. jassertfalse;
  616. }
  617. }
  618. return kResultTrue;
  619. }
  620. //==============================================================================
  621. tresult PLUGIN_API getControllerClassId (TUID classID) override
  622. {
  623. memcpy (classID, JuceVST3EditController::iid, sizeof (TUID));
  624. return kResultTrue;
  625. }
  626. Steinberg::int32 PLUGIN_API getBusCount (Vst::MediaType type, Vst::BusDirection dir) override
  627. {
  628. if (Vst::BusList* const busList = getBusListFor (type, dir))
  629. return busList->total();
  630. return 0;
  631. }
  632. tresult PLUGIN_API getBusInfo (Vst::MediaType type, Vst::BusDirection dir,
  633. Steinberg::int32 index, Vst::BusInfo& info) override
  634. {
  635. if (Vst::BusList* const busList = getBusListFor (type, dir))
  636. {
  637. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  638. {
  639. info.mediaType = type;
  640. info.direction = dir;
  641. if (bus->getInfo (info))
  642. return kResultTrue;
  643. }
  644. }
  645. zerostruct (info);
  646. return kResultFalse;
  647. }
  648. tresult PLUGIN_API activateBus (Vst::MediaType type, Vst::BusDirection dir,
  649. Steinberg::int32 index, TBool state) override
  650. {
  651. if (Vst::BusList* const busList = getBusListFor (type, dir))
  652. {
  653. if (Vst::Bus* const bus = (Vst::Bus*) busList->at (index))
  654. {
  655. bus->setActive (state);
  656. return kResultTrue;
  657. }
  658. }
  659. jassertfalse;
  660. return kResultFalse;
  661. }
  662. tresult PLUGIN_API setActive (TBool state) override
  663. {
  664. if (! state)
  665. {
  666. getPluginInstance().releaseResources();
  667. }
  668. else
  669. {
  670. double sampleRate = getPluginInstance().getSampleRate();
  671. int bufferSize = getPluginInstance().getBlockSize();
  672. sampleRate = processSetup.sampleRate > 0.0
  673. ? processSetup.sampleRate
  674. : sampleRate;
  675. bufferSize = processSetup.maxSamplesPerBlock > 0
  676. ? (int) processSetup.maxSamplesPerBlock
  677. : bufferSize;
  678. channelList.clear();
  679. channelList.insertMultiple (0, nullptr, jmax (JucePlugin_MaxNumInputChannels, JucePlugin_MaxNumOutputChannels) + 1);
  680. preparePlugin (sampleRate, bufferSize);
  681. }
  682. return kResultOk;
  683. }
  684. tresult PLUGIN_API setIoMode (Vst::IoMode) override { return kNotImplemented; }
  685. tresult PLUGIN_API getRoutingInfo (Vst::RoutingInfo&, Vst::RoutingInfo&) override { return kNotImplemented; }
  686. #if JUCE_VST3_CAN_REPLACE_VST2
  687. void loadVST2VstWBlock (const char* data, int size)
  688. {
  689. const int headerLen = htonl (*(juce::int32*) (data + 4));
  690. const struct fxBank* bank = (const struct fxBank*) (data + (8 + headerLen));
  691. const int version = htonl (bank->version); (void) version;
  692. jassert ('VstW' == htonl (*(juce::int32*) data));
  693. jassert (1 == htonl (*(juce::int32*) (data + 8))); // version should be 1 according to Steinberg's docs
  694. jassert (cMagic == htonl (bank->chunkMagic));
  695. jassert (chunkBankMagic == htonl (bank->fxMagic));
  696. jassert (version == 1 || version == 2);
  697. jassert (JucePlugin_VSTUniqueID == htonl (bank->fxID));
  698. pluginInstance->setStateInformation (bank->content.data.chunk,
  699. jmin ((int) (size - (bank->content.data.chunk - data)),
  700. (int) htonl (bank->content.data.size)));
  701. }
  702. bool loadVST3PresetFile (const char* data, int size)
  703. {
  704. if (size < 48)
  705. return false;
  706. // At offset 4 there's a little-endian version number which seems to typically be 1
  707. // At offset 8 there's 32 bytes the SDK calls "ASCII-encoded class id"
  708. const int chunkListOffset = (int) ByteOrder::littleEndianInt (data + 40);
  709. jassert (memcmp (data + chunkListOffset, "List", 4) == 0);
  710. const int entryCount = (int) ByteOrder::littleEndianInt (data + chunkListOffset + 4);
  711. jassert (entryCount > 0);
  712. for (int i = 0; i < entryCount; ++i)
  713. {
  714. const int entryOffset = chunkListOffset + 8 + 20 * i;
  715. if (entryOffset + 20 > size)
  716. return false;
  717. if (memcmp (data + entryOffset, "Comp", 4) == 0)
  718. {
  719. // "Comp" entries seem to contain the data.
  720. juce::uint64 chunkOffset = ByteOrder::littleEndianInt64 (data + entryOffset + 4);
  721. juce::uint64 chunkSize = ByteOrder::littleEndianInt64 (data + entryOffset + 12);
  722. if (chunkOffset + chunkSize > size)
  723. {
  724. jassertfalse;
  725. return false;
  726. }
  727. loadVST2VstWBlock (data + chunkOffset, (int) chunkSize);
  728. }
  729. }
  730. return true;
  731. }
  732. bool loadVST2CompatibleState (const char* data, int size)
  733. {
  734. if (size < 4)
  735. return false;
  736. if (htonl (*(juce::int32*) data) == 'VstW')
  737. {
  738. loadVST2VstWBlock (data, size);
  739. return true;
  740. }
  741. if (memcmp (data, "VST3", 4) == 0)
  742. {
  743. // In Cubase 5, when loading VST3 .vstpreset files,
  744. // we get the whole content of the files to load.
  745. // In Cubase 7 we get just the contents within and
  746. // we go directly to the loadVST2VstW codepath instead.
  747. return loadVST3PresetFile (data, size);
  748. }
  749. return false;
  750. }
  751. #endif
  752. bool loadStateData (const void* data, int size)
  753. {
  754. #if JUCE_VST3_CAN_REPLACE_VST2
  755. return loadVST2CompatibleState ((const char*) data, size);
  756. #else
  757. pluginInstance->setStateInformation (data, size);
  758. return true;
  759. #endif
  760. }
  761. bool readFromMemoryStream (IBStream* state)
  762. {
  763. FUnknownPtr<MemoryStream> s (state);
  764. if (s != nullptr
  765. && s->getData() != nullptr
  766. && s->getSize() > 0
  767. && s->getSize() < 1024 * 1024 * 100) // (some hosts seem to return junk for the size)
  768. {
  769. // Adobe Audition CS6 hack to avoid trying to use corrupted streams:
  770. if (getHostType().isAdobeAudition())
  771. if (s->getSize() >= 5 && memcmp (s->getData(), "VC2!E", 5) == 0)
  772. return false;
  773. return loadStateData (s->getData(), (int) s->getSize());
  774. }
  775. return false;
  776. }
  777. bool readFromUnknownStream (IBStream* state)
  778. {
  779. MemoryOutputStream allData;
  780. {
  781. const size_t bytesPerBlock = 4096;
  782. HeapBlock<char> buffer (bytesPerBlock);
  783. for (;;)
  784. {
  785. Steinberg::int32 bytesRead = 0;
  786. const Steinberg::tresult status = state->read (buffer, (Steinberg::int32) bytesPerBlock, &bytesRead);
  787. if (bytesRead <= 0 || (status != kResultTrue && ! getHostType().isWavelab()))
  788. break;
  789. allData.write (buffer, bytesRead);
  790. }
  791. }
  792. const size_t dataSize = allData.getDataSize();
  793. return dataSize > 0 && dataSize < 0x7fffffff
  794. && loadStateData (allData.getData(), (int) dataSize);
  795. }
  796. tresult PLUGIN_API setState (IBStream* state) override
  797. {
  798. if (state == nullptr)
  799. return kInvalidArgument;
  800. FUnknownPtr<IBStream> stateRefHolder (state); // just in case the caller hasn't properly ref-counted the stream object
  801. if (state->seek (0, IBStream::kIBSeekSet, nullptr) == kResultTrue)
  802. if (readFromMemoryStream (state) || readFromUnknownStream (state))
  803. return kResultTrue;
  804. return kResultFalse;
  805. }
  806. #if JUCE_VST3_CAN_REPLACE_VST2
  807. static tresult writeVST2Int (IBStream* state, int n)
  808. {
  809. juce::int32 t = (juce::int32) htonl (n);
  810. return state->write (&t, 4);
  811. }
  812. static tresult writeVST2Header (IBStream* state)
  813. {
  814. tresult status = writeVST2Int (state, 'VstW');
  815. if (status == kResultOk) status = writeVST2Int (state, 8); // header size
  816. if (status == kResultOk) status = writeVST2Int (state, 1); // version
  817. if (status == kResultOk) status = writeVST2Int (state, 0); // bypass
  818. return status;
  819. }
  820. #endif
  821. tresult PLUGIN_API getState (IBStream* state) override
  822. {
  823. if (state == nullptr)
  824. return kInvalidArgument;
  825. juce::MemoryBlock mem;
  826. pluginInstance->getStateInformation (mem);
  827. #if JUCE_VST3_CAN_REPLACE_VST2
  828. tresult status = writeVST2Header (state);
  829. if (status != kResultOk)
  830. return status;
  831. const int bankBlockSize = 160;
  832. struct fxBank bank;
  833. zerostruct (bank);
  834. bank.chunkMagic = htonl (cMagic);
  835. bank.byteSize = htonl (bankBlockSize - 8 + (unsigned int) mem.getSize());
  836. bank.fxMagic = htonl (chunkBankMagic);
  837. bank.version = htonl (2);
  838. bank.fxID = htonl (JucePlugin_VSTUniqueID);
  839. bank.fxVersion = htonl (JucePlugin_VersionCode);
  840. bank.content.data.size = htonl ((unsigned int) mem.getSize());
  841. status = state->write (&bank, bankBlockSize);
  842. if (status != kResultOk)
  843. return status;
  844. #endif
  845. return state->write (mem.getData(), (Steinberg::int32) mem.getSize());
  846. }
  847. //==============================================================================
  848. Steinberg::int32 PLUGIN_API getUnitCount() override
  849. {
  850. return 1;
  851. }
  852. tresult PLUGIN_API getUnitInfo (Steinberg::int32 unitIndex, Vst::UnitInfo& info) override
  853. {
  854. if (unitIndex == 0)
  855. {
  856. info.id = Vst::kRootUnitId;
  857. info.parentUnitId = Vst::kNoParentUnitId;
  858. info.programListId = Vst::kNoProgramListId;
  859. toString128 (info.name, TRANS("Root Unit"));
  860. return kResultTrue;
  861. }
  862. zerostruct (info);
  863. return kResultFalse;
  864. }
  865. Steinberg::int32 PLUGIN_API getProgramListCount() override
  866. {
  867. if (getPluginInstance().getNumPrograms() > 0)
  868. return 1;
  869. return 0;
  870. }
  871. tresult PLUGIN_API getProgramListInfo (Steinberg::int32 listIndex, Vst::ProgramListInfo& info) override
  872. {
  873. if (listIndex == 0)
  874. {
  875. info.id = paramPreset;
  876. info.programCount = (Steinberg::int32) getPluginInstance().getNumPrograms();
  877. toString128 (info.name, TRANS("Factory Presets"));
  878. return kResultTrue;
  879. }
  880. jassertfalse;
  881. zerostruct (info);
  882. return kResultFalse;
  883. }
  884. tresult PLUGIN_API getProgramName (Vst::ProgramListID listId, Steinberg::int32 programIndex, Vst::String128 name) override
  885. {
  886. if (listId == paramPreset
  887. && isPositiveAndBelow ((int) programIndex, getPluginInstance().getNumPrograms()))
  888. {
  889. toString128 (name, getPluginInstance().getProgramName ((int) programIndex));
  890. return kResultTrue;
  891. }
  892. jassertfalse;
  893. toString128 (name, juce::String());
  894. return kResultFalse;
  895. }
  896. tresult PLUGIN_API getProgramInfo (Vst::ProgramListID, Steinberg::int32, Vst::CString, Vst::String128) override { return kNotImplemented; }
  897. tresult PLUGIN_API hasProgramPitchNames (Vst::ProgramListID, Steinberg::int32) override { return kNotImplemented; }
  898. tresult PLUGIN_API getProgramPitchName (Vst::ProgramListID, Steinberg::int32, Steinberg::int16, Vst::String128) override { return kNotImplemented; }
  899. tresult PLUGIN_API selectUnit (Vst::UnitID) override { return kNotImplemented; }
  900. tresult PLUGIN_API setUnitProgramData (Steinberg::int32, Steinberg::int32, IBStream*) override { return kNotImplemented; }
  901. Vst::UnitID PLUGIN_API getSelectedUnit() override { return Vst::kRootUnitId; }
  902. tresult PLUGIN_API getUnitByBus (Vst::MediaType, Vst::BusDirection,
  903. Steinberg::int32, Steinberg::int32,
  904. Vst::UnitID& unitId) override
  905. {
  906. zerostruct (unitId);
  907. return kNotImplemented;
  908. }
  909. //==============================================================================
  910. bool getCurrentPosition (CurrentPositionInfo& info) override
  911. {
  912. info.timeInSamples = jmax ((juce::int64) 0, processContext.projectTimeSamples);
  913. info.timeInSeconds = processContext.systemTime / 1000000000.0;
  914. info.bpm = jmax (1.0, processContext.tempo);
  915. info.timeSigNumerator = jmax (1, (int) processContext.timeSigNumerator);
  916. info.timeSigDenominator = jmax (1, (int) processContext.timeSigDenominator);
  917. info.ppqPositionOfLastBarStart = processContext.barPositionMusic;
  918. info.ppqPosition = processContext.projectTimeMusic;
  919. info.ppqLoopStart = processContext.cycleStartMusic;
  920. info.ppqLoopEnd = processContext.cycleEndMusic;
  921. info.isRecording = (processContext.state & Vst::ProcessContext::kRecording) != 0;
  922. info.isPlaying = (processContext.state & Vst::ProcessContext::kPlaying) != 0;
  923. info.isLooping = (processContext.state & Vst::ProcessContext::kCycleActive) != 0;
  924. info.editOriginTime = 0.0;
  925. info.frameRate = AudioPlayHead::fpsUnknown;
  926. if ((processContext.state & Vst::ProcessContext::kSmpteValid) != 0)
  927. {
  928. switch (processContext.frameRate.framesPerSecond)
  929. {
  930. case 24: info.frameRate = AudioPlayHead::fps24; break;
  931. case 25: info.frameRate = AudioPlayHead::fps25; break;
  932. case 29: info.frameRate = AudioPlayHead::fps30drop; break;
  933. case 30:
  934. {
  935. if ((processContext.frameRate.flags & Vst::FrameRate::kDropRate) != 0)
  936. info.frameRate = AudioPlayHead::fps30drop;
  937. else
  938. info.frameRate = AudioPlayHead::fps30;
  939. }
  940. break;
  941. default: break;
  942. }
  943. }
  944. return true;
  945. }
  946. //==============================================================================
  947. static tresult setBusArrangementFor (Vst::BusList& list,
  948. Vst::SpeakerArrangement* arrangement,
  949. Steinberg::int32 numBusses)
  950. {
  951. if (arrangement != nullptr && numBusses == 1) //Should only be 1 bus per BusList
  952. {
  953. Steinberg::int32 counter = 0;
  954. FOREACH_CAST (IPtr<Vst::Bus>, Vst::AudioBus, bus, list)
  955. {
  956. if (counter < numBusses)
  957. bus->setArrangement (arrangement[counter]);
  958. counter++;
  959. }
  960. ENDFOR
  961. return kResultTrue;
  962. }
  963. return kResultFalse;
  964. }
  965. tresult PLUGIN_API setBusArrangements (Vst::SpeakerArrangement* inputs, Steinberg::int32 numIns,
  966. Vst::SpeakerArrangement* outputs, Steinberg::int32 numOuts) override
  967. {
  968. (void) inputs; (void) outputs;
  969. #if JucePlugin_MaxNumInputChannels > 0
  970. if (setBusArrangementFor (audioInputs, inputs, numIns) != kResultTrue)
  971. return kResultFalse;
  972. #else
  973. if (numIns != 0)
  974. return kResultFalse;
  975. #endif
  976. #if JucePlugin_MaxNumOutputChannels > 0
  977. if (setBusArrangementFor (audioOutputs, outputs, numOuts) != kResultTrue)
  978. return kResultFalse;
  979. #else
  980. if (numOuts != 0)
  981. return kResultFalse;
  982. #endif
  983. preparePlugin (getPluginInstance().getSampleRate(),
  984. getPluginInstance().getBlockSize());
  985. return kResultTrue;
  986. }
  987. tresult PLUGIN_API getBusArrangement (Vst::BusDirection dir, Steinberg::int32 index, Vst::SpeakerArrangement& arr) override
  988. {
  989. if (Vst::BusList* const busList = getBusListFor (Vst::kAudio, dir))
  990. {
  991. if (Vst::AudioBus* const audioBus = FCast<Vst::AudioBus> (busList->at (index)))
  992. {
  993. arr = audioBus->getArrangement();
  994. return kResultTrue;
  995. }
  996. }
  997. return kResultFalse;
  998. }
  999. tresult PLUGIN_API canProcessSampleSize (Steinberg::int32 symbolicSampleSize) override
  1000. {
  1001. return symbolicSampleSize == Vst::kSample32 ? kResultTrue : kResultFalse;
  1002. }
  1003. Steinberg::uint32 PLUGIN_API getLatencySamples() override
  1004. {
  1005. return (Steinberg::uint32) jmax (0, getPluginInstance().getLatencySamples());
  1006. }
  1007. tresult PLUGIN_API setupProcessing (Vst::ProcessSetup& newSetup) override
  1008. {
  1009. if (canProcessSampleSize (newSetup.symbolicSampleSize) != kResultTrue)
  1010. return kResultFalse;
  1011. processSetup = newSetup;
  1012. processContext.sampleRate = processSetup.sampleRate;
  1013. preparePlugin (processSetup.sampleRate, processSetup.maxSamplesPerBlock);
  1014. return kResultTrue;
  1015. }
  1016. tresult PLUGIN_API setProcessing (TBool state) override
  1017. {
  1018. if (! state)
  1019. getPluginInstance().reset();
  1020. return kResultTrue;
  1021. }
  1022. Steinberg::uint32 PLUGIN_API getTailSamples() override
  1023. {
  1024. const double tailLengthSeconds = getPluginInstance().getTailLengthSeconds();
  1025. if (tailLengthSeconds <= 0.0 || processSetup.sampleRate > 0.0)
  1026. return Vst::kNoTail;
  1027. return (Steinberg::uint32) roundToIntAccurate (tailLengthSeconds * processSetup.sampleRate);
  1028. }
  1029. //==============================================================================
  1030. void processParameterChanges (Vst::IParameterChanges& paramChanges)
  1031. {
  1032. jassert (pluginInstance != nullptr);
  1033. const Steinberg::int32 numParamsChanged = paramChanges.getParameterCount();
  1034. for (Steinberg::int32 i = 0; i < numParamsChanged; ++i)
  1035. {
  1036. if (Vst::IParamValueQueue* paramQueue = paramChanges.getParameterData (i))
  1037. {
  1038. const Steinberg::int32 numPoints = paramQueue->getPointCount();
  1039. Steinberg::int32 offsetSamples;
  1040. double value = 0.0;
  1041. if (paramQueue->getPoint (numPoints - 1, offsetSamples, value) == kResultTrue)
  1042. {
  1043. const int id = (int) paramQueue->getParameterId();
  1044. if (isPositiveAndBelow (id, pluginInstance->getNumParameters()))
  1045. pluginInstance->setParameter (id, (float) value);
  1046. else
  1047. addParameterChangeToMidiBuffer (offsetSamples, id, value);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. void addParameterChangeToMidiBuffer (const Steinberg::int32 offsetSamples, const int id, const double value)
  1053. {
  1054. // If the parameter is mapped to a MIDI CC message then insert it into the midiBuffer.
  1055. int channel, ctrlNumber;
  1056. if (juceVST3EditController->getMidiControllerForParameter (id, channel, ctrlNumber))
  1057. {
  1058. if (ctrlNumber == Vst::kAfterTouch)
  1059. midiBuffer.addEvent (MidiMessage::channelPressureChange (channel,
  1060. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1061. else if (ctrlNumber == Vst::kPitchBend)
  1062. midiBuffer.addEvent (MidiMessage::pitchWheel (channel,
  1063. jlimit (0, 0x3fff, (int) (value * 0x4000))), offsetSamples);
  1064. else
  1065. midiBuffer.addEvent (MidiMessage::controllerEvent (channel,
  1066. jlimit (0, 127, ctrlNumber),
  1067. jlimit (0, 127, (int) (value * 128.0))), offsetSamples);
  1068. }
  1069. }
  1070. tresult PLUGIN_API process (Vst::ProcessData& data) override
  1071. {
  1072. if (pluginInstance == nullptr)
  1073. return kResultFalse;
  1074. if (data.processContext != nullptr)
  1075. processContext = *data.processContext;
  1076. else
  1077. zerostruct (processContext);
  1078. midiBuffer.clear();
  1079. #if JucePlugin_WantsMidiInput
  1080. if (data.inputEvents != nullptr)
  1081. MidiEventList::toMidiBuffer (midiBuffer, *data.inputEvents);
  1082. #endif
  1083. #if JUCE_DEBUG && ! JucePlugin_ProducesMidiOutput
  1084. const int numMidiEventsComingIn = midiBuffer.getNumEvents();
  1085. #endif
  1086. const int numInputChans = (data.inputs != nullptr && data.inputs[0].channelBuffers32 != nullptr) ? (int) data.inputs[0].numChannels : 0;
  1087. const int numOutputChans = (data.outputs != nullptr && data.outputs[0].channelBuffers32 != nullptr) ? (int) data.outputs[0].numChannels : 0;
  1088. int totalChans = 0;
  1089. while (totalChans < numInputChans)
  1090. {
  1091. channelList.set (totalChans, data.inputs[0].channelBuffers32[totalChans]);
  1092. ++totalChans;
  1093. }
  1094. while (totalChans < numOutputChans)
  1095. {
  1096. channelList.set (totalChans, data.outputs[0].channelBuffers32[totalChans]);
  1097. ++totalChans;
  1098. }
  1099. AudioSampleBuffer buffer;
  1100. if (totalChans != 0)
  1101. buffer.setDataToReferTo (channelList.getRawDataPointer(), totalChans, (int) data.numSamples);
  1102. else if (getHostType().isWavelab()
  1103. && pluginInstance->getNumInputChannels() + pluginInstance->getNumOutputChannels() > 0)
  1104. return kResultFalse;
  1105. {
  1106. const ScopedLock sl (pluginInstance->getCallbackLock());
  1107. pluginInstance->setNonRealtime (data.processMode == Vst::kOffline);
  1108. if (data.inputParameterChanges != nullptr)
  1109. processParameterChanges (*data.inputParameterChanges);
  1110. if (pluginInstance->isSuspended())
  1111. buffer.clear();
  1112. else
  1113. pluginInstance->processBlock (buffer, midiBuffer);
  1114. }
  1115. for (int i = 0; i < numOutputChans; ++i)
  1116. FloatVectorOperations::copy (data.outputs[0].channelBuffers32[i], buffer.getReadPointer (i), (int) data.numSamples);
  1117. // clear extra busses..
  1118. if (data.outputs != nullptr)
  1119. for (int i = 1; i < data.numOutputs; ++i)
  1120. for (int f = 0; f < data.outputs[i].numChannels; ++f)
  1121. FloatVectorOperations::clear (data.outputs[i].channelBuffers32[f], (int) data.numSamples);
  1122. #if JucePlugin_ProducesMidiOutput
  1123. if (data.outputEvents != nullptr)
  1124. MidiEventList::toEventList (*data.outputEvents, midiBuffer);
  1125. #elif JUCE_DEBUG
  1126. /* This assertion is caused when you've added some events to the
  1127. midiMessages array in your processBlock() method, which usually means
  1128. that you're trying to send them somewhere. But in this case they're
  1129. getting thrown away.
  1130. If your plugin does want to send MIDI messages, you'll need to set
  1131. the JucePlugin_ProducesMidiOutput macro to 1 in your
  1132. JucePluginCharacteristics.h file.
  1133. If you don't want to produce any MIDI output, then you should clear the
  1134. midiMessages array at the end of your processBlock() method, to
  1135. indicate that you don't want any of the events to be passed through
  1136. to the output.
  1137. */
  1138. jassert (midiBuffer.getNumEvents() <= numMidiEventsComingIn);
  1139. #endif
  1140. return kResultTrue;
  1141. }
  1142. private:
  1143. //==============================================================================
  1144. Atomic<int> refCount;
  1145. AudioProcessor* pluginInstance;
  1146. ComSmartPtr<Vst::IHostApplication> host;
  1147. ComSmartPtr<JuceAudioProcessor> comPluginInstance;
  1148. ComSmartPtr<JuceVST3EditController> juceVST3EditController;
  1149. /**
  1150. Since VST3 does not provide a way of knowing the buffer size and sample rate at any point,
  1151. this object needs to be copied on every call to process() to be up-to-date...
  1152. */
  1153. Vst::ProcessContext processContext;
  1154. Vst::ProcessSetup processSetup;
  1155. Vst::BusList audioInputs, audioOutputs, eventInputs, eventOutputs;
  1156. MidiBuffer midiBuffer;
  1157. Array<float*> channelList;
  1158. ScopedJuceInitialiser_GUI libraryInitialiser;
  1159. //==============================================================================
  1160. void addBusTo (Vst::BusList& busList, Vst::Bus* newBus)
  1161. {
  1162. busList.append (IPtr<Vst::Bus> (newBus, false));
  1163. }
  1164. void addAudioBusTo (Vst::BusList& busList, const juce::String& name, Vst::SpeakerArrangement arr)
  1165. {
  1166. addBusTo (busList, new Vst::AudioBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, arr));
  1167. }
  1168. void addEventBusTo (Vst::BusList& busList, const juce::String& name)
  1169. {
  1170. addBusTo (busList, new Vst::EventBus (toString (name), Vst::kMain, Vst::BusInfo::kDefaultActive, 16));
  1171. }
  1172. Vst::BusList* getBusListFor (Vst::MediaType type, Vst::BusDirection dir)
  1173. {
  1174. if (type == Vst::kAudio) return dir == Vst::kInput ? &audioInputs : &audioOutputs;
  1175. if (type == Vst::kEvent) return dir == Vst::kInput ? &eventInputs : &eventOutputs;
  1176. return nullptr;
  1177. }
  1178. //==============================================================================
  1179. enum InternalParameters
  1180. {
  1181. paramPreset = 'prst'
  1182. };
  1183. static int getNumChannels (Vst::BusList& busList)
  1184. {
  1185. Vst::BusInfo info;
  1186. info.channelCount = 0;
  1187. if (Vst::Bus* bus = busList.first())
  1188. bus->getInfo (info);
  1189. return (int) info.channelCount;
  1190. }
  1191. void preparePlugin (double sampleRate, int bufferSize)
  1192. {
  1193. getPluginInstance().setPlayConfigDetails (getNumChannels (audioInputs),
  1194. getNumChannels (audioOutputs),
  1195. sampleRate, bufferSize);
  1196. getPluginInstance().prepareToPlay (sampleRate, bufferSize);
  1197. }
  1198. //==============================================================================
  1199. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceVST3Component)
  1200. };
  1201. #if JucePlugin_Build_VST3 && JUCE_VST3_CAN_REPLACE_VST2
  1202. Steinberg::FUID getJuceVST3ComponentIID();
  1203. Steinberg::FUID getJuceVST3ComponentIID() { return JuceVST3Component::iid; }
  1204. #endif
  1205. //==============================================================================
  1206. #if JUCE_MSVC
  1207. #pragma warning (push, 0)
  1208. #pragma warning (disable: 4310)
  1209. #elif JUCE_CLANG
  1210. #pragma clang diagnostic push
  1211. #pragma clang diagnostic ignored "-Wall"
  1212. #endif
  1213. DECLARE_CLASS_IID (JuceAudioProcessor, 0x0101ABAB, 0xABCDEF01, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1214. DEF_CLASS_IID (JuceAudioProcessor)
  1215. #if JUCE_VST3_CAN_REPLACE_VST2
  1216. // NB: Nasty old-fashioned code in here because it's copied from the Steinberg example code.
  1217. static FUID getFUIDForVST2ID (bool forControllerUID)
  1218. {
  1219. char uidString[33];
  1220. const int vstfxid = (('V' << 16) | ('S' << 8) | (forControllerUID ? 'E' : 'T'));
  1221. char vstfxidStr[7] = { 0 };
  1222. sprintf (vstfxidStr, "%06X", vstfxid);
  1223. strcpy (uidString, vstfxidStr);
  1224. char uidStr[9] = { 0 };
  1225. sprintf (uidStr, "%08X", JucePlugin_VSTUniqueID);
  1226. strcat (uidString, uidStr);
  1227. char nameidStr[3] = { 0 };
  1228. const size_t len = strlen (JucePlugin_Name);
  1229. for (size_t i = 0; i <= 8; ++i)
  1230. {
  1231. juce::uint8 c = i < len ? JucePlugin_Name[i] : 0;
  1232. if (c >= 'A' && c <= 'Z')
  1233. c += 'a' - 'A';
  1234. sprintf (nameidStr, "%02X", c);
  1235. strcat (uidString, nameidStr);
  1236. }
  1237. FUID newOne;
  1238. newOne.fromString (uidString);
  1239. return newOne;
  1240. }
  1241. const Steinberg::FUID JuceVST3Component ::iid (getFUIDForVST2ID (false));
  1242. const Steinberg::FUID JuceVST3EditController::iid (getFUIDForVST2ID (true));
  1243. #else
  1244. DECLARE_CLASS_IID (JuceVST3EditController, 0xABCDEF01, 0x1234ABCD, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1245. DEF_CLASS_IID (JuceVST3EditController)
  1246. DECLARE_CLASS_IID (JuceVST3Component, 0xABCDEF01, 0x9182FAEB, JucePlugin_ManufacturerCode, JucePlugin_PluginCode)
  1247. DEF_CLASS_IID (JuceVST3Component)
  1248. #endif
  1249. #if JUCE_MSVC
  1250. #pragma warning (pop)
  1251. #elif JUCE_CLANG
  1252. #pragma clang diagnostic pop
  1253. #endif
  1254. //==============================================================================
  1255. bool initModule()
  1256. {
  1257. #if JUCE_MAC
  1258. initialiseMac();
  1259. #endif
  1260. return true;
  1261. }
  1262. bool shutdownModule()
  1263. {
  1264. return true;
  1265. }
  1266. #undef JUCE_EXPORTED_FUNCTION
  1267. #if JUCE_WINDOWS
  1268. extern "C" __declspec (dllexport) bool InitDll() { return initModule(); }
  1269. extern "C" __declspec (dllexport) bool ExitDll() { return shutdownModule(); }
  1270. #define JUCE_EXPORTED_FUNCTION
  1271. #else
  1272. #define JUCE_EXPORTED_FUNCTION extern "C" __attribute__ ((visibility ("default")))
  1273. CFBundleRef globalBundleInstance = nullptr;
  1274. juce::uint32 numBundleRefs = 0;
  1275. juce::Array<CFBundleRef> bundleRefs;
  1276. enum { MaxPathLength = 2048 };
  1277. char modulePath[MaxPathLength] = { 0 };
  1278. void* moduleHandle = nullptr;
  1279. JUCE_EXPORTED_FUNCTION bool bundleEntry (CFBundleRef ref)
  1280. {
  1281. if (ref != nullptr)
  1282. {
  1283. ++numBundleRefs;
  1284. CFRetain (ref);
  1285. bundleRefs.add (ref);
  1286. if (moduleHandle == nullptr)
  1287. {
  1288. globalBundleInstance = ref;
  1289. moduleHandle = ref;
  1290. CFURLRef tempURL = CFBundleCopyBundleURL (ref);
  1291. CFURLGetFileSystemRepresentation (tempURL, true, (UInt8*) modulePath, MaxPathLength);
  1292. CFRelease (tempURL);
  1293. }
  1294. }
  1295. return initModule();
  1296. }
  1297. JUCE_EXPORTED_FUNCTION bool bundleExit()
  1298. {
  1299. if (shutdownModule())
  1300. {
  1301. if (--numBundleRefs == 0)
  1302. {
  1303. for (int i = 0; i < bundleRefs.size(); ++i)
  1304. CFRelease (bundleRefs.getUnchecked (i));
  1305. bundleRefs.clear();
  1306. }
  1307. return true;
  1308. }
  1309. return false;
  1310. }
  1311. #endif
  1312. //==============================================================================
  1313. /** This typedef represents VST3's createInstance() function signature */
  1314. typedef FUnknown* (*CreateFunction) (Vst::IHostApplication*);
  1315. static FUnknown* createComponentInstance (Vst::IHostApplication* host)
  1316. {
  1317. return (Vst::IAudioProcessor*) new JuceVST3Component (host);
  1318. }
  1319. static FUnknown* createControllerInstance (Vst::IHostApplication* host)
  1320. {
  1321. return (Vst::IEditController*) new JuceVST3EditController (host);
  1322. }
  1323. //==============================================================================
  1324. class JucePluginFactory;
  1325. static JucePluginFactory* globalFactory = nullptr;
  1326. //==============================================================================
  1327. class JucePluginFactory : public IPluginFactory3
  1328. {
  1329. public:
  1330. JucePluginFactory()
  1331. : refCount (1),
  1332. factoryInfo (JucePlugin_Manufacturer, JucePlugin_ManufacturerWebsite,
  1333. JucePlugin_ManufacturerEmail, Vst::kDefaultFactoryFlags)
  1334. {
  1335. }
  1336. virtual ~JucePluginFactory()
  1337. {
  1338. if (globalFactory == this)
  1339. globalFactory = nullptr;
  1340. }
  1341. //==============================================================================
  1342. bool registerClass (const PClassInfo2& info, CreateFunction createFunction)
  1343. {
  1344. if (createFunction == nullptr)
  1345. {
  1346. jassertfalse;
  1347. return false;
  1348. }
  1349. ClassEntry* entry = classes.add (new ClassEntry (info, createFunction));
  1350. entry->infoW.fromAscii (info);
  1351. return true;
  1352. }
  1353. bool isClassRegistered (const FUID& cid) const
  1354. {
  1355. for (int i = 0; i < classes.size(); ++i)
  1356. if (classes.getUnchecked (i)->infoW.cid == cid)
  1357. return true;
  1358. return false;
  1359. }
  1360. //==============================================================================
  1361. JUCE_DECLARE_VST3_COM_REF_METHODS
  1362. tresult PLUGIN_API queryInterface (const TUID targetIID, void** obj) override
  1363. {
  1364. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory3)
  1365. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory2)
  1366. TEST_FOR_AND_RETURN_IF_VALID (targetIID, IPluginFactory)
  1367. TEST_FOR_AND_RETURN_IF_VALID (targetIID, FUnknown)
  1368. jassertfalse; // Something new?
  1369. *obj = nullptr;
  1370. return kNotImplemented;
  1371. }
  1372. //==============================================================================
  1373. Steinberg::int32 PLUGIN_API countClasses() override
  1374. {
  1375. return (Steinberg::int32) classes.size();
  1376. }
  1377. tresult PLUGIN_API getFactoryInfo (PFactoryInfo* info) override
  1378. {
  1379. if (info == nullptr)
  1380. return kInvalidArgument;
  1381. memcpy (info, &factoryInfo, sizeof (PFactoryInfo));
  1382. return kResultOk;
  1383. }
  1384. tresult PLUGIN_API getClassInfo (Steinberg::int32 index, PClassInfo* info) override
  1385. {
  1386. return getPClassInfo<PClassInfo> (index, info);
  1387. }
  1388. tresult PLUGIN_API getClassInfo2 (Steinberg::int32 index, PClassInfo2* info) override
  1389. {
  1390. return getPClassInfo<PClassInfo2> (index, info);
  1391. }
  1392. tresult PLUGIN_API getClassInfoUnicode (Steinberg::int32 index, PClassInfoW* info) override
  1393. {
  1394. if (info != nullptr)
  1395. {
  1396. if (ClassEntry* entry = classes[(int) index])
  1397. {
  1398. memcpy (info, &entry->infoW, sizeof (PClassInfoW));
  1399. return kResultOk;
  1400. }
  1401. }
  1402. return kInvalidArgument;
  1403. }
  1404. tresult PLUGIN_API createInstance (FIDString cid, FIDString sourceIid, void** obj) override
  1405. {
  1406. *obj = nullptr;
  1407. FUID sourceFuid = sourceIid;
  1408. if (cid == nullptr || sourceIid == nullptr || ! sourceFuid.isValid())
  1409. {
  1410. jassertfalse; // The host you're running in has severe implementation issues!
  1411. return kInvalidArgument;
  1412. }
  1413. TUID iidToQuery;
  1414. sourceFuid.toTUID (iidToQuery);
  1415. for (int i = 0; i < classes.size(); ++i)
  1416. {
  1417. const ClassEntry& entry = *classes.getUnchecked (i);
  1418. if (doUIDsMatch (entry.infoW.cid, cid))
  1419. {
  1420. if (FUnknown* const instance = entry.createFunction (host))
  1421. {
  1422. const FReleaser releaser (instance);
  1423. if (instance->queryInterface (iidToQuery, obj) == kResultOk)
  1424. return kResultOk;
  1425. }
  1426. break;
  1427. }
  1428. }
  1429. return kNoInterface;
  1430. }
  1431. tresult PLUGIN_API setHostContext (FUnknown* context) override
  1432. {
  1433. host.loadFrom (context);
  1434. if (host != nullptr)
  1435. {
  1436. Vst::String128 name;
  1437. host->getName (name);
  1438. return kResultTrue;
  1439. }
  1440. return kNotImplemented;
  1441. }
  1442. private:
  1443. //==============================================================================
  1444. ScopedJuceInitialiser_GUI libraryInitialiser;
  1445. Atomic<int> refCount;
  1446. const PFactoryInfo factoryInfo;
  1447. ComSmartPtr<Vst::IHostApplication> host;
  1448. //==============================================================================
  1449. struct ClassEntry
  1450. {
  1451. ClassEntry() noexcept : createFunction (nullptr), isUnicode (false) {}
  1452. ClassEntry (const PClassInfo2& info, CreateFunction fn) noexcept
  1453. : info2 (info), createFunction (fn), isUnicode (false) {}
  1454. PClassInfo2 info2;
  1455. PClassInfoW infoW;
  1456. CreateFunction createFunction;
  1457. bool isUnicode;
  1458. private:
  1459. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ClassEntry)
  1460. };
  1461. OwnedArray<ClassEntry> classes;
  1462. //==============================================================================
  1463. template<class PClassInfoType>
  1464. tresult PLUGIN_API getPClassInfo (Steinberg::int32 index, PClassInfoType* info)
  1465. {
  1466. if (info != nullptr)
  1467. {
  1468. zerostruct (*info);
  1469. if (ClassEntry* entry = classes[(int) index])
  1470. {
  1471. if (entry->isUnicode)
  1472. return kResultFalse;
  1473. memcpy (info, &entry->info2, sizeof (PClassInfoType));
  1474. return kResultOk;
  1475. }
  1476. }
  1477. jassertfalse;
  1478. return kInvalidArgument;
  1479. }
  1480. //==============================================================================
  1481. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JucePluginFactory)
  1482. };
  1483. } // juce namespace
  1484. //==============================================================================
  1485. #ifndef JucePlugin_Vst3ComponentFlags
  1486. #if JucePlugin_IsSynth
  1487. #define JucePlugin_Vst3ComponentFlags Vst::kSimpleModeSupported
  1488. #else
  1489. #define JucePlugin_Vst3ComponentFlags 0
  1490. #endif
  1491. #endif
  1492. #ifndef JucePlugin_Vst3Category
  1493. #if JucePlugin_IsSynth
  1494. #define JucePlugin_Vst3Category Vst::PlugType::kInstrumentSynth
  1495. #else
  1496. #define JucePlugin_Vst3Category Vst::PlugType::kFx
  1497. #endif
  1498. #endif
  1499. //==============================================================================
  1500. // The VST3 plugin entry point.
  1501. JUCE_EXPORTED_FUNCTION IPluginFactory* PLUGIN_API GetPluginFactory()
  1502. {
  1503. #if JUCE_WINDOWS
  1504. // Cunning trick to force this function to be exported. Life's too short to
  1505. // faff around creating .def files for this kind of thing.
  1506. #pragma comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
  1507. #endif
  1508. if (globalFactory == nullptr)
  1509. {
  1510. globalFactory = new JucePluginFactory();
  1511. static const PClassInfo2 componentClass (JuceVST3Component::iid,
  1512. PClassInfo::kManyInstances,
  1513. kVstAudioEffectClass,
  1514. JucePlugin_Name,
  1515. JucePlugin_Vst3ComponentFlags,
  1516. JucePlugin_Vst3Category,
  1517. JucePlugin_Manufacturer,
  1518. JucePlugin_VersionString,
  1519. kVstVersionString);
  1520. globalFactory->registerClass (componentClass, createComponentInstance);
  1521. static const PClassInfo2 controllerClass (JuceVST3EditController::iid,
  1522. PClassInfo::kManyInstances,
  1523. kVstComponentControllerClass,
  1524. JucePlugin_Name,
  1525. JucePlugin_Vst3ComponentFlags,
  1526. JucePlugin_Vst3Category,
  1527. JucePlugin_Manufacturer,
  1528. JucePlugin_VersionString,
  1529. kVstVersionString);
  1530. globalFactory->registerClass (controllerClass, createControllerInstance);
  1531. }
  1532. else
  1533. {
  1534. globalFactory->addRef();
  1535. }
  1536. return dynamic_cast<IPluginFactory*> (globalFactory);
  1537. }
  1538. #endif //JucePlugin_Build_VST3