Audio plugin host https://kx.studio/carla
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.

2520 lines
80KB

  1. /*
  2. * Carla VST Plugin
  3. * Copyright (C) 2011-2013 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the GPL.txt file
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #ifdef WANT_VST
  19. #include "CarlaPluginGui.hpp"
  20. #include "CarlaVstUtils.hpp"
  21. //#ifdef Q_WS_X11
  22. //# include <QtGui/QX11Info>
  23. //#endif
  24. CARLA_BACKEND_START_NAMESPACE
  25. #if 0
  26. }
  27. #endif
  28. /*!
  29. * @defgroup PluginHints Plugin Hints
  30. * @{
  31. */
  32. const unsigned int PLUGIN_CAN_PROCESS_REPLACING = 0x1000; //!< VST Plugin cas use processReplacing()
  33. const unsigned int PLUGIN_HAS_COCKOS_EXTENSIONS = 0x2000; //!< VST Plugin has Cockos extensions
  34. const unsigned int PLUGIN_USES_OLD_VSTSDK = 0x4000; //!< VST Plugin uses an old VST SDK
  35. const unsigned int PLUGIN_WANTS_MIDI_INPUT = 0x8000; //!< VST Plugin wants MIDI input
  36. /**@}*/
  37. class VstPlugin : public CarlaPlugin,
  38. public CarlaPluginGui::Callback
  39. {
  40. public:
  41. VstPlugin(CarlaEngine* const engine, const unsigned int id)
  42. : CarlaPlugin(engine, id),
  43. fUnique1(1),
  44. fEffect(nullptr),
  45. fLastChunk(nullptr),
  46. fMidiEventCount(0),
  47. fIsProcessing(false),
  48. fNeedIdle(false),
  49. fUnique2(2)
  50. {
  51. carla_debug("VstPlugin::VstPlugin(%p, %i)", engine, id);
  52. carla_zeroStruct<VstMidiEvent>(fMidiEvents, MAX_MIDI_EVENTS*2);
  53. carla_zeroStruct<VstTimeInfo_R>(fTimeInfo);
  54. for (unsigned short i=0; i < MAX_MIDI_EVENTS*2; ++i)
  55. fEvents.data[i] = (VstEvent*)&fMidiEvents[i];
  56. kData->osc.thread.setMode(CarlaPluginThread::PLUGIN_THREAD_VST_GUI);
  57. // make plugin valid
  58. srand(id);
  59. fUnique1 = fUnique2 = rand();
  60. }
  61. ~VstPlugin() override
  62. {
  63. carla_debug("VstPlugin::~VstPlugin()");
  64. // close UI
  65. if (fHints & PLUGIN_HAS_GUI)
  66. {
  67. showGui(false);
  68. if (fGui.isOsc)
  69. {
  70. // Wait a bit first, then force kill
  71. if (kData->osc.thread.isRunning() && ! kData->osc.thread.wait(kData->engine->getOptions().oscUiTimeout))
  72. {
  73. carla_stderr("VST OSC-GUI thread still running, forcing termination now");
  74. kData->osc.thread.terminate();
  75. }
  76. }
  77. }
  78. kData->singleMutex.lock();
  79. kData->masterMutex.lock();
  80. CARLA_ASSERT(! fIsProcessing);
  81. if (kData->active)
  82. {
  83. deactivate();
  84. kData->active = false;
  85. }
  86. if (fEffect != nullptr)
  87. {
  88. dispatcher(effClose, 0, 0, nullptr, 0.0f);
  89. fEffect = nullptr;
  90. }
  91. // make plugin invalid
  92. fUnique2 += 1;
  93. if (fLastChunk != nullptr)
  94. {
  95. std::free(fLastChunk);
  96. fLastChunk = nullptr;
  97. }
  98. clearBuffers();
  99. }
  100. // -------------------------------------------------------------------
  101. // Information (base)
  102. PluginType type() const override
  103. {
  104. return PLUGIN_VST;
  105. }
  106. PluginCategory category() override
  107. {
  108. CARLA_ASSERT(fEffect != nullptr);
  109. const intptr_t category(dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f));
  110. switch (category)
  111. {
  112. case kPlugCategSynth:
  113. return PLUGIN_CATEGORY_SYNTH;
  114. case kPlugCategAnalysis:
  115. return PLUGIN_CATEGORY_UTILITY;
  116. case kPlugCategMastering:
  117. return PLUGIN_CATEGORY_DYNAMICS;
  118. case kPlugCategRoomFx:
  119. return PLUGIN_CATEGORY_DELAY;
  120. case kPlugCategRestoration:
  121. return PLUGIN_CATEGORY_UTILITY;
  122. case kPlugCategGenerator:
  123. return PLUGIN_CATEGORY_SYNTH;
  124. }
  125. if (fEffect->flags & effFlagsIsSynth)
  126. return PLUGIN_CATEGORY_SYNTH;
  127. return getPluginCategoryFromName(fName);
  128. }
  129. long uniqueId() const override
  130. {
  131. CARLA_ASSERT(fEffect != nullptr);
  132. return fEffect->uniqueID;
  133. }
  134. // -------------------------------------------------------------------
  135. // Information (count)
  136. // nothing
  137. // -------------------------------------------------------------------
  138. // Information (current data)
  139. int32_t chunkData(void** const dataPtr) override
  140. {
  141. CARLA_ASSERT(fOptions & PLUGIN_OPTION_USE_CHUNKS);
  142. CARLA_ASSERT(fEffect != nullptr);
  143. CARLA_ASSERT(dataPtr != nullptr);
  144. return dispatcher(effGetChunk, 0 /* bank */, 0, dataPtr, 0.0f);
  145. }
  146. // -------------------------------------------------------------------
  147. // Information (per-plugin data)
  148. unsigned int availableOptions() override
  149. {
  150. CARLA_ASSERT(fEffect != nullptr);
  151. if (fEffect == nullptr)
  152. return 0x0;
  153. unsigned int options = 0x0;
  154. options |= PLUGIN_OPTION_FIXED_BUFFER;
  155. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  156. if (fEffect->flags & effFlagsProgramChunks)
  157. options |= PLUGIN_OPTION_USE_CHUNKS;
  158. if (vstPluginCanDo(fEffect, "receiveVstEvents") || vstPluginCanDo(fEffect, "receiveVstMidiEvent") || (fEffect->flags & effFlagsIsSynth) > 0 || (fHints & PLUGIN_WANTS_MIDI_INPUT))
  159. {
  160. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  161. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  162. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  163. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  164. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  165. }
  166. return options;
  167. }
  168. float getParameterValue(const uint32_t parameterId) override
  169. {
  170. CARLA_ASSERT(fEffect != nullptr);
  171. CARLA_ASSERT(parameterId < kData->param.count);
  172. return fEffect->getParameter(fEffect, parameterId);
  173. }
  174. void getLabel(char* const strBuf) override
  175. {
  176. CARLA_ASSERT(fEffect != nullptr);
  177. strBuf[0] = '\0';
  178. dispatcher(effGetProductString, 0, 0, strBuf, 0.0f);
  179. }
  180. void getMaker(char* const strBuf) override
  181. {
  182. CARLA_ASSERT(fEffect != nullptr);
  183. strBuf[0] = '\0';
  184. dispatcher(effGetVendorString, 0, 0, strBuf, 0.0f);
  185. }
  186. void getCopyright(char* const strBuf) override
  187. {
  188. CARLA_ASSERT(fEffect != nullptr);
  189. strBuf[0] = '\0';
  190. dispatcher(effGetVendorString, 0, 0, strBuf, 0.0f);
  191. }
  192. void getRealName(char* const strBuf) override
  193. {
  194. CARLA_ASSERT(fEffect != nullptr);
  195. strBuf[0] = '\0';
  196. dispatcher(effGetEffectName, 0, 0, strBuf, 0.0f);
  197. }
  198. void getParameterName(const uint32_t parameterId, char* const strBuf) override
  199. {
  200. CARLA_ASSERT(fEffect != nullptr);
  201. CARLA_ASSERT(parameterId < kData->param.count);
  202. strBuf[0] = '\0';
  203. dispatcher(effGetParamName, parameterId, 0, strBuf, 0.0f);
  204. }
  205. void getParameterText(const uint32_t parameterId, char* const strBuf) override
  206. {
  207. CARLA_ASSERT(fEffect != nullptr);
  208. CARLA_ASSERT(parameterId < kData->param.count);
  209. strBuf[0] = '\0';
  210. dispatcher(effGetParamDisplay, parameterId, 0, strBuf, 0.0f);
  211. if (strBuf[0] == '\0')
  212. std::snprintf(strBuf, STR_MAX, "%f", getParameterValue(parameterId));
  213. }
  214. void getParameterUnit(const uint32_t parameterId, char* const strBuf) override
  215. {
  216. CARLA_ASSERT(fEffect != nullptr);
  217. CARLA_ASSERT(parameterId < kData->param.count);
  218. strBuf[0] = '\0';
  219. dispatcher(effGetParamLabel, parameterId, 0, strBuf, 0.0f);
  220. }
  221. // -------------------------------------------------------------------
  222. // Set data (state)
  223. // nothing
  224. // -------------------------------------------------------------------
  225. // Set data (internal stuff)
  226. // nothing
  227. // -------------------------------------------------------------------
  228. // Set data (plugin-specific stuff)
  229. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  230. {
  231. CARLA_ASSERT(fEffect != nullptr);
  232. CARLA_ASSERT(parameterId < kData->param.count);
  233. const float fixedValue(kData->param.fixValue(parameterId, value));
  234. fEffect->setParameter(fEffect, parameterId, fixedValue);
  235. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  236. }
  237. void setChunkData(const char* const stringData) override
  238. {
  239. CARLA_ASSERT(fOptions & PLUGIN_OPTION_USE_CHUNKS);
  240. CARLA_ASSERT(fEffect != nullptr);
  241. CARLA_ASSERT(stringData != nullptr);
  242. if (fLastChunk != nullptr)
  243. {
  244. std::free(fLastChunk);
  245. fLastChunk = nullptr;
  246. }
  247. QByteArray chunk(QByteArray::fromBase64(stringData));
  248. CARLA_ASSERT(chunk.size() > 0);
  249. if (chunk.size() > 0)
  250. {
  251. fLastChunk = std::malloc(chunk.size());
  252. std::memcpy(fLastChunk, chunk.constData(), chunk.size());
  253. {
  254. const ScopedSingleProcessLocker spl(this, true);
  255. dispatcher(effSetChunk, 0 /* bank */, chunk.size(), fLastChunk, 0.0f);
  256. }
  257. // simulate an updateDisplay callback
  258. handleAudioMasterCallback(audioMasterUpdateDisplay, 0, 0, nullptr, 0.0f);
  259. }
  260. }
  261. void setProgram(int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback) override
  262. {
  263. CARLA_ASSERT(fEffect != nullptr);
  264. CARLA_ASSERT(index >= -1 && index < static_cast<int32_t>(kData->prog.count));
  265. if (index < -1)
  266. index = -1;
  267. else if (index > static_cast<int32_t>(kData->prog.count))
  268. return;
  269. if (index >= 0)
  270. {
  271. const ScopedSingleProcessLocker spl(this, (sendGui || sendOsc || sendCallback));
  272. dispatcher(effBeginSetProgram, 0, 0, nullptr, 0.0f);
  273. dispatcher(effSetProgram, 0, index, nullptr, 0.0f);
  274. dispatcher(effEndSetProgram, 0, 0, nullptr, 0.0f);
  275. }
  276. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback);
  277. }
  278. // -------------------------------------------------------------------
  279. // Set gui stuff
  280. void showGui(const bool yesNo) override
  281. {
  282. if (fGui.isOsc)
  283. {
  284. if (yesNo)
  285. {
  286. kData->osc.thread.start();
  287. }
  288. else
  289. {
  290. if (kData->osc.data.target != nullptr)
  291. {
  292. osc_send_hide(&kData->osc.data);
  293. osc_send_quit(&kData->osc.data);
  294. kData->osc.data.free();
  295. }
  296. if (kData->osc.thread.isRunning() && ! kData->osc.thread.wait(kData->engine->getOptions().oscUiTimeout))
  297. kData->osc.thread.terminate();
  298. }
  299. }
  300. else
  301. {
  302. if (yesNo)
  303. {
  304. if (kData->gui == nullptr)
  305. {
  306. CarlaPluginGui::Options guiOptions;
  307. guiOptions.parented = true;
  308. guiOptions.resizable = false;
  309. kData->gui = new CarlaPluginGui(kData->engine, this, guiOptions);
  310. }
  311. int32_t value = 0;
  312. #ifdef Q_WS_X11
  313. //value = (intptr_t)QX11Info::display();
  314. #endif
  315. void* const ptr = kData->gui->getContainerWinId();
  316. if (dispatcher(effEditOpen, 0, value, ptr, 0.0f) != 0)
  317. {
  318. ERect* vstRect = nullptr;
  319. dispatcher(effEditGetRect, 0, 0, &vstRect, 0.0f);
  320. if (vstRect != nullptr)
  321. {
  322. const int16_t width(vstRect->right - vstRect->left);
  323. const int16_t height(vstRect->bottom - vstRect->top);
  324. if (width > 0 && height > 0)
  325. kData->gui->setSize(width, height);
  326. }
  327. kData->gui->setWindowTitle(QString("%1 (GUI)").arg((const char*)fName));
  328. kData->gui->show();
  329. }
  330. else
  331. {
  332. if (kData->gui != nullptr)
  333. {
  334. kData->gui->close();
  335. delete kData->gui;
  336. kData->gui = nullptr;
  337. }
  338. kData->engine->callback(CALLBACK_ERROR, fId, 0, 0, 0.0f, "Plugin refused to open its own UI");
  339. kData->engine->callback(CALLBACK_SHOW_GUI, fId, -1, 0, 0.0f, nullptr);
  340. return;
  341. }
  342. }
  343. else
  344. {
  345. dispatcher(effEditClose, 0, 0, nullptr, 0.0f);
  346. if (kData->gui != nullptr)
  347. {
  348. kData->gui->close();
  349. delete kData->gui;
  350. kData->gui = nullptr;
  351. }
  352. }
  353. }
  354. fGui.isVisible = yesNo;
  355. }
  356. void idleGui() override
  357. {
  358. #ifdef VESTIGE_HEADER
  359. if (fEffect != nullptr /*&& effect->ptr1*/)
  360. #else
  361. if (fEffect != nullptr /*&& effect->resvd1*/)
  362. #endif
  363. {
  364. if (fNeedIdle)
  365. dispatcher(effIdle, 0, 0, nullptr, 0.0f);
  366. if (fGui.isVisible && ! fGui.isOsc)
  367. {
  368. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  369. //kData->gui->idle();
  370. }
  371. }
  372. CarlaPlugin::idleGui();
  373. }
  374. // -------------------------------------------------------------------
  375. // Plugin state
  376. void reload() override
  377. {
  378. carla_debug("VstPlugin::reload() - start");
  379. CARLA_ASSERT(kData->engine != nullptr);
  380. CARLA_ASSERT(fEffect != nullptr);
  381. if (kData->engine == nullptr)
  382. return;
  383. if (fEffect == nullptr)
  384. return;
  385. const ProcessMode processMode(kData->engine->getProccessMode());
  386. // Safely disable plugin for reload
  387. const ScopedDisabler sd(this);
  388. if (kData->active)
  389. deactivate();
  390. clearBuffers();
  391. uint32_t aIns, aOuts, mIns, mOuts, params, j;
  392. bool needsCtrlIn, needsCtrlOut;
  393. needsCtrlIn = needsCtrlOut = false;
  394. aIns = fEffect->numInputs;
  395. aOuts = fEffect->numOutputs;
  396. params = fEffect->numParams;
  397. if (vstPluginCanDo(fEffect, "receiveVstEvents") || vstPluginCanDo(fEffect, "receiveVstMidiEvent") || (fEffect->flags & effFlagsIsSynth) > 0 || (fHints & PLUGIN_WANTS_MIDI_INPUT))
  398. {
  399. mIns = 1;
  400. needsCtrlIn = true;
  401. }
  402. else
  403. mIns = 0;
  404. if (vstPluginCanDo(fEffect, "sendVstEvents") || vstPluginCanDo(fEffect, "sendVstMidiEvent"))
  405. {
  406. mOuts = 1;
  407. needsCtrlOut = true;
  408. }
  409. else
  410. mOuts = 0;
  411. if (aIns > 0)
  412. {
  413. kData->audioIn.createNew(aIns);
  414. }
  415. if (aOuts > 0)
  416. {
  417. kData->audioOut.createNew(aOuts);
  418. needsCtrlIn = true;
  419. }
  420. if (params > 0)
  421. {
  422. kData->param.createNew(params);
  423. needsCtrlIn = true;
  424. }
  425. const uint portNameSize(kData->engine->maxPortNameSize());
  426. CarlaString portName;
  427. // Audio Ins
  428. for (j=0; j < aIns; ++j)
  429. {
  430. portName.clear();
  431. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  432. {
  433. portName = fName;
  434. portName += ":";
  435. }
  436. if (aIns > 1)
  437. {
  438. portName += "input_";
  439. portName += CarlaString(j+1);
  440. }
  441. else
  442. portName += "input";
  443. portName.truncate(portNameSize);
  444. kData->audioIn.ports[j].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, true);
  445. kData->audioIn.ports[j].rindex = j;
  446. }
  447. // Audio Outs
  448. for (j=0; j < aOuts; ++j)
  449. {
  450. portName.clear();
  451. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  452. {
  453. portName = fName;
  454. portName += ":";
  455. }
  456. if (aOuts > 1)
  457. {
  458. portName += "output_";
  459. portName += CarlaString(j+1);
  460. }
  461. else
  462. portName += "output";
  463. portName.truncate(portNameSize);
  464. kData->audioOut.ports[j].port = (CarlaEngineAudioPort*)kData->client->addPort(kEnginePortTypeAudio, portName, false);
  465. kData->audioOut.ports[j].rindex = j;
  466. }
  467. for (j=0; j < params; ++j)
  468. {
  469. kData->param.data[j].type = PARAMETER_INPUT;
  470. kData->param.data[j].index = j;
  471. kData->param.data[j].rindex = j;
  472. kData->param.data[j].hints = 0x0;
  473. kData->param.data[j].midiChannel = 0;
  474. kData->param.data[j].midiCC = -1;
  475. float min, max, def, step, stepSmall, stepLarge;
  476. VstParameterProperties prop;
  477. carla_zeroStruct<VstParameterProperties>(prop);
  478. if (fHints & PLUGIN_HAS_COCKOS_EXTENSIONS)
  479. {
  480. double range[2] = { 0.0, 1.0 };
  481. if (dispatcher(effVendorSpecific, 0xdeadbef0, j, range, 0.0f) >= 0xbeef)
  482. {
  483. min = range[0];
  484. max = range[1];
  485. if (min > max)
  486. max = min;
  487. else if (max < min)
  488. min = max;
  489. if (max - min == 0.0f)
  490. {
  491. carla_stderr2("WARNING - Broken plugin parameter: max - min == 0.0f (with cockos extensions)");
  492. max = min + 0.1f;
  493. }
  494. }
  495. else
  496. {
  497. min = 0.0f;
  498. max = 1.0f;
  499. }
  500. if (dispatcher(effVendorSpecific, kVstParameterUsesIntStep, j, nullptr, 0.0f) >= 0xbeef)
  501. {
  502. step = 1.0f;
  503. stepSmall = 1.0f;
  504. stepLarge = 10.0f;
  505. }
  506. else
  507. {
  508. float range = max - min;
  509. step = range/100.0f;
  510. stepSmall = range/1000.0f;
  511. stepLarge = range/10.0f;
  512. }
  513. }
  514. else if (dispatcher(effGetParameterProperties, j, 0, &prop, 0) == 1)
  515. {
  516. if (prop.flags & kVstParameterUsesIntegerMinMax)
  517. {
  518. min = float(prop.minInteger);
  519. max = float(prop.maxInteger);
  520. if (min > max)
  521. max = min;
  522. else if (max < min)
  523. min = max;
  524. if (max - min == 0.0f)
  525. {
  526. carla_stderr2("WARNING - Broken plugin parameter: max - min == 0.0f");
  527. max = min + 0.1f;
  528. }
  529. }
  530. else
  531. {
  532. min = 0.0f;
  533. max = 1.0f;
  534. }
  535. if (prop.flags & kVstParameterIsSwitch)
  536. {
  537. step = max - min;
  538. stepSmall = step;
  539. stepLarge = step;
  540. kData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  541. }
  542. else if (prop.flags & kVstParameterUsesIntStep)
  543. {
  544. step = float(prop.stepInteger);
  545. stepSmall = float(prop.stepInteger)/10;
  546. stepLarge = float(prop.largeStepInteger);
  547. kData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  548. }
  549. else if (prop.flags & kVstParameterUsesFloatStep)
  550. {
  551. step = prop.stepFloat;
  552. stepSmall = prop.smallStepFloat;
  553. stepLarge = prop.largeStepFloat;
  554. }
  555. else
  556. {
  557. float range = max - min;
  558. step = range/100.0f;
  559. stepSmall = range/1000.0f;
  560. stepLarge = range/10.0f;
  561. }
  562. if (prop.flags & kVstParameterCanRamp)
  563. kData->param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  564. }
  565. else
  566. {
  567. min = 0.0f;
  568. max = 1.0f;
  569. step = 0.001f;
  570. stepSmall = 0.0001f;
  571. stepLarge = 0.1f;
  572. }
  573. kData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  574. #ifndef BUILD_BRIDGE
  575. kData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  576. #endif
  577. if ((fHints & PLUGIN_USES_OLD_VSTSDK) != 0 || dispatcher(effCanBeAutomated, j, 0, nullptr, 0.0f) == 1)
  578. kData->param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  579. // no such thing as VST default parameters
  580. def = fEffect->getParameter(fEffect, j);
  581. if (def < min)
  582. def = min;
  583. else if (def > max)
  584. def = max;
  585. kData->param.ranges[j].min = min;
  586. kData->param.ranges[j].max = max;
  587. kData->param.ranges[j].def = def;
  588. kData->param.ranges[j].step = step;
  589. kData->param.ranges[j].stepSmall = stepSmall;
  590. kData->param.ranges[j].stepLarge = stepLarge;
  591. }
  592. if (needsCtrlIn)
  593. {
  594. portName.clear();
  595. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  596. {
  597. portName = fName;
  598. portName += ":";
  599. }
  600. portName += "events-in";
  601. portName.truncate(portNameSize);
  602. kData->event.portIn = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, true);
  603. }
  604. if (needsCtrlOut)
  605. {
  606. portName.clear();
  607. if (processMode == PROCESS_MODE_SINGLE_CLIENT)
  608. {
  609. portName = fName;
  610. portName += ":";
  611. }
  612. portName += "events-out";
  613. portName.truncate(portNameSize);
  614. kData->event.portOut = (CarlaEngineEventPort*)kData->client->addPort(kEnginePortTypeEvent, portName, false);
  615. }
  616. // plugin hints
  617. const intptr_t vstCategory = dispatcher(effGetPlugCategory, 0, 0, nullptr, 0.0f);
  618. fHints = 0x0;
  619. if (vstCategory == kPlugCategSynth || vstCategory == kPlugCategGenerator)
  620. fHints |= PLUGIN_IS_SYNTH;
  621. if (fEffect->flags & effFlagsHasEditor)
  622. {
  623. fHints |= PLUGIN_HAS_GUI;
  624. if (! fGui.isOsc)
  625. fHints |= PLUGIN_HAS_SINGLE_THREAD;
  626. }
  627. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  628. fHints |= PLUGIN_USES_OLD_VSTSDK;
  629. if ((fEffect->flags & effFlagsCanReplacing) != 0 && fEffect->processReplacing != fEffect->process)
  630. fHints |= PLUGIN_CAN_PROCESS_REPLACING;
  631. if (fEffect->flags & effFlagsHasEditor)
  632. fHints |= PLUGIN_HAS_GUI;
  633. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, (void*)"hasCockosExtensions", 0.0f)) == 0xbeef0000)
  634. fHints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  635. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  636. fHints |= PLUGIN_CAN_DRYWET;
  637. if (aOuts > 0)
  638. fHints |= PLUGIN_CAN_VOLUME;
  639. if (aOuts >= 2 && aOuts % 2 == 0)
  640. fHints |= PLUGIN_CAN_BALANCE;
  641. // extra plugin hints
  642. kData->extraHints = 0x0;
  643. if (mIns > 0)
  644. kData->extraHints |= PLUGIN_HINT_HAS_MIDI_IN;
  645. if (mOuts > 0)
  646. kData->extraHints |= PLUGIN_HINT_HAS_MIDI_OUT;
  647. if (aIns <= 2 && aOuts <= 2 && (aIns == aOuts || aIns == 0 || aOuts == 0))
  648. kData->extraHints |= PLUGIN_HINT_CAN_RUN_RACK;
  649. // dummy pre-start to get latency and wantEvents() on old plugins
  650. {
  651. activate();
  652. deactivate();
  653. }
  654. // check latency
  655. if (fHints & PLUGIN_CAN_DRYWET)
  656. {
  657. #ifdef VESTIGE_HEADER
  658. char* const empty3Ptr = &fEffect->empty3[0];
  659. int32_t* initialDelayPtr = (int32_t*)empty3Ptr;
  660. kData->latency = *initialDelayPtr;
  661. #else
  662. kData->latency = fEffect->initialDelay;
  663. #endif
  664. kData->client->setLatency(kData->latency);
  665. kData->recreateLatencyBuffers();
  666. }
  667. // special plugin fixes
  668. // 1. IL Harmless - disable threaded processing
  669. if (fEffect->uniqueID == 1229484653)
  670. {
  671. char strBuf[STR_MAX+1] = { '\0' };
  672. getLabel(strBuf);
  673. if (std::strcmp(strBuf, "IL Harmless") == 0)
  674. {
  675. // TODO - disable threaded processing
  676. }
  677. }
  678. bufferSizeChanged(kData->engine->getBufferSize());
  679. reloadPrograms(true);
  680. if (kData->active)
  681. activate();
  682. carla_debug("VstPlugin::reload() - end");
  683. }
  684. void reloadPrograms(const bool init) override
  685. {
  686. carla_debug("VstPlugin::reloadPrograms(%s)", bool2str(init));
  687. uint32_t i, oldCount = kData->prog.count;
  688. const int32_t current = kData->prog.current;
  689. // Delete old programs
  690. kData->prog.clear();
  691. // Query new programs
  692. uint32_t count = static_cast<uint32_t>(fEffect->numPrograms);
  693. if (count > 0)
  694. {
  695. kData->prog.createNew(count);
  696. // Update names
  697. for (i=0; i < count; ++i)
  698. {
  699. char strBuf[STR_MAX+1] = { '\0' };
  700. if (dispatcher(effGetProgramNameIndexed, i, 0, strBuf, 0.0f) != 1)
  701. {
  702. // program will be [re-]changed later
  703. dispatcher(effSetProgram, 0, i, nullptr, 0.0f);
  704. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  705. }
  706. kData->prog.names[i] = strdup(strBuf);
  707. }
  708. }
  709. #ifndef BUILD_BRIDGE
  710. // Update OSC Names
  711. if (kData->engine->isOscControlRegistered())
  712. {
  713. kData->engine->osc_send_control_set_program_count(fId, count);
  714. for (i=0; i < count; ++i)
  715. kData->engine->osc_send_control_set_program_name(fId, i, kData->prog.names[i]);
  716. }
  717. #endif
  718. if (init)
  719. {
  720. if (count > 0)
  721. setProgram(0, false, false, false);
  722. }
  723. else
  724. {
  725. // Check if current program is invalid
  726. bool programChanged = false;
  727. if (count == oldCount+1)
  728. {
  729. // one program added, probably created by user
  730. kData->prog.current = oldCount;
  731. programChanged = true;
  732. }
  733. else if (current < 0 && count > 0)
  734. {
  735. // programs exist now, but not before
  736. kData->prog.current = 0;
  737. programChanged = true;
  738. }
  739. else if (current >= 0 && count == 0)
  740. {
  741. // programs existed before, but not anymore
  742. kData->prog.current = -1;
  743. programChanged = true;
  744. }
  745. else if (current >= static_cast<int32_t>(count))
  746. {
  747. // current program > count
  748. kData->prog.current = 0;
  749. programChanged = true;
  750. }
  751. else
  752. {
  753. // no change
  754. kData->prog.current = current;
  755. }
  756. if (programChanged)
  757. {
  758. setProgram(kData->prog.current, true, true, true);
  759. }
  760. else
  761. {
  762. // Program was changed during update, re-set it
  763. if (kData->prog.current >= 0)
  764. dispatcher(effSetProgram, 0, kData->prog.current, nullptr, 0.0f);
  765. }
  766. kData->engine->callback(CALLBACK_RELOAD_PROGRAMS, fId, 0, 0, 0.0f, nullptr);
  767. }
  768. }
  769. // -------------------------------------------------------------------
  770. // Plugin processing
  771. void activate() override
  772. {
  773. dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  774. dispatcher(effStartProcess, 0, 0, nullptr, 0.0f);
  775. }
  776. void deactivate() override
  777. {
  778. dispatcher(effStopProcess, 0, 0, nullptr, 0.0f);
  779. dispatcher(effMainsChanged, 0, 0, nullptr, 0.0f);
  780. }
  781. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames) override
  782. {
  783. uint32_t i, k;
  784. // --------------------------------------------------------------------------------------------------------
  785. // Check if active
  786. if (! kData->active)
  787. {
  788. // disable any output sound
  789. for (i=0; i < kData->audioOut.count; ++i)
  790. carla_zeroFloat(outBuffer[i], frames);
  791. return;
  792. }
  793. fMidiEventCount = 0;
  794. carla_zeroStruct<VstMidiEvent>(fMidiEvents, MAX_MIDI_EVENTS*2);
  795. // --------------------------------------------------------------------------------------------------------
  796. // Check if needs reset
  797. if (kData->needsReset)
  798. {
  799. // TODO!
  800. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  801. {
  802. for (k=0, i=MAX_MIDI_CHANNELS; k < MAX_MIDI_CHANNELS; ++k)
  803. {
  804. fMidiEvents[k].type = kVstMidiType;
  805. fMidiEvents[k].byteSize = sizeof(VstMidiEvent);
  806. fMidiEvents[k].midiData[0] = MIDI_STATUS_CONTROL_CHANGE + k;
  807. fMidiEvents[k].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  808. fMidiEvents[k+i].type = kVstMidiType;
  809. fMidiEvents[k+i].byteSize = sizeof(VstMidiEvent);
  810. fMidiEvents[k+i].midiData[0] = MIDI_STATUS_CONTROL_CHANGE + k;
  811. fMidiEvents[k+i].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  812. }
  813. fMidiEventCount = MAX_MIDI_CHANNELS*2;
  814. }
  815. else
  816. {
  817. }
  818. if (kData->latency > 0)
  819. {
  820. for (i=0; i < kData->audioIn.count; ++i)
  821. carla_zeroFloat(kData->latencyBuffers[i], kData->latency);
  822. }
  823. kData->needsReset = false;
  824. }
  825. CARLA_PROCESS_CONTINUE_CHECK;
  826. // --------------------------------------------------------------------------------------------------------
  827. // Set TimeInfo
  828. const EngineTimeInfo& timeInfo(kData->engine->getTimeInfo());
  829. fTimeInfo.flags = kVstTransportChanged;
  830. if (timeInfo.playing)
  831. fTimeInfo.flags |= kVstTransportPlaying;
  832. fTimeInfo.samplePos = timeInfo.frame;
  833. fTimeInfo.sampleRate = kData->engine->getSampleRate();
  834. if (timeInfo.usecs != 0)
  835. {
  836. fTimeInfo.nanoSeconds = timeInfo.usecs/1000;
  837. fTimeInfo.flags |= kVstNanosValid;
  838. }
  839. if (timeInfo.valid & EngineTimeInfo::ValidBBT)
  840. {
  841. double ppqBar = double(timeInfo.bbt.bar - 1) * timeInfo.bbt.beatsPerBar;
  842. double ppqBeat = double(timeInfo.bbt.beat - 1);
  843. double ppqTick = double(timeInfo.bbt.tick) / timeInfo.bbt.ticksPerBeat;
  844. // PPQ Pos
  845. fTimeInfo.ppqPos = ppqBar + ppqBeat + ppqTick;
  846. fTimeInfo.flags |= kVstPpqPosValid;
  847. // Tempo
  848. fTimeInfo.tempo = timeInfo.bbt.beatsPerMinute;
  849. fTimeInfo.flags |= kVstTempoValid;
  850. // Bars
  851. fTimeInfo.barStartPos = ppqBar;
  852. fTimeInfo.flags |= kVstBarsValid;
  853. // Time Signature
  854. fTimeInfo.timeSigNumerator = timeInfo.bbt.beatsPerBar;
  855. fTimeInfo.timeSigDenominator = timeInfo.bbt.beatType;
  856. fTimeInfo.flags |= kVstTimeSigValid;
  857. }
  858. else
  859. {
  860. // Tempo
  861. fTimeInfo.tempo = 120.0;
  862. fTimeInfo.flags |= kVstTempoValid;
  863. // Time Signature
  864. fTimeInfo.timeSigNumerator = 4;
  865. fTimeInfo.timeSigDenominator = 4;
  866. fTimeInfo.flags |= kVstTimeSigValid;
  867. // Missing info
  868. fTimeInfo.ppqPos = 0.0;
  869. fTimeInfo.barStartPos = 0.0;
  870. }
  871. CARLA_PROCESS_CONTINUE_CHECK;
  872. // --------------------------------------------------------------------------------------------------------
  873. // Event Input and Processing
  874. if (kData->event.portIn != nullptr)
  875. {
  876. // ----------------------------------------------------------------------------------------------------
  877. // MIDI Input (External)
  878. if (kData->extNotes.mutex.tryLock())
  879. {
  880. while (fMidiEventCount < MAX_MIDI_EVENTS*2 && ! kData->extNotes.data.isEmpty())
  881. {
  882. const ExternalMidiNote& note(kData->extNotes.data.getFirst(true));
  883. CARLA_ASSERT(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  884. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  885. fMidiEvents[fMidiEventCount].byteSize = sizeof(VstMidiEvent);
  886. fMidiEvents[fMidiEventCount].midiData[0] = (note.velo > 0) ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF;
  887. fMidiEvents[fMidiEventCount].midiData[0] += note.channel;
  888. fMidiEvents[fMidiEventCount].midiData[1] = note.note;
  889. fMidiEvents[fMidiEventCount].midiData[2] = note.velo;
  890. fMidiEventCount += 1;
  891. }
  892. kData->extNotes.mutex.unlock();
  893. } // End of MIDI Input (External)
  894. // ----------------------------------------------------------------------------------------------------
  895. // Event Input (System)
  896. bool allNotesOffSent = false;
  897. bool sampleAccurate = (fOptions & PLUGIN_OPTION_FIXED_BUFFER) == 0;
  898. uint32_t time, nEvents = kData->event.portIn->getEventCount();
  899. uint32_t startTime = 0;
  900. uint32_t timeOffset = 0;
  901. for (i=0; i < nEvents; ++i)
  902. {
  903. const EngineEvent& event(kData->event.portIn->getEvent(i));
  904. time = event.time;
  905. if (time >= frames)
  906. continue;
  907. CARLA_ASSERT_INT2(time >= timeOffset, time, timeOffset);
  908. if (time > timeOffset && sampleAccurate)
  909. {
  910. if (processSingle(inBuffer, outBuffer, time - timeOffset, timeOffset))
  911. {
  912. startTime = 0;
  913. timeOffset = time;
  914. if (fMidiEventCount > 0)
  915. {
  916. carla_zeroStruct<VstMidiEvent>(fMidiEvents, fMidiEventCount);
  917. fMidiEventCount = 0;
  918. }
  919. }
  920. else
  921. startTime += timeOffset;
  922. }
  923. // Control change
  924. switch (event.type)
  925. {
  926. case kEngineEventTypeNull:
  927. break;
  928. case kEngineEventTypeControl:
  929. {
  930. const EngineControlEvent& ctrlEvent = event.ctrl;
  931. switch (ctrlEvent.type)
  932. {
  933. case kEngineControlEventTypeNull:
  934. break;
  935. case kEngineControlEventTypeParameter:
  936. {
  937. // Control backend stuff
  938. if (event.channel == kData->ctrlChannel)
  939. {
  940. float value;
  941. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (fHints & PLUGIN_CAN_DRYWET) > 0)
  942. {
  943. value = ctrlEvent.value;
  944. setDryWet(value, false, false);
  945. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_DRYWET, 0, value);
  946. continue;
  947. }
  948. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (fHints & PLUGIN_CAN_VOLUME) > 0)
  949. {
  950. value = ctrlEvent.value*127.0f/100.0f;
  951. setVolume(value, false, false);
  952. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_VOLUME, 0, value);
  953. continue;
  954. }
  955. if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (fHints & PLUGIN_CAN_BALANCE) > 0)
  956. {
  957. float left, right;
  958. value = ctrlEvent.value/0.5f - 1.0f;
  959. if (value < 0.0f)
  960. {
  961. left = -1.0f;
  962. right = (value*2.0f)+1.0f;
  963. }
  964. else if (value > 0.0f)
  965. {
  966. left = (value*2.0f)-1.0f;
  967. right = 1.0f;
  968. }
  969. else
  970. {
  971. left = -1.0f;
  972. right = 1.0f;
  973. }
  974. setBalanceLeft(left, false, false);
  975. setBalanceRight(right, false, false);
  976. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  977. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  978. continue;
  979. }
  980. }
  981. // Control plugin parameters
  982. for (k=0; k < kData->param.count; ++k)
  983. {
  984. if (kData->param.data[k].midiChannel != event.channel)
  985. continue;
  986. if (kData->param.data[k].midiCC != ctrlEvent.param)
  987. continue;
  988. if (kData->param.data[k].type != PARAMETER_INPUT)
  989. continue;
  990. if ((kData->param.data[k].hints & PARAMETER_IS_AUTOMABLE) == 0)
  991. continue;
  992. float value;
  993. if (kData->param.data[k].hints & PARAMETER_IS_BOOLEAN)
  994. {
  995. value = (ctrlEvent.value < 0.5f) ? kData->param.ranges[k].min : kData->param.ranges[k].max;
  996. }
  997. else
  998. {
  999. value = kData->param.ranges[i].unnormalizeValue(ctrlEvent.value);
  1000. if (kData->param.data[k].hints & PARAMETER_IS_INTEGER)
  1001. value = std::rint(value);
  1002. }
  1003. setParameterValue(k, value, false, false, false);
  1004. postponeRtEvent(kPluginPostRtEventParameterChange, static_cast<int32_t>(k), 0, value);
  1005. }
  1006. break;
  1007. }
  1008. case kEngineControlEventTypeMidiBank:
  1009. break;
  1010. case kEngineControlEventTypeMidiProgram:
  1011. if (event.channel == kData->ctrlChannel && (fOptions & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  1012. {
  1013. if (ctrlEvent.param < kData->prog.count)
  1014. {
  1015. setProgram(ctrlEvent.param, false, false, false);
  1016. postponeRtEvent(kPluginPostRtEventProgramChange, ctrlEvent.param, 0, 0.0f);
  1017. break;
  1018. }
  1019. }
  1020. break;
  1021. case kEngineControlEventTypeAllSoundOff:
  1022. if (event.channel == kData->ctrlChannel)
  1023. {
  1024. if (! allNotesOffSent)
  1025. {
  1026. sendMidiAllNotesOff();
  1027. allNotesOffSent = true;
  1028. }
  1029. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_ACTIVE, 0, 0.0f);
  1030. postponeRtEvent(kPluginPostRtEventParameterChange, PARAMETER_ACTIVE, 0, 1.0f);
  1031. }
  1032. if (fMidiEventCount >= MAX_MIDI_EVENTS*2)
  1033. continue;
  1034. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1035. {
  1036. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1037. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1038. fMidiEvents[fMidiEventCount].byteSize = sizeof(VstMidiEvent);
  1039. fMidiEvents[fMidiEventCount].midiData[0] = MIDI_STATUS_CONTROL_CHANGE + event.channel;
  1040. fMidiEvents[fMidiEventCount].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  1041. fMidiEvents[fMidiEventCount].deltaFrames = sampleAccurate ? startTime : time;
  1042. fMidiEventCount += 1;
  1043. }
  1044. break;
  1045. case kEngineControlEventTypeAllNotesOff:
  1046. if (event.channel == kData->ctrlChannel)
  1047. {
  1048. if (! allNotesOffSent)
  1049. {
  1050. allNotesOffSent = true;
  1051. sendMidiAllNotesOff();
  1052. }
  1053. }
  1054. if (fMidiEventCount >= MAX_MIDI_EVENTS*2)
  1055. continue;
  1056. if (fOptions & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1057. {
  1058. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1059. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1060. fMidiEvents[fMidiEventCount].byteSize = sizeof(VstMidiEvent);
  1061. fMidiEvents[fMidiEventCount].midiData[0] = MIDI_STATUS_CONTROL_CHANGE + event.channel;
  1062. fMidiEvents[fMidiEventCount].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  1063. fMidiEvents[fMidiEventCount].deltaFrames = sampleAccurate ? startTime : time;
  1064. fMidiEventCount += 1;
  1065. }
  1066. break;
  1067. }
  1068. break;
  1069. }
  1070. case kEngineEventTypeMidi:
  1071. {
  1072. if (fMidiEventCount >= MAX_MIDI_EVENTS*2)
  1073. continue;
  1074. const EngineMidiEvent& midiEvent = event.midi;
  1075. uint8_t status = MIDI_GET_STATUS_FROM_DATA(midiEvent.data);
  1076. uint8_t channel = event.channel;
  1077. if (MIDI_IS_STATUS_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1078. continue;
  1079. if (MIDI_IS_STATUS_CONTROL_CHANGE(status) && (fOptions & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1080. continue;
  1081. if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status) && (fOptions & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1082. continue;
  1083. if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status) && (fOptions & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1084. continue;
  1085. // Fix bad note-off
  1086. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1087. status -= 0x10;
  1088. carla_zeroStruct<VstMidiEvent>(fMidiEvents[fMidiEventCount]);
  1089. fMidiEvents[fMidiEventCount].type = kVstMidiType;
  1090. fMidiEvents[fMidiEventCount].byteSize = sizeof(VstMidiEvent);
  1091. fMidiEvents[fMidiEventCount].midiData[0] = status + channel;
  1092. fMidiEvents[fMidiEventCount].midiData[1] = midiEvent.data[1];
  1093. fMidiEvents[fMidiEventCount].midiData[2] = midiEvent.data[2];
  1094. fMidiEvents[fMidiEventCount].deltaFrames = sampleAccurate ? startTime : time;
  1095. fMidiEventCount += 1;
  1096. if (status == MIDI_STATUS_NOTE_ON)
  1097. postponeRtEvent(kPluginPostRtEventNoteOn, channel, midiEvent.data[1], midiEvent.data[2]);
  1098. else if (status == MIDI_STATUS_NOTE_OFF)
  1099. postponeRtEvent(kPluginPostRtEventNoteOff, channel, midiEvent.data[1], 0.0f);
  1100. break;
  1101. }
  1102. }
  1103. }
  1104. kData->postRtEvents.trySplice();
  1105. if (frames > timeOffset)
  1106. processSingle(inBuffer, outBuffer, frames - timeOffset, timeOffset);
  1107. } // End of Event Input and Processing
  1108. // --------------------------------------------------------------------------------------------------------
  1109. // Plugin processing (no events)
  1110. else
  1111. {
  1112. processSingle(inBuffer, outBuffer, frames, 0);
  1113. } // End of Plugin processing (no events)
  1114. CARLA_PROCESS_CONTINUE_CHECK;
  1115. // --------------------------------------------------------------------------------------------------------
  1116. // MIDI Output
  1117. if (kData->event.portOut != nullptr)
  1118. {
  1119. // reverse lookup MIDI events
  1120. for (k = (MAX_MIDI_EVENTS*2)-1; k >= fMidiEventCount; --k)
  1121. {
  1122. if (fMidiEvents[k].type == 0)
  1123. break;
  1124. const uint8_t channel = MIDI_GET_CHANNEL_FROM_DATA(fMidiEvents[k].midiData);
  1125. uint8_t midiData[3] = { 0 };
  1126. midiData[0] = fMidiEvents[k].midiData[0];
  1127. midiData[1] = fMidiEvents[k].midiData[1];
  1128. midiData[2] = fMidiEvents[k].midiData[2];
  1129. kData->event.portOut->writeMidiEvent(fMidiEvents[k].deltaFrames, channel, 0, midiData, 3);
  1130. }
  1131. } // End of Control and MIDI Output
  1132. }
  1133. bool processSingle(float** const inBuffer, float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  1134. {
  1135. CARLA_ASSERT(frames > 0);
  1136. if (frames == 0)
  1137. return false;
  1138. if (kData->audioIn.count > 0)
  1139. {
  1140. CARLA_ASSERT(inBuffer != nullptr);
  1141. if (inBuffer == nullptr)
  1142. return false;
  1143. }
  1144. if (kData->audioOut.count > 0)
  1145. {
  1146. CARLA_ASSERT(outBuffer != nullptr);
  1147. if (outBuffer == nullptr)
  1148. return false;
  1149. }
  1150. uint32_t i, k;
  1151. // --------------------------------------------------------------------------------------------------------
  1152. // Try lock, silence otherwise
  1153. if (kData->engine->isOffline())
  1154. {
  1155. kData->singleMutex.lock();
  1156. }
  1157. else if (! kData->singleMutex.tryLock())
  1158. {
  1159. for (i=0; i < kData->audioOut.count; ++i)
  1160. {
  1161. for (k=0; k < frames; ++k)
  1162. outBuffer[i][k+timeOffset] = 0.0f;
  1163. }
  1164. return false;
  1165. }
  1166. // --------------------------------------------------------------------------------------------------------
  1167. // Set audio buffers
  1168. float* vstInBuffer[kData->audioIn.count];
  1169. float* vstOutBuffer[kData->audioOut.count];
  1170. for (i=0; i < kData->audioIn.count; ++i)
  1171. vstInBuffer[i] = inBuffer[i]+timeOffset;
  1172. for (i=0; i < kData->audioOut.count; ++i)
  1173. vstOutBuffer[i] = outBuffer[i]+timeOffset;
  1174. // --------------------------------------------------------------------------------------------------------
  1175. // Set MIDI events
  1176. if (fMidiEventCount > 0)
  1177. {
  1178. fEvents.numEvents = fMidiEventCount;
  1179. fEvents.reserved = 0;
  1180. dispatcher(effProcessEvents, 0, 0, &fEvents, 0.0f);
  1181. }
  1182. // --------------------------------------------------------------------------------------------------------
  1183. // Run plugin
  1184. fIsProcessing = true;
  1185. if (fHints & PLUGIN_CAN_PROCESS_REPLACING)
  1186. {
  1187. fEffect->processReplacing(fEffect,
  1188. (kData->audioIn.count > 0) ? vstInBuffer : nullptr,
  1189. (kData->audioOut.count > 0) ? vstOutBuffer : nullptr,
  1190. frames);
  1191. }
  1192. else
  1193. {
  1194. for (i=0; i < kData->audioOut.count; ++i)
  1195. carla_zeroFloat(vstOutBuffer[i], frames);
  1196. #if ! VST_FORCE_DEPRECATED
  1197. fEffect->process(fEffect,
  1198. (kData->audioIn.count > 0) ? vstInBuffer : nullptr,
  1199. (kData->audioOut.count > 0) ? vstOutBuffer : nullptr,
  1200. frames);
  1201. #endif
  1202. }
  1203. fIsProcessing = false;
  1204. fTimeInfo.samplePos += frames;
  1205. // --------------------------------------------------------------------------------------------------------
  1206. // Post-processing (dry/wet, volume and balance)
  1207. {
  1208. const bool doVolume = (fHints & PLUGIN_CAN_VOLUME) != 0 && kData->postProc.volume != 1.0f;
  1209. const bool doDryWet = (fHints & PLUGIN_CAN_DRYWET) != 0 && kData->postProc.dryWet != 1.0f;
  1210. const bool doBalance = (fHints & PLUGIN_CAN_BALANCE) != 0 && (kData->postProc.balanceLeft != -1.0f || kData->postProc.balanceRight != 1.0f);
  1211. bool isPair;
  1212. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1213. for (i=0; i < kData->audioOut.count; ++i)
  1214. {
  1215. // Dry/Wet
  1216. if (doDryWet)
  1217. {
  1218. for (k=0; k < frames; ++k)
  1219. {
  1220. bufValue = inBuffer[(kData->audioIn.count == 1) ? 0 : i][k+timeOffset];
  1221. outBuffer[i][k+timeOffset] = (outBuffer[i][k+timeOffset] * kData->postProc.dryWet) + (bufValue * (1.0f - kData->postProc.dryWet));
  1222. }
  1223. }
  1224. // Balance
  1225. if (doBalance)
  1226. {
  1227. isPair = (i % 2 == 0);
  1228. if (isPair)
  1229. {
  1230. CARLA_ASSERT(i+1 < kData->audioOut.count);
  1231. carla_copyFloat(oldBufLeft, outBuffer[i]+timeOffset, frames);
  1232. }
  1233. float balRangeL = (kData->postProc.balanceLeft + 1.0f)/2.0f;
  1234. float balRangeR = (kData->postProc.balanceRight + 1.0f)/2.0f;
  1235. for (k=0; k < frames; ++k)
  1236. {
  1237. if (isPair)
  1238. {
  1239. // left
  1240. outBuffer[i][k+timeOffset] = oldBufLeft[k] * (1.0f - balRangeL);
  1241. outBuffer[i][k+timeOffset] += outBuffer[i+1][k+timeOffset] * (1.0f - balRangeR);
  1242. }
  1243. else
  1244. {
  1245. // right
  1246. outBuffer[i][k+timeOffset] = outBuffer[i][k+timeOffset] * balRangeR;
  1247. outBuffer[i][k+timeOffset] += oldBufLeft[k] * balRangeL;
  1248. }
  1249. }
  1250. }
  1251. // Volume
  1252. if (doVolume)
  1253. {
  1254. for (k=0; k < frames; ++k)
  1255. outBuffer[i][k+timeOffset] *= kData->postProc.volume;
  1256. }
  1257. }
  1258. } // End of Post-processing
  1259. // --------------------------------------------------------------------------------------------------------
  1260. kData->singleMutex.unlock();
  1261. return true;
  1262. }
  1263. void bufferSizeChanged(const uint32_t newBufferSize) override
  1264. {
  1265. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1266. carla_debug("VstPlugin::bufferSizeChanged(%i)", newBufferSize);
  1267. if (kData->active)
  1268. deactivate();
  1269. #if ! VST_FORCE_DEPRECATED
  1270. dispatcher(effSetBlockSizeAndSampleRate, 0, newBufferSize, nullptr, kData->engine->getSampleRate());
  1271. #endif
  1272. dispatcher(effSetBlockSize, 0, newBufferSize, nullptr, 0.0f);
  1273. if (kData->active)
  1274. activate();
  1275. }
  1276. void sampleRateChanged(const double newSampleRate) override
  1277. {
  1278. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1279. carla_debug("VstPlugin::sampleRateChanged(%g)", newSampleRate);
  1280. if (kData->active)
  1281. deactivate();
  1282. #if ! VST_FORCE_DEPRECATED
  1283. dispatcher(effSetBlockSizeAndSampleRate, 0, kData->engine->getBufferSize(), nullptr, newSampleRate);
  1284. #endif
  1285. dispatcher(effSetSampleRate, 0, 0, nullptr, newSampleRate);
  1286. if (kData->active)
  1287. activate();
  1288. }
  1289. // -------------------------------------------------------------------
  1290. // Plugin buffers
  1291. // nothing
  1292. // -------------------------------------------------------------------
  1293. // Post-poned UI Stuff
  1294. void uiParameterChange(const uint32_t index, const float value) override
  1295. {
  1296. CARLA_ASSERT(index < kData->param.count);
  1297. if (index >= kData->param.count)
  1298. return;
  1299. if (! fGui.isOsc)
  1300. return;
  1301. if (kData->osc.data.target == nullptr)
  1302. return;
  1303. osc_send_control(&kData->osc.data, kData->param.data[index].rindex, value);
  1304. }
  1305. void uiProgramChange(const uint32_t index) override
  1306. {
  1307. CARLA_ASSERT(index < kData->prog.count);
  1308. if (index >= kData->prog.count)
  1309. return;
  1310. if (! fGui.isOsc)
  1311. return;
  1312. if (kData->osc.data.target == nullptr)
  1313. return;
  1314. osc_send_program(&kData->osc.data, index);
  1315. }
  1316. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo) override
  1317. {
  1318. CARLA_ASSERT(channel < MAX_MIDI_CHANNELS);
  1319. CARLA_ASSERT(note < MAX_MIDI_NOTE);
  1320. CARLA_ASSERT(velo > 0 && velo < MAX_MIDI_VALUE);
  1321. if (channel >= MAX_MIDI_CHANNELS)
  1322. return;
  1323. if (note >= MAX_MIDI_NOTE)
  1324. return;
  1325. if (velo >= MAX_MIDI_VALUE)
  1326. return;
  1327. if (! fGui.isOsc)
  1328. return;
  1329. if (kData->osc.data.target == nullptr)
  1330. return;
  1331. uint8_t midiData[4] = { 0 };
  1332. midiData[1] = MIDI_STATUS_NOTE_ON + channel;
  1333. midiData[2] = note;
  1334. midiData[3] = velo;
  1335. osc_send_midi(&kData->osc.data, midiData);
  1336. }
  1337. void uiNoteOff(const uint8_t channel, const uint8_t note) override
  1338. {
  1339. CARLA_ASSERT(channel < MAX_MIDI_CHANNELS);
  1340. CARLA_ASSERT(note < MAX_MIDI_NOTE);
  1341. if (channel >= MAX_MIDI_CHANNELS)
  1342. return;
  1343. if (note >= MAX_MIDI_NOTE)
  1344. return;
  1345. if (! fGui.isOsc)
  1346. return;
  1347. if (kData->osc.data.target == nullptr)
  1348. return;
  1349. uint8_t midiData[4] = { 0 };
  1350. midiData[1] = MIDI_STATUS_NOTE_OFF + channel;
  1351. midiData[2] = note;
  1352. osc_send_midi(&kData->osc.data, midiData);
  1353. }
  1354. // -------------------------------------------------------------------
  1355. protected:
  1356. void guiClosedCallback() override
  1357. {
  1358. showGui(false);
  1359. kData->engine->callback(CALLBACK_SHOW_GUI, fId, 0, 0, 0.0f, nullptr);
  1360. }
  1361. intptr_t dispatcher(int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  1362. {
  1363. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  1364. if (opcode != effEditIdle && opcode != effProcessEvents)
  1365. carla_debug("VstPlugin::dispatcher(%02i:%s, %i, " P_INTPTR ", %p, %f)", opcode, vstEffectOpcode2str(opcode), index, value, ptr, opt);
  1366. #endif
  1367. CARLA_ASSERT(fEffect != nullptr);
  1368. return (fEffect != nullptr) ? fEffect->dispatcher(fEffect, opcode, index, value, ptr, opt) : 0;
  1369. }
  1370. intptr_t handleAudioMasterCallback(const int32_t opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  1371. {
  1372. #if 0
  1373. // Cockos VST extensions
  1374. if (ptr != nullptr && static_cast<uint32_t>(opcode) == 0xdeadbeef && static_cast<uint32_t>(index) == 0xdeadf00d)
  1375. {
  1376. const char* const func = (char*)ptr;
  1377. if (std::strcmp(func, "GetPlayPosition") == 0)
  1378. return 0;
  1379. if (std::strcmp(func, "GetPlayPosition2") == 0)
  1380. return 0;
  1381. if (std::strcmp(func, "GetCursorPosition") == 0)
  1382. return 0;
  1383. if (std::strcmp(func, "GetPlayState") == 0)
  1384. return 0;
  1385. if (std::strcmp(func, "SetEditCurPos") == 0)
  1386. return 0;
  1387. if (std::strcmp(func, "GetSetRepeat") == 0)
  1388. return 0;
  1389. if (std::strcmp(func, "GetProjectPath") == 0)
  1390. return 0;
  1391. if (std::strcmp(func, "OnPlayButton") == 0)
  1392. return 0;
  1393. if (std::strcmp(func, "OnStopButton") == 0)
  1394. return 0;
  1395. if (std::strcmp(func, "OnPauseButton") == 0)
  1396. return 0;
  1397. if (std::strcmp(func, "IsInRealTimeAudio") == 0)
  1398. return 0;
  1399. if (std::strcmp(func, "Audio_IsRunning") == 0)
  1400. return 0;
  1401. }
  1402. #endif
  1403. intptr_t ret = 0;
  1404. switch (opcode)
  1405. {
  1406. case audioMasterAutomate:
  1407. if (! fEnabled)
  1408. break;
  1409. // plugins should never do this:
  1410. CARLA_SAFE_ASSERT_INT(index < static_cast<int32_t>(kData->param.count), index);
  1411. if (index < 0 || index >= static_cast<int32_t>(kData->param.count))
  1412. break;
  1413. if (fGui.isVisible && ! fIsProcessing)
  1414. {
  1415. // Called from GUI
  1416. setParameterValue(index, opt, false, true, true);
  1417. }
  1418. else if (fIsProcessing)
  1419. {
  1420. // Called from engine
  1421. const float fixedValue(kData->param.fixValue(index, opt));
  1422. if (kData->engine->isOffline())
  1423. {
  1424. CarlaPlugin::setParameterValue(index, fixedValue, true, true, true);
  1425. }
  1426. else
  1427. {
  1428. CarlaPlugin::setParameterValue(index, fixedValue, false, false, false);
  1429. postponeRtEvent(kPluginPostRtEventParameterChange, index, 0, fixedValue);
  1430. }
  1431. }
  1432. else
  1433. {
  1434. carla_stdout("audioMasterAutomate called from unknown source");
  1435. }
  1436. break;
  1437. case audioMasterCurrentId:
  1438. // TODO
  1439. // if using old sdk, return effect->uniqueID
  1440. break;
  1441. case audioMasterIdle:
  1442. if (fGui.isVisible)
  1443. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  1444. break;
  1445. #if ! VST_FORCE_DEPRECATED
  1446. case audioMasterPinConnected:
  1447. // Deprecated in VST SDK 2.4
  1448. // TODO
  1449. break;
  1450. case audioMasterWantMidi:
  1451. // Deprecated in VST SDK 2.4
  1452. fHints |= PLUGIN_WANTS_MIDI_INPUT;
  1453. break;
  1454. #endif
  1455. case audioMasterGetTime:
  1456. #ifdef VESTIGE_HEADER
  1457. ret = getAddressFromPointer(&fTimeInfo);
  1458. #else
  1459. ret = ToVstPtr<VstTimeInfo_R>(&fTimeInfo);
  1460. #endif
  1461. break;
  1462. case audioMasterProcessEvents:
  1463. CARLA_ASSERT(fEnabled);
  1464. CARLA_ASSERT(fIsProcessing);
  1465. CARLA_ASSERT(kData->event.portOut != nullptr);
  1466. CARLA_ASSERT(ptr != nullptr);
  1467. if (! fEnabled)
  1468. return 0;
  1469. if (! fIsProcessing)
  1470. return 0;
  1471. if (kData->event.portOut == nullptr)
  1472. return 0;
  1473. if (ptr == nullptr)
  1474. return 0;
  1475. if (! fIsProcessing)
  1476. {
  1477. carla_stderr2("audioMasterProcessEvents(%p) - received MIDI out events outside audio thread, ignoring", ptr);
  1478. return 0;
  1479. }
  1480. if (fMidiEventCount >= MAX_MIDI_EVENTS*2)
  1481. return 0;
  1482. {
  1483. const VstEvents* const vstEvents((const VstEvents*)ptr);
  1484. for (int32_t i=0; i < vstEvents->numEvents && i < MAX_MIDI_EVENTS*2; ++i)
  1485. {
  1486. if (vstEvents->events[i] == nullptr)
  1487. break;
  1488. const VstMidiEvent* const vstMidiEvent = (const VstMidiEvent*)vstEvents->events[i];
  1489. if (vstMidiEvent->type != kVstMidiType)
  1490. continue;
  1491. // reverse-find first free event, and put it there
  1492. for (uint32_t j=(MAX_MIDI_EVENTS*2)-1; j >= fMidiEventCount; --j)
  1493. {
  1494. if (fMidiEvents[j].type == 0)
  1495. {
  1496. std::memcpy(&fMidiEvents[j], vstMidiEvent, sizeof(VstMidiEvent));
  1497. break;
  1498. }
  1499. }
  1500. }
  1501. }
  1502. ret = 1;
  1503. break;
  1504. #if ! VST_FORCE_DEPRECATED
  1505. case audioMasterSetTime:
  1506. // Deprecated in VST SDK 2.4
  1507. break;
  1508. case audioMasterTempoAt:
  1509. // Deprecated in VST SDK 2.4
  1510. CARLA_ASSERT(fIsProcessing);
  1511. ret = fTimeInfo.tempo * 10000;
  1512. break;
  1513. case audioMasterGetNumAutomatableParameters:
  1514. // Deprecated in VST SDK 2.4
  1515. ret = carla_min<intptr_t>(0, fEffect->numParams, kData->engine->getOptions().maxParameters);
  1516. break;
  1517. case audioMasterGetParameterQuantization:
  1518. // Deprecated in VST SDK 2.4
  1519. ret = 1; // full single float precision
  1520. break;
  1521. #endif
  1522. #if 0
  1523. case audioMasterIOChanged:
  1524. CARLA_ASSERT(fEnabled);
  1525. // TESTING
  1526. if (! fEnabled)
  1527. {
  1528. ret = 1;
  1529. break;
  1530. }
  1531. if (x_engine->getOptions().processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1532. {
  1533. carla_stderr2("VstPlugin::handleAudioMasterIOChanged() - plugin asked IO change, but it's not supported in rack mode");
  1534. return 0;
  1535. }
  1536. engineProcessLock();
  1537. m_enabled = false;
  1538. engineProcessUnlock();
  1539. if (m_active)
  1540. {
  1541. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  1542. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  1543. }
  1544. reload();
  1545. if (m_active)
  1546. {
  1547. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1548. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  1549. }
  1550. x_engine->callback(CALLBACK_RELOAD_ALL, m_id, 0, 0, 0.0, nullptr);
  1551. ret = 1;
  1552. break;
  1553. #endif
  1554. case audioMasterNeedIdle:
  1555. // Deprecated in VST SDK 2.4
  1556. fNeedIdle = true;
  1557. ret = 1;
  1558. break;
  1559. case audioMasterSizeWindow:
  1560. if (kData->gui != nullptr)
  1561. {
  1562. kData->gui->setSize(index, value);
  1563. ret = 1;
  1564. }
  1565. break;
  1566. case audioMasterGetSampleRate:
  1567. ret = kData->engine->getSampleRate();
  1568. break;
  1569. case audioMasterGetBlockSize:
  1570. ret = kData->engine->getBufferSize();
  1571. break;
  1572. case audioMasterGetInputLatency:
  1573. ret = 0;
  1574. break;
  1575. case audioMasterGetOutputLatency:
  1576. ret = 0;
  1577. break;
  1578. #if ! VST_FORCE_DEPRECATED
  1579. case audioMasterGetPreviousPlug:
  1580. // Deprecated in VST SDK 2.4
  1581. // TODO
  1582. break;
  1583. case audioMasterGetNextPlug:
  1584. // Deprecated in VST SDK 2.4
  1585. // TODO
  1586. break;
  1587. case audioMasterWillReplaceOrAccumulate:
  1588. // Deprecated in VST SDK 2.4
  1589. ret = 1; // replace
  1590. break;
  1591. #endif
  1592. case audioMasterGetCurrentProcessLevel:
  1593. if (kData->engine->isOffline())
  1594. ret = kVstProcessLevelOffline;
  1595. else if (fIsProcessing)
  1596. ret = kVstProcessLevelRealtime;
  1597. else
  1598. ret = kVstProcessLevelUser;
  1599. break;
  1600. case audioMasterGetAutomationState:
  1601. ret = kData->active ? kVstAutomationReadWrite : kVstAutomationOff;
  1602. break;
  1603. case audioMasterOfflineStart:
  1604. case audioMasterOfflineRead:
  1605. case audioMasterOfflineWrite:
  1606. case audioMasterOfflineGetCurrentPass:
  1607. case audioMasterOfflineGetCurrentMetaPass:
  1608. // TODO
  1609. break;
  1610. #if ! VST_FORCE_DEPRECATED
  1611. case audioMasterSetOutputSampleRate:
  1612. // Deprecated in VST SDK 2.4
  1613. break;
  1614. case audioMasterGetOutputSpeakerArrangement:
  1615. // Deprecated in VST SDK 2.4
  1616. // TODO
  1617. break;
  1618. #endif
  1619. case audioMasterVendorSpecific:
  1620. // TODO - cockos extensions
  1621. break;
  1622. #if ! VST_FORCE_DEPRECATED
  1623. case audioMasterSetIcon:
  1624. // Deprecated in VST SDK 2.4
  1625. break;
  1626. #endif
  1627. #if ! VST_FORCE_DEPRECATED
  1628. case audioMasterOpenWindow:
  1629. case audioMasterCloseWindow:
  1630. // Deprecated in VST SDK 2.4
  1631. // TODO
  1632. break;
  1633. #endif
  1634. case audioMasterGetDirectory:
  1635. // TODO
  1636. break;
  1637. case audioMasterUpdateDisplay:
  1638. // Idle UI if visible
  1639. if (fGui.isVisible)
  1640. dispatcher(effEditIdle, 0, 0, nullptr, 0.0f);
  1641. // Update current program
  1642. if (kData->prog.count > 0)
  1643. {
  1644. const int32_t current = dispatcher(effGetProgram, 0, 0, nullptr, 0.0f);
  1645. if (current >= 0 && current < static_cast<int32_t>(kData->prog.count))
  1646. {
  1647. char strBuf[STR_MAX+1] = { '\0' };
  1648. dispatcher(effGetProgramName, 0, 0, strBuf, 0.0f);
  1649. if (kData->prog.names[current] != nullptr)
  1650. delete[] kData->prog.names[current];
  1651. kData->prog.names[current] = carla_strdup(strBuf);
  1652. if (kData->prog.current != current)
  1653. {
  1654. kData->prog.current = current;
  1655. kData->engine->callback(CALLBACK_PROGRAM_CHANGED, fId, current, 0, 0.0f, nullptr);
  1656. }
  1657. }
  1658. }
  1659. kData->engine->callback(CALLBACK_UPDATE, fId, 0, 0, 0.0f, nullptr);
  1660. ret = 1;
  1661. break;
  1662. case audioMasterBeginEdit:
  1663. case audioMasterEndEdit:
  1664. // TODO
  1665. break;
  1666. case audioMasterOpenFileSelector:
  1667. case audioMasterCloseFileSelector:
  1668. // TODO
  1669. break;
  1670. #if ! VST_FORCE_DEPRECATED
  1671. case audioMasterEditFile:
  1672. // Deprecated in VST SDK 2.4
  1673. // TODO
  1674. break;
  1675. case audioMasterGetChunkFile:
  1676. // Deprecated in VST SDK 2.4
  1677. // TODO
  1678. break;
  1679. case audioMasterGetInputSpeakerArrangement:
  1680. // Deprecated in VST SDK 2.4
  1681. // TODO
  1682. break;
  1683. #endif
  1684. default:
  1685. carla_debug("VstPlugin::handleAudioMasterCallback(%02i:%s, %i, " P_INTPTR ", %p, %f)", opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1686. break;
  1687. }
  1688. return ret;
  1689. }
  1690. // -------------------------------------------------------------------
  1691. public:
  1692. bool init(const char* const filename, const char* const name)
  1693. {
  1694. CARLA_ASSERT(kData->engine != nullptr);
  1695. CARLA_ASSERT(kData->client == nullptr);
  1696. CARLA_ASSERT(filename != nullptr);
  1697. // ---------------------------------------------------------------
  1698. // first checks
  1699. if (kData->engine == nullptr)
  1700. {
  1701. return false;
  1702. }
  1703. if (kData->client != nullptr)
  1704. {
  1705. kData->engine->setLastError("Plugin client is already registered");
  1706. return false;
  1707. }
  1708. if (filename == nullptr)
  1709. {
  1710. kData->engine->setLastError("null filename");
  1711. return false;
  1712. }
  1713. // ---------------------------------------------------------------
  1714. // open DLL
  1715. if (! kData->libOpen(filename))
  1716. {
  1717. kData->engine->setLastError(kData->libError(filename));
  1718. return false;
  1719. }
  1720. // ---------------------------------------------------------------
  1721. // get DLL main entry
  1722. VST_Function vstFn = (VST_Function)kData->libSymbol("VSTPluginMain");
  1723. if (vstFn == nullptr)
  1724. {
  1725. vstFn = (VST_Function)kData->libSymbol("main");
  1726. if (vstFn == nullptr)
  1727. {
  1728. kData->engine->setLastError("Could not find the VST main entry in the plugin library");
  1729. return false;
  1730. }
  1731. }
  1732. // ---------------------------------------------------------------
  1733. // initialize plugin (part 1)
  1734. sLastVstPlugin = this;
  1735. fEffect = vstFn(carla_vst_audioMasterCallback);
  1736. sLastVstPlugin = nullptr;
  1737. if (fEffect == nullptr)
  1738. {
  1739. kData->engine->setLastError("Plugin failed to initialize");
  1740. return false;
  1741. }
  1742. if (fEffect->magic != kEffectMagic)
  1743. {
  1744. kData->engine->setLastError("Plugin is not valid (wrong vst effect magic code)");
  1745. return false;
  1746. }
  1747. #ifdef VESTIGE_HEADER
  1748. fEffect->ptr1 = this;
  1749. #else
  1750. fEffect->resvd1 = ToVstPtr<VstPlugin>(this);
  1751. #endif
  1752. dispatcher(effOpen, 0, 0, nullptr, 0.0f);
  1753. // ---------------------------------------------------------------
  1754. // get info
  1755. if (name != nullptr)
  1756. {
  1757. fName = kData->engine->getUniquePluginName(name);
  1758. }
  1759. else
  1760. {
  1761. char strBuf[STR_MAX+1] = { '\0' };
  1762. dispatcher(effGetEffectName, 0, 0, strBuf, 0.0f);
  1763. if (strBuf[0] != '\0')
  1764. {
  1765. fName = kData->engine->getUniquePluginName(strBuf);
  1766. }
  1767. else
  1768. {
  1769. const char* const label = std::strrchr(filename, OS_SEP)+1;
  1770. fName = kData->engine->getUniquePluginName(label);
  1771. }
  1772. }
  1773. fFilename = filename;
  1774. // ---------------------------------------------------------------
  1775. // register client
  1776. kData->client = kData->engine->addClient(this);
  1777. if (kData->client == nullptr || ! kData->client->isOk())
  1778. {
  1779. kData->engine->setLastError("Failed to register plugin client");
  1780. return false;
  1781. }
  1782. // ---------------------------------------------------------------
  1783. // initialize plugin (part 2)
  1784. #if ! VST_FORCE_DEPRECATED
  1785. dispatcher(effSetBlockSizeAndSampleRate, 0, kData->engine->getBufferSize(), nullptr, kData->engine->getSampleRate());
  1786. #endif
  1787. dispatcher(effSetSampleRate, 0, 0, nullptr, kData->engine->getSampleRate());
  1788. dispatcher(effSetBlockSize, 0, kData->engine->getBufferSize(), nullptr, 0.0f);
  1789. dispatcher(effSetProcessPrecision, 0, kVstProcessPrecision32, nullptr, 0.0f);
  1790. dispatcher(effStopProcess, 0, 0, nullptr, 0.0f);
  1791. dispatcher(effMainsChanged, 0, 0, nullptr, 0.0f);
  1792. if (dispatcher(effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  1793. fHints |= PLUGIN_USES_OLD_VSTSDK;
  1794. if (static_cast<uintptr_t>(dispatcher(effCanDo, 0, 0, (void*)"hasCockosExtensions", 0.0f)) == 0xbeef0000)
  1795. fHints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  1796. // ---------------------------------------------------------------
  1797. // gui stuff
  1798. if (fEffect->flags & effFlagsHasEditor)
  1799. {
  1800. const EngineOptions& engineOptions(kData->engine->getOptions());
  1801. #if defined(Q_WS_X11)
  1802. CarlaString uiBridgeBinary(engineOptions.bridge_vstX11);
  1803. #elif defined(CARLA_OS_MAC)
  1804. CarlaString uiBridgeBinary(engineOptions.bridge_vstCocoa);
  1805. #elif defined(CARLA_OS_WIN)
  1806. CarlaString uiBridgeBinary(engineOptions.bridge_vstHWND);
  1807. #else
  1808. CarlaString uiBridgeBinary;
  1809. #endif
  1810. if (engineOptions.preferUiBridges && uiBridgeBinary.isNotEmpty() && (fEffect->flags & effFlagsProgramChunks) == 0)
  1811. {
  1812. kData->osc.thread.setOscData(uiBridgeBinary, nullptr);
  1813. fGui.isOsc = true;
  1814. }
  1815. }
  1816. // ---------------------------------------------------------------
  1817. // load plugin settings
  1818. {
  1819. // set default options
  1820. fOptions = 0x0;
  1821. fOptions |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1822. if (fEffect->flags & effFlagsProgramChunks)
  1823. fOptions |= PLUGIN_OPTION_USE_CHUNKS;
  1824. if (vstPluginCanDo(fEffect, "receiveVstEvents") || vstPluginCanDo(fEffect, "receiveVstMidiEvent") || (fEffect->flags & effFlagsIsSynth) > 0 || (fHints & PLUGIN_WANTS_MIDI_INPUT))
  1825. {
  1826. fOptions |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1827. fOptions |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1828. fOptions |= PLUGIN_OPTION_SEND_PITCHBEND;
  1829. fOptions |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1830. }
  1831. // load settings
  1832. kData->idStr = "VST/";
  1833. kData->idStr += std::strrchr(filename, OS_SEP)+1;
  1834. kData->idStr += "/";
  1835. kData->idStr += CarlaString(uniqueId());
  1836. fOptions = kData->loadSettings(fOptions, availableOptions());
  1837. }
  1838. return true;
  1839. }
  1840. private:
  1841. int fUnique1;
  1842. AEffect* fEffect;
  1843. void* fLastChunk;
  1844. uint32_t fMidiEventCount;
  1845. VstMidiEvent fMidiEvents[MAX_MIDI_EVENTS*2];
  1846. VstTimeInfo_R fTimeInfo;
  1847. struct FixedVstEvents {
  1848. int32_t numEvents;
  1849. intptr_t reserved;
  1850. VstEvent* data[MAX_MIDI_EVENTS*2];
  1851. FixedVstEvents()
  1852. : numEvents(0),
  1853. reserved(0),
  1854. data{nullptr} {}
  1855. } fEvents;
  1856. struct GuiInfo {
  1857. bool isOsc;
  1858. bool isVisible;
  1859. GuiInfo()
  1860. : isOsc(false),
  1861. isVisible(false) {}
  1862. } fGui;
  1863. bool fIsProcessing;
  1864. bool fNeedIdle;
  1865. int fUnique2;
  1866. static VstPlugin* sLastVstPlugin;
  1867. // -------------------------------------------------------------------
  1868. static intptr_t carla_vst_hostCanDo(const char* const feature)
  1869. {
  1870. carla_debug("carla_vst_hostCanDo(\"%s\")", feature);
  1871. if (std::strcmp(feature, "supplyIdle") == 0)
  1872. return 1;
  1873. if (std::strcmp(feature, "sendVstEvents") == 0)
  1874. return 1;
  1875. if (std::strcmp(feature, "sendVstMidiEvent") == 0)
  1876. return 1;
  1877. if (std::strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  1878. return 1;
  1879. if (std::strcmp(feature, "sendVstTimeInfo") == 0)
  1880. return 1;
  1881. if (std::strcmp(feature, "receiveVstEvents") == 0)
  1882. return 1;
  1883. if (std::strcmp(feature, "receiveVstMidiEvent") == 0)
  1884. return 1;
  1885. if (std::strcmp(feature, "receiveVstTimeInfo") == 0)
  1886. return -1;
  1887. if (std::strcmp(feature, "reportConnectionChanges") == 0)
  1888. return -1;
  1889. if (std::strcmp(feature, "acceptIOChanges") == 0)
  1890. return 1;
  1891. if (std::strcmp(feature, "sizeWindow") == 0)
  1892. return 1;
  1893. if (std::strcmp(feature, "offline") == 0)
  1894. return -1;
  1895. if (std::strcmp(feature, "openFileSelector") == 0)
  1896. return -1;
  1897. if (std::strcmp(feature, "closeFileSelector") == 0)
  1898. return -1;
  1899. if (std::strcmp(feature, "startStopProcess") == 0)
  1900. return 1;
  1901. if (std::strcmp(feature, "supportShell") == 0)
  1902. return -1;
  1903. if (std::strcmp(feature, "shellCategory") == 0)
  1904. return -1;
  1905. // unimplemented
  1906. carla_stderr("carla_vst_hostCanDo(\"%s\") - unknown feature", feature);
  1907. return 0;
  1908. }
  1909. static intptr_t VSTCALLBACK carla_vst_audioMasterCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  1910. {
  1911. #if defined(DEBUG) && ! defined(CARLA_OS_WIN)
  1912. if (opcode != audioMasterGetTime && opcode != audioMasterProcessEvents && opcode != audioMasterGetCurrentProcessLevel && opcode != audioMasterGetOutputLatency)
  1913. carla_debug("carla_vst_audioMasterCallback(%p, %02i:%s, %i, " P_INTPTR ", %p, %f)", effect, opcode, vstMasterOpcode2str(opcode), index, value, ptr, opt);
  1914. #endif
  1915. switch (opcode)
  1916. {
  1917. case audioMasterVersion:
  1918. return kVstVersion;
  1919. case audioMasterGetVendorString:
  1920. CARLA_ASSERT(ptr != nullptr);
  1921. if (ptr != nullptr)
  1922. {
  1923. std::strcpy((char*)ptr, "falkTX");
  1924. return 1;
  1925. }
  1926. else
  1927. {
  1928. carla_stderr("carla_vst_audioMasterCallback() - audioMasterGetVendorString called with invalid pointer");
  1929. return 0;
  1930. }
  1931. case audioMasterGetProductString:
  1932. CARLA_ASSERT(ptr != nullptr);
  1933. if (ptr != nullptr)
  1934. {
  1935. std::strcpy((char*)ptr, "Carla");
  1936. return 1;
  1937. }
  1938. else
  1939. {
  1940. carla_stderr("carla_vst_audioMasterCallback() - audioMasterGetProductString called with invalid pointer");
  1941. return 0;
  1942. }
  1943. case audioMasterGetVendorVersion:
  1944. return 0x1000; // 1.0.0
  1945. case audioMasterCanDo:
  1946. CARLA_ASSERT(ptr != nullptr);
  1947. if (ptr != nullptr)
  1948. {
  1949. return carla_vst_hostCanDo((const char*)ptr);
  1950. }
  1951. else
  1952. {
  1953. carla_stderr("carla_vst_audioMasterCallback() - audioMasterCanDo called with invalid pointer");
  1954. return 0;
  1955. }
  1956. case audioMasterGetLanguage:
  1957. return kVstLangEnglish;
  1958. }
  1959. // Check if 'resvd1' points to us, otherwise register ourselfs if possible
  1960. VstPlugin* self = nullptr;
  1961. if (effect != nullptr)
  1962. {
  1963. #ifdef VESTIGE_HEADER
  1964. if (effect->ptr1 != nullptr)
  1965. {
  1966. self = (VstPlugin*)effect->ptr1;
  1967. #else
  1968. if (effect->resvd1 != 0)
  1969. {
  1970. self = FromVstPtr<VstPlugin>(effect->resvd1);
  1971. #endif
  1972. if (self->fUnique1 != self->fUnique2)
  1973. self = nullptr;
  1974. }
  1975. if (self != nullptr)
  1976. {
  1977. if (self->fEffect == nullptr)
  1978. self->fEffect = effect;
  1979. if (self->fEffect != effect)
  1980. {
  1981. carla_stderr2("carla_vst_audioMasterCallback() - host pointer mismatch: %p != %p", self->fEffect, effect);
  1982. self = nullptr;
  1983. }
  1984. }
  1985. else if (sLastVstPlugin != nullptr)
  1986. {
  1987. #ifdef VESTIGE_HEADER
  1988. effect->ptr1 = sLastVstPlugin;
  1989. #else
  1990. effect->resvd1 = ToVstPtr<VstPlugin>(sLastVstPlugin);
  1991. #endif
  1992. self = sLastVstPlugin;
  1993. }
  1994. }
  1995. return (self != nullptr) ? self->handleAudioMasterCallback(opcode, index, value, ptr, opt) : 0;
  1996. }
  1997. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(VstPlugin)
  1998. };
  1999. VstPlugin* VstPlugin::sLastVstPlugin = nullptr;
  2000. CARLA_BACKEND_END_NAMESPACE
  2001. #else // WANT_VST
  2002. # warning Building without VST support
  2003. #endif
  2004. CARLA_BACKEND_START_NAMESPACE
  2005. CarlaPlugin* CarlaPlugin::newVST(const Initializer& init)
  2006. {
  2007. carla_debug("CarlaPlugin::newVST({%p, \"%s\", \"%s\"})", init.engine, init.filename, init.name);
  2008. #ifdef WANT_VST
  2009. VstPlugin* const plugin(new VstPlugin(init.engine, init.id));
  2010. if (! plugin->init(init.filename, init.name))
  2011. {
  2012. delete plugin;
  2013. return nullptr;
  2014. }
  2015. plugin->reload();
  2016. if (init.engine->getProccessMode() == PROCESS_MODE_CONTINUOUS_RACK && ! CarlaPluginProtectedData::canRunInRack(plugin))
  2017. {
  2018. init.engine->setLastError("Carla's rack mode can only work with Stereo VST plugins, sorry!");
  2019. delete plugin;
  2020. return nullptr;
  2021. }
  2022. return plugin;
  2023. #else
  2024. init.engine->setLastError("VST support not available");
  2025. return nullptr;
  2026. #endif
  2027. }
  2028. CARLA_BACKEND_END_NAMESPACE