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.

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