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.

2223 lines
77KB

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