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.

2152 lines
75KB

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