Collection of tools useful for audio production
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.

2115 lines
65KB

  1. /*
  2. * Carla Backend
  3. * Copyright (C) 2011-2012 Filipe Coelho <falktx@gmail.com>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * 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 COPYING file
  16. */
  17. #include "carla_plugin.h"
  18. #include "carla_vst.h"
  19. #ifndef __WINE__
  20. #include <QtGui/QDialog>
  21. #endif
  22. CARLA_BACKEND_START_NAMESPACE
  23. #if 0
  24. } /* adjust editor indent */
  25. #endif
  26. /*!
  27. * @defgroup CarlaBackendVstPlugin Carla Backend VST Plugin
  28. *
  29. * The Carla Backend VST Plugin.
  30. * @{
  31. */
  32. /*!
  33. * @defgroup PluginHints Plugin Hints
  34. * @{
  35. */
  36. const unsigned int PLUGIN_CAN_PROCESS_REPLACING = 0x100; //!< VST Plugin cas use processReplacing()
  37. const unsigned int PLUGIN_HAS_COCKOS_EXTENSIONS = 0x200; //!< VST Plugin has Cockos extensions
  38. const unsigned int PLUGIN_USES_OLD_VSTSDK = 0x400; //!< VST Plugin uses an old VST SDK
  39. const unsigned int PLUGIN_WANTS_MIDI_INPUT = 0x800; //!< VST Plugin wants MIDI input
  40. /**@}*/
  41. class VstPlugin : public CarlaPlugin
  42. {
  43. public:
  44. VstPlugin(CarlaEngine* const engine, const unsigned short id)
  45. : CarlaPlugin(engine, id)
  46. {
  47. qDebug("VstPlugin::VstPlugin()");
  48. m_type = PLUGIN_VST;
  49. effect = nullptr;
  50. events.numEvents = 0;
  51. events.reserved = 0;
  52. gui.type = GUI_NONE;
  53. gui.visible = false;
  54. gui.width = 0;
  55. gui.height = 0;
  56. memset(midiEvents, 0, sizeof(VstMidiEvent)*MAX_MIDI_EVENTS*2);
  57. for (unsigned short i=0; i < MAX_MIDI_EVENTS*2; i++)
  58. events.data[i] = (VstEvent*)&midiEvents[i];
  59. // make plugin valid
  60. srand(id);
  61. unique1 = unique2 = rand();
  62. }
  63. ~VstPlugin()
  64. {
  65. qDebug("VstPlugin::~VstPlugin()");
  66. // make plugin invalid
  67. unique2 += 1;
  68. if (effect)
  69. {
  70. // close UI
  71. if (m_hints & PLUGIN_HAS_GUI)
  72. {
  73. showGui(false);
  74. if (gui.type == GUI_EXTERNAL_OSC)
  75. {
  76. if (osc.thread)
  77. {
  78. // Wait a bit first, try safe quit, then force kill
  79. if (osc.thread->isRunning() && ! osc.thread->wait(carlaOptions.oscUiTimeout * 100))
  80. {
  81. qWarning("Failed to properly stop VST OSC GUI thread");
  82. osc.thread->terminate();
  83. }
  84. delete osc.thread;
  85. }
  86. }
  87. else
  88. effect->dispatcher(effect, effEditClose, 0, 0, nullptr, 0.0f);
  89. }
  90. if (m_activeBefore)
  91. {
  92. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  93. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  94. }
  95. effect->dispatcher(effect, effClose, 0, 0, nullptr, 0.0f);
  96. }
  97. }
  98. // -------------------------------------------------------------------
  99. // Information (base)
  100. PluginCategory category()
  101. {
  102. Q_ASSERT(effect);
  103. intptr_t category = effect->dispatcher(effect, effGetPlugCategory, 0, 0, nullptr, 0.0f);
  104. switch (category)
  105. {
  106. case kPlugCategSynth:
  107. return PLUGIN_CATEGORY_SYNTH;
  108. case kPlugCategAnalysis:
  109. return PLUGIN_CATEGORY_UTILITY;
  110. case kPlugCategMastering:
  111. return PLUGIN_CATEGORY_DYNAMICS;
  112. case kPlugCategRoomFx:
  113. return PLUGIN_CATEGORY_DELAY;
  114. case kPlugCategRestoration:
  115. return PLUGIN_CATEGORY_UTILITY;
  116. case kPlugCategGenerator:
  117. return PLUGIN_CATEGORY_SYNTH;
  118. }
  119. if (effect->flags & effFlagsIsSynth)
  120. return PLUGIN_CATEGORY_SYNTH;
  121. return getPluginCategoryFromName(m_name);
  122. }
  123. long uniqueId()
  124. {
  125. Q_ASSERT(effect);
  126. return effect->uniqueID;
  127. }
  128. // -------------------------------------------------------------------
  129. // Information (current data)
  130. int32_t chunkData(void** const dataPtr)
  131. {
  132. Q_ASSERT(dataPtr);
  133. Q_ASSERT(effect);
  134. if (effect)
  135. return effect->dispatcher(effect, effGetChunk, 0 /* bank */, 0, dataPtr, 0.0f);
  136. return 0;
  137. }
  138. // -------------------------------------------------------------------
  139. // Information (per-plugin data)
  140. double getParameterValue(const uint32_t parameterId)
  141. {
  142. Q_ASSERT(effect);
  143. Q_ASSERT(parameterId < param.count);
  144. if (effect)
  145. return effect->getParameter(effect, parameterId);
  146. return 0.0;
  147. }
  148. void getLabel(char* const strBuf)
  149. {
  150. Q_ASSERT(effect);
  151. if (effect)
  152. effect->dispatcher(effect, effGetProductString, 0, 0, strBuf, 0.0f);
  153. else
  154. CarlaPlugin::getLabel(strBuf);
  155. }
  156. void getMaker(char* const strBuf)
  157. {
  158. Q_ASSERT(effect);
  159. if (effect)
  160. effect->dispatcher(effect, effGetVendorString, 0, 0, strBuf, 0.0f);
  161. else
  162. CarlaPlugin::getMaker(strBuf);
  163. }
  164. void getCopyright(char* const strBuf)
  165. {
  166. Q_ASSERT(effect);
  167. if (effect)
  168. effect->dispatcher(effect, effGetVendorString, 0, 0, strBuf, 0.0f);
  169. else
  170. CarlaPlugin::getCopyright(strBuf);
  171. }
  172. void getRealName(char* const strBuf)
  173. {
  174. Q_ASSERT(effect);
  175. if (effect)
  176. effect->dispatcher(effect, effGetEffectName, 0, 0, strBuf, 0.0f);
  177. else
  178. CarlaPlugin::getRealName(strBuf);
  179. }
  180. void getParameterName(const uint32_t parameterId, char* const strBuf)
  181. {
  182. Q_ASSERT(effect);
  183. Q_ASSERT(parameterId < param.count);
  184. if (effect)
  185. effect->dispatcher(effect, effGetParamName, parameterId, 0, strBuf, 0.0f);
  186. else
  187. CarlaPlugin::getParameterName(parameterId, strBuf);
  188. }
  189. void getParameterText(const uint32_t parameterId, char* const strBuf)
  190. {
  191. Q_ASSERT(effect);
  192. Q_ASSERT(parameterId < param.count);
  193. if (effect)
  194. {
  195. effect->dispatcher(effect, effGetParamDisplay, parameterId, 0, strBuf, 0.0f);
  196. if (*strBuf == 0)
  197. sprintf(strBuf, "%f", getParameterValue(parameterId));
  198. }
  199. else
  200. CarlaPlugin::getParameterText(parameterId, strBuf);
  201. }
  202. void getParameterUnit(const uint32_t parameterId, char* const strBuf)
  203. {
  204. Q_ASSERT(effect);
  205. Q_ASSERT(parameterId < param.count);
  206. if (effect)
  207. effect->dispatcher(effect, effGetParamLabel, parameterId, 0, strBuf, 0.0f);
  208. else
  209. CarlaPlugin::getParameterUnit(parameterId, strBuf);
  210. }
  211. void getGuiInfo(GuiType* const type, bool* const resizable)
  212. {
  213. *type = gui.type;
  214. *resizable = false;
  215. }
  216. // -------------------------------------------------------------------
  217. // Set data (plugin-specific stuff)
  218. void setParameterValue(const uint32_t parameterId, double value, const bool sendGui, const bool sendOsc, const bool sendCallback)
  219. {
  220. Q_ASSERT(parameterId < param.count);
  221. effect->setParameter(effect, parameterId, fixParameterValue(value, param.ranges[parameterId]));
  222. CarlaPlugin::setParameterValue(parameterId, value, sendGui, sendOsc, sendCallback);
  223. }
  224. void setChunkData(const char* const stringData)
  225. {
  226. Q_ASSERT(m_hints & PLUGIN_USES_CHUNKS);
  227. Q_ASSERT(stringData);
  228. static QByteArray chunk;
  229. chunk = QByteArray::fromBase64(stringData);
  230. if (x_engine->isOffline())
  231. {
  232. const CarlaEngine::ScopedLocker m(x_engine);
  233. effect->dispatcher(effect, effSetChunk, 0 /* bank */, chunk.size(), chunk.data(), 0.0f);
  234. }
  235. else
  236. {
  237. const CarlaPlugin::ScopedDisabler m(this);
  238. effect->dispatcher(effect, effSetChunk, 0 /* bank */, chunk.size(), chunk.data(), 0.0f);
  239. }
  240. }
  241. void setProgram(int32_t index, const bool sendGui, const bool sendOsc, const bool sendCallback, const bool block)
  242. {
  243. Q_ASSERT(index >= -1 && index < (int32_t)prog.count);
  244. if (index < -1)
  245. index = -1;
  246. else if (index > (int32_t)prog.count)
  247. return;
  248. if (index >= 0)
  249. {
  250. if (x_engine->isOffline())
  251. {
  252. const CarlaEngine::ScopedLocker m(x_engine, block);
  253. effect->dispatcher(effect, effSetProgram, 0, index, nullptr, 0.0f);
  254. }
  255. else
  256. {
  257. const ScopedDisabler m(this, block);
  258. effect->dispatcher(effect, effSetProgram, 0, index, nullptr, 0.0f);
  259. }
  260. }
  261. CarlaPlugin::setProgram(index, sendGui, sendOsc, sendCallback, block);
  262. }
  263. // -------------------------------------------------------------------
  264. // Set gui stuff
  265. void setGuiData(const int data, const GuiDataHandle handle)
  266. {
  267. if (gui.type == GUI_EXTERNAL_OSC)
  268. return;
  269. #ifdef __WINE__
  270. if (effect->dispatcher(effect, effEditOpen, 0, data, handle, 0.0f) == 1)
  271. #else
  272. const QDialog* const dialog = handle;
  273. if (effect->dispatcher(effect, effEditOpen, 0, data, (void*)dialog->winId(), 0.0f) == 1)
  274. #endif
  275. {
  276. ERect* vstRect = nullptr;
  277. if (effect->dispatcher(effect, effEditGetRect, 0, 0, &vstRect, 0.0f) && vstRect)
  278. {
  279. int width = vstRect->right - vstRect->left;
  280. int height = vstRect->bottom - vstRect->top;
  281. if (width <= 0 || height <= 0)
  282. {
  283. qCritical("Failed to get proper Plugin Window size");
  284. return;
  285. }
  286. gui.width = width;
  287. gui.height = height;
  288. }
  289. else
  290. qCritical("Failed to get Plugin Window size");
  291. }
  292. else
  293. {
  294. // failed to open UI
  295. m_hints &= ~PLUGIN_HAS_GUI;
  296. x_engine->callback(CALLBACK_SHOW_GUI, m_id, -1, 0, 0.0);
  297. effect->dispatcher(effect, effEditClose, 0, 0, nullptr, 0.0f);
  298. }
  299. }
  300. void showGui(const bool yesNo)
  301. {
  302. if (gui.type == GUI_EXTERNAL_OSC)
  303. {
  304. Q_ASSERT(osc.thread);
  305. if (! osc.thread)
  306. {
  307. qCritical("VstPlugin::showGui(%s) - attempt to show gui, but it does not exist!", bool2str(yesNo));
  308. return;
  309. }
  310. if (yesNo)
  311. {
  312. osc.thread->start();
  313. }
  314. else
  315. {
  316. if (osc.data.target)
  317. {
  318. osc_send_hide(&osc.data);
  319. osc_send_quit(&osc.data);
  320. osc_clear_data(&osc.data);
  321. }
  322. if (! osc.thread->wait(500))
  323. osc.thread->quit();
  324. }
  325. }
  326. else
  327. {
  328. if (yesNo && gui.width > 0 && gui.height > 0)
  329. x_engine->callback(CALLBACK_RESIZE_GUI, m_id, gui.width, gui.height, 0.0);
  330. }
  331. gui.visible = yesNo;
  332. }
  333. void idleGui()
  334. {
  335. //effect->dispatcher(effect, effIdle, 0, 0, nullptr, 0.0f);
  336. // FIXME
  337. if (gui.type != GUI_EXTERNAL_OSC && gui.visible)
  338. effect->dispatcher(effect, effEditIdle, 0, 0, nullptr, 0.0f);
  339. CarlaPlugin::idleGui();
  340. }
  341. // -------------------------------------------------------------------
  342. // Plugin state
  343. void reload()
  344. {
  345. qDebug("VstPlugin::reload() - start");
  346. Q_ASSERT(effect);
  347. // Safely disable plugin for reload
  348. const ScopedDisabler m(this);
  349. if (x_client->isActive())
  350. x_client->deactivate();
  351. // Remove client ports
  352. removeClientPorts();
  353. // Delete old data
  354. deleteBuffers();
  355. uint32_t aIns, aOuts, mIns, mOuts, params, j;
  356. aIns = aOuts = mIns = mOuts = params = 0;
  357. aIns = effect->numInputs;
  358. aOuts = effect->numOutputs;
  359. params = effect->numParams;
  360. if (VstPluginCanDo(effect, "receiveVstEvents") || VstPluginCanDo(effect, "receiveVstMidiEvent") || (effect->flags & effFlagsIsSynth) > 0 || (m_hints & PLUGIN_WANTS_MIDI_INPUT))
  361. mIns = 1;
  362. if (VstPluginCanDo(effect, "sendVstEvents") || VstPluginCanDo(effect, "sendVstMidiEvent"))
  363. mOuts = 1;
  364. if (aIns > 0)
  365. {
  366. aIn.ports = new CarlaEngineAudioPort*[aIns];
  367. aIn.rindexes = new uint32_t[aIns];
  368. }
  369. if (aOuts > 0)
  370. {
  371. aOut.ports = new CarlaEngineAudioPort*[aOuts];
  372. aOut.rindexes = new uint32_t[aOuts];
  373. }
  374. if (params > 0)
  375. {
  376. param.data = new ParameterData[params];
  377. param.ranges = new ParameterRanges[params];
  378. }
  379. const int portNameSize = CarlaEngine::maxPortNameSize() - 1;
  380. char portName[portNameSize];
  381. bool needsCtrlIn = (aOuts > 0 || params > 0);
  382. for (j=0; j < aIns; j++)
  383. {
  384. #ifndef BUILD_BRIDGE
  385. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  386. sprintf(portName, "%s:input_%02i", m_name, j+1);
  387. else
  388. #endif
  389. sprintf(portName, "input_%02i", j+1);
  390. aIn.ports[j] = (CarlaEngineAudioPort*)x_client->addPort(CarlaEnginePortTypeAudio, portName, true);
  391. aIn.rindexes[j] = j;
  392. }
  393. for (j=0; j < aOuts; j++)
  394. {
  395. #ifndef BUILD_BRIDGE
  396. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  397. sprintf(portName, "%s:output_%02i", m_name, j+1);
  398. else
  399. #endif
  400. sprintf(portName, "output_%02i", j+1);
  401. aOut.ports[j] = (CarlaEngineAudioPort*)x_client->addPort(CarlaEnginePortTypeAudio, portName, false);
  402. aOut.rindexes[j] = j;
  403. }
  404. for (j=0; j<params; j++)
  405. {
  406. param.data[j].type = PARAMETER_INPUT;
  407. param.data[j].index = j;
  408. param.data[j].rindex = j;
  409. param.data[j].hints = 0;
  410. param.data[j].midiChannel = 0;
  411. param.data[j].midiCC = -1;
  412. double min, max, def, step, stepSmall, stepLarge;
  413. VstParameterProperties prop;
  414. prop.flags = 0;
  415. if (effect->dispatcher(effect, effGetParameterProperties, j, 0, &prop, 0))
  416. {
  417. double range[2] = { 0.0, 1.0 };
  418. if ((m_hints & PLUGIN_HAS_COCKOS_EXTENSIONS) > 0 && effect->dispatcher(effect, effVendorSpecific, 0xdeadbef0, j, range, 0.0) >= 0xbeef)
  419. {
  420. min = range[0];
  421. max = range[1];
  422. }
  423. else if (prop.flags & kVstParameterUsesIntegerMinMax)
  424. {
  425. min = prop.minInteger;
  426. max = prop.maxInteger;
  427. }
  428. else
  429. {
  430. min = 0.0;
  431. max = 1.0;
  432. }
  433. if (min > max)
  434. max = min;
  435. else if (max < min)
  436. min = max;
  437. if (max - min == 0.0)
  438. {
  439. qWarning("Broken plugin parameter: max - min == 0");
  440. max = min + 0.1;
  441. }
  442. if ((m_hints & PLUGIN_HAS_COCKOS_EXTENSIONS) > 0 && effect->dispatcher(effect, effVendorSpecific, kVstParameterUsesIntStep, j, nullptr, 0.0f) >= 0xbeef)
  443. {
  444. step = 1.0;
  445. stepSmall = 1.0;
  446. stepLarge = 10.0;
  447. }
  448. else if (prop.flags & kVstParameterIsSwitch)
  449. {
  450. step = max - min;
  451. stepSmall = step;
  452. stepLarge = step;
  453. param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  454. }
  455. else if (prop.flags & kVstParameterUsesIntStep)
  456. {
  457. step = prop.stepInteger;
  458. stepSmall = prop.stepInteger;
  459. stepLarge = prop.largeStepInteger;
  460. param.data[j].hints |= PARAMETER_IS_INTEGER;
  461. }
  462. else if (prop.flags & kVstParameterUsesFloatStep)
  463. {
  464. step = prop.stepFloat;
  465. stepSmall = prop.smallStepFloat;
  466. stepLarge = prop.largeStepFloat;
  467. }
  468. else
  469. {
  470. double range = max - min;
  471. step = range/100.0;
  472. stepSmall = range/1000.0;
  473. stepLarge = range/10.0;
  474. }
  475. if (prop.flags & kVstParameterCanRamp)
  476. param.data[j].hints |= PARAMETER_IS_LOGARITHMIC;
  477. }
  478. else
  479. {
  480. min = 0.0;
  481. max = 1.0;
  482. step = 0.001;
  483. stepSmall = 0.0001;
  484. stepLarge = 0.1;
  485. }
  486. // no such thing as VST default parameters
  487. def = effect->getParameter(effect, j);
  488. if (def < min)
  489. def = min;
  490. else if (def > max)
  491. def = max;
  492. param.ranges[j].min = min;
  493. param.ranges[j].max = max;
  494. param.ranges[j].def = def;
  495. param.ranges[j].step = step;
  496. param.ranges[j].stepSmall = stepSmall;
  497. param.ranges[j].stepLarge = stepLarge;
  498. param.data[j].hints |= PARAMETER_IS_ENABLED;
  499. #ifndef BUILD_BRIDGE
  500. param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  501. #endif
  502. if ((m_hints & PLUGIN_USES_OLD_VSTSDK) > 0 || effect->dispatcher(effect, effCanBeAutomated, j, 0, nullptr, 0.0f) == 1)
  503. param.data[j].hints |= PARAMETER_IS_AUTOMABLE;
  504. }
  505. if (needsCtrlIn)
  506. {
  507. #ifndef BUILD_BRIDGE
  508. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  509. {
  510. strcpy(portName, m_name);
  511. strcat(portName, ":control-in");
  512. }
  513. else
  514. #endif
  515. strcpy(portName, "control-in");
  516. param.portCin = (CarlaEngineControlPort*)x_client->addPort(CarlaEnginePortTypeControl, portName, true);
  517. }
  518. if (mIns == 1)
  519. {
  520. #ifndef BUILD_BRIDGE
  521. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  522. {
  523. strcpy(portName, m_name);
  524. strcat(portName, ":midi-in");
  525. }
  526. else
  527. #endif
  528. strcpy(portName, "midi-in");
  529. midi.portMin = (CarlaEngineMidiPort*)x_client->addPort(CarlaEnginePortTypeMIDI, portName, true);
  530. }
  531. if (mOuts == 1)
  532. {
  533. #ifndef BUILD_BRIDGE
  534. if (carlaOptions.processMode != PROCESS_MODE_MULTIPLE_CLIENTS)
  535. {
  536. strcpy(portName, m_name);
  537. strcat(portName, ":midi-out");
  538. }
  539. else
  540. #endif
  541. strcpy(portName, "midi-out");
  542. midi.portMout = (CarlaEngineMidiPort*)x_client->addPort(CarlaEnginePortTypeMIDI, portName, false);
  543. }
  544. aIn.count = aIns;
  545. aOut.count = aOuts;
  546. param.count = params;
  547. // plugin checks
  548. m_hints &= ~(PLUGIN_IS_SYNTH | PLUGIN_USES_CHUNKS | PLUGIN_CAN_DRYWET | PLUGIN_CAN_VOLUME | PLUGIN_CAN_BALANCE);
  549. intptr_t vstCategory = effect->dispatcher(effect, effGetPlugCategory, 0, 0, nullptr, 0.0f);
  550. if (vstCategory == kPlugCategSynth || vstCategory == kPlugCategGenerator)
  551. m_hints |= PLUGIN_IS_SYNTH;
  552. if (effect->flags & effFlagsProgramChunks)
  553. m_hints |= PLUGIN_USES_CHUNKS;
  554. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  555. m_hints |= PLUGIN_CAN_DRYWET;
  556. if (aOuts > 0)
  557. m_hints |= PLUGIN_CAN_VOLUME;
  558. if (aOuts >= 2 && aOuts%2 == 0)
  559. m_hints |= PLUGIN_CAN_BALANCE;
  560. reloadPrograms(true);
  561. x_client->activate();
  562. qDebug("VstPlugin::reload() - end");
  563. }
  564. void reloadPrograms(const bool init)
  565. {
  566. qDebug("VstPlugin::reloadPrograms(%s)", bool2str(init));
  567. uint32_t i, oldCount = prog.count;
  568. // Delete old programs
  569. if (prog.count > 0)
  570. {
  571. for (i=0; i < prog.count; i++)
  572. {
  573. if (prog.names[i])
  574. free((void*)prog.names[i]);
  575. }
  576. delete[] prog.names;
  577. }
  578. prog.count = 0;
  579. prog.names = nullptr;
  580. // Query new programs
  581. prog.count = effect->numPrograms;
  582. if (prog.count > 0)
  583. prog.names = new const char* [prog.count];
  584. // Update names
  585. for (i=0; i < prog.count; i++)
  586. {
  587. char strBuf[STR_MAX] = { 0 };
  588. if (effect->dispatcher(effect, effGetProgramNameIndexed, i, 0, strBuf, 0.0f) != 1)
  589. {
  590. // program will be [re-]changed later
  591. effect->dispatcher(effect, effSetProgram, 0, i, nullptr, 0.0f);
  592. effect->dispatcher(effect, effGetProgramName, 0, 0, strBuf, 0.0f);
  593. }
  594. prog.names[i] = strdup(strBuf);
  595. }
  596. #ifndef BUILD_BRIDGE
  597. // Update OSC Names
  598. x_engine->osc_send_set_program_count(m_id, prog.count);
  599. for (i=0; i < prog.count; i++)
  600. x_engine->osc_send_set_program_name(m_id, i, prog.names[i]);
  601. #endif
  602. if (init)
  603. {
  604. if (prog.count > 0)
  605. setProgram(0, false, false, false, true);
  606. }
  607. else
  608. {
  609. x_engine->callback(CALLBACK_RELOAD_PROGRAMS, m_id, 0, 0, 0.0);
  610. // Check if current program is invalid
  611. bool programChanged = false;
  612. if (prog.count == oldCount+1)
  613. {
  614. // one program added, probably created by user
  615. prog.current = oldCount;
  616. programChanged = true;
  617. }
  618. else if (prog.current >= (int32_t)prog.count)
  619. {
  620. // current program > count
  621. prog.current = 0;
  622. programChanged = true;
  623. }
  624. else if (prog.current < 0 && prog.count > 0)
  625. {
  626. // programs exist now, but not before
  627. prog.current = 0;
  628. programChanged = true;
  629. }
  630. else if (prog.current >= 0 && prog.count == 0)
  631. {
  632. // programs existed before, but not anymore
  633. prog.current = -1;
  634. programChanged = true;
  635. }
  636. if (programChanged)
  637. {
  638. setProgram(prog.current, true, true, true, true);
  639. }
  640. else
  641. {
  642. // Program was changed during update, re-set it
  643. if (prog.current >= 0)
  644. effect->dispatcher(effect, effSetProgram, 0, prog.current, nullptr, 0.0f);
  645. }
  646. }
  647. }
  648. // -------------------------------------------------------------------
  649. // Plugin processing
  650. void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const uint32_t framesOffset)
  651. {
  652. uint32_t i, k;
  653. uint32_t midiEventCount = 0;
  654. double aInsPeak[2] = { 0.0 };
  655. double aOutsPeak[2] = { 0.0 };
  656. // reset MIDI
  657. events.numEvents = 0;
  658. midiEvents[0].type = 0;
  659. CARLA_PROCESS_CONTINUE_CHECK;
  660. // --------------------------------------------------------------------------------------------------------
  661. // Input VU
  662. if (aIn.count > 0)
  663. {
  664. if (aIn.count == 1)
  665. {
  666. for (k=0; k < frames; k++)
  667. {
  668. if (abs(inBuffer[0][k]) > aInsPeak[0])
  669. aInsPeak[0] = abs(inBuffer[0][k]);
  670. }
  671. }
  672. else if (aIn.count > 1)
  673. {
  674. for (k=0; k < frames; k++)
  675. {
  676. if (abs(inBuffer[0][k]) > aInsPeak[0])
  677. aInsPeak[0] = abs(inBuffer[0][k]);
  678. if (abs(inBuffer[1][k]) > aInsPeak[1])
  679. aInsPeak[1] = abs(inBuffer[1][k]);
  680. }
  681. }
  682. }
  683. CARLA_PROCESS_CONTINUE_CHECK;
  684. // --------------------------------------------------------------------------------------------------------
  685. // Parameters Input [Automation]
  686. if (param.portCin && m_active && m_activeBefore)
  687. {
  688. bool allNotesOffSent = false;
  689. const CarlaEngineControlEvent* cinEvent;
  690. uint32_t time, nEvents = param.portCin->getEventCount();
  691. for (i=0; i < nEvents; i++)
  692. {
  693. cinEvent = param.portCin->getEvent(i);
  694. if (! cinEvent)
  695. continue;
  696. time = cinEvent->time - framesOffset;
  697. if (time >= frames)
  698. continue;
  699. // Control change
  700. switch (cinEvent->type)
  701. {
  702. case CarlaEngineEventNull:
  703. break;
  704. case CarlaEngineEventControlChange:
  705. {
  706. double value;
  707. // Control backend stuff
  708. if (cinEvent->channel == m_ctrlInChannel)
  709. {
  710. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(cinEvent->controller) && (m_hints & PLUGIN_CAN_DRYWET) > 0)
  711. {
  712. value = cinEvent->value;
  713. setDryWet(value, false, false);
  714. postponeEvent(PluginPostEventParameterChange, PARAMETER_DRYWET, 0, value);
  715. continue;
  716. }
  717. if (MIDI_IS_CONTROL_CHANNEL_VOLUME(cinEvent->controller) && (m_hints & PLUGIN_CAN_VOLUME) > 0)
  718. {
  719. value = cinEvent->value*127/100;
  720. setVolume(value, false, false);
  721. postponeEvent(PluginPostEventParameterChange, PARAMETER_VOLUME, 0, value);
  722. continue;
  723. }
  724. if (MIDI_IS_CONTROL_BALANCE(cinEvent->controller) && (m_hints & PLUGIN_CAN_BALANCE) > 0)
  725. {
  726. double left, right;
  727. value = cinEvent->value/0.5 - 1.0;
  728. if (value < 0.0)
  729. {
  730. left = -1.0;
  731. right = (value*2)+1.0;
  732. }
  733. else if (value > 0.0)
  734. {
  735. left = (value*2)-1.0;
  736. right = 1.0;
  737. }
  738. else
  739. {
  740. left = -1.0;
  741. right = 1.0;
  742. }
  743. setBalanceLeft(left, false, false);
  744. setBalanceRight(right, false, false);
  745. postponeEvent(PluginPostEventParameterChange, PARAMETER_BALANCE_LEFT, 0, left);
  746. postponeEvent(PluginPostEventParameterChange, PARAMETER_BALANCE_RIGHT, 0, right);
  747. continue;
  748. }
  749. }
  750. // Control plugin parameters
  751. for (k=0; k < param.count; k++)
  752. {
  753. if (param.data[k].midiChannel != cinEvent->channel)
  754. continue;
  755. if (param.data[k].midiCC != cinEvent->controller)
  756. continue;
  757. if (param.data[k].type != PARAMETER_INPUT)
  758. continue;
  759. if (param.data[k].hints & PARAMETER_IS_AUTOMABLE)
  760. {
  761. if (param.data[k].hints & PARAMETER_IS_BOOLEAN)
  762. {
  763. value = cinEvent->value < 0.5 ? param.ranges[k].min : param.ranges[k].max;
  764. }
  765. else
  766. {
  767. value = cinEvent->value * (param.ranges[k].max - param.ranges[k].min) + param.ranges[k].min;
  768. if (param.data[k].hints & PARAMETER_IS_INTEGER)
  769. value = rint(value);
  770. }
  771. setParameterValue(k, value, false, false, false);
  772. postponeEvent(PluginPostEventParameterChange, k, 0, value);
  773. }
  774. }
  775. break;
  776. }
  777. case CarlaEngineEventMidiBankChange:
  778. break;
  779. case CarlaEngineEventMidiProgramChange:
  780. if (cinEvent->channel == m_ctrlInChannel)
  781. {
  782. uint32_t progId = rint(cinEvent->value);
  783. if (progId < prog.count)
  784. {
  785. setProgram(progId, false, false, false, false);
  786. postponeEvent(PluginPostEventMidiProgramChange, progId, 0, 0.0);
  787. }
  788. }
  789. break;
  790. case CarlaEngineEventAllSoundOff:
  791. if (cinEvent->channel == m_ctrlInChannel)
  792. {
  793. if (midi.portMin && ! allNotesOffSent)
  794. sendMidiAllNotesOff();
  795. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  796. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  797. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  798. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  799. allNotesOffSent = true;
  800. }
  801. break;
  802. case CarlaEngineEventAllNotesOff:
  803. if (cinEvent->channel == m_ctrlInChannel)
  804. {
  805. if (midi.portMin && ! allNotesOffSent)
  806. sendMidiAllNotesOff();
  807. allNotesOffSent = true;
  808. }
  809. break;
  810. }
  811. }
  812. } // End of Parameters Input
  813. CARLA_PROCESS_CONTINUE_CHECK;
  814. // --------------------------------------------------------------------------------------------------------
  815. // MIDI Input
  816. if (midi.portMin && m_active && m_activeBefore)
  817. {
  818. // ----------------------------------------------------------------------------------------------------
  819. // MIDI Input (External)
  820. if (m_ctrlInChannel >= 0 && m_ctrlInChannel < 16)
  821. {
  822. engineMidiLock();
  823. for (i=0; i < MAX_MIDI_EVENTS && midiEventCount < MAX_MIDI_EVENTS; i++)
  824. {
  825. if (extMidiNotes[i].channel < 0)
  826. break;
  827. VstMidiEvent* const midiEvent = &midiEvents[midiEventCount];
  828. memset(midiEvent, 0, sizeof(VstMidiEvent));
  829. midiEvent->type = kVstMidiType;
  830. midiEvent->byteSize = sizeof(VstMidiEvent);
  831. midiEvent->midiData[0] = m_ctrlInChannel + extMidiNotes[i].velo ? MIDI_STATUS_NOTE_ON : MIDI_STATUS_NOTE_OFF;
  832. midiEvent->midiData[1] = extMidiNotes[i].note;
  833. midiEvent->midiData[2] = extMidiNotes[i].velo;
  834. extMidiNotes[i].channel = -1; // mark as invalid
  835. midiEventCount += 1;
  836. }
  837. engineMidiUnlock();
  838. } // End of MIDI Input (External)
  839. CARLA_PROCESS_CONTINUE_CHECK;
  840. // ----------------------------------------------------------------------------------------------------
  841. // MIDI Input (System)
  842. {
  843. const CarlaEngineMidiEvent* minEvent;
  844. uint32_t time, nEvents = midi.portMin->getEventCount();
  845. for (i=0; i < nEvents && midiEventCount < MAX_MIDI_EVENTS; i++)
  846. {
  847. minEvent = midi.portMin->getEvent(i);
  848. if (! minEvent)
  849. continue;
  850. time = minEvent->time - framesOffset;
  851. if (time >= frames)
  852. continue;
  853. uint8_t status = minEvent->data[0];
  854. uint8_t channel = status & 0x0F;
  855. // Fix bad note-off
  856. if (MIDI_IS_STATUS_NOTE_ON(status) && minEvent->data[2] == 0)
  857. status -= 0x10;
  858. VstMidiEvent* const midiEvent = &midiEvents[midiEventCount];
  859. memset(midiEvent, 0, sizeof(VstMidiEvent));
  860. midiEvent->type = kVstMidiType;
  861. midiEvent->byteSize = sizeof(VstMidiEvent);
  862. midiEvent->deltaFrames = minEvent->time;
  863. if (MIDI_IS_STATUS_NOTE_OFF(status))
  864. {
  865. uint8_t note = minEvent->data[1];
  866. midiEvent->midiData[0] = status;
  867. midiEvent->midiData[1] = note;
  868. postponeEvent(PluginPostEventNoteOff, channel, note, 0.0);
  869. }
  870. else if (MIDI_IS_STATUS_NOTE_ON(status))
  871. {
  872. uint8_t note = minEvent->data[1];
  873. uint8_t velo = minEvent->data[2];
  874. midiEvent->midiData[0] = status;
  875. midiEvent->midiData[1] = note;
  876. midiEvent->midiData[2] = velo;
  877. postponeEvent(PluginPostEventNoteOn, channel, note, velo);
  878. }
  879. else if (MIDI_IS_STATUS_POLYPHONIC_AFTERTOUCH(status))
  880. {
  881. uint8_t note = minEvent->data[1];
  882. uint8_t pressure = minEvent->data[2];
  883. midiEvent->midiData[0] = status;
  884. midiEvent->midiData[1] = note;
  885. midiEvent->midiData[2] = pressure;
  886. }
  887. else if (MIDI_IS_STATUS_AFTERTOUCH(status))
  888. {
  889. uint8_t pressure = minEvent->data[1];
  890. midiEvent->midiData[0] = status;
  891. midiEvent->midiData[1] = pressure;
  892. }
  893. else if (MIDI_IS_STATUS_PITCH_WHEEL_CONTROL(status))
  894. {
  895. uint8_t lsb = minEvent->data[1];
  896. uint8_t msb = minEvent->data[2];
  897. midiEvent->midiData[0] = status;
  898. midiEvent->midiData[1] = lsb;
  899. midiEvent->midiData[2] = msb;
  900. }
  901. else
  902. continue;
  903. midiEventCount += 1;
  904. }
  905. } // End of MIDI Input (System)
  906. } // End of MIDI Input
  907. CARLA_PROCESS_CONTINUE_CHECK;
  908. // --------------------------------------------------------------------------------------------------------
  909. // Plugin processing
  910. if (m_active)
  911. {
  912. if (! m_activeBefore)
  913. {
  914. if (midi.portMin && m_ctrlInChannel >= 0 && m_ctrlInChannel < 16)
  915. {
  916. memset(&midiEvents[0], 0, sizeof(VstMidiEvent));
  917. midiEvents[0].type = kVstMidiType;
  918. midiEvents[0].byteSize = sizeof(VstMidiEvent);
  919. midiEvents[0].midiData[0] = MIDI_STATUS_CONTROL_CHANGE + m_ctrlInChannel;
  920. midiEvents[0].midiData[1] = MIDI_CONTROL_ALL_SOUND_OFF;
  921. memset(&midiEvents[1], 0, sizeof(VstMidiEvent));
  922. midiEvents[1].type = kVstMidiType;
  923. midiEvents[1].byteSize = sizeof(VstMidiEvent);
  924. midiEvents[1].midiData[0] = MIDI_STATUS_CONTROL_CHANGE + m_ctrlInChannel;
  925. midiEvents[1].midiData[1] = MIDI_CONTROL_ALL_NOTES_OFF;
  926. midiEventCount = 2;
  927. }
  928. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  929. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  930. }
  931. if (midiEventCount > 0)
  932. {
  933. events.numEvents = midiEventCount;
  934. events.reserved = 0;
  935. effect->dispatcher(effect, effProcessEvents, 0, 0, &events, 0.0f);
  936. }
  937. // FIXME - make this a global option
  938. // don't process if not needed
  939. //if ((effect->flags & effFlagsNoSoundInStop) > 0 && aInsPeak[0] == 0.0 && aInsPeak[1] == 0.0 && midiEventCount == 0 && ! midi.port_mout)
  940. //{
  941. if (m_hints & PLUGIN_CAN_PROCESS_REPLACING)
  942. {
  943. effect->processReplacing(effect, inBuffer, outBuffer, frames);
  944. }
  945. else
  946. {
  947. for (i=0; i < aOut.count; i++)
  948. memset(outBuffer[i], 0, sizeof(float)*frames);
  949. #if ! VST_FORCE_DEPRECATED
  950. effect->process(effect, inBuffer, outBuffer, frames);
  951. #endif
  952. }
  953. //}
  954. }
  955. else
  956. {
  957. if (m_activeBefore)
  958. {
  959. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  960. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  961. }
  962. }
  963. CARLA_PROCESS_CONTINUE_CHECK;
  964. // --------------------------------------------------------------------------------------------------------
  965. // Post-processing (dry/wet, volume and balance)
  966. if (m_active)
  967. {
  968. bool do_drywet = (m_hints & PLUGIN_CAN_DRYWET) > 0 && x_dryWet != 1.0;
  969. bool do_volume = (m_hints & PLUGIN_CAN_VOLUME) > 0 && x_volume != 1.0;
  970. bool do_balance = (m_hints & PLUGIN_CAN_BALANCE) > 0 && (x_balanceLeft != -1.0 || x_balanceRight != 1.0);
  971. double bal_rangeL, bal_rangeR;
  972. float oldBufLeft[do_balance ? frames : 0];
  973. for (i=0; i < aOut.count; i++)
  974. {
  975. // Dry/Wet
  976. if (do_drywet)
  977. {
  978. for (k=0; k < frames; k++)
  979. {
  980. if (aOut.count == 1)
  981. outBuffer[i][k] = (outBuffer[i][k]*x_dryWet)+(inBuffer[0][k]*(1.0-x_dryWet));
  982. else
  983. outBuffer[i][k] = (outBuffer[i][k]*x_dryWet)+(inBuffer[i][k]*(1.0-x_dryWet));
  984. }
  985. }
  986. // Balance
  987. if (do_balance)
  988. {
  989. if (i%2 == 0)
  990. memcpy(&oldBufLeft, outBuffer[i], sizeof(float)*frames);
  991. bal_rangeL = (x_balanceLeft+1.0)/2;
  992. bal_rangeR = (x_balanceRight+1.0)/2;
  993. for (k=0; k < frames; k++)
  994. {
  995. if (i%2 == 0)
  996. {
  997. // left output
  998. outBuffer[i][k] = oldBufLeft[k]*(1.0-bal_rangeL);
  999. outBuffer[i][k] += outBuffer[i+1][k]*(1.0-bal_rangeR);
  1000. }
  1001. else
  1002. {
  1003. // right
  1004. outBuffer[i][k] = outBuffer[i][k]*bal_rangeR;
  1005. outBuffer[i][k] += oldBufLeft[k]*bal_rangeL;
  1006. }
  1007. }
  1008. }
  1009. // Volume
  1010. if (do_volume)
  1011. {
  1012. for (k=0; k < frames; k++)
  1013. outBuffer[i][k] *= x_volume;
  1014. }
  1015. // Output VU
  1016. for (k=0; i < 2 && k < frames; k++)
  1017. {
  1018. if (abs(outBuffer[i][k]) > aOutsPeak[i])
  1019. aOutsPeak[i] = abs(outBuffer[i][k]);
  1020. }
  1021. }
  1022. }
  1023. else
  1024. {
  1025. // disable any output sound if not active
  1026. for (i=0; i < aOut.count; i++)
  1027. memset(outBuffer[i], 0.0f, sizeof(float)*frames);
  1028. aOutsPeak[0] = 0.0;
  1029. aOutsPeak[1] = 0.0;
  1030. } // End of Post-processing
  1031. CARLA_PROCESS_CONTINUE_CHECK;
  1032. // --------------------------------------------------------------------------------------------------------
  1033. // MIDI Output
  1034. if (midi.portMout && m_active)
  1035. {
  1036. uint8_t data[4] = { 0 };
  1037. for (int32_t i = midiEventCount; i < events.numEvents; i++)
  1038. {
  1039. data[0] = midiEvents[i].midiData[0];
  1040. data[1] = midiEvents[i].midiData[1];
  1041. data[2] = midiEvents[i].midiData[2];
  1042. // Fix bad note-off
  1043. if (MIDI_IS_STATUS_NOTE_ON(data[0]) && data[2] == 0)
  1044. data[0] -= 0x10;
  1045. midi.portMout->writeEvent(midiEvents[i].deltaFrames, data, 3);
  1046. }
  1047. } // End of MIDI Output
  1048. CARLA_PROCESS_CONTINUE_CHECK;
  1049. // --------------------------------------------------------------------------------------------------------
  1050. // Peak Values
  1051. x_engine->setInputPeak(m_id, 0, aInsPeak[0]);
  1052. x_engine->setInputPeak(m_id, 1, aInsPeak[1]);
  1053. x_engine->setOutputPeak(m_id, 0, aOutsPeak[0]);
  1054. x_engine->setOutputPeak(m_id, 1, aOutsPeak[1]);
  1055. m_activeBefore = m_active;
  1056. }
  1057. void bufferSizeChanged(uint32_t newBufferSize)
  1058. {
  1059. if (m_active)
  1060. {
  1061. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  1062. effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  1063. }
  1064. #if ! VST_FORCE_DEPRECATED
  1065. effect->dispatcher(effect, effSetBlockSizeAndSampleRate, 0, newBufferSize, nullptr, x_engine->getSampleRate());
  1066. #endif
  1067. effect->dispatcher(effect, effSetBlockSize, 0, newBufferSize, nullptr, 0.0f);
  1068. if (m_active)
  1069. {
  1070. effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1071. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  1072. }
  1073. }
  1074. // -------------------------------------------------------------------
  1075. // Post-poned events
  1076. void uiParameterChange(const uint32_t index, const double value)
  1077. {
  1078. Q_ASSERT(index < param.count);
  1079. if (index >= param.count)
  1080. return;
  1081. if (gui.type == GUI_EXTERNAL_OSC && osc.data.target)
  1082. osc_send_control(&osc.data, param.data[index].rindex, value);
  1083. }
  1084. void uiProgramChange(const uint32_t index)
  1085. {
  1086. Q_ASSERT(index < prog.count);
  1087. if (index >= prog.count)
  1088. return;
  1089. if (gui.type == GUI_EXTERNAL_OSC && osc.data.target)
  1090. osc_send_program(&osc.data, index);
  1091. }
  1092. void uiNoteOn(const uint8_t channel, const uint8_t note, const uint8_t velo)
  1093. {
  1094. Q_ASSERT(channel < 16);
  1095. Q_ASSERT(note < 128);
  1096. Q_ASSERT(velo < 128);
  1097. if (gui.type == GUI_EXTERNAL_OSC && osc.data.target)
  1098. {
  1099. uint8_t midiData[4] = { 0 };
  1100. midiData[1] = MIDI_STATUS_NOTE_ON + channel;
  1101. midiData[2] = note;
  1102. midiData[3] = velo;
  1103. osc_send_midi(&osc.data, midiData);
  1104. }
  1105. }
  1106. void uiNoteOff(const uint8_t channel, const uint8_t note)
  1107. {
  1108. Q_ASSERT(channel < 16);
  1109. Q_ASSERT(note < 128);
  1110. if (gui.type == GUI_EXTERNAL_OSC && osc.data.target)
  1111. {
  1112. uint8_t midiData[4] = { 0 };
  1113. midiData[1] = MIDI_STATUS_NOTE_OFF + channel;
  1114. midiData[2] = note;
  1115. osc_send_midi(&osc.data, midiData);
  1116. }
  1117. }
  1118. // -------------------------------------------------------------------
  1119. void handleAudioMasterAutomate(const uint32_t index, const double value)
  1120. {
  1121. //Q_ASSERT(m_enabled);
  1122. Q_ASSERT(index < param.count);
  1123. if (index >= param.count /*|| ! m_enabled*/)
  1124. return;
  1125. if (x_engine->isOnAudioThread() && ! x_engine->isOffline())
  1126. {
  1127. setParameterValue(index, value, false, false, false);
  1128. postponeEvent(PluginPostEventParameterChange, index, 0, value);
  1129. }
  1130. else
  1131. setParameterValue(index, value, true, true, true);
  1132. }
  1133. intptr_t handleAudioMasterGetCurrentProcessLevel()
  1134. {
  1135. if (x_engine->isOffline())
  1136. return kVstProcessLevelOffline;
  1137. if (x_engine->isOnAudioThread())
  1138. return kVstProcessLevelRealtime;
  1139. return kVstProcessLevelUser;
  1140. }
  1141. intptr_t handleAudioMasterGetBlockSize()
  1142. {
  1143. return x_engine->getBufferSize();
  1144. }
  1145. intptr_t handleAudioMasterGetSampleRate()
  1146. {
  1147. return x_engine->getSampleRate();
  1148. }
  1149. const VstTimeInfo_R* handleAudioMasterGetTime()
  1150. {
  1151. static VstTimeInfo_R vstTimeInfo;
  1152. memset(&vstTimeInfo, 0, sizeof(VstTimeInfo_R));
  1153. const CarlaTimeInfo* const timeInfo = x_engine->getTimeInfo();
  1154. vstTimeInfo.flags |= kVstTransportChanged;
  1155. if (timeInfo->playing)
  1156. vstTimeInfo.flags |= kVstTransportPlaying;
  1157. vstTimeInfo.samplePos = timeInfo->frame;
  1158. vstTimeInfo.sampleRate = x_engine->getSampleRate();
  1159. vstTimeInfo.nanoSeconds = timeInfo->time;
  1160. vstTimeInfo.flags |= kVstNanosValid;
  1161. if (timeInfo->valid & CarlaEngineTimeBBT)
  1162. {
  1163. double ppqBar = double(timeInfo->bbt.bar) * timeInfo->bbt.beats_per_bar - timeInfo->bbt.beats_per_bar;
  1164. double ppqBeat = double(timeInfo->bbt.beat) - 1.0;
  1165. double ppqTick = double(timeInfo->bbt.tick) / timeInfo->bbt.ticks_per_beat;
  1166. // Bars
  1167. vstTimeInfo.barStartPos = ppqBar + ppqBeat;
  1168. vstTimeInfo.flags |= kVstBarsValid;
  1169. // PPQ Pos
  1170. vstTimeInfo.ppqPos = ppqBar + ppqBeat + ppqTick;
  1171. vstTimeInfo.flags |= kVstPpqPosValid;
  1172. // Tempo
  1173. vstTimeInfo.tempo = timeInfo->bbt.beats_per_minute;
  1174. vstTimeInfo.flags |= kVstTempoValid;
  1175. // Time Signature
  1176. vstTimeInfo.timeSigNumerator = timeInfo->bbt.beats_per_bar;
  1177. vstTimeInfo.timeSigDenominator = timeInfo->bbt.beat_type;
  1178. vstTimeInfo.flags |= kVstTimeSigValid;
  1179. }
  1180. return &vstTimeInfo;
  1181. }
  1182. intptr_t handleAudioMasterIOChanged()
  1183. {
  1184. Q_ASSERT(m_enabled);
  1185. // TESTING
  1186. qWarning("audioMasterIOChanged called!");
  1187. if (! m_enabled)
  1188. return 1;
  1189. //carla_proc_lock();
  1190. //self->m_enabled = false;
  1191. //carla_proc_unlock();
  1192. //if (self->m_active)
  1193. //{
  1194. // self->effect->dispatcher(self->effect, effStopProcess, 0, 0, nullptr, 0.0f);
  1195. // self->effect->dispatcher(self->effect, effMainsChanged, 0, 0, nullptr, 0.0f);
  1196. //}
  1197. //self->reload();
  1198. //if (self->m_active)
  1199. //{
  1200. // self->effect->dispatcher(self->effect, effMainsChanged, 0, 1, nullptr, 0.0f);
  1201. // self->effect->dispatcher(self->effect, effStartProcess, 0, 0, nullptr, 0.0f);
  1202. //}
  1203. //callback_action(CALLBACK_RELOAD_ALL, self->m_id, 0, 0, 0.0);
  1204. return 0; // FIXME - set as 1 when supported
  1205. }
  1206. intptr_t handleAudioMasterProcessEvents(const VstEvents* const vstEvents)
  1207. {
  1208. Q_ASSERT(m_enabled);
  1209. if (! m_enabled)
  1210. return 0;
  1211. if (! midi.portMout)
  1212. return 0;
  1213. if (! x_engine->isOnAudioThread())
  1214. {
  1215. qCritical("VstPlugin:handleAudioMasterProcessEvents(%p) - received MIDI out events outside audio thread, ignoring", vstEvents);
  1216. return 0;
  1217. }
  1218. for (int32_t i=0; i < vstEvents->numEvents && events.numEvents < MAX_MIDI_EVENTS*2; i++)
  1219. {
  1220. if (! vstEvents->events[i])
  1221. break;
  1222. const VstMidiEvent* const vstMidiEvent = (const VstMidiEvent*)vstEvents->events[i];
  1223. if (vstMidiEvent->type != kVstMidiType)
  1224. memcpy(&midiEvents[events.numEvents++], vstMidiEvent, sizeof(VstMidiEvent));
  1225. }
  1226. return 1;
  1227. }
  1228. intptr_t handleAudioMasterTempoAt()
  1229. {
  1230. const CarlaTimeInfo* const timeInfo = x_engine->getTimeInfo();
  1231. if (timeInfo->valid & CarlaEngineTimeBBT)
  1232. return timeInfo->bbt.beats_per_minute * 10000;
  1233. return 0;
  1234. }
  1235. intptr_t handleAdioMasterSizeWindow(int32_t width, int32_t height)
  1236. {
  1237. gui.width = width;
  1238. gui.height = height;
  1239. x_engine->callback(CALLBACK_RESIZE_GUI, m_id, width, height, 0.0);
  1240. return 1;
  1241. }
  1242. void handleAudioMasterUpdateDisplay()
  1243. {
  1244. // Update current program name
  1245. if (prog.count > 0 && prog.current >= 0)
  1246. {
  1247. const int32_t index = prog.current;
  1248. char strBuf[STR_MAX] = { 0 };
  1249. effect->dispatcher(effect, effGetProgramName, 0, 0, strBuf, 0.0f);
  1250. if (! prog.names[index])
  1251. {
  1252. prog.names[index] = strdup(strBuf);
  1253. }
  1254. else if (strBuf[0] != 0 && strcmp(strBuf, prog.names[index]) != 0)
  1255. {
  1256. free((void*)prog.names[index]);
  1257. prog.names[index] = strdup(strBuf);
  1258. }
  1259. }
  1260. // Tell backend to update
  1261. x_engine->callback(CALLBACK_UPDATE, m_id, 0, 0, 0.0);
  1262. }
  1263. void handleAudioMasterWantMidi()
  1264. {
  1265. m_hints |= PLUGIN_WANTS_MIDI_INPUT;
  1266. }
  1267. static intptr_t handleAudioMasterCanDo(const char* const feature)
  1268. {
  1269. qDebug("VstPlugin::handleAudioMasterCanDo(\"%s\")", feature);
  1270. if (strcmp(feature, "supplyIdle") == 0)
  1271. return 1;
  1272. if (strcmp(feature, "sendVstEvents") == 0)
  1273. return 1;
  1274. if (strcmp(feature, "sendVstMidiEvent") == 0)
  1275. return 1;
  1276. if (strcmp(feature, "sendVstMidiEventFlagIsRealtime") == 0)
  1277. return -1;
  1278. if (strcmp(feature, "sendVstTimeInfo") == 0)
  1279. return 1;
  1280. if (strcmp(feature, "receiveVstEvents") == 0)
  1281. return 1;
  1282. if (strcmp(feature, "receiveVstMidiEvent") == 0)
  1283. return 1;
  1284. if (strcmp(feature, "receiveVstTimeInfo") == 0)
  1285. return -1;
  1286. if (strcmp(feature, "reportConnectionChanges") == 0)
  1287. return -1;
  1288. if (strcmp(feature, "acceptIOChanges") == 0)
  1289. return 1;
  1290. if (strcmp(feature, "sizeWindow") == 0)
  1291. return 1;
  1292. if (strcmp(feature, "offline") == 0)
  1293. return -1;
  1294. if (strcmp(feature, "openFileSelector") == 0)
  1295. return -1;
  1296. if (strcmp(feature, "closeFileSelector") == 0)
  1297. return -1;
  1298. if (strcmp(feature, "startStopProcess") == 0)
  1299. return 1;
  1300. if (strcmp(feature, "supportShell") == 0)
  1301. return -1;
  1302. if (strcmp(feature, "shellCategory") == 0)
  1303. return -1;
  1304. // unimplemented
  1305. qWarning("VstPlugin::handleAudioMasterCanDo(\"%s\") - unknown feature", feature);
  1306. return 0;
  1307. }
  1308. // -------------------------------------------------------------------
  1309. static intptr_t VstHostCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  1310. {
  1311. #ifdef DEBUG
  1312. qDebug("VstHostCallback(%p, opcode: %s, index: %i, value: " P_INTPTR ", opt: %f", effect, VstMasterOpcode2str(opcode), index, value, opt);
  1313. #endif
  1314. // Cockos VST extensions
  1315. if (/*effect &&*/ ptr && (uint32_t)opcode == 0xdeadbeef && (uint32_t)index == 0xdeadf00d)
  1316. {
  1317. const char* const func = (char*)ptr;
  1318. if (strcmp(func, "GetPlayPosition") == 0)
  1319. return 0;
  1320. if (strcmp(func, "GetPlayPosition2") == 0)
  1321. return 0;
  1322. if (strcmp(func, "GetCursorPosition") == 0)
  1323. return 0;
  1324. if (strcmp(func, "GetPlayState") == 0)
  1325. return 0;
  1326. if (strcmp(func, "SetEditCurPos") == 0)
  1327. return 0;
  1328. if (strcmp(func, "GetSetRepeat") == 0)
  1329. return 0;
  1330. if (strcmp(func, "GetProjectPath") == 0)
  1331. return 0;
  1332. if (strcmp(func, "OnPlayButton") == 0)
  1333. return 0;
  1334. if (strcmp(func, "OnStopButton") == 0)
  1335. return 0;
  1336. if (strcmp(func, "OnPauseButton") == 0)
  1337. return 0;
  1338. if (strcmp(func, "IsInRealTimeAudio") == 0)
  1339. return 0;
  1340. if (strcmp(func, "Audio_IsRunning") == 0)
  1341. return 0;
  1342. }
  1343. // Check if 'resvd1' points to this plugin
  1344. VstPlugin* self = nullptr;
  1345. #ifdef VESTIGE_HEADER
  1346. if (effect && effect->ptr1)
  1347. {
  1348. self = (VstPlugin*)effect->ptr1;
  1349. #else
  1350. if (effect && effect->resvd1)
  1351. {
  1352. self = (VstPlugin*)getPointer(effect->resvd1);
  1353. #endif
  1354. if (self->unique1 != self->unique2)
  1355. self = nullptr;
  1356. }
  1357. intptr_t ret = 0;
  1358. switch (opcode)
  1359. {
  1360. case audioMasterAutomate:
  1361. if (self)
  1362. self->handleAudioMasterAutomate(index, opt);
  1363. break;
  1364. case audioMasterVersion:
  1365. ret = kVstVersion;
  1366. break;
  1367. case audioMasterCurrentId:
  1368. // TODO
  1369. break;
  1370. case audioMasterIdle:
  1371. //if (effect)
  1372. // effect->dispatcher(effect, effEditIdle, 0, 0, nullptr, 0.0f);
  1373. break;
  1374. #if ! VST_FORCE_DEPRECATED
  1375. case audioMasterPinConnected:
  1376. // Deprecated in VST SDK 2.4
  1377. // TODO
  1378. break;
  1379. case audioMasterWantMidi:
  1380. // Deprecated in VST SDK 2.4
  1381. if (self)
  1382. self->handleAudioMasterWantMidi();
  1383. break;
  1384. #endif
  1385. case audioMasterGetTime:
  1386. if (self)
  1387. ret = (intptr_t)self->handleAudioMasterGetTime();
  1388. break;
  1389. case audioMasterProcessEvents:
  1390. if (self && ptr)
  1391. ret = self->handleAudioMasterProcessEvents((const VstEvents*)ptr);
  1392. break;
  1393. #if ! VST_FORCE_DEPRECATED
  1394. case audioMasterSetTime:
  1395. // Deprecated in VST SDK 2.4
  1396. break;
  1397. case audioMasterTempoAt:
  1398. // Deprecated in VST SDK 2.4
  1399. if (self)
  1400. ret = self->handleAudioMasterTempoAt();
  1401. if (ret == 0)
  1402. ret = 120 * 10000;
  1403. break;
  1404. case audioMasterGetNumAutomatableParameters:
  1405. // Deprecated in VST SDK 2.4
  1406. #ifdef BUILD_BRIDGE
  1407. ret = MAX_PARAMETERS;
  1408. #else
  1409. ret = carlaOptions.maxParameters;
  1410. #endif
  1411. break;
  1412. case audioMasterGetParameterQuantization:
  1413. // Deprecated in VST SDK 2.4
  1414. // TODO
  1415. break;
  1416. #endif
  1417. case audioMasterIOChanged:
  1418. if (self)
  1419. ret = self->handleAudioMasterIOChanged();
  1420. break;
  1421. case audioMasterNeedIdle:
  1422. // Deprecated in VST SDK 2.4
  1423. // TODO
  1424. break;
  1425. case audioMasterSizeWindow:
  1426. if (self && index > 0 && value > 0)
  1427. ret = self->handleAdioMasterSizeWindow(index, value);
  1428. break;
  1429. case audioMasterGetSampleRate:
  1430. if (self)
  1431. ret = self->handleAudioMasterGetSampleRate();
  1432. break;
  1433. case audioMasterGetBlockSize:
  1434. if (self)
  1435. ret = self->handleAudioMasterGetBlockSize();
  1436. break;
  1437. case audioMasterGetInputLatency:
  1438. // TODO
  1439. break;
  1440. case audioMasterGetOutputLatency:
  1441. // TODO
  1442. break;
  1443. #if ! VST_FORCE_DEPRECATED
  1444. case audioMasterGetPreviousPlug:
  1445. // Deprecated in VST SDK 2.4
  1446. // TODO
  1447. break;
  1448. case audioMasterGetNextPlug:
  1449. // Deprecated in VST SDK 2.4
  1450. // TODO
  1451. break;
  1452. case audioMasterWillReplaceOrAccumulate:
  1453. // Deprecated in VST SDK 2.4
  1454. break;
  1455. #endif
  1456. case audioMasterGetCurrentProcessLevel:
  1457. if (self)
  1458. ret = self->handleAudioMasterGetCurrentProcessLevel();
  1459. else
  1460. ret = kVstProcessLevelUnknown;
  1461. break;
  1462. case audioMasterGetAutomationState:
  1463. ret = kVstAutomationReadWrite;
  1464. break;
  1465. case audioMasterOfflineStart:
  1466. case audioMasterOfflineRead:
  1467. case audioMasterOfflineWrite:
  1468. case audioMasterOfflineGetCurrentPass:
  1469. case audioMasterOfflineGetCurrentMetaPass:
  1470. // TODO
  1471. break;
  1472. #if ! VST_FORCE_DEPRECATED
  1473. case audioMasterSetOutputSampleRate:
  1474. // Deprecated in VST SDK 2.4
  1475. break;
  1476. #ifdef VESTIGE_HEADER
  1477. case audioMasterGetSpeakerArrangement:
  1478. #else
  1479. case audioMasterGetOutputSpeakerArrangement:
  1480. #endif
  1481. // Deprecated in VST SDK 2.4
  1482. // TODO
  1483. break;
  1484. #endif
  1485. case audioMasterGetVendorString:
  1486. if (ptr)
  1487. strcpy((char*)ptr, "falkTX");
  1488. break;
  1489. case audioMasterGetProductString:
  1490. if (ptr)
  1491. strcpy((char*)ptr, "Carla");
  1492. break;
  1493. case audioMasterGetVendorVersion:
  1494. ret = 0x05; // 0.5
  1495. break;
  1496. case audioMasterVendorSpecific:
  1497. // TODO - cockos extensions
  1498. break;
  1499. #if ! VST_FORCE_DEPRECATED
  1500. case audioMasterSetIcon:
  1501. // Deprecated in VST SDK 2.4
  1502. break;
  1503. #endif
  1504. case audioMasterCanDo:
  1505. if (ptr)
  1506. ret = handleAudioMasterCanDo((const char*)ptr);
  1507. break;
  1508. case audioMasterGetLanguage:
  1509. ret = kVstLangEnglish;
  1510. break;
  1511. #if ! VST_FORCE_DEPRECATED
  1512. case audioMasterOpenWindow:
  1513. case audioMasterCloseWindow:
  1514. // Deprecated in VST SDK 2.4
  1515. // TODO
  1516. break;
  1517. #endif
  1518. case audioMasterGetDirectory:
  1519. // TODO
  1520. break;
  1521. case audioMasterUpdateDisplay:
  1522. if (self)
  1523. self->handleAudioMasterUpdateDisplay();
  1524. break;
  1525. case audioMasterBeginEdit:
  1526. case audioMasterEndEdit:
  1527. // TODO
  1528. break;
  1529. case audioMasterOpenFileSelector:
  1530. case audioMasterCloseFileSelector:
  1531. // TODO
  1532. break;
  1533. #if ! VST_FORCE_DEPRECATED
  1534. case audioMasterEditFile:
  1535. // Deprecated in VST SDK 2.4
  1536. // TODO
  1537. break;
  1538. case audioMasterGetChunkFile:
  1539. // Deprecated in VST SDK 2.4
  1540. // TODO
  1541. break;
  1542. case audioMasterGetInputSpeakerArrangement:
  1543. // Deprecated in VST SDK 2.4
  1544. // TODO
  1545. break;
  1546. #endif
  1547. default:
  1548. #ifdef DEBUG
  1549. qDebug("VstHostCallback(%p, opcode: %s, index: %i, value: " P_INTPTR ", opt: %f", effect, VstMasterOpcode2str(opcode), index, value, opt);
  1550. #endif
  1551. break;
  1552. }
  1553. return ret;
  1554. }
  1555. // -------------------------------------------------------------------
  1556. bool init(const char* const filename, const char* const name, const char* const label)
  1557. {
  1558. // ---------------------------------------------------------------
  1559. // open DLL
  1560. if (! libOpen(filename))
  1561. {
  1562. setLastError(libError(filename));
  1563. return false;
  1564. }
  1565. // ---------------------------------------------------------------
  1566. // get DLL main entry
  1567. VST_Function vstFn = (VST_Function)libSymbol("VSTPluginMain");
  1568. if (! vstFn)
  1569. {
  1570. vstFn = (VST_Function)libSymbol("main");
  1571. if (! vstFn)
  1572. {
  1573. setLastError("Could not find the VST main entry in the plugin library");
  1574. return false;
  1575. }
  1576. }
  1577. // ---------------------------------------------------------------
  1578. // initialize plugin
  1579. effect = vstFn(VstHostCallback);
  1580. if ((! effect) || effect->magic != kEffectMagic)
  1581. {
  1582. setLastError("Plugin failed to initialize");
  1583. return false;
  1584. }
  1585. // ---------------------------------------------------------------
  1586. // get info
  1587. m_filename = strdup(filename);
  1588. if (name)
  1589. {
  1590. m_name = x_engine->getUniqueName(name);
  1591. }
  1592. else
  1593. {
  1594. char strBuf[STR_MAX] = { 0 };
  1595. effect->dispatcher(effect, effGetEffectName, 0, 0, strBuf, 0.0f);
  1596. if (strBuf[0] != 0)
  1597. m_name = x_engine->getUniqueName(strBuf);
  1598. else
  1599. m_name = x_engine->getUniqueName(label);
  1600. }
  1601. // ---------------------------------------------------------------
  1602. // initialize VST stuff
  1603. effect->dispatcher(effect, effOpen, 0, 0, nullptr, 0.0f);
  1604. #if ! VST_FORCE_DEPRECATED
  1605. effect->dispatcher(effect, effSetBlockSizeAndSampleRate, 0, x_engine->getBufferSize(), nullptr, x_engine->getSampleRate());
  1606. #endif
  1607. effect->dispatcher(effect, effSetSampleRate, 0, 0, nullptr, x_engine->getSampleRate());
  1608. effect->dispatcher(effect, effSetBlockSize, 0, x_engine->getBufferSize(), nullptr, 0.0f);
  1609. effect->dispatcher(effect, effSetProcessPrecision, 0, kVstProcessPrecision32, nullptr, 0.0f);
  1610. #ifdef VESTIGE_HEADER
  1611. effect->ptr1 = this;
  1612. #else
  1613. effect->resvd1 = (intptr_t)this;
  1614. #endif
  1615. #if ! VST_FORCE_DEPRECATED
  1616. // dummy pre-start to catch possible wantEvents() call on old plugins
  1617. effect->dispatcher(effect, effStartProcess, 0, 0, nullptr, 0.0f);
  1618. effect->dispatcher(effect, effStopProcess, 0, 0, nullptr, 0.0f);
  1619. #endif
  1620. // special checks
  1621. if (effect->dispatcher(effect, effCanDo, 0, 0, (void*)"hasCockosExtensions", 0.0f) == 0xbeef0000)
  1622. m_hints |= PLUGIN_HAS_COCKOS_EXTENSIONS;
  1623. if (effect->dispatcher(effect, effGetVstVersion, 0, 0, nullptr, 0.0f) < kVstVersion)
  1624. m_hints |= PLUGIN_USES_OLD_VSTSDK;
  1625. if ((effect->flags & effFlagsCanReplacing) > 0 && effect->processReplacing != effect->process)
  1626. m_hints |= PLUGIN_CAN_PROCESS_REPLACING;
  1627. // ---------------------------------------------------------------
  1628. // register client
  1629. x_client = x_engine->addClient(this);
  1630. if (! x_client->isOk())
  1631. {
  1632. setLastError("Failed to register plugin client");
  1633. return false;
  1634. }
  1635. // ---------------------------------------------------------------
  1636. // gui stuff
  1637. if (effect->flags & effFlagsHasEditor)
  1638. {
  1639. m_hints |= PLUGIN_HAS_GUI;
  1640. #ifdef Q_OS_LINUX
  1641. if (carlaOptions.bridge_vstx11 && carlaOptions.preferUiBridges && ! (effect->flags & effFlagsProgramChunks))
  1642. {
  1643. osc.thread = new CarlaPluginThread(x_engine, this, CarlaPluginThread::PLUGIN_THREAD_VST_GUI);
  1644. osc.thread->setOscData(carlaOptions.bridge_vstx11, label);
  1645. gui.type = GUI_EXTERNAL_OSC;
  1646. }
  1647. else
  1648. #endif
  1649. {
  1650. #if defined(Q_OS_WIN)
  1651. gui.type = GUI_INTERNAL_HWND;
  1652. #elif defined(Q_OS_MACOS)
  1653. gui.type = GUI_INTERNAL_COCOA;
  1654. #elif defined(Q_OS_LINUX)
  1655. gui.type = GUI_INTERNAL_X11;
  1656. #else
  1657. m_hints &= ~PLUGIN_HAS_GUI;
  1658. #endif
  1659. }
  1660. }
  1661. return true;
  1662. }
  1663. private:
  1664. int unique1;
  1665. AEffect* effect;
  1666. struct {
  1667. int32_t numEvents;
  1668. intptr_t reserved;
  1669. VstEvent* data[MAX_MIDI_EVENTS*2];
  1670. } events;
  1671. VstMidiEvent midiEvents[MAX_MIDI_EVENTS*2];
  1672. struct {
  1673. GuiType type;
  1674. bool visible;
  1675. int width;
  1676. int height;
  1677. } gui;
  1678. int unique2;
  1679. };
  1680. CarlaPlugin* CarlaPlugin::newVST(const initializer& init)
  1681. {
  1682. qDebug("CarlaPlugin::newVST(%p, \"%s\", \"%s\", \"%s\")", init.engine, init.filename, init.name, init.label);
  1683. short id = init.engine->getNewPluginId();
  1684. if (id < 0 || id > MAX_PLUGINS)
  1685. {
  1686. setLastError("Maximum number of plugins reached");
  1687. return nullptr;
  1688. }
  1689. VstPlugin* const plugin = new VstPlugin(init.engine, id);
  1690. if (! plugin->init(init.filename, init.name, init.label))
  1691. {
  1692. delete plugin;
  1693. return nullptr;
  1694. }
  1695. plugin->reload();
  1696. #ifndef BUILD_BRIDGE
  1697. if (carlaOptions.processMode == PROCESS_MODE_CONTINUOUS_RACK)
  1698. {
  1699. const uint32_t ins = plugin->audioInCount();
  1700. const uint32_t outs = plugin->audioOutCount();
  1701. const bool stereoInput = ins == 0 || ins == 2;
  1702. const bool stereoOutput = outs == 0 || outs == 2;
  1703. if (! (stereoInput || stereoOutput))
  1704. {
  1705. setLastError("Carla's rack mode can only work with Stereo VST plugins, sorry!");
  1706. delete plugin;
  1707. return nullptr;
  1708. }
  1709. }
  1710. #endif
  1711. plugin->registerToOsc();
  1712. return plugin;
  1713. }
  1714. /**@}*/
  1715. CARLA_BACKEND_END_NAMESPACE