Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2137 lines
74KB

  1. /*
  2. * Carla VST3 Plugin
  3. * Copyright (C) 2014-2022 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #include "CarlaPluginInternal.hpp"
  18. #include "CarlaEngine.hpp"
  19. #include "AppConfig.h"
  20. #if defined(USING_JUCE) && JUCE_PLUGINHOST_VST3
  21. # define USE_JUCE_FOR_VST3
  22. #endif
  23. #include "CarlaBackendUtils.hpp"
  24. #include "CarlaVst3Utils.hpp"
  25. #include "CarlaPluginUI.hpp"
  26. #include "water/files/File.h"
  27. CARLA_BACKEND_START_NAMESPACE
  28. // --------------------------------------------------------------------------------------------------------------------
  29. static inline
  30. size_t strlen_utf16(const int16_t* const str)
  31. {
  32. size_t i = 0;
  33. while (str[i] != 0)
  34. ++i;
  35. return i;
  36. }
  37. // --------------------------------------------------------------------------------------------------------------------
  38. static inline
  39. void strncpy_utf8(char* const dst, const int16_t* const src, const size_t length)
  40. {
  41. CARLA_SAFE_ASSERT_RETURN(length > 0,);
  42. if (const size_t len = std::min(strlen_utf16(src), length-1U))
  43. {
  44. for (size_t i=0; i<len; ++i)
  45. {
  46. // skip non-ascii chars, unsupported
  47. if (src[i] >= 0x80)
  48. continue;
  49. dst[i] = src[i];
  50. }
  51. dst[len] = 0;
  52. }
  53. else
  54. {
  55. dst[0] = 0;
  56. }
  57. }
  58. // --------------------------------------------------------------------------------------------------------------------
  59. static uint32_t V3_API v3_ref_static(void*) { return 1; }
  60. static uint32_t V3_API v3_unref_static(void*) { return 0; }
  61. struct carla_v3_host_application : v3_host_application_cpp {
  62. carla_v3_host_application()
  63. {
  64. query_interface = carla_query_interface;
  65. ref = v3_ref_static;
  66. unref = v3_unref_static;
  67. app.get_name = carla_get_name;
  68. app.create_instance = carla_create_instance;
  69. }
  70. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  71. {
  72. if (v3_tuid_match(iid, v3_funknown_iid) ||
  73. v3_tuid_match(iid, v3_host_application_iid))
  74. {
  75. *iface = self;
  76. return V3_OK;
  77. }
  78. *iface = nullptr;
  79. return V3_NO_INTERFACE;
  80. }
  81. static v3_result V3_API carla_get_name(void*, v3_str_128 name)
  82. {
  83. static const char hostname[] = "Carla-Discovery\0";
  84. for (size_t i=0; i<sizeof(hostname); ++i)
  85. name[i] = hostname[i];
  86. return V3_OK;
  87. }
  88. // TODO
  89. static v3_result V3_API carla_create_instance(void*, v3_tuid, v3_tuid, void**) { return V3_NOT_IMPLEMENTED; }
  90. };
  91. struct carla_v3_plugin_frame : v3_plugin_frame_cpp {
  92. };
  93. // --------------------------------------------------------------------------------------------------------------------
  94. struct carla_v3_param_changes : v3_param_changes_cpp {
  95. carla_v3_param_changes()
  96. {
  97. query_interface = carla_query_interface;
  98. ref = v3_ref_static;
  99. unref = v3_unref_static;
  100. changes.get_param_count = carla_get_param_count;
  101. changes.get_param_data = carla_get_param_data;
  102. changes.add_param_data = carla_add_param_data;
  103. }
  104. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  105. {
  106. if (v3_tuid_match(iid, v3_funknown_iid) ||
  107. v3_tuid_match(iid, v3_param_changes_iid))
  108. {
  109. *iface = self;
  110. return V3_OK;
  111. }
  112. *iface = nullptr;
  113. return V3_NO_INTERFACE;
  114. }
  115. static int32_t V3_API carla_get_param_count(void*) { return 0; }
  116. static v3_param_value_queue** V3_API carla_get_param_data(void*, int32_t) { return nullptr; }
  117. static v3_param_value_queue** V3_API carla_add_param_data(void*, v3_param_id*, int32_t*) { return nullptr; }
  118. };
  119. struct carla_v3_event_list : v3_event_list_cpp {
  120. carla_v3_event_list()
  121. {
  122. query_interface = carla_query_interface;
  123. ref = v3_ref_static;
  124. unref = v3_unref_static;
  125. list.get_event_count = carla_get_event_count;
  126. list.get_event = carla_get_event;
  127. list.add_event = carla_add_event;
  128. }
  129. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  130. {
  131. if (v3_tuid_match(iid, v3_funknown_iid) ||
  132. v3_tuid_match(iid, v3_event_list_iid))
  133. {
  134. *iface = self;
  135. return V3_OK;
  136. }
  137. *iface = nullptr;
  138. return V3_NO_INTERFACE;
  139. }
  140. static uint32_t V3_API carla_get_event_count(void*) { return 0; }
  141. static v3_result V3_API carla_get_event(void*, int32_t, v3_event*) { return V3_NOT_IMPLEMENTED; }
  142. static v3_result V3_API carla_add_event(void*, v3_event*) { return V3_NOT_IMPLEMENTED; }
  143. };
  144. // --------------------------------------------------------------------------------------------------------------------
  145. class CarlaPluginVST3 : public CarlaPlugin,
  146. private CarlaPluginUI::Callback
  147. {
  148. public:
  149. CarlaPluginVST3(CarlaEngine* const engine, const uint id)
  150. : CarlaPlugin(engine, id),
  151. fFirstActive(true),
  152. fAudioOutBuffers(nullptr),
  153. fLastTimeInfo(),
  154. fV3TimeContext(),
  155. fV3Application(new carla_v3_host_application),
  156. fV3ClassInfo(),
  157. fV3(),
  158. fUI()
  159. {
  160. carla_debug("CarlaPluginVST3::CarlaPluginVST3(%p, %i)", engine, id);
  161. carla_zeroStruct(fV3TimeContext);
  162. }
  163. ~CarlaPluginVST3() override
  164. {
  165. carla_debug("CarlaPluginVST3::~CarlaPluginVST3()");
  166. // close UI
  167. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  168. {
  169. if (! fUI.isEmbed)
  170. showCustomUI(false);
  171. if (fUI.isAttached)
  172. {
  173. fUI.isAttached = false;
  174. v3_cpp_obj(fV3.view)->removed(fV3.view);
  175. }
  176. }
  177. if (fV3.view != nullptr)
  178. {
  179. v3_cpp_obj_unref(fV3.view);
  180. fV3.view = nullptr;
  181. }
  182. pData->singleMutex.lock();
  183. pData->masterMutex.lock();
  184. if (pData->client != nullptr && pData->client->isActive())
  185. pData->client->deactivate(true);
  186. if (pData->active)
  187. {
  188. deactivate();
  189. pData->active = false;
  190. }
  191. clearBuffers();
  192. fV3.exit();
  193. }
  194. // -------------------------------------------------------------------
  195. // Information (base)
  196. PluginType getType() const noexcept override
  197. {
  198. return PLUGIN_VST3;
  199. }
  200. PluginCategory getCategory() const noexcept override
  201. {
  202. return getPluginCategoryFromV3SubCategories(fV3ClassInfo.v2.sub_categories);
  203. }
  204. // -------------------------------------------------------------------
  205. // Information (count)
  206. // nothing
  207. // -------------------------------------------------------------------
  208. // Information (per-plugin data)
  209. uint getOptionsAvailable() const noexcept override
  210. {
  211. uint options = 0x0;
  212. // can't disable fixed buffers if using latency
  213. if (pData->latency.frames == 0)
  214. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  215. /*
  216. if (numPrograms > 1)
  217. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  218. */
  219. options |= PLUGIN_OPTION_USE_CHUNKS;
  220. /*
  221. if (hasMidiInput())
  222. {
  223. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  224. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  225. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  226. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  227. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  228. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  229. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  230. }
  231. */
  232. return options;
  233. }
  234. float getParameterValue(const uint32_t parameterId) const noexcept override
  235. {
  236. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, 0.0f);
  237. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  238. const double normalized = v3_cpp_obj(fV3.controller)->get_parameter_normalised(fV3.controller, parameterId);
  239. return v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, parameterId, normalized);
  240. }
  241. bool getLabel(char* const strBuf) const noexcept override
  242. {
  243. std::strncpy(strBuf, fV3ClassInfo.v1.name, STR_MAX);
  244. return true;
  245. }
  246. bool getMaker(char* const strBuf) const noexcept override
  247. {
  248. std::strncpy(strBuf, fV3ClassInfo.v2.vendor, STR_MAX);
  249. return true;
  250. }
  251. bool getCopyright(char* const strBuf) const noexcept override
  252. {
  253. return getMaker(strBuf);
  254. }
  255. bool getRealName(char* const strBuf) const noexcept override
  256. {
  257. std::strncpy(strBuf, fV3ClassInfo.v1.name, STR_MAX);
  258. return true;
  259. }
  260. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  261. {
  262. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, 0.0f);
  263. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  264. v3_param_info paramInfo = {};
  265. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller, parameterId, &paramInfo) == V3_OK, false);
  266. strncpy_utf8(strBuf, paramInfo.title, STR_MAX);
  267. return true;
  268. }
  269. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  270. {
  271. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, false);
  272. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  273. const double normalized = v3_cpp_obj(fV3.controller)->get_parameter_normalised(fV3.controller, parameterId);
  274. v3_str_128 paramText;
  275. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_string_for_value(fV3.controller, parameterId, normalized, paramText) == V3_OK, false);
  276. if (paramText[0] != '\0')
  277. strncpy_utf8(strBuf, paramText, STR_MAX);
  278. else
  279. std::snprintf(strBuf, STR_MAX, "%.12g",
  280. v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, parameterId, normalized));
  281. return true;
  282. }
  283. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  284. {
  285. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, false);
  286. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  287. v3_param_info paramInfo = {};
  288. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller, parameterId, &paramInfo) == V3_OK, false);
  289. strncpy_utf8(strBuf, paramInfo.units, STR_MAX);
  290. return true;
  291. }
  292. // -------------------------------------------------------------------
  293. // Set data (state)
  294. // nothing
  295. // -------------------------------------------------------------------
  296. // Set data (internal stuff)
  297. // -------------------------------------------------------------------
  298. // Set data (plugin-specific stuff)
  299. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  300. {
  301. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  302. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  303. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  304. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller, parameterId, fixedValue);
  305. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, parameterId, normalized);
  306. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  307. }
  308. void setParameterValueRT(const uint32_t parameterId, const float value, const bool sendCallbackLater) noexcept override
  309. {
  310. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  311. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  312. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  313. // TODO append value to V3 changes queue list
  314. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, sendCallbackLater);
  315. }
  316. // -------------------------------------------------------------------
  317. // Set ui stuff
  318. void setCustomUITitle(const char* const title) noexcept override
  319. {
  320. if (fUI.window != nullptr)
  321. {
  322. try {
  323. fUI.window->setTitle(title);
  324. } CARLA_SAFE_EXCEPTION("set custom ui title");
  325. }
  326. CarlaPlugin::setCustomUITitle(title);
  327. }
  328. void showCustomUI(const bool yesNo) override
  329. {
  330. if (fUI.isVisible == yesNo)
  331. return;
  332. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr,);
  333. if (yesNo)
  334. {
  335. CarlaString uiTitle;
  336. if (pData->uiTitle.isNotEmpty())
  337. {
  338. uiTitle = pData->uiTitle;
  339. }
  340. else
  341. {
  342. uiTitle = pData->name;
  343. uiTitle += " (GUI)";
  344. }
  345. if (fUI.window == nullptr)
  346. {
  347. const char* msg = nullptr;
  348. const EngineOptions& opts(pData->engine->getOptions());
  349. #if defined(CARLA_OS_MAC)
  350. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, opts.pluginsAreStandalone, false);
  351. #elif defined(CARLA_OS_WIN)
  352. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, opts.pluginsAreStandalone, false);
  353. #elif defined(HAVE_X11)
  354. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, opts.pluginsAreStandalone, false, false);
  355. #else
  356. msg = "Unsupported UI type";
  357. #endif
  358. if (fUI.window == nullptr)
  359. return pData->engine->callback(true, true,
  360. ENGINE_CALLBACK_UI_STATE_CHANGED,
  361. pData->id,
  362. -1,
  363. 0, 0, 0.0f,
  364. msg);
  365. fUI.window->setTitle(uiTitle.buffer());
  366. #ifndef CARLA_OS_MAC
  367. // TODO inform plugin of what UI scale we use
  368. #endif
  369. if (v3_cpp_obj(fV3.view)->attached(fV3.view, fUI.window->getPtr(), V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_OK)
  370. {
  371. v3_view_rect rect = {};
  372. if (v3_cpp_obj(fV3.view)->get_size(fV3.view, 0) == V3_OK)
  373. {
  374. const int32_t width = rect.right - rect.left;
  375. const int32_t height = rect.bottom - rect.top;
  376. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  377. if (width > 1 && height > 1)
  378. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true);
  379. }
  380. }
  381. else
  382. {
  383. delete fUI.window;
  384. fUI.window = nullptr;
  385. carla_stderr2("Plugin refused to open its own UI");
  386. return pData->engine->callback(true, true,
  387. ENGINE_CALLBACK_UI_STATE_CHANGED,
  388. pData->id,
  389. -1,
  390. 0, 0, 0.0f,
  391. "Plugin refused to open its own UI");
  392. }
  393. }
  394. fUI.window->show();
  395. fUI.isVisible = true;
  396. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  397. }
  398. else
  399. {
  400. fUI.isVisible = false;
  401. pData->hints &= ~PLUGIN_NEEDS_UI_MAIN_THREAD;
  402. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  403. fUI.window->hide();
  404. }
  405. }
  406. // -------------------------------------------------------------------
  407. // Plugin state
  408. void reload() override
  409. {
  410. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  411. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  412. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  413. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  414. carla_debug("CarlaPluginVST3::reload() - start");
  415. // Safely disable plugin for reload
  416. const ScopedDisabler sd(this);
  417. if (pData->active)
  418. deactivate();
  419. clearBuffers();
  420. const int32_t numAudioInputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_AUDIO, V3_INPUT);
  421. const int32_t numEventInputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_INPUT);
  422. const int32_t numAudioOutputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_AUDIO, V3_OUTPUT);
  423. const int32_t numEventOutputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_OUTPUT);
  424. const int32_t numParameters = v3_cpp_obj(fV3.controller)->get_parameter_count(fV3.controller);
  425. CARLA_SAFE_ASSERT(numAudioInputBuses >= 0);
  426. CARLA_SAFE_ASSERT(numEventInputBuses >= 0);
  427. CARLA_SAFE_ASSERT(numAudioOutputBuses >= 0);
  428. CARLA_SAFE_ASSERT(numEventOutputBuses >= 0);
  429. CARLA_SAFE_ASSERT(numParameters >= 0);
  430. uint32_t aIns, aOuts, cvIns, cvOuts, params;
  431. aIns = aOuts = cvIns = cvOuts = params = 0;
  432. bool needsCtrlIn, needsCtrlOut;
  433. needsCtrlIn = needsCtrlOut = false;
  434. for (int32_t j=0; j<numAudioInputBuses; ++j)
  435. {
  436. v3_bus_info busInfo = {};
  437. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_INPUT, j, &busInfo) == V3_OK);
  438. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  439. cvIns += busInfo.channel_count;
  440. else
  441. aIns += busInfo.channel_count;
  442. }
  443. for (int32_t j=0; j<numAudioInputBuses; ++j)
  444. {
  445. v3_bus_info busInfo = {};
  446. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_OUTPUT, j, &busInfo) == V3_OK);
  447. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  448. cvOuts += busInfo.channel_count;
  449. else
  450. aOuts += busInfo.channel_count;
  451. }
  452. for (int32_t j=0; j<numParameters; ++j)
  453. {
  454. v3_param_info paramInfo = {};
  455. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller, j, &paramInfo) == V3_OK);
  456. if ((paramInfo.flags & (V3_PARAM_IS_BYPASS|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE)) == 0x0)
  457. ++params;
  458. }
  459. if (aIns > 0)
  460. {
  461. pData->audioIn.createNew(aIns);
  462. }
  463. if (aOuts > 0)
  464. {
  465. pData->audioOut.createNew(aOuts);
  466. needsCtrlIn = true;
  467. }
  468. if (cvIns > 0)
  469. pData->cvIn.createNew(cvIns);
  470. if (cvOuts > 0)
  471. pData->cvOut.createNew(cvOuts);
  472. if (numEventInputBuses > 0)
  473. needsCtrlIn = true;
  474. if (numEventOutputBuses > 0)
  475. needsCtrlOut = true;
  476. if (params > 0)
  477. {
  478. pData->param.createNew(params, false);
  479. needsCtrlIn = true;
  480. }
  481. if (aOuts + cvIns > 0)
  482. {
  483. fAudioOutBuffers = new float*[aOuts + cvIns];
  484. for (uint32_t i=0; i < aOuts + cvIns; ++i)
  485. fAudioOutBuffers[i] = nullptr;
  486. }
  487. const EngineProcessMode processMode = pData->engine->getProccessMode();
  488. const uint portNameSize = pData->engine->getMaxPortNameSize();
  489. CarlaString portName;
  490. // Audio Ins
  491. for (uint32_t j=0; j < aIns; ++j)
  492. {
  493. portName.clear();
  494. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  495. {
  496. portName = pData->name;
  497. portName += ":";
  498. }
  499. if (aIns > 1)
  500. {
  501. portName += "input_";
  502. portName += CarlaString(j+1);
  503. }
  504. else
  505. portName += "input";
  506. portName.truncate(portNameSize);
  507. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  508. pData->audioIn.ports[j].rindex = j;
  509. }
  510. // Audio Outs
  511. for (uint32_t j=0; j < aOuts; ++j)
  512. {
  513. portName.clear();
  514. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  515. {
  516. portName = pData->name;
  517. portName += ":";
  518. }
  519. if (aOuts > 1)
  520. {
  521. portName += "output_";
  522. portName += CarlaString(j+1);
  523. }
  524. else
  525. portName += "output";
  526. portName.truncate(portNameSize);
  527. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  528. pData->audioOut.ports[j].rindex = j;
  529. }
  530. // CV Ins
  531. for (uint32_t j=0; j < cvIns; ++j)
  532. {
  533. portName.clear();
  534. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  535. {
  536. portName = pData->name;
  537. portName += ":";
  538. }
  539. if (cvIns > 1)
  540. {
  541. portName += "cv_input_";
  542. portName += CarlaString(j+1);
  543. }
  544. else
  545. portName += "cv_input";
  546. portName.truncate(portNameSize);
  547. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  548. pData->cvIn.ports[j].rindex = j;
  549. }
  550. // CV Outs
  551. for (uint32_t j=0; j < cvOuts; ++j)
  552. {
  553. portName.clear();
  554. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  555. {
  556. portName = pData->name;
  557. portName += ":";
  558. }
  559. if (cvOuts > 1)
  560. {
  561. portName += "cv_output_";
  562. portName += CarlaString(j+1);
  563. }
  564. else
  565. portName += "cv_output";
  566. portName.truncate(portNameSize);
  567. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  568. pData->cvOut.ports[j].rindex = j;
  569. }
  570. for (uint32_t j=0; j < params; ++j)
  571. {
  572. const int32_t ij = static_cast<int32_t>(j);
  573. pData->param.data[j].type = PARAMETER_INPUT;
  574. pData->param.data[j].index = ij;
  575. pData->param.data[j].rindex = ij;
  576. v3_param_info paramInfo = {};
  577. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller, j, &paramInfo) == V3_OK);
  578. if (paramInfo.flags & (V3_PARAM_IS_BYPASS|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  579. continue;
  580. float min, max, def, step, stepSmall, stepLarge;
  581. min = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, j, 0.0);
  582. max = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, j, 1.0);
  583. def = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, j, paramInfo.default_normalised_value);
  584. if (min >= max)
  585. max = min + 0.1f;
  586. if (def < min)
  587. def = min;
  588. else if (def > max)
  589. def = max;
  590. if (paramInfo.flags & V3_PARAM_READ_ONLY)
  591. pData->param.data[j].type = PARAMETER_OUTPUT;
  592. else
  593. pData->param.data[j].type = PARAMETER_INPUT;
  594. if (paramInfo.step_count == 1)
  595. {
  596. step = max - min;
  597. stepSmall = step;
  598. stepLarge = step;
  599. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  600. }
  601. /*
  602. else if (paramInfo.step_count != 0 && (paramInfo.flags & V3_PARAM_IS_LIST) != 0x0)
  603. {
  604. step = 1.0f;
  605. stepSmall = 1.0f;
  606. stepLarge = 10.0f;
  607. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  608. }
  609. */
  610. else
  611. {
  612. float range = max - min;
  613. step = range/100.0f;
  614. stepSmall = range/1000.0f;
  615. stepLarge = range/10.0f;
  616. }
  617. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  618. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  619. if (paramInfo.flags & V3_PARAM_CAN_AUTOMATE)
  620. {
  621. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  622. if ((paramInfo.flags & V3_PARAM_IS_LIST) == 0x0)
  623. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  624. }
  625. pData->param.ranges[j].min = min;
  626. pData->param.ranges[j].max = max;
  627. pData->param.ranges[j].def = def;
  628. pData->param.ranges[j].step = step;
  629. pData->param.ranges[j].stepSmall = stepSmall;
  630. pData->param.ranges[j].stepLarge = stepLarge;
  631. }
  632. if (needsCtrlIn)
  633. {
  634. portName.clear();
  635. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  636. {
  637. portName = pData->name;
  638. portName += ":";
  639. }
  640. portName += "events-in";
  641. portName.truncate(portNameSize);
  642. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  643. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  644. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  645. #endif
  646. }
  647. if (needsCtrlOut)
  648. {
  649. portName.clear();
  650. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  651. {
  652. portName = pData->name;
  653. portName += ":";
  654. }
  655. portName += "events-out";
  656. portName.truncate(portNameSize);
  657. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  658. }
  659. // plugin hints
  660. const PluginCategory v3category = getPluginCategoryFromV3SubCategories(fV3ClassInfo.v2.sub_categories);
  661. pData->hints = 0x0;
  662. if (v3category == PLUGIN_CATEGORY_SYNTH)
  663. pData->hints |= PLUGIN_IS_SYNTH;
  664. if (fV3.view != nullptr &&
  665. v3_cpp_obj(fV3.view)->is_platform_type_supported(fV3.view, V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_TRUE)
  666. {
  667. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  668. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  669. }
  670. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  671. pData->hints |= PLUGIN_CAN_DRYWET;
  672. if (aOuts > 0)
  673. pData->hints |= PLUGIN_CAN_VOLUME;
  674. if (aOuts >= 2 && aOuts % 2 == 0)
  675. pData->hints |= PLUGIN_CAN_BALANCE;
  676. // extra plugin hints
  677. pData->extraHints = 0x0;
  678. if (numEventInputBuses > 0)
  679. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  680. if (numEventOutputBuses > 0)
  681. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  682. // check initial latency
  683. if (const uint32_t latency = v3_cpp_obj(fV3.processor)->get_latency_samples(fV3.processor))
  684. {
  685. pData->client->setLatency(latency);
  686. #ifndef BUILD_BRIDGE
  687. pData->latency.recreateBuffers(std::max(aIns+cvIns, aOuts+cvOuts), latency);
  688. #endif
  689. }
  690. // initial audio setup
  691. v3_process_setup setup = {
  692. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  693. V3_SAMPLE_32,
  694. static_cast<int32_t>(pData->engine->getBufferSize()),
  695. pData->engine->getSampleRate()
  696. };
  697. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  698. // activate all buses
  699. for (int32_t j=0; j<numAudioInputBuses; ++j)
  700. {
  701. v3_bus_info busInfo = {};
  702. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_INPUT, j, &busInfo) == V3_OK);
  703. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  704. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component, V3_AUDIO, V3_INPUT, j, true) == V3_OK);
  705. }
  706. }
  707. for (int32_t j=0; j<numAudioInputBuses; ++j)
  708. {
  709. v3_bus_info busInfo = {};
  710. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_OUTPUT, j, &busInfo) == V3_OK);
  711. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  712. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component, V3_AUDIO, V3_OUTPUT, j, true) == V3_OK);
  713. }
  714. }
  715. bufferSizeChanged(pData->engine->getBufferSize());
  716. reloadPrograms(true);
  717. if (pData->active)
  718. activate();
  719. carla_debug("CarlaPluginVST3::reload() - end");
  720. }
  721. // -------------------------------------------------------------------
  722. // Plugin processing
  723. void activate() noexcept override
  724. {
  725. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  726. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  727. try {
  728. v3_cpp_obj(fV3.component)->set_active(fV3.component, true);
  729. } CARLA_SAFE_EXCEPTION("set_active on");
  730. try {
  731. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, true);
  732. } CARLA_SAFE_EXCEPTION("set_processing on");
  733. fFirstActive = true;
  734. }
  735. void deactivate() noexcept override
  736. {
  737. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  738. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  739. try {
  740. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, false);
  741. } CARLA_SAFE_EXCEPTION("set_processing off");
  742. try {
  743. v3_cpp_obj(fV3.component)->set_active(fV3.component, false);
  744. } CARLA_SAFE_EXCEPTION("set_active off");
  745. }
  746. void process(const float* const* const audioIn, float** const audioOut,
  747. const float* const* const cvIn, float** const cvOut, const uint32_t frames) override
  748. {
  749. // --------------------------------------------------------------------------------------------------------
  750. // Check if active
  751. if (! pData->active)
  752. {
  753. // disable any output sound
  754. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  755. carla_zeroFloats(audioOut[i], frames);
  756. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  757. carla_zeroFloats(cvOut[i], frames);
  758. return;
  759. }
  760. // --------------------------------------------------------------------------------------------------------
  761. // Check if needs reset
  762. if (pData->needsReset)
  763. {
  764. pData->needsReset = false;
  765. }
  766. // --------------------------------------------------------------------------------------------------------
  767. // Set TimeInfo
  768. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  769. fV3TimeContext.state = V3_PROCESS_CTX_PROJECT_TIME_VALID | V3_PROCESS_CTX_CONT_TIME_VALID;
  770. fV3TimeContext.sample_rate = pData->engine->getSampleRate();
  771. fV3TimeContext.project_time_in_samples = fV3TimeContext.continuous_time_in_samples
  772. = static_cast<int64_t>(timeInfo.frame);
  773. if (fFirstActive || ! fLastTimeInfo.compareIgnoringRollingFrames(timeInfo, frames))
  774. fLastTimeInfo = timeInfo;
  775. if (timeInfo.playing)
  776. fV3TimeContext.state |= V3_PROCESS_CTX_PLAYING;
  777. if (timeInfo.usecs != 0)
  778. {
  779. fV3TimeContext.system_time_ns = static_cast<int64_t>(timeInfo.usecs);
  780. fV3TimeContext.state |= V3_PROCESS_CTX_SYSTEM_TIME_VALID;
  781. }
  782. if (timeInfo.bbt.valid)
  783. {
  784. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  785. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  786. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  787. // const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  788. // const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  789. // PPQ Pos
  790. fV3TimeContext.project_time_quarters = static_cast<double>(timeInfo.frame) / (fV3TimeContext.sample_rate * 60 / timeInfo.bbt.beatsPerMinute);
  791. // fTimeInfo.project_time_quarters = ppqBar + ppqBeat + ppqTick;
  792. fV3TimeContext.state |= V3_PROCESS_CTX_PROJECT_TIME_VALID;
  793. // Tempo
  794. fV3TimeContext.bpm = timeInfo.bbt.beatsPerMinute;
  795. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  796. // Bars
  797. fV3TimeContext.bar_position_quarters = ppqBar;
  798. fV3TimeContext.state |= V3_PROCESS_CTX_BAR_POSITION_VALID;
  799. // Time Signature
  800. fV3TimeContext.time_sig_numerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  801. fV3TimeContext.time_sig_denom = static_cast<int32_t>(timeInfo.bbt.beatType + 0.5f);
  802. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  803. }
  804. else
  805. {
  806. // Tempo
  807. fV3TimeContext.bpm = 120.0;
  808. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  809. // Time Signature
  810. fV3TimeContext.time_sig_numerator = 4;
  811. fV3TimeContext.time_sig_denom = 4;
  812. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  813. // Missing info
  814. fV3TimeContext.project_time_quarters = 0.0;
  815. fV3TimeContext.bar_position_quarters = 0.0;
  816. }
  817. // --------------------------------------------------------------------------------------------------------
  818. // Event Input and Processing
  819. if (pData->event.portIn != nullptr)
  820. {
  821. // ----------------------------------------------------------------------------------------------------
  822. // MIDI Input (External)
  823. if (pData->extNotes.mutex.tryLock())
  824. {
  825. // TODO
  826. pData->extNotes.mutex.unlock();
  827. } // End of MIDI Input (External)
  828. // ----------------------------------------------------------------------------------------------------
  829. // Event Input (System)
  830. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  831. bool allNotesOffSent = false;
  832. #endif
  833. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  834. uint32_t startTime = 0;
  835. uint32_t timeOffset = 0;
  836. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  837. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  838. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, isSampleAccurate, pData->event.portIn);
  839. #endif
  840. for (uint32_t i=0, numEvents = pData->event.portIn->getEventCount(); i < numEvents; ++i)
  841. {
  842. EngineEvent& event(pData->event.portIn->getEvent(i));
  843. uint32_t eventTime = event.time;
  844. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  845. if (eventTime < timeOffset)
  846. {
  847. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  848. eventTime, timeOffset, pData->name);
  849. eventTime = timeOffset;
  850. }
  851. if (isSampleAccurate && eventTime > timeOffset)
  852. {
  853. if (processSingle(audioIn, audioOut, eventTime - timeOffset, timeOffset))
  854. {
  855. startTime = 0;
  856. timeOffset = eventTime;
  857. // TODO
  858. }
  859. else
  860. {
  861. startTime += timeOffset;
  862. }
  863. }
  864. switch (event.type)
  865. {
  866. case kEngineEventTypeNull:
  867. break;
  868. case kEngineEventTypeControl: {
  869. EngineControlEvent& ctrlEvent(event.ctrl);
  870. switch (ctrlEvent.type)
  871. {
  872. case kEngineControlEventTypeNull:
  873. break;
  874. case kEngineControlEventTypeParameter: {
  875. float value;
  876. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  877. // non-midi
  878. if (event.channel == kEngineEventNonMidiChannel)
  879. {
  880. const uint32_t k = ctrlEvent.param;
  881. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  882. ctrlEvent.handled = true;
  883. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  884. setParameterValueRT(k, value, true);
  885. continue;
  886. }
  887. // Control backend stuff
  888. if (event.channel == pData->ctrlChannel)
  889. {
  890. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  891. {
  892. ctrlEvent.handled = true;
  893. value = ctrlEvent.normalizedValue;
  894. setDryWetRT(value, true);
  895. }
  896. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  897. {
  898. ctrlEvent.handled = true;
  899. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  900. setVolumeRT(value, true);
  901. }
  902. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  903. {
  904. float left, right;
  905. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  906. if (value < 0.0f)
  907. {
  908. left = -1.0f;
  909. right = (value*2.0f)+1.0f;
  910. }
  911. else if (value > 0.0f)
  912. {
  913. left = (value*2.0f)-1.0f;
  914. right = 1.0f;
  915. }
  916. else
  917. {
  918. left = -1.0f;
  919. right = 1.0f;
  920. }
  921. ctrlEvent.handled = true;
  922. setBalanceLeftRT(left, true);
  923. setBalanceRightRT(right, true);
  924. }
  925. }
  926. #endif
  927. // Control plugin parameters
  928. uint32_t k;
  929. for (k=0; k < pData->param.count; ++k)
  930. {
  931. if (pData->param.data[k].midiChannel != event.channel)
  932. continue;
  933. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  934. continue;
  935. if (pData->param.data[k].type != PARAMETER_INPUT)
  936. continue;
  937. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  938. continue;
  939. ctrlEvent.handled = true;
  940. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  941. setParameterValueRT(k, value, true);
  942. }
  943. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  944. {
  945. // TODO
  946. }
  947. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  948. if (! ctrlEvent.handled)
  949. checkForMidiLearn(event);
  950. #endif
  951. break;
  952. } // case kEngineControlEventTypeParameter
  953. case kEngineControlEventTypeMidiBank:
  954. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  955. {
  956. // TODO
  957. }
  958. break;
  959. case kEngineControlEventTypeMidiProgram:
  960. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  961. {
  962. if (ctrlEvent.param < pData->prog.count)
  963. {
  964. setProgramRT(ctrlEvent.param, true);
  965. break;
  966. }
  967. }
  968. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  969. {
  970. // TODO
  971. }
  972. break;
  973. case kEngineControlEventTypeAllSoundOff:
  974. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  975. {
  976. // TODO
  977. }
  978. break;
  979. case kEngineControlEventTypeAllNotesOff:
  980. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  981. {
  982. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  983. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  984. {
  985. allNotesOffSent = true;
  986. postponeRtAllNotesOff();
  987. }
  988. #endif
  989. // TODO
  990. }
  991. break;
  992. } // switch (ctrlEvent.type)
  993. break;
  994. } // case kEngineEventTypeControl
  995. case kEngineEventTypeMidi: {
  996. const EngineMidiEvent& midiEvent(event.midi);
  997. if (midiEvent.size > 3)
  998. continue;
  999. #ifdef CARLA_PROPER_CPP11_SUPPORT
  1000. static_assert(3 <= EngineMidiEvent::kDataSize, "Incorrect data");
  1001. #endif
  1002. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  1003. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1004. continue;
  1005. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  1006. continue;
  1007. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  1008. continue;
  1009. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  1010. continue;
  1011. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  1012. continue;
  1013. // Fix bad note-off
  1014. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  1015. status = MIDI_STATUS_NOTE_OFF;
  1016. // TODO
  1017. if (status == MIDI_STATUS_NOTE_ON)
  1018. {
  1019. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  1020. }
  1021. else if (status == MIDI_STATUS_NOTE_OFF)
  1022. {
  1023. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  1024. }
  1025. } break;
  1026. } // switch (event.type)
  1027. }
  1028. pData->postRtEvents.trySplice();
  1029. if (frames > timeOffset)
  1030. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset);
  1031. } // End of Event Input and Processing
  1032. // --------------------------------------------------------------------------------------------------------
  1033. // Plugin processing (no events)
  1034. else
  1035. {
  1036. processSingle(audioIn, audioOut, frames, 0);
  1037. } // End of Plugin processing (no events)
  1038. // --------------------------------------------------------------------------------------------------------
  1039. // MIDI Output
  1040. if (pData->event.portOut != nullptr)
  1041. {
  1042. // TODO
  1043. } // End of MIDI Output
  1044. fFirstActive = false;
  1045. // --------------------------------------------------------------------------------------------------------
  1046. }
  1047. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  1048. {
  1049. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  1050. if (pData->audioIn.count > 0)
  1051. {
  1052. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  1053. }
  1054. if (pData->audioOut.count > 0)
  1055. {
  1056. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  1057. CARLA_SAFE_ASSERT_RETURN(fAudioOutBuffers != nullptr, false);
  1058. }
  1059. // --------------------------------------------------------------------------------------------------------
  1060. // Try lock, silence otherwise
  1061. #ifndef STOAT_TEST_BUILD
  1062. if (pData->engine->isOffline())
  1063. {
  1064. pData->singleMutex.lock();
  1065. }
  1066. else
  1067. #endif
  1068. if (! pData->singleMutex.tryLock())
  1069. {
  1070. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1071. {
  1072. for (uint32_t k=0; k < frames; ++k)
  1073. outBuffer[i][k+timeOffset] = 0.0f;
  1074. }
  1075. return false;
  1076. }
  1077. // --------------------------------------------------------------------------------------------------------
  1078. // Set audio buffers
  1079. float* bufferAudioIn[std::max(1u, pData->audioIn.count + pData->cvIn.count)];
  1080. float* bufferAudioOut[std::max(1u, pData->audioOut.count + pData->cvOut.count)];
  1081. {
  1082. uint32_t i=0;
  1083. for (; i < pData->audioIn.count; ++i)
  1084. bufferAudioIn[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  1085. for (; i < pData->cvIn.count; ++i)
  1086. bufferAudioIn[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  1087. }
  1088. {
  1089. uint32_t i=0;
  1090. for (; i < pData->audioOut.count; ++i)
  1091. bufferAudioOut[i] = fAudioOutBuffers[i]+timeOffset;
  1092. for (; i < pData->cvOut.count; ++i)
  1093. bufferAudioOut[i] = fAudioOutBuffers[i]+timeOffset;
  1094. }
  1095. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  1096. carla_zeroFloats(fAudioOutBuffers[i], frames);
  1097. // --------------------------------------------------------------------------------------------------------
  1098. // Set MIDI events
  1099. // TODO
  1100. // --------------------------------------------------------------------------------------------------------
  1101. // Run plugin
  1102. carla_v3_event_list eventList;
  1103. carla_v3_event_list* eventListPtr = &eventList;
  1104. carla_v3_param_changes paramChanges;
  1105. carla_v3_param_changes* paramChangesPtr = &paramChanges;
  1106. v3_audio_bus_buffers processInputs = {
  1107. static_cast<int32_t>(pData->audioIn.count + pData->cvIn.count),
  1108. 0, { bufferAudioIn }
  1109. };
  1110. v3_audio_bus_buffers processOutputs = {
  1111. static_cast<int32_t>(pData->audioOut.count + pData->cvOut.count),
  1112. 0, { bufferAudioOut }
  1113. };
  1114. v3_process_data processData = {
  1115. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  1116. V3_SAMPLE_32,
  1117. static_cast<int32_t>(frames),
  1118. static_cast<int32_t>(pData->audioIn.count + pData->cvIn.count),
  1119. static_cast<int32_t>(pData->audioOut.count + pData->cvOut.count),
  1120. &processInputs,
  1121. &processOutputs,
  1122. (v3_param_changes**)&paramChangesPtr,
  1123. (v3_param_changes**)&paramChangesPtr,
  1124. (v3_event_list**)&eventListPtr,
  1125. (v3_event_list**)&eventListPtr,
  1126. &fV3TimeContext
  1127. };
  1128. try {
  1129. v3_cpp_obj(fV3.processor)->process(fV3.processor, &processData);
  1130. } CARLA_SAFE_EXCEPTION("process");
  1131. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1132. // --------------------------------------------------------------------------------------------------------
  1133. // Post-processing (dry/wet, volume and balance)
  1134. {
  1135. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  1136. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  1137. const bool isMono = (pData->audioIn.count == 1);
  1138. bool isPair;
  1139. float bufValue, oldBufLeft[doBalance ? frames : 1];
  1140. uint32_t i=0;
  1141. for (; i < pData->audioOut.count; ++i)
  1142. {
  1143. // Dry/Wet
  1144. if (doDryWet)
  1145. {
  1146. const uint32_t c = isMono ? 0 : i;
  1147. for (uint32_t k=0; k < frames; ++k)
  1148. {
  1149. bufValue = inBuffer[c][k+timeOffset];
  1150. fAudioOutBuffers[i][k] = (fAudioOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  1151. }
  1152. }
  1153. // Balance
  1154. if (doBalance)
  1155. {
  1156. isPair = (i % 2 == 0);
  1157. if (isPair)
  1158. {
  1159. CARLA_ASSERT(i+1 < pData->audioOut.count);
  1160. carla_copyFloats(oldBufLeft, fAudioOutBuffers[i], frames);
  1161. }
  1162. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  1163. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  1164. for (uint32_t k=0; k < frames; ++k)
  1165. {
  1166. if (isPair)
  1167. {
  1168. // left
  1169. fAudioOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  1170. fAudioOutBuffers[i][k] += fAudioOutBuffers[i+1][k] * (1.0f - balRangeR);
  1171. }
  1172. else
  1173. {
  1174. // right
  1175. fAudioOutBuffers[i][k] = fAudioOutBuffers[i][k] * balRangeR;
  1176. fAudioOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  1177. }
  1178. }
  1179. }
  1180. // Volume (and buffer copy)
  1181. {
  1182. for (uint32_t k=0; k < frames; ++k)
  1183. outBuffer[i][k+timeOffset] = fAudioOutBuffers[i][k] * pData->postProc.volume;
  1184. }
  1185. }
  1186. for (; i < pData->cvOut.count; ++i)
  1187. carla_copyFloats(outBuffer[i] + timeOffset, fAudioOutBuffers[i] + timeOffset, frames);
  1188. } // End of Post-processing
  1189. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  1190. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  1191. carla_copyFloats(outBuffer[i] + timeOffset, fAudioOutBuffers[i] + timeOffset, frames);
  1192. #endif
  1193. // --------------------------------------------------------------------------------------------------------
  1194. pData->singleMutex.unlock();
  1195. return true;
  1196. }
  1197. void bufferSizeChanged(const uint32_t newBufferSize) override
  1198. {
  1199. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  1200. carla_debug("CarlaPluginVST2::bufferSizeChanged(%i)", newBufferSize);
  1201. if (pData->active)
  1202. deactivate();
  1203. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  1204. {
  1205. if (fAudioOutBuffers[i] != nullptr)
  1206. delete[] fAudioOutBuffers[i];
  1207. fAudioOutBuffers[i] = new float[newBufferSize];
  1208. }
  1209. v3_process_setup setup = {
  1210. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  1211. V3_SAMPLE_32,
  1212. static_cast<int32_t>(newBufferSize),
  1213. pData->engine->getSampleRate()
  1214. };
  1215. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  1216. if (pData->active)
  1217. activate();
  1218. }
  1219. void sampleRateChanged(const double newSampleRate) override
  1220. {
  1221. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  1222. carla_debug("CarlaPluginVST3::sampleRateChanged(%g)", newSampleRate);
  1223. if (pData->active)
  1224. deactivate();
  1225. v3_process_setup setup = {
  1226. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  1227. V3_SAMPLE_32,
  1228. static_cast<int32_t>(pData->engine->getBufferSize()),
  1229. newSampleRate
  1230. };
  1231. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  1232. if (pData->active)
  1233. activate();
  1234. }
  1235. void offlineModeChanged(const bool isOffline) override
  1236. {
  1237. carla_debug("CarlaPluginVST3::offlineModeChanged(%d)", isOffline);
  1238. if (pData->active)
  1239. deactivate();
  1240. v3_process_setup setup = {
  1241. isOffline ? V3_OFFLINE : V3_REALTIME,
  1242. V3_SAMPLE_32,
  1243. static_cast<int32_t>(pData->engine->getBufferSize()),
  1244. pData->engine->getSampleRate()
  1245. };
  1246. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  1247. if (pData->active)
  1248. activate();
  1249. }
  1250. // -------------------------------------------------------------------
  1251. // Plugin buffers
  1252. void clearBuffers() noexcept override
  1253. {
  1254. carla_debug("CarlaPluginVST2::clearBuffers() - start");
  1255. if (fAudioOutBuffers != nullptr)
  1256. {
  1257. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  1258. {
  1259. if (fAudioOutBuffers[i] != nullptr)
  1260. {
  1261. delete[] fAudioOutBuffers[i];
  1262. fAudioOutBuffers[i] = nullptr;
  1263. }
  1264. }
  1265. delete[] fAudioOutBuffers;
  1266. fAudioOutBuffers = nullptr;
  1267. }
  1268. CarlaPlugin::clearBuffers();
  1269. carla_debug("CarlaPluginVST2::clearBuffers() - end");
  1270. }
  1271. // -------------------------------------------------------------------
  1272. // Post-poned UI Stuff
  1273. void uiParameterChange(const uint32_t index, const float value) noexcept override
  1274. {
  1275. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1276. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  1277. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller, index, value);
  1278. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, index, normalized);
  1279. }
  1280. // ----------------------------------------------------------------------------------------------------------------
  1281. const void* getNativeDescriptor() const noexcept override
  1282. {
  1283. return fV3.component;
  1284. }
  1285. const void* getExtraStuff() const noexcept override
  1286. {
  1287. return fV3.controller;
  1288. }
  1289. // ----------------------------------------------------------------------------------------------------------------
  1290. bool init(const CarlaPluginPtr plugin,
  1291. const char* const filename,
  1292. const char* name,
  1293. const char* const label,
  1294. const uint options)
  1295. {
  1296. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  1297. // ------------------------------------------------------------------------------------------------------------
  1298. // first checks
  1299. if (pData->client != nullptr)
  1300. {
  1301. pData->engine->setLastError("Plugin client is already registered");
  1302. return false;
  1303. }
  1304. if (filename == nullptr || filename[0] == '\0')
  1305. {
  1306. pData->engine->setLastError("null filename");
  1307. return false;
  1308. }
  1309. V3_ENTRYFN v3_entry;
  1310. V3_EXITFN v3_exit;
  1311. V3_GETFN v3_get;
  1312. // filename is full path to binary
  1313. if (water::File(filename).existsAsFile())
  1314. {
  1315. if (! pData->libOpen(filename))
  1316. {
  1317. pData->engine->setLastError(pData->libError(filename));
  1318. return false;
  1319. }
  1320. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  1321. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  1322. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  1323. }
  1324. // assume filename is a vst3 bundle
  1325. else
  1326. {
  1327. #ifdef CARLA_OS_MAC
  1328. if (! fMacBundleLoader.load(filename))
  1329. {
  1330. pData->engine->setLastError("Failed to load VST3 bundle executable");
  1331. return false;
  1332. }
  1333. v3_entry = (V3_ENTRYFN)CFBundleGetFunctionPointerForName(fMacBundleLoader.getRef(), CFSTR(V3_ENTRYFNNAME));
  1334. v3_exit = (V3_EXITFN)CFBundleGetFunctionPointerForName(fMacBundleLoader.getRef(), CFSTR(V3_EXITFNNAME));
  1335. v3_get = (V3_GETFN)CFBundleGetFunctionPointerForName(fMacBundleLoader.getRef(), CFSTR(V3_GETFNNAME));
  1336. #else
  1337. water::String binaryfilename = filename;
  1338. if (!binaryfilename.endsWithChar(CARLA_OS_SEP))
  1339. binaryfilename += CARLA_OS_SEP_STR;
  1340. binaryfilename += "Contents" CARLA_OS_SEP_STR V3_CONTENT_DIR CARLA_OS_SEP_STR;
  1341. binaryfilename += water::File(filename).getFileNameWithoutExtension();
  1342. #ifdef CARLA_OS_WIN
  1343. binaryfilename += ".vst3";
  1344. #else
  1345. binaryfilename += ".so";
  1346. #endif
  1347. if (! water::File(binaryfilename).existsAsFile())
  1348. {
  1349. pData->engine->setLastError("Failed to find a suitable VST3 bundle binary");
  1350. return false;
  1351. }
  1352. if (! pData->libOpen(binaryfilename.toRawUTF8()))
  1353. {
  1354. pData->engine->setLastError(pData->libError(binaryfilename.toRawUTF8()));
  1355. return false;
  1356. }
  1357. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  1358. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  1359. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  1360. #endif
  1361. }
  1362. // ------------------------------------------------------------------------------------------------------------
  1363. // ensure entry and exit points are available
  1364. if (v3_entry == nullptr || v3_exit == nullptr || v3_get == nullptr)
  1365. {
  1366. pData->engine->setLastError("Not a VST3 plugin");
  1367. return false;
  1368. }
  1369. // ------------------------------------------------------------------------------------------------------------
  1370. // call entry point
  1371. #if defined(CARLA_OS_MAC)
  1372. v3_entry(pData->lib != nullptr ? pData->lib : fMacBundleLoader.ref);
  1373. #elif defined(CARLA_OS_WIN)
  1374. v3_entry();
  1375. #else
  1376. v3_entry(pData->lib);
  1377. #endif
  1378. // ------------------------------------------------------------------------------------------------------------
  1379. // fetch initial factory
  1380. v3_plugin_factory** const factory = v3_get();
  1381. if (factory == nullptr)
  1382. {
  1383. pData->engine->setLastError("VST3 factory failed to create a valid instance");
  1384. return false;
  1385. }
  1386. // ------------------------------------------------------------------------------------------------------------
  1387. // initialize and find requested plugin
  1388. fV3.exitfn = v3_exit;
  1389. fV3.factory1 = factory;
  1390. if (! fV3.queryFactories(getHostContext()))
  1391. {
  1392. pData->engine->setLastError("VST3 plugin failed to properly create factories");
  1393. return false;
  1394. }
  1395. if (! fV3.findPlugin(fV3ClassInfo))
  1396. {
  1397. pData->engine->setLastError("Failed to find the requested plugin in the VST3 bundle");
  1398. return false;
  1399. }
  1400. if (! fV3.initializePlugin(fV3ClassInfo.v1.class_id, getHostContext()))
  1401. {
  1402. pData->engine->setLastError("VST3 plugin failed to initialize");
  1403. return false;
  1404. }
  1405. // ------------------------------------------------------------------------------------------------------------
  1406. // do some basic safety checks
  1407. if (v3_cpp_obj(fV3.processor)->can_process_sample_size(fV3.processor, V3_SAMPLE_32) != V3_OK)
  1408. {
  1409. pData->engine->setLastError("VST3 plugin does not support 32bit audio, cannot continue");
  1410. return false;
  1411. }
  1412. // ------------------------------------------------------------------------------------------------------------
  1413. // get info
  1414. if (name != nullptr && name[0] != '\0')
  1415. {
  1416. pData->name = pData->engine->getUniquePluginName(name);
  1417. }
  1418. else
  1419. {
  1420. if (fV3ClassInfo.v1.name[0] != '\0')
  1421. pData->name = pData->engine->getUniquePluginName(fV3ClassInfo.v1.name);
  1422. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  1423. pData->name = pData->engine->getUniquePluginName(shortname+1);
  1424. else
  1425. pData->name = pData->engine->getUniquePluginName("unknown");
  1426. }
  1427. pData->filename = carla_strdup(filename);
  1428. // ------------------------------------------------------------------------------------------------------------
  1429. // register client
  1430. pData->client = pData->engine->addClient(plugin);
  1431. if (pData->client == nullptr || ! pData->client->isOk())
  1432. {
  1433. pData->engine->setLastError("Failed to register plugin client");
  1434. return false;
  1435. }
  1436. // ------------------------------------------------------------------------------------------------------------
  1437. // set default options
  1438. pData->options = 0x0;
  1439. if (v3_cpp_obj(fV3.processor)->get_latency_samples(fV3.processor) != 0 /*|| hasMidiOutput()*/ ||
  1440. isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  1441. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1442. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  1443. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  1444. /*
  1445. if (hasMidiInput())
  1446. {
  1447. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  1448. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1449. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  1450. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1451. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  1452. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1453. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  1454. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1455. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  1456. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1457. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  1458. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1459. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  1460. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1461. }
  1462. */
  1463. /*
  1464. if (numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  1465. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  1466. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1467. */
  1468. // ------------------------------------------------------------------------------------------------------------
  1469. return true;
  1470. }
  1471. protected:
  1472. void handlePluginUIClosed() override
  1473. {
  1474. // CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1475. carla_debug("CarlaPluginVST3::handlePluginUIClosed()");
  1476. showCustomUI(false);
  1477. pData->engine->callback(true, true,
  1478. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1479. pData->id,
  1480. 0,
  1481. 0, 0, 0.0f, nullptr);
  1482. }
  1483. void handlePluginUIResized(const uint width, const uint height) override
  1484. {
  1485. // CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  1486. carla_debug("CarlaPluginVST3::handlePluginUIResized(%u, %u)", width, height);
  1487. return; // unused
  1488. (void)width; (void)height;
  1489. }
  1490. private:
  1491. #ifdef CARLA_OS_MAC
  1492. BundleLoader fMacBundleLoader;
  1493. #endif
  1494. bool fFirstActive; // first process() call after activate()
  1495. float** fAudioOutBuffers;
  1496. EngineTimeInfo fLastTimeInfo;
  1497. v3_process_context fV3TimeContext;
  1498. CarlaScopedPointer<carla_v3_host_application> fV3Application;
  1499. inline v3_funknown** getHostContext() const noexcept { return (v3_funknown**)&fV3Application; }
  1500. // v3_class_info_2 is ABI compatible with v3_class_info
  1501. union ClassInfo {
  1502. v3_class_info v1;
  1503. v3_class_info_2 v2;
  1504. } fV3ClassInfo;
  1505. struct Pointers {
  1506. V3_EXITFN exitfn;
  1507. v3_plugin_factory** factory1;
  1508. v3_plugin_factory_2** factory2;
  1509. v3_plugin_factory_3** factory3;
  1510. v3_component** component;
  1511. v3_edit_controller** controller;
  1512. v3_audio_processor** processor;
  1513. v3_plugin_view** view;
  1514. bool shouldTerminateComponent;
  1515. bool shouldTerminateController;
  1516. Pointers()
  1517. : exitfn(nullptr),
  1518. factory1(nullptr),
  1519. factory2(nullptr),
  1520. factory3(nullptr),
  1521. component(nullptr),
  1522. controller(nullptr),
  1523. processor(nullptr),
  1524. view(nullptr),
  1525. shouldTerminateComponent(false),
  1526. shouldTerminateController(false) {}
  1527. ~Pointers()
  1528. {
  1529. // must have been cleaned up by now
  1530. CARLA_SAFE_ASSERT(exitfn == nullptr);
  1531. }
  1532. // must have exitfn and factory1 set
  1533. bool queryFactories(v3_funknown** const hostContext)
  1534. {
  1535. // query 2nd factory
  1536. if (v3_cpp_obj_query_interface(factory1, v3_plugin_factory_2_iid, &factory2) == V3_OK)
  1537. {
  1538. CARLA_SAFE_ASSERT_RETURN(factory2 != nullptr, exit());
  1539. }
  1540. else
  1541. {
  1542. CARLA_SAFE_ASSERT(factory2 == nullptr);
  1543. factory2 = nullptr;
  1544. }
  1545. // query 3rd factory
  1546. if (factory2 != nullptr && v3_cpp_obj_query_interface(factory2, v3_plugin_factory_3_iid, &factory3) == V3_OK)
  1547. {
  1548. CARLA_SAFE_ASSERT_RETURN(factory3 != nullptr, exit());
  1549. }
  1550. else
  1551. {
  1552. CARLA_SAFE_ASSERT(factory3 == nullptr);
  1553. factory3 = nullptr;
  1554. }
  1555. // set host context (application) if 3rd factory provided
  1556. if (factory3 != nullptr)
  1557. v3_cpp_obj(factory3)->set_host_context(factory3, hostContext);
  1558. return true;
  1559. }
  1560. // must have all possible factories and exitfn set
  1561. bool findPlugin(ClassInfo& classInfo)
  1562. {
  1563. // get factory info
  1564. v3_factory_info factoryInfo = {};
  1565. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->get_factory_info(factory1, &factoryInfo) == V3_OK, exit());
  1566. // get num classes
  1567. const int32_t numClasses = v3_cpp_obj(factory1)->num_classes(factory1);
  1568. CARLA_SAFE_ASSERT_RETURN(numClasses > 0, exit());
  1569. // go through all relevant classes
  1570. for (int32_t i=0; i<numClasses; ++i)
  1571. {
  1572. carla_zeroStruct(classInfo);
  1573. if (factory2 != nullptr)
  1574. v3_cpp_obj(factory2)->get_class_info_2(factory2, i, &classInfo.v2);
  1575. else
  1576. v3_cpp_obj(factory1)->get_class_info(factory1, i, &classInfo.v1);
  1577. // safety check
  1578. CARLA_SAFE_ASSERT_CONTINUE(classInfo.v1.cardinality == 0x7FFFFFFF);
  1579. // only check for audio plugins
  1580. if (std::strcmp(classInfo.v1.category, "Audio Module Class") != 0)
  1581. continue;
  1582. // FIXME multi-plugin bundle
  1583. break;
  1584. }
  1585. return true;
  1586. }
  1587. bool initializePlugin(const v3_tuid uid, v3_funknown** const hostContext)
  1588. {
  1589. // create instance
  1590. void* instance = nullptr;
  1591. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->create_instance(factory1, uid, v3_component_iid,
  1592. &instance) == V3_OK,
  1593. exit());
  1594. CARLA_SAFE_ASSERT_RETURN(instance != nullptr, exit());
  1595. component = static_cast<v3_component**>(instance);
  1596. // initialize instance
  1597. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(component, hostContext) == V3_OK, exit());
  1598. shouldTerminateComponent = true;
  1599. // create edit controller
  1600. if (v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller) != V3_OK)
  1601. controller = nullptr;
  1602. // if we cannot cast from component, try to create edit controller from factory
  1603. if (controller == nullptr)
  1604. {
  1605. v3_tuid uid = {};
  1606. if (v3_cpp_obj(component)->get_controller_class_id(component, uid) == V3_OK)
  1607. {
  1608. instance = nullptr;
  1609. if (v3_cpp_obj(factory1)->create_instance(factory1, uid, v3_edit_controller_iid, &instance) == V3_OK && instance != nullptr)
  1610. controller = static_cast<v3_edit_controller**>(instance);
  1611. }
  1612. CARLA_SAFE_ASSERT_RETURN(controller != nullptr, exit());
  1613. // component is separate from controller, needs its dedicated initialize and terminate
  1614. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(controller, hostContext) == V3_OK, exit());
  1615. shouldTerminateController = true;
  1616. }
  1617. // create processor
  1618. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_query_interface(component, v3_audio_processor_iid,
  1619. &processor) == V3_OK, exit());
  1620. CARLA_SAFE_ASSERT_RETURN(processor != nullptr, exit());
  1621. // create view, ignoring result
  1622. view = v3_cpp_obj(controller)->create_view(controller, "view");
  1623. return true;
  1624. }
  1625. bool exit()
  1626. {
  1627. // must be deleted by now
  1628. CARLA_SAFE_ASSERT(view == nullptr);
  1629. if (processor != nullptr)
  1630. {
  1631. v3_cpp_obj_unref(processor);
  1632. processor = nullptr;
  1633. }
  1634. if (controller != nullptr)
  1635. {
  1636. if (shouldTerminateController)
  1637. {
  1638. v3_cpp_obj_terminate(controller);
  1639. shouldTerminateController = false;
  1640. }
  1641. v3_cpp_obj_unref(controller);
  1642. component = nullptr;
  1643. }
  1644. if (component != nullptr)
  1645. {
  1646. if (shouldTerminateComponent)
  1647. {
  1648. v3_cpp_obj_terminate(component);
  1649. shouldTerminateComponent = false;
  1650. }
  1651. v3_cpp_obj_unref(component);
  1652. component = nullptr;
  1653. }
  1654. if (factory3 != nullptr)
  1655. {
  1656. v3_cpp_obj_unref(factory3);
  1657. factory3 = nullptr;
  1658. }
  1659. if (factory2 != nullptr)
  1660. {
  1661. v3_cpp_obj_unref(factory2);
  1662. factory2 = nullptr;
  1663. }
  1664. if (factory1 != nullptr)
  1665. {
  1666. v3_cpp_obj_unref(factory1);
  1667. factory1 = nullptr;
  1668. }
  1669. if (exitfn != nullptr)
  1670. {
  1671. exitfn();
  1672. exitfn = nullptr;
  1673. }
  1674. // return false so it can be used as error/fail condition
  1675. return false;
  1676. }
  1677. } fV3;
  1678. struct UI {
  1679. bool isAttached;
  1680. bool isEmbed;
  1681. bool isVisible;
  1682. CarlaPluginUI* window;
  1683. UI() noexcept
  1684. : isAttached(false),
  1685. isEmbed(false),
  1686. isVisible(false),
  1687. window(nullptr) {}
  1688. ~UI()
  1689. {
  1690. CARLA_ASSERT(isEmbed || ! isVisible);
  1691. if (window != nullptr)
  1692. {
  1693. delete window;
  1694. window = nullptr;
  1695. }
  1696. }
  1697. CARLA_DECLARE_NON_COPY_STRUCT(UI);
  1698. } fUI;
  1699. };
  1700. // --------------------------------------------------------------------------------------------------------------------
  1701. CarlaPluginPtr CarlaPlugin::newVST3(const Initializer& init)
  1702. {
  1703. carla_debug("CarlaPlugin::newVST3({%p, \"%s\", \"%s\", \"%s\"})",
  1704. init.engine, init.filename, init.name, init.label);
  1705. #ifdef USE_JUCE_FOR_VST3
  1706. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST3") == nullptr)
  1707. return newJuce(init, "VST3");
  1708. #endif
  1709. std::shared_ptr<CarlaPluginVST3> plugin(new CarlaPluginVST3(init.engine, init.id));
  1710. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  1711. return nullptr;
  1712. return plugin;
  1713. }
  1714. // -------------------------------------------------------------------------------------------------------------------
  1715. CARLA_BACKEND_END_NAMESPACE