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.

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