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.

1822 lines
62KB

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