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.

2543 lines
87KB

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