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.

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