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.

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