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.

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