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.

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