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.

3664 lines
125KB

  1. /*
  2. * Carla VST3 Plugin
  3. * Copyright (C) 2014-2023 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. #include "water/misc/Time.h"
  36. #ifdef _POSIX_VERSION
  37. # ifdef CARLA_OS_LINUX
  38. # define CARLA_VST3_POSIX_EPOLL
  39. # include <sys/epoll.h>
  40. # else
  41. # include <sys/event.h>
  42. # include <sys/types.h>
  43. # endif
  44. #endif
  45. #include <atomic>
  46. #include <unordered_map>
  47. CARLA_BACKEND_START_NAMESPACE
  48. // --------------------------------------------------------------------------------------------------------------------
  49. static inline
  50. size_t strlen_utf16(const int16_t* const str)
  51. {
  52. size_t i = 0;
  53. while (str[i] != 0)
  54. ++i;
  55. return i;
  56. }
  57. // --------------------------------------------------------------------------------------------------------------------
  58. static inline
  59. void strncpy_utf8(char* const dst, const int16_t* const src, const size_t length)
  60. {
  61. CARLA_SAFE_ASSERT_RETURN(length > 0,);
  62. if (const size_t len = std::min(strlen_utf16(src), length-1U))
  63. {
  64. for (size_t i=0; i<len; ++i)
  65. {
  66. // skip non-ascii chars, unsupported
  67. if (src[i] >= 0x80)
  68. continue;
  69. dst[i] = static_cast<char>(src[i]);
  70. }
  71. dst[len] = 0;
  72. }
  73. else
  74. {
  75. dst[0] = 0;
  76. }
  77. }
  78. // --------------------------------------------------------------------------------------------------------------------
  79. static uint32_t V3_API v3_ref_static(void*) { return 1; }
  80. static uint32_t V3_API v3_unref_static(void*) { return 0; }
  81. // --------------------------------------------------------------------------------------------------------------------
  82. struct v3_var {
  83. char type;
  84. uint32_t size;
  85. union {
  86. int64_t i;
  87. double f;
  88. int16_t* s;
  89. void* b;
  90. } value;
  91. };
  92. static void v3_var_cleanup(v3_var& var)
  93. {
  94. switch (var.type)
  95. {
  96. case 's':
  97. std::free(var.value.s);
  98. break;
  99. case 'b':
  100. std::free(var.value.b);
  101. break;
  102. }
  103. carla_zeroStruct(var);
  104. }
  105. struct carla_v3_attribute_list : v3_attribute_list_cpp {
  106. // std::atomic<int> refcounter;
  107. std::unordered_map<std::string, v3_var> vars;
  108. carla_v3_attribute_list()
  109. // : refcounter(1)
  110. {
  111. query_interface = carla_query_interface;
  112. ref = v3_ref_static;
  113. unref = v3_unref_static;
  114. attrlist.set_int = carla_set_int;
  115. attrlist.get_int = carla_get_int;
  116. attrlist.set_float = carla_set_float;
  117. attrlist.get_float = carla_get_float;
  118. attrlist.set_string = carla_set_string;
  119. attrlist.get_string = carla_get_string;
  120. attrlist.set_binary = carla_set_binary;
  121. attrlist.get_binary = carla_get_binary;
  122. }
  123. ~carla_v3_attribute_list()
  124. {
  125. for (std::unordered_map<std::string, v3_var>::iterator it = vars.begin(); it != vars.end(); ++it)
  126. v3_var_cleanup(it->second);
  127. }
  128. v3_result add(const char* const id, const v3_var& var)
  129. {
  130. const std::string sid(id);
  131. for (std::unordered_map<std::string, v3_var>::iterator it = vars.begin(); it != vars.end(); ++it)
  132. {
  133. if (it->first == sid)
  134. {
  135. v3_var_cleanup(it->second);
  136. break;
  137. }
  138. }
  139. vars[sid] = var;
  140. return V3_OK;
  141. }
  142. bool get(const char* const id, v3_var& var)
  143. {
  144. const std::string sid(id);
  145. for (std::unordered_map<std::string, v3_var>::iterator it = vars.begin(); it != vars.end(); ++it)
  146. {
  147. if (it->first == sid)
  148. {
  149. var = it->second;
  150. return true;
  151. }
  152. }
  153. return false;
  154. }
  155. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  156. {
  157. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  158. // carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  159. if (v3_tuid_match(iid, v3_funknown_iid) ||
  160. v3_tuid_match(iid, v3_attribute_list_iid))
  161. {
  162. // ++attrlist->refcounter;
  163. *iface = self;
  164. return V3_OK;
  165. }
  166. *iface = nullptr;
  167. carla_stdout("TODO carla_v3_attribute_list::query_interface %s", tuid2str(iid));
  168. return V3_NO_INTERFACE;
  169. }
  170. /*
  171. static uint32_t V3_API carla_ref(void* const self)
  172. {
  173. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  174. const int refcount = ++msg->refcounter;
  175. carla_debug("carla_v3_attribute_list::ref => %p | refcount %i", self, refcount);
  176. return refcount;
  177. }
  178. static uint32_t V3_API carla_unref(void* const self)
  179. {
  180. carla_v3_attribute_list** const attrlistptr = static_cast<carla_v3_attribute_list**>(self);
  181. carla_v3_attribute_list* const attrlist = *attrlistptr;
  182. if (const int refcount = --attrlist->refcounter)
  183. {
  184. carla_debug("carla_v3_attribute_list::unref => %p | refcount %i", self, refcount);
  185. return refcount;
  186. }
  187. carla_debug("carla_v3_attribute_list::unref => %p | refcount is zero, deleting factory", self);
  188. delete attrlist;
  189. delete attrlistptr;
  190. return 0;
  191. }
  192. */
  193. static v3_result V3_API carla_set_int(void* const self, const char* const id, const int64_t value)
  194. {
  195. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  196. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  197. v3_var var = {};
  198. var.type = 'i';
  199. var.value.i = value;
  200. return attrlist->add(id, var);
  201. }
  202. static v3_result V3_API carla_get_int(void* const self, const char* const id, int64_t* const value)
  203. {
  204. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  205. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  206. v3_var var = {};
  207. if (attrlist->get(id, var))
  208. {
  209. *value = var.value.i;
  210. return V3_OK;
  211. }
  212. return V3_INVALID_ARG;
  213. }
  214. static v3_result V3_API carla_set_float(void* const self, const char* const id, const double value)
  215. {
  216. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  217. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  218. v3_var var = {};
  219. var.type = 'f';
  220. var.value.f = value;
  221. return attrlist->add(id, var);
  222. }
  223. static v3_result V3_API carla_get_float(void* const self, const char* const id, double* const value)
  224. {
  225. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  226. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  227. v3_var var = {};
  228. if (attrlist->get(id, var))
  229. {
  230. *value = var.value.f;
  231. return V3_OK;
  232. }
  233. return V3_INVALID_ARG;
  234. }
  235. static v3_result V3_API carla_set_string(void* const self, const char* const id, const int16_t* const string)
  236. {
  237. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  238. CARLA_SAFE_ASSERT_RETURN(string != nullptr, V3_INVALID_ARG);
  239. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  240. const size_t size = sizeof(int16_t) * (strlen_utf16(string) + 1);
  241. int16_t* const s = static_cast<int16_t*>(std::malloc(size));
  242. CARLA_SAFE_ASSERT_RETURN(s != nullptr, V3_NOMEM);
  243. std::memcpy(s, string, size);
  244. v3_var var = {};
  245. var.type = 's';
  246. var.size = size;
  247. var.value.s = s;
  248. return attrlist->add(id, var);
  249. }
  250. static v3_result V3_API carla_get_string(void* const self, const char* const id,
  251. int16_t* const string, const uint32_t size)
  252. {
  253. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  254. CARLA_SAFE_ASSERT_RETURN(string != nullptr, V3_INVALID_ARG);
  255. CARLA_SAFE_ASSERT_RETURN(size != 0, V3_INVALID_ARG);
  256. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  257. v3_var var = {};
  258. if (attrlist->get(id, var))
  259. {
  260. CARLA_SAFE_ASSERT_UINT2_RETURN(var.size >= size, var.size, size, V3_INVALID_ARG);
  261. std::memcpy(string, var.value.s, size);
  262. return V3_OK;
  263. }
  264. return V3_INVALID_ARG;
  265. }
  266. static v3_result V3_API carla_set_binary(void* const self, const char* const id,
  267. const void* const data, const uint32_t size)
  268. {
  269. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  270. CARLA_SAFE_ASSERT_RETURN(data != nullptr, V3_INVALID_ARG);
  271. CARLA_SAFE_ASSERT_RETURN(size != 0, V3_INVALID_ARG);
  272. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  273. void* const b = std::malloc(size);
  274. CARLA_SAFE_ASSERT_RETURN(b != nullptr, V3_NOMEM);
  275. std::memcpy(b, data, size);
  276. v3_var var = {};
  277. var.type = 'b';
  278. var.size = size;
  279. var.value.b = b;
  280. return attrlist->add(id, var);
  281. }
  282. static v3_result V3_API carla_get_binary(void* const self, const char* const id,
  283. const void** const data, uint32_t* const size)
  284. {
  285. CARLA_SAFE_ASSERT_RETURN(id != nullptr, V3_INVALID_ARG);
  286. carla_v3_attribute_list* const attrlist = *static_cast<carla_v3_attribute_list**>(self);
  287. v3_var var = {};
  288. if (attrlist->get(id, var))
  289. {
  290. *data = var.value.b;
  291. *size = var.size;
  292. return V3_OK;
  293. }
  294. return V3_INVALID_ARG;
  295. }
  296. };
  297. struct carla_v3_message : v3_message_cpp {
  298. std::atomic<int> refcounter;
  299. carla_v3_attribute_list attrlist;
  300. carla_v3_attribute_list* attrlistptr;
  301. const char* msgId;
  302. carla_v3_message()
  303. : refcounter(1),
  304. attrlistptr(&attrlist),
  305. msgId(nullptr)
  306. {
  307. query_interface = carla_query_interface;
  308. ref = carla_ref;
  309. unref = carla_unref;
  310. msg.get_message_id = carla_get_message_id;
  311. msg.set_message_id = carla_set_message_id;
  312. msg.get_attributes = carla_get_attributes;
  313. }
  314. ~carla_v3_message()
  315. {
  316. delete[] msgId;
  317. }
  318. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  319. {
  320. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  321. carla_v3_message* const msg = *static_cast<carla_v3_message**>(self);
  322. if (v3_tuid_match(iid, v3_funknown_iid) ||
  323. v3_tuid_match(iid, v3_message_iid))
  324. {
  325. ++msg->refcounter;
  326. *iface = self;
  327. return V3_OK;
  328. }
  329. *iface = nullptr;
  330. carla_stdout("TODO carla_v3_message::query_interface %s", tuid2str(iid));
  331. return V3_NO_INTERFACE;
  332. }
  333. static uint32_t V3_API carla_ref(void* const self)
  334. {
  335. carla_v3_message* const msg = *static_cast<carla_v3_message**>(self);
  336. const int refcount = ++msg->refcounter;
  337. carla_debug("carla_v3_message::ref => %p | refcount %i", self, refcount);
  338. return refcount;
  339. }
  340. static uint32_t V3_API carla_unref(void* const self)
  341. {
  342. carla_v3_message** const msgptr = static_cast<carla_v3_message**>(self);
  343. carla_v3_message* const msg = *msgptr;
  344. if (const int refcount = --msg->refcounter)
  345. {
  346. carla_debug("carla_v3_message::unref => %p | refcount %i", self, refcount);
  347. return refcount;
  348. }
  349. carla_debug("carla_v3_message::unref => %p | refcount is zero, deleting factory", self);
  350. delete msg;
  351. delete msgptr;
  352. return 0;
  353. }
  354. static const char* V3_API carla_get_message_id(void* const self)
  355. {
  356. carla_v3_message* const msg = *static_cast<carla_v3_message**>(self);
  357. return msg->msgId;
  358. }
  359. static void V3_API carla_set_message_id(void* const self, const char* const id)
  360. {
  361. carla_v3_message* const msg = *static_cast<carla_v3_message**>(self);
  362. delete[] msg->msgId;
  363. msg->msgId = id != nullptr ? carla_strdup(id) : nullptr;
  364. }
  365. static v3_attribute_list** V3_API carla_get_attributes(void* const self)
  366. {
  367. carla_v3_message* const msg = *static_cast<carla_v3_message**>(self);
  368. return (v3_attribute_list**)&msg->attrlistptr;
  369. }
  370. CARLA_DECLARE_NON_COPYABLE(carla_v3_message)
  371. };
  372. // --------------------------------------------------------------------------------------------------------------------
  373. struct carla_v3_bstream : v3_bstream_cpp {
  374. void* buffer;
  375. int64_t size;
  376. int64_t pos;
  377. carla_v3_bstream()
  378. : buffer(nullptr),
  379. size(0),
  380. pos(0)
  381. {
  382. query_interface = carla_query_interface;
  383. ref = v3_ref_static;
  384. unref = v3_unref_static;
  385. stream.read = carla_read;
  386. stream.write = carla_write;
  387. stream.seek = carla_seek;
  388. stream.tell = carla_tell;
  389. }
  390. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  391. {
  392. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  393. if (v3_tuid_match(iid, v3_funknown_iid) ||
  394. v3_tuid_match(iid, v3_bstream_iid))
  395. {
  396. *iface = self;
  397. return V3_OK;
  398. }
  399. *iface = nullptr;
  400. carla_stdout("TODO carla_v3_bstream::query_interface %s", tuid2str(iid));
  401. return V3_NO_INTERFACE;
  402. }
  403. static v3_result carla_read(void* const self, void* const buffer, int32_t num_bytes, int32_t* const bytes_read)
  404. {
  405. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr, V3_INVALID_ARG);
  406. CARLA_SAFE_ASSERT_RETURN(num_bytes > 0, V3_INVALID_ARG);
  407. CARLA_SAFE_ASSERT_RETURN(bytes_read != nullptr, V3_INVALID_ARG);
  408. carla_v3_bstream* const stream = *static_cast<carla_v3_bstream**>(self);
  409. if (stream->pos + num_bytes > stream->size)
  410. num_bytes = stream->size - stream->pos;
  411. std::memcpy(buffer, static_cast<uint8_t*>(stream->buffer) + stream->pos, num_bytes);
  412. stream->pos += num_bytes;
  413. *bytes_read = num_bytes;
  414. return V3_OK;
  415. }
  416. static v3_result carla_write(void* const self,
  417. void* const buffer, const int32_t num_bytes, int32_t* const bytes_read)
  418. {
  419. CARLA_SAFE_ASSERT_RETURN(buffer != nullptr, V3_INVALID_ARG);
  420. CARLA_SAFE_ASSERT_RETURN(num_bytes > 0, V3_INVALID_ARG);
  421. CARLA_SAFE_ASSERT_RETURN(bytes_read != nullptr, V3_INVALID_ARG);
  422. carla_v3_bstream* const stream = *static_cast<carla_v3_bstream**>(self);
  423. const int64_t size = stream->size + num_bytes;
  424. void* const oldbuffer = stream->buffer;
  425. stream->buffer = std::realloc(oldbuffer, size); // FIXME detect alloc failure
  426. CARLA_SAFE_ASSERT_RETURN(stream->buffer != oldbuffer, V3_NOMEM);
  427. stream->size += num_bytes;
  428. *bytes_read = num_bytes;
  429. return V3_OK;
  430. }
  431. static v3_result carla_seek(void* const self, const int64_t pos, const int32_t seek_mode, int64_t* const result)
  432. {
  433. CARLA_SAFE_ASSERT_RETURN(result != nullptr, V3_INVALID_ARG);
  434. carla_v3_bstream* const stream = *static_cast<carla_v3_bstream**>(self);
  435. switch (seek_mode)
  436. {
  437. case V3_SEEK_SET:
  438. CARLA_SAFE_ASSERT_INT2_RETURN(pos <= stream->size, pos, stream->size, V3_INVALID_ARG);
  439. *result = stream->pos = pos;
  440. return V3_OK;
  441. case V3_SEEK_CUR:
  442. CARLA_SAFE_ASSERT_INT2_RETURN(stream->pos + pos <= stream->size, pos, stream->size, V3_INVALID_ARG);
  443. *result = stream->pos = stream->pos + pos;
  444. return V3_OK;
  445. case V3_SEEK_END:
  446. CARLA_SAFE_ASSERT_INT2_RETURN(pos <= stream->size, pos, stream->size, V3_INVALID_ARG);
  447. *result = stream->pos = stream->size - pos;
  448. return V3_OK;
  449. }
  450. return V3_INVALID_ARG;
  451. }
  452. static v3_result carla_tell(void* const self, int64_t* const pos)
  453. {
  454. CARLA_SAFE_ASSERT_RETURN(pos != nullptr, V3_INVALID_ARG);
  455. carla_v3_bstream* const stream = *static_cast<carla_v3_bstream**>(self);
  456. *pos = stream->pos;
  457. return V3_OK;
  458. }
  459. CARLA_DECLARE_NON_COPYABLE(carla_v3_bstream)
  460. };
  461. // --------------------------------------------------------------------------------------------------------------------
  462. struct carla_v3_host_application : v3_host_application_cpp {
  463. carla_v3_host_application()
  464. {
  465. query_interface = carla_query_interface;
  466. ref = v3_ref_static;
  467. unref = v3_unref_static;
  468. app.get_name = carla_get_name;
  469. app.create_instance = carla_create_instance;
  470. }
  471. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  472. {
  473. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  474. if (v3_tuid_match(iid, v3_funknown_iid) ||
  475. v3_tuid_match(iid, v3_host_application_iid))
  476. {
  477. *iface = self;
  478. return V3_OK;
  479. }
  480. *iface = nullptr;
  481. carla_stdout("TODO carla_v3_host_application::query_interface %s", tuid2str(iid));
  482. return V3_NO_INTERFACE;
  483. }
  484. static v3_result V3_API carla_get_name(void*, v3_str_128 name)
  485. {
  486. static const char hostname[] = "Carla\0";
  487. for (size_t i=0; i<sizeof(hostname); ++i)
  488. name[i] = hostname[i];
  489. return V3_OK;
  490. }
  491. static v3_result V3_API carla_create_instance(void*, v3_tuid cid, v3_tuid iid, void** const obj)
  492. {
  493. if (v3_tuid_match(cid, v3_message_iid) && (v3_tuid_match(iid, v3_message_iid) ||
  494. v3_tuid_match(iid, v3_funknown_iid)))
  495. {
  496. carla_v3_message** const messageptr = new carla_v3_message*;
  497. *messageptr = new carla_v3_message();
  498. *obj = static_cast<void*>(messageptr);
  499. return V3_OK;
  500. }
  501. carla_stdout("TODO carla_create_instance %s", tuid2str(cid));
  502. return V3_NOT_IMPLEMENTED;
  503. }
  504. CARLA_DECLARE_NON_COPYABLE(carla_v3_host_application)
  505. };
  506. // --------------------------------------------------------------------------------------------------------------------
  507. struct carla_v3_input_param_value_queue : v3_param_value_queue_cpp {
  508. const v3_param_id paramId;
  509. int8_t numUsed;
  510. struct Point {
  511. int32_t offset;
  512. float value;
  513. } points[32];
  514. carla_v3_input_param_value_queue(const v3_param_id pId)
  515. : paramId(pId),
  516. numUsed(0)
  517. {
  518. query_interface = carla_query_interface;
  519. ref = v3_ref_static;
  520. unref = v3_unref_static;
  521. queue.get_param_id = carla_get_param_id;
  522. queue.get_point_count = carla_get_point_count;
  523. queue.get_point = carla_get_point;
  524. queue.add_point = carla_add_point;
  525. }
  526. private:
  527. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  528. {
  529. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  530. if (v3_tuid_match(iid, v3_funknown_iid) ||
  531. v3_tuid_match(iid, v3_param_value_queue_iid))
  532. {
  533. *iface = self;
  534. return V3_OK;
  535. }
  536. *iface = nullptr;
  537. carla_stdout("TODO carla_v3_input_param_value_queue::query_interface %s", tuid2str(iid));
  538. return V3_NO_INTERFACE;
  539. }
  540. static v3_param_id V3_API carla_get_param_id(void* self)
  541. {
  542. carla_v3_input_param_value_queue* const me = *static_cast<carla_v3_input_param_value_queue**>(self);
  543. return me->paramId;
  544. }
  545. static int32_t V3_API carla_get_point_count(void* self)
  546. {
  547. carla_v3_input_param_value_queue* const me = *static_cast<carla_v3_input_param_value_queue**>(self);
  548. return me->numUsed;
  549. }
  550. static v3_result V3_API carla_get_point(void* const self,
  551. const int32_t idx, int32_t* const sample_offset, double* const value)
  552. {
  553. carla_v3_input_param_value_queue* const me = *static_cast<carla_v3_input_param_value_queue**>(self);
  554. CARLA_SAFE_ASSERT_INT2_RETURN(idx < me->numUsed, idx, me->numUsed, V3_INVALID_ARG);
  555. *sample_offset = me->points[idx].offset;
  556. *value = me->points[idx].value;
  557. return V3_OK;
  558. }
  559. static v3_result V3_API carla_add_point(void*, int32_t, double, int32_t*)
  560. {
  561. // there is nothing here for input parameters, plugins are not meant to call this!
  562. return V3_NOT_IMPLEMENTED;
  563. }
  564. CARLA_DECLARE_NON_COPYABLE(carla_v3_input_param_value_queue)
  565. };
  566. struct carla_v3_input_param_changes : v3_param_changes_cpp {
  567. const uint32_t paramCount;
  568. struct UpdatedParam {
  569. bool updated;
  570. float value;
  571. }* const updatedParams;
  572. carla_v3_input_param_value_queue** const queue;
  573. // data given to plugins
  574. v3_param_value_queue*** pluginExposedQueue;
  575. int32_t pluginExposedCount;
  576. carla_v3_input_param_changes(const PluginParameterData& paramData)
  577. : paramCount(paramData.count),
  578. updatedParams(new UpdatedParam[paramData.count]),
  579. queue(new carla_v3_input_param_value_queue*[paramData.count]),
  580. pluginExposedQueue(new v3_param_value_queue**[paramData.count]),
  581. pluginExposedCount(0)
  582. {
  583. for (uint32_t i=0; i<paramData.count; ++i)
  584. queue[i] = new carla_v3_input_param_value_queue(static_cast<v3_param_id>(paramData.data[i].rindex));
  585. query_interface = carla_query_interface;
  586. ref = v3_ref_static;
  587. unref = v3_unref_static;
  588. changes.get_param_count = carla_get_param_count;
  589. changes.get_param_data = carla_get_param_data;
  590. changes.add_param_data = carla_add_param_data;
  591. }
  592. // called during start of process, gathering all parameter update requests so far
  593. void init()
  594. {
  595. for (uint32_t i=0; i<paramCount; ++i)
  596. {
  597. if (updatedParams[i].updated)
  598. {
  599. queue[i]->numUsed = 1;
  600. queue[i]->points[0].offset = 0;
  601. queue[i]->points[0].value = updatedParams[i].value;
  602. }
  603. else
  604. {
  605. queue[i]->numUsed = 0;
  606. }
  607. }
  608. }
  609. // called just before plugin processing, creating local queue
  610. void prepare()
  611. {
  612. int32_t count = 0;
  613. for (uint32_t i=0; i<paramCount; ++i)
  614. {
  615. if (queue[i]->numUsed)
  616. pluginExposedQueue[count++] = (v3_param_value_queue**)&queue[i];
  617. }
  618. pluginExposedCount = count;
  619. }
  620. // called when a parameter is set from non-rt thread
  621. void setParamValue(const uint32_t index, const float value) noexcept
  622. {
  623. updatedParams[index].value = value;
  624. updatedParams[index].updated = true;
  625. }
  626. private:
  627. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  628. {
  629. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  630. if (v3_tuid_match(iid, v3_funknown_iid) ||
  631. v3_tuid_match(iid, v3_param_changes_iid))
  632. {
  633. *iface = self;
  634. return V3_OK;
  635. }
  636. *iface = nullptr;
  637. carla_stdout("TODO carla_v3_input_param_changes::query_interface %s", tuid2str(iid));
  638. return V3_NO_INTERFACE;
  639. }
  640. static int32_t V3_API carla_get_param_count(void* const self)
  641. {
  642. carla_v3_input_param_changes* const me = *static_cast<carla_v3_input_param_changes**>(self);
  643. return me->pluginExposedCount;
  644. }
  645. static v3_param_value_queue** V3_API carla_get_param_data(void* const self, const int32_t index)
  646. {
  647. carla_v3_input_param_changes* const me = *static_cast<carla_v3_input_param_changes**>(self);
  648. return me->pluginExposedQueue[index];
  649. }
  650. static v3_param_value_queue** V3_API carla_add_param_data(void*, v3_param_id*, int32_t*)
  651. {
  652. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  653. // there is nothing here for input parameters, plugins are not meant to call this!
  654. return nullptr;
  655. }
  656. CARLA_DECLARE_NON_COPYABLE(carla_v3_input_param_changes)
  657. };
  658. // --------------------------------------------------------------------------------------------------------------------
  659. struct carla_v3_output_param_changes : v3_param_changes_cpp {
  660. carla_v3_output_param_changes()
  661. {
  662. query_interface = carla_query_interface;
  663. ref = v3_ref_static;
  664. unref = v3_unref_static;
  665. changes.get_param_count = carla_get_param_count;
  666. changes.get_param_data = carla_get_param_data;
  667. changes.add_param_data = carla_add_param_data;
  668. }
  669. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  670. {
  671. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  672. if (v3_tuid_match(iid, v3_funknown_iid) ||
  673. v3_tuid_match(iid, v3_param_changes_iid))
  674. {
  675. *iface = self;
  676. return V3_OK;
  677. }
  678. *iface = nullptr;
  679. carla_stdout("TODO carla_v3_output_param_changes::query_interface %s", tuid2str(iid));
  680. return V3_NO_INTERFACE;
  681. }
  682. static int32_t V3_API carla_get_param_count(void*)
  683. {
  684. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  685. return 0;
  686. }
  687. static v3_param_value_queue** V3_API carla_get_param_data(void*, int32_t)
  688. {
  689. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  690. return nullptr;
  691. }
  692. static v3_param_value_queue** V3_API carla_add_param_data(void*, v3_param_id*, int32_t*)
  693. {
  694. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  695. return nullptr;
  696. }
  697. CARLA_DECLARE_NON_COPYABLE(carla_v3_output_param_changes)
  698. };
  699. // --------------------------------------------------------------------------------------------------------------------
  700. struct carla_v3_input_event_list : v3_event_list_cpp {
  701. v3_event events[kPluginMaxMidiEvents];
  702. uint16_t numEvents;
  703. carla_v3_input_event_list()
  704. : numEvents(0)
  705. {
  706. query_interface = carla_query_interface;
  707. ref = v3_ref_static;
  708. unref = v3_unref_static;
  709. list.get_event_count = carla_get_event_count;
  710. list.get_event = carla_get_event;
  711. list.add_event = carla_add_event;
  712. }
  713. private:
  714. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  715. {
  716. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  717. if (v3_tuid_match(iid, v3_funknown_iid) ||
  718. v3_tuid_match(iid, v3_event_list_iid))
  719. {
  720. *iface = self;
  721. return V3_OK;
  722. }
  723. *iface = nullptr;
  724. carla_stdout("TODO carla_v3_input_event_list::query_interface %s", tuid2str(iid));
  725. return V3_NO_INTERFACE;
  726. }
  727. static uint32_t V3_API carla_get_event_count(void* const self)
  728. {
  729. const carla_v3_input_event_list* const me = *static_cast<const carla_v3_input_event_list**>(self);
  730. return me->numEvents;
  731. }
  732. static v3_result V3_API carla_get_event(void* const self, const int32_t index, v3_event* const event)
  733. {
  734. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  735. const carla_v3_input_event_list* const me = *static_cast<const carla_v3_input_event_list**>(self);
  736. CARLA_SAFE_ASSERT_RETURN(index < static_cast<int32_t>(me->numEvents), V3_INVALID_ARG);
  737. std::memcpy(event, &me->events[index], sizeof(v3_event));
  738. return V3_OK;
  739. }
  740. static v3_result V3_API carla_add_event(void*, v3_event*)
  741. {
  742. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  743. // there is nothing here for input events, plugins are not meant to call this!
  744. return V3_NOT_IMPLEMENTED;
  745. }
  746. CARLA_DECLARE_NON_COPYABLE(carla_v3_input_event_list)
  747. };
  748. // --------------------------------------------------------------------------------------------------------------------
  749. struct carla_v3_output_event_list : v3_event_list_cpp {
  750. carla_v3_output_event_list()
  751. {
  752. query_interface = carla_query_interface;
  753. ref = v3_ref_static;
  754. unref = v3_unref_static;
  755. list.get_event_count = carla_get_event_count;
  756. list.get_event = carla_get_event;
  757. list.add_event = carla_add_event;
  758. }
  759. private:
  760. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  761. {
  762. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  763. if (v3_tuid_match(iid, v3_funknown_iid) ||
  764. v3_tuid_match(iid, v3_event_list_iid))
  765. {
  766. *iface = self;
  767. return V3_OK;
  768. }
  769. *iface = nullptr;
  770. carla_stdout("TODO carla_v3_output_event_list::query_interface %s", tuid2str(iid));
  771. return V3_NO_INTERFACE;
  772. }
  773. static uint32_t V3_API carla_get_event_count(void*)
  774. {
  775. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  776. return 0;
  777. }
  778. static v3_result V3_API carla_get_event(void*, int32_t, v3_event*)
  779. {
  780. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  781. return V3_NOT_IMPLEMENTED;
  782. }
  783. static v3_result V3_API carla_add_event(void*, v3_event*)
  784. {
  785. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  786. return V3_NOT_IMPLEMENTED;
  787. }
  788. CARLA_DECLARE_NON_COPYABLE(carla_v3_output_event_list)
  789. };
  790. // --------------------------------------------------------------------------------------------------------------------
  791. struct HostTimer {
  792. v3_timer_handler** handler;
  793. uint64_t periodInMs;
  794. uint64_t lastCallTimeInMs;
  795. };
  796. static constexpr const HostTimer kTimerFallback = { nullptr, 0, 0 };
  797. static /* */ HostTimer kTimerFallbackNC = { nullptr, 0, 0 };
  798. #ifdef _POSIX_VERSION
  799. struct HostPosixFileDescriptor {
  800. v3_event_handler** handler;
  801. int hostfd;
  802. int pluginfd;
  803. };
  804. static constexpr const HostPosixFileDescriptor kPosixFileDescriptorFallback = { nullptr, -1, -1 };
  805. static /* */ HostPosixFileDescriptor kPosixFileDescriptorFallbackNC = { nullptr, -1, -1 };
  806. #endif
  807. struct carla_v3_run_loop : v3_run_loop_cpp {
  808. LinkedList<HostTimer> timers;
  809. #ifdef _POSIX_VERSION
  810. LinkedList<HostPosixFileDescriptor> posixfds;
  811. #endif
  812. carla_v3_run_loop()
  813. {
  814. query_interface = carla_query_interface;
  815. ref = v3_ref_static;
  816. unref = v3_unref_static;
  817. loop.register_event_handler = carla_register_event_handler;
  818. loop.unregister_event_handler = carla_unregister_event_handler;
  819. loop.register_timer = carla_register_timer;
  820. loop.unregister_timer = carla_unregister_timer;
  821. }
  822. private:
  823. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  824. {
  825. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  826. if (v3_tuid_match(iid, v3_funknown_iid) ||
  827. v3_tuid_match(iid, v3_run_loop_iid))
  828. {
  829. *iface = self;
  830. return V3_OK;
  831. }
  832. *iface = nullptr;
  833. carla_stdout("TODO carla_v3_run_loop::query_interface %s", tuid2str(iid));
  834. return V3_NO_INTERFACE;
  835. }
  836. static v3_result V3_API carla_register_event_handler(void* const self,
  837. v3_event_handler** const handler, const int fd)
  838. {
  839. #ifdef _POSIX_VERSION
  840. carla_v3_run_loop* const loop = *static_cast<carla_v3_run_loop**>(self);
  841. #ifdef CARLA_VST3_POSIX_EPOLL
  842. const int hostfd = ::epoll_create1(0);
  843. #else
  844. const int hostfd = ::kqueue();
  845. #endif
  846. CARLA_SAFE_ASSERT_RETURN(hostfd >= 0, V3_INTERNAL_ERR);
  847. #ifdef CARLA_VST3_POSIX_EPOLL
  848. struct ::epoll_event ev = {};
  849. ev.events = EPOLLIN|EPOLLOUT;
  850. ev.data.fd = fd;
  851. if (::epoll_ctl(hostfd, EPOLL_CTL_ADD, fd, &ev) < 0)
  852. {
  853. ::close(hostfd);
  854. return V3_INTERNAL_ERR;
  855. }
  856. #endif
  857. const HostPosixFileDescriptor posixfd = { handler, hostfd, fd };
  858. return loop->posixfds.append(posixfd) ? V3_OK : V3_NOMEM;
  859. #else
  860. return V3_NOT_IMPLEMENTED;
  861. #endif
  862. }
  863. static v3_result V3_API carla_unregister_event_handler(void* const self, v3_event_handler** const handler)
  864. {
  865. #ifdef _POSIX_VERSION
  866. carla_v3_run_loop* const loop = *static_cast<carla_v3_run_loop**>(self);
  867. for (LinkedList<HostPosixFileDescriptor>::Itenerator it = loop->posixfds.begin2(); it.valid(); it.next())
  868. {
  869. const HostPosixFileDescriptor& posixfd(it.getValue(kPosixFileDescriptorFallback));
  870. if (posixfd.handler == handler)
  871. {
  872. #ifdef CARLA_VST3_POSIX_EPOLL
  873. ::epoll_ctl(posixfd.hostfd, EPOLL_CTL_DEL, posixfd.pluginfd, nullptr);
  874. #endif
  875. ::close(posixfd.hostfd);
  876. loop->posixfds.remove(it);
  877. return V3_OK;
  878. }
  879. }
  880. return V3_INVALID_ARG;
  881. #else
  882. return V3_NOT_IMPLEMENTED;
  883. #endif
  884. }
  885. static v3_result V3_API carla_register_timer(void* const self, v3_timer_handler** const handler, const uint64_t ms)
  886. {
  887. carla_v3_run_loop* const loop = *static_cast<carla_v3_run_loop**>(self);
  888. const HostTimer timer = { handler, ms, 0 };
  889. return loop->timers.append(timer) ? V3_OK : V3_NOMEM;
  890. }
  891. static v3_result V3_API carla_unregister_timer(void* const self, v3_timer_handler** const handler)
  892. {
  893. carla_v3_run_loop* const loop = *static_cast<carla_v3_run_loop**>(self);
  894. for (LinkedList<HostTimer>::Itenerator it = loop->timers.begin2(); it.valid(); it.next())
  895. {
  896. const HostTimer& timer(it.getValue(kTimerFallback));
  897. if (timer.handler == handler)
  898. {
  899. loop->timers.remove(it);
  900. return V3_OK;
  901. }
  902. }
  903. return V3_INVALID_ARG;
  904. }
  905. CARLA_DECLARE_NON_COPYABLE(carla_v3_run_loop)
  906. };
  907. // --------------------------------------------------------------------------------------------------------------------
  908. struct ComponentCallback {
  909. virtual ~ComponentCallback() {}
  910. virtual v3_result v3BeginEdit(v3_param_id) = 0;
  911. virtual v3_result v3PerformEdit(v3_param_id, double) = 0;
  912. virtual v3_result v3EndEdit(v3_param_id) = 0;
  913. virtual v3_result v3RestartComponent(int32_t) = 0;
  914. };
  915. struct carla_v3_component_handler : v3_component_handler_cpp {
  916. ComponentCallback* const callback;
  917. carla_v3_component_handler(ComponentCallback* const cb)
  918. : callback(cb)
  919. {
  920. query_interface = carla_query_interface;
  921. ref = v3_ref_static;
  922. unref = v3_unref_static;
  923. comp.begin_edit = carla_begin_edit;
  924. comp.perform_edit = carla_perform_edit;
  925. comp.end_edit = carla_end_edit;
  926. comp.restart_component = carla_restart_component;
  927. }
  928. private:
  929. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  930. {
  931. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  932. if (v3_tuid_match(iid, v3_funknown_iid) ||
  933. v3_tuid_match(iid, v3_component_handler_iid))
  934. {
  935. *iface = self;
  936. return V3_OK;
  937. }
  938. // TODO
  939. if (v3_tuid_match(iid, v3_component_handler2_iid))
  940. {
  941. *iface = nullptr;
  942. return V3_NO_INTERFACE;
  943. }
  944. *iface = nullptr;
  945. carla_stdout("TODO carla_v3_component_handler::query_interface %s", tuid2str(iid));
  946. return V3_NO_INTERFACE;
  947. }
  948. static v3_result V3_API carla_begin_edit(void* const self, const v3_param_id paramId)
  949. {
  950. carla_v3_component_handler* const comp = *static_cast<carla_v3_component_handler**>(self);
  951. return comp->callback->v3BeginEdit(paramId);
  952. }
  953. static v3_result V3_API carla_perform_edit(void* const self, const v3_param_id paramId, const double value)
  954. {
  955. carla_v3_component_handler* const comp = *static_cast<carla_v3_component_handler**>(self);
  956. return comp->callback->v3PerformEdit(paramId, value);
  957. }
  958. static v3_result V3_API carla_end_edit(void* const self, const v3_param_id paramId)
  959. {
  960. carla_v3_component_handler* const comp = *static_cast<carla_v3_component_handler**>(self);
  961. return comp->callback->v3EndEdit(paramId);
  962. }
  963. static v3_result V3_API carla_restart_component(void* const self, const int32_t flags)
  964. {
  965. carla_v3_component_handler* const comp = *static_cast<carla_v3_component_handler**>(self);
  966. return comp->callback->v3RestartComponent(flags);
  967. }
  968. CARLA_DECLARE_NON_COPYABLE(carla_v3_component_handler)
  969. };
  970. // --------------------------------------------------------------------------------------------------------------------
  971. struct carla_v3_plugin_frame : v3_plugin_frame_cpp {
  972. CarlaPluginUI::Callback* const callback;
  973. carla_v3_run_loop loop;
  974. carla_v3_run_loop* loopPtr;
  975. carla_v3_plugin_frame(CarlaPluginUI::Callback* const cb)
  976. : callback(cb),
  977. loopPtr(&loop)
  978. {
  979. query_interface = carla_query_interface;
  980. ref = v3_ref_static;
  981. unref = v3_unref_static;
  982. frame.resize_view = carla_resize_view;
  983. }
  984. private:
  985. static v3_result V3_API carla_query_interface(void* const self, const v3_tuid iid, void** const iface)
  986. {
  987. carla_debug("%s %s %p", __PRETTY_FUNCTION__, tuid2str(iid), iface);
  988. carla_v3_plugin_frame* const frame = *static_cast<carla_v3_plugin_frame**>(self);
  989. if (v3_tuid_match(iid, v3_funknown_iid) ||
  990. v3_tuid_match(iid, v3_plugin_frame_iid))
  991. {
  992. *iface = self;
  993. return V3_OK;
  994. }
  995. if (v3_tuid_match(iid, v3_run_loop_iid))
  996. {
  997. *iface = &frame->loopPtr;
  998. return V3_OK;
  999. }
  1000. *iface = nullptr;
  1001. carla_stdout("TODO carla_v3_plugin_frame::query_interface %s", tuid2str(iid));
  1002. return V3_NO_INTERFACE;
  1003. }
  1004. static v3_result V3_API carla_resize_view(void* const self,
  1005. struct v3_plugin_view**,
  1006. struct v3_view_rect* const rect)
  1007. {
  1008. carla_debug("TODO %s", __PRETTY_FUNCTION__);
  1009. const carla_v3_plugin_frame* const me = *static_cast<const carla_v3_plugin_frame**>(self);
  1010. me->callback->handlePluginUIResized(rect->right - rect->left, rect->bottom - rect->top);
  1011. return V3_OK;
  1012. }
  1013. CARLA_DECLARE_NON_COPYABLE(carla_v3_plugin_frame)
  1014. };
  1015. // --------------------------------------------------------------------------------------------------------------------
  1016. class CarlaPluginVST3 : public CarlaPlugin,
  1017. private CarlaPluginUI::Callback,
  1018. private ComponentCallback
  1019. {
  1020. public:
  1021. CarlaPluginVST3(CarlaEngine* const engine, const uint id)
  1022. : CarlaPlugin(engine, id),
  1023. kEngineHasIdleOnMainThread(engine->hasIdleOnMainThread()),
  1024. fFirstActive(true),
  1025. fAudioAndCvOutBuffers(nullptr),
  1026. fLastKnownLatency(0),
  1027. fRestartFlags(0),
  1028. fLastTimeInfo(),
  1029. fV3TimeContext(),
  1030. fV3Application(),
  1031. fV3ApplicationPtr(&fV3Application),
  1032. fComponentHandler(this),
  1033. fComponentHandlerPtr(&fComponentHandler),
  1034. fPluginFrame(this),
  1035. fPluginFramePtr(&fPluginFrame),
  1036. fV3ClassInfo(),
  1037. fV3(),
  1038. fEvents(),
  1039. fUI()
  1040. {
  1041. carla_debug("CarlaPluginVST3::CarlaPluginVST3(%p, %i)", engine, id);
  1042. carla_zeroStruct(fV3TimeContext);
  1043. }
  1044. ~CarlaPluginVST3() override
  1045. {
  1046. carla_debug("CarlaPluginVST3::~CarlaPluginVST3()");
  1047. runIdleCallbacksAsNeeded(false);
  1048. // close UI
  1049. if (pData->hints & PLUGIN_HAS_CUSTOM_UI)
  1050. {
  1051. if (! fUI.isEmbed)
  1052. showCustomUI(false);
  1053. if (fUI.isAttached)
  1054. {
  1055. fUI.isAttached = false;
  1056. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1057. v3_cpp_obj(fV3.view)->removed(fV3.view);
  1058. }
  1059. }
  1060. if (fV3.view != nullptr)
  1061. {
  1062. v3_cpp_obj_unref(fV3.view);
  1063. fV3.view = nullptr;
  1064. }
  1065. pData->singleMutex.lock();
  1066. pData->masterMutex.lock();
  1067. if (pData->client != nullptr && pData->client->isActive())
  1068. pData->client->deactivate(true);
  1069. if (pData->active)
  1070. {
  1071. deactivate();
  1072. pData->active = false;
  1073. }
  1074. clearBuffers();
  1075. fV3.exit();
  1076. }
  1077. // -------------------------------------------------------------------
  1078. // Information (base)
  1079. PluginType getType() const noexcept override
  1080. {
  1081. return PLUGIN_VST3;
  1082. }
  1083. PluginCategory getCategory() const noexcept override
  1084. {
  1085. return getPluginCategoryFromV3SubCategories(fV3ClassInfo.v2.sub_categories);
  1086. }
  1087. uint32_t getLatencyInFrames() const noexcept override
  1088. {
  1089. return fLastKnownLatency;
  1090. }
  1091. // -------------------------------------------------------------------
  1092. // Information (count)
  1093. /* TODO
  1094. uint32_t getMidiInCount() const noexcept override
  1095. {
  1096. }
  1097. uint32_t getMidiOutCount() const noexcept override
  1098. {
  1099. }
  1100. uint32_t getParameterScalePointCount(uint32_t parameterId) const noexcept override
  1101. {
  1102. }
  1103. */
  1104. // -------------------------------------------------------------------
  1105. // Information (current data)
  1106. /* TODO
  1107. std::size_t getChunkData(void** dataPtr) noexcept override
  1108. {
  1109. }
  1110. */
  1111. // -------------------------------------------------------------------
  1112. // Information (per-plugin data)
  1113. uint getOptionsAvailable() const noexcept override
  1114. {
  1115. uint options = 0x0;
  1116. // can't disable fixed buffers if using latency
  1117. if (fLastKnownLatency == 0)
  1118. options |= PLUGIN_OPTION_FIXED_BUFFERS;
  1119. /* TODO
  1120. if (numPrograms > 1)
  1121. options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  1122. */
  1123. options |= PLUGIN_OPTION_USE_CHUNKS;
  1124. /* TODO
  1125. if (hasMidiInput())
  1126. {
  1127. options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  1128. options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  1129. options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  1130. options |= PLUGIN_OPTION_SEND_PITCHBEND;
  1131. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1132. options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  1133. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1134. }
  1135. */
  1136. return options;
  1137. }
  1138. float getParameterValue(const uint32_t parameterId) const noexcept override
  1139. {
  1140. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, 0.0f);
  1141. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, 0.0f);
  1142. const v3_param_id v3id = pData->param.data[parameterId].rindex;
  1143. const double normalized = v3_cpp_obj(fV3.controller)->get_parameter_normalised(fV3.controller, v3id);
  1144. return static_cast<float>(
  1145. v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, v3id, normalized));
  1146. }
  1147. /* TODO
  1148. float getParameterScalePointValue(uint32_t parameterId, uint32_t scalePointId) const noexcept override
  1149. {
  1150. }
  1151. */
  1152. bool getLabel(char* const strBuf) const noexcept override
  1153. {
  1154. std::strncpy(strBuf, fV3ClassInfo.v1.name, STR_MAX);
  1155. return true;
  1156. }
  1157. bool getMaker(char* const strBuf) const noexcept override
  1158. {
  1159. std::strncpy(strBuf, fV3ClassInfo.v2.vendor, STR_MAX);
  1160. return true;
  1161. }
  1162. bool getCopyright(char* const strBuf) const noexcept override
  1163. {
  1164. return getMaker(strBuf);
  1165. }
  1166. bool getRealName(char* const strBuf) const noexcept override
  1167. {
  1168. std::strncpy(strBuf, fV3ClassInfo.v1.name, STR_MAX);
  1169. return true;
  1170. }
  1171. bool getParameterName(const uint32_t parameterId, char* const strBuf) const noexcept override
  1172. {
  1173. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, 0.0f);
  1174. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  1175. v3_param_info paramInfo = {};
  1176. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller,
  1177. static_cast<int32_t>(parameterId),
  1178. &paramInfo) == V3_OK, false);
  1179. strncpy_utf8(strBuf, paramInfo.title, STR_MAX);
  1180. return true;
  1181. }
  1182. /* TODO
  1183. bool getParameterSymbol(uint32_t parameterId, char* strBuf) const noexcept override
  1184. {
  1185. }
  1186. */
  1187. bool getParameterText(const uint32_t parameterId, char* const strBuf) noexcept override
  1188. {
  1189. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, false);
  1190. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  1191. const v3_param_id v3id = pData->param.data[parameterId].rindex;
  1192. const double normalized = v3_cpp_obj(fV3.controller)->get_parameter_normalised(fV3.controller, v3id);
  1193. v3_str_128 paramText;
  1194. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_string_for_value(fV3.controller,
  1195. v3id,
  1196. normalized,
  1197. paramText) == V3_OK, false);
  1198. if (paramText[0] != '\0')
  1199. strncpy_utf8(strBuf, paramText, STR_MAX);
  1200. else
  1201. std::snprintf(strBuf, STR_MAX, "%.12g",
  1202. v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, v3id, normalized));
  1203. return true;
  1204. }
  1205. bool getParameterUnit(const uint32_t parameterId, char* const strBuf) const noexcept override
  1206. {
  1207. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, false);
  1208. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count, false);
  1209. v3_param_info paramInfo = {};
  1210. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller,
  1211. static_cast<int32_t>(parameterId),
  1212. &paramInfo) == V3_OK, false);
  1213. strncpy_utf8(strBuf, paramInfo.units, STR_MAX);
  1214. return true;
  1215. }
  1216. /* TODO
  1217. bool getParameterGroupName(uint32_t parameterId, char* strBuf) const noexcept override
  1218. {
  1219. }
  1220. bool getParameterScalePointLabel(uint32_t parameterId, uint32_t scalePointId, char* strBuf) const noexcept override
  1221. {
  1222. }
  1223. */
  1224. // -------------------------------------------------------------------
  1225. // Set data (state)
  1226. /* TODO
  1227. void prepareForSave(const bool temporary) override
  1228. {
  1229. // component to edit controller state or vice-versa here
  1230. }
  1231. */
  1232. // -------------------------------------------------------------------
  1233. // Set data (internal stuff)
  1234. /* TODO
  1235. void setName(const char* newName) override
  1236. {
  1237. }
  1238. */
  1239. // -------------------------------------------------------------------
  1240. // Set data (plugin-specific stuff)
  1241. void setParameterValue(const uint32_t parameterId, const float value, const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  1242. {
  1243. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1244. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  1245. const v3_param_id v3id = pData->param.data[parameterId].rindex;
  1246. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  1247. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  1248. v3id,
  1249. fixedValue);
  1250. // report value to component (next process call)
  1251. fEvents.paramInputs->setParamValue(parameterId, static_cast<float>(normalized));
  1252. // report value to edit controller
  1253. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, v3id, normalized);
  1254. CarlaPlugin::setParameterValue(parameterId, fixedValue, sendGui, sendOsc, sendCallback);
  1255. }
  1256. void setParameterValueRT(const uint32_t parameterId, const float value, const uint32_t frameOffset, const bool sendCallbackLater) noexcept override
  1257. {
  1258. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1259. CARLA_SAFE_ASSERT_RETURN(parameterId < pData->param.count,);
  1260. const v3_param_id v3id = pData->param.data[parameterId].rindex;
  1261. const float fixedValue = pData->param.getFixedValue(parameterId, value);
  1262. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  1263. v3id,
  1264. fixedValue);
  1265. // report value to component (next process call)
  1266. fEvents.paramInputs->setParamValue(parameterId, static_cast<float>(normalized));
  1267. CarlaPlugin::setParameterValueRT(parameterId, fixedValue, frameOffset, sendCallbackLater);
  1268. }
  1269. /*
  1270. void setChunkData(const void* data, std::size_t dataSize) override
  1271. {
  1272. }
  1273. */
  1274. // -------------------------------------------------------------------
  1275. // Set ui stuff
  1276. void setCustomUITitle(const char* const title) noexcept override
  1277. {
  1278. if (fUI.window != nullptr)
  1279. {
  1280. try {
  1281. fUI.window->setTitle(title);
  1282. } CARLA_SAFE_EXCEPTION("set custom ui title");
  1283. }
  1284. CarlaPlugin::setCustomUITitle(title);
  1285. }
  1286. void showCustomUI(const bool yesNo) override
  1287. {
  1288. if (fUI.isVisible == yesNo)
  1289. return;
  1290. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr,);
  1291. if (yesNo)
  1292. {
  1293. CarlaString uiTitle;
  1294. if (pData->uiTitle.isNotEmpty())
  1295. {
  1296. uiTitle = pData->uiTitle;
  1297. }
  1298. else
  1299. {
  1300. uiTitle = pData->name;
  1301. uiTitle += " (GUI)";
  1302. }
  1303. if (fUI.window == nullptr)
  1304. {
  1305. const char* msg = nullptr;
  1306. const EngineOptions& opts(pData->engine->getOptions());
  1307. #if defined(CARLA_OS_MAC)
  1308. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, opts.pluginsAreStandalone, false);
  1309. #elif defined(CARLA_OS_WIN)
  1310. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, opts.pluginsAreStandalone, false);
  1311. #elif defined(HAVE_X11)
  1312. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, opts.pluginsAreStandalone, false, false);
  1313. #else
  1314. msg = "Unsupported UI type";
  1315. #endif
  1316. if (fUI.window == nullptr)
  1317. return pData->engine->callback(true, true,
  1318. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1319. pData->id,
  1320. -1,
  1321. 0, 0, 0.0f,
  1322. msg);
  1323. fUI.window->setTitle(uiTitle.buffer());
  1324. #ifndef CARLA_OS_MAC
  1325. // TODO inform plugin of what UI scale we use
  1326. #endif
  1327. v3_cpp_obj(fV3.view)->set_frame(fV3.view, (v3_plugin_frame**)&fPluginFramePtr);
  1328. if (v3_cpp_obj(fV3.view)->attached(fV3.view, fUI.window->getPtr(),
  1329. V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_OK)
  1330. {
  1331. v3_view_rect rect = {};
  1332. if (v3_cpp_obj(fV3.view)->get_size(fV3.view, &rect) == V3_OK)
  1333. {
  1334. const int32_t width = rect.right - rect.left;
  1335. const int32_t height = rect.bottom - rect.top;
  1336. carla_stdout("view attached ok, size %i %i", width, height);
  1337. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  1338. if (width > 1 && height > 1)
  1339. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true, true);
  1340. }
  1341. else
  1342. {
  1343. carla_stdout("view attached ok, size failed");
  1344. }
  1345. }
  1346. else
  1347. {
  1348. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1349. delete fUI.window;
  1350. fUI.window = nullptr;
  1351. carla_stderr2("Plugin refused to open its own UI");
  1352. return pData->engine->callback(true, true,
  1353. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1354. pData->id,
  1355. -1,
  1356. 0, 0, 0.0f,
  1357. "Plugin refused to open its own UI");
  1358. }
  1359. }
  1360. fUI.window->show();
  1361. fUI.isVisible = true;
  1362. }
  1363. else
  1364. {
  1365. fUI.isVisible = false;
  1366. if (fUI.isEmbed && fUI.isAttached)
  1367. {
  1368. fUI.isAttached = false;
  1369. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1370. v3_cpp_obj(fV3.view)->removed(fV3.view);
  1371. }
  1372. if (fUI.window != nullptr)
  1373. fUI.window->hide();
  1374. }
  1375. runIdleCallbacksAsNeeded(true);
  1376. }
  1377. void* embedCustomUI(void* const ptr) override
  1378. {
  1379. CARLA_SAFE_ASSERT_RETURN(fUI.window == nullptr, nullptr);
  1380. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr, nullptr);
  1381. v3_cpp_obj(fV3.view)->set_frame(fV3.view, (v3_plugin_frame**)&fPluginFramePtr);
  1382. #ifndef CARLA_OS_MAC
  1383. const EngineOptions& opts(pData->engine->getOptions());
  1384. if (carla_isNotZero(opts.uiScale))
  1385. {
  1386. // TODO
  1387. }
  1388. #endif
  1389. if (v3_cpp_obj(fV3.view)->attached(fV3.view, ptr, V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_OK)
  1390. {
  1391. fUI.isAttached = true;
  1392. fUI.isEmbed = true;
  1393. fUI.isVisible = true;
  1394. v3_view_rect rect = {};
  1395. if (v3_cpp_obj(fV3.view)->get_size(fV3.view, &rect) == V3_OK)
  1396. {
  1397. const int32_t width = rect.right - rect.left;
  1398. const int32_t height = rect.bottom - rect.top;
  1399. carla_stdout("view attached ok, size %i %i", width, height);
  1400. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  1401. if (width > 1 && height > 1)
  1402. pData->engine->callback(true, true,
  1403. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  1404. pData->id, width, height,
  1405. 0, 0.0f, nullptr);
  1406. }
  1407. else
  1408. {
  1409. carla_stdout("view attached ok, size failed");
  1410. }
  1411. }
  1412. else
  1413. {
  1414. fUI.isVisible = false;
  1415. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1416. carla_stderr2("Plugin refused to open its own UI");
  1417. pData->engine->callback(true, true,
  1418. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1419. pData->id,
  1420. -1,
  1421. 0, 0, 0.0f,
  1422. "Plugin refused to open its own UI");
  1423. }
  1424. return nullptr;
  1425. }
  1426. void runIdleCallbacksAsNeeded(const bool isIdleCallback)
  1427. {
  1428. int32_t flags = fRestartFlags;
  1429. if (isIdleCallback)
  1430. {
  1431. }
  1432. fRestartFlags = flags;
  1433. #ifdef _POSIX_VERSION
  1434. LinkedList<HostPosixFileDescriptor>& posixfds(fPluginFrame.loop.posixfds);
  1435. if (posixfds.isNotEmpty())
  1436. {
  1437. for (LinkedList<HostPosixFileDescriptor>::Itenerator it = posixfds.begin2(); it.valid(); it.next())
  1438. {
  1439. HostPosixFileDescriptor& posixfd(it.getValue(kPosixFileDescriptorFallbackNC));
  1440. #ifdef CARLA_VST3_POSIX_EPOLL
  1441. struct ::epoll_event event;
  1442. #else
  1443. const int16_t filter = EVFILT_WRITE;
  1444. struct ::kevent kev = {}, event;
  1445. struct ::timespec timeout = {};
  1446. EV_SET(&kev, posixfd.pluginfd, filter, EV_ADD|EV_ENABLE, 0, 0, nullptr);
  1447. #endif
  1448. for (int i=0; i<50; ++i)
  1449. {
  1450. #ifdef CARLA_VST3_POSIX_EPOLL
  1451. switch (::epoll_wait(posixfd.hostfd, &event, 1, 0))
  1452. #else
  1453. switch (::kevent(posixfd.hostfd, &kev, 1, &event, 1, &timeout))
  1454. #endif
  1455. {
  1456. case 1:
  1457. v3_cpp_obj(posixfd.handler)->on_fd_is_set(posixfd.handler, posixfd.pluginfd);
  1458. break;
  1459. case -1:
  1460. // fall through
  1461. case 0:
  1462. i = 50;
  1463. break;
  1464. default:
  1465. carla_safe_exception("posix fd received abnormal value", __FILE__, __LINE__);
  1466. i = 50;
  1467. break;
  1468. }
  1469. }
  1470. }
  1471. }
  1472. #endif
  1473. LinkedList<HostTimer>& timers(fPluginFrame.loop.timers);
  1474. if (timers.isNotEmpty())
  1475. {
  1476. for (LinkedList<HostTimer>::Itenerator it = timers.begin2(); it.valid(); it.next())
  1477. {
  1478. HostTimer& timer(it.getValue(kTimerFallbackNC));
  1479. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  1480. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  1481. {
  1482. timer.lastCallTimeInMs = currentTimeInMs;
  1483. v3_cpp_obj(timer.handler)->on_timer(timer.handler);
  1484. }
  1485. }
  1486. }
  1487. }
  1488. void idle() override
  1489. {
  1490. if (kEngineHasIdleOnMainThread)
  1491. runIdleCallbacksAsNeeded(true);
  1492. CarlaPlugin::idle();
  1493. }
  1494. void uiIdle() override
  1495. {
  1496. if (fUI.window != nullptr)
  1497. fUI.window->idle();
  1498. if (!kEngineHasIdleOnMainThread)
  1499. runIdleCallbacksAsNeeded(true);
  1500. CarlaPlugin::uiIdle();
  1501. }
  1502. // -------------------------------------------------------------------
  1503. // Plugin state
  1504. void reload() override
  1505. {
  1506. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1507. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1508. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1509. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1510. carla_debug("CarlaPluginVST3::reload() - start");
  1511. // Safely disable plugin for reload
  1512. const ScopedDisabler sd(this);
  1513. if (pData->active)
  1514. deactivate();
  1515. clearBuffers();
  1516. const int32_t numAudioInputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_AUDIO, V3_INPUT);
  1517. const int32_t numAudioOutputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_AUDIO, V3_OUTPUT);
  1518. const int32_t numEventInputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_INPUT);
  1519. const int32_t numEventOutputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_OUTPUT);
  1520. const int32_t numParameters = v3_cpp_obj(fV3.controller)->get_parameter_count(fV3.controller);
  1521. CARLA_SAFE_ASSERT(numAudioInputBuses >= 0);
  1522. CARLA_SAFE_ASSERT(numAudioOutputBuses >= 0);
  1523. CARLA_SAFE_ASSERT(numEventInputBuses >= 0);
  1524. CARLA_SAFE_ASSERT(numEventOutputBuses >= 0);
  1525. CARLA_SAFE_ASSERT(numParameters >= 0);
  1526. uint32_t aIns, aOuts, cvIns, cvOuts, params;
  1527. aIns = aOuts = cvIns = cvOuts = params = 0;
  1528. bool needsCtrlIn, needsCtrlOut;
  1529. needsCtrlIn = needsCtrlOut = false;
  1530. for (int32_t j=0; j<numAudioInputBuses; ++j)
  1531. {
  1532. v3_bus_info busInfo = {};
  1533. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_INPUT, j, &busInfo) == V3_OK);
  1534. CARLA_SAFE_ASSERT_BREAK(busInfo.channel_count >= 0);
  1535. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  1536. cvIns += static_cast<uint32_t>(busInfo.channel_count);
  1537. else
  1538. aIns += static_cast<uint32_t>(busInfo.channel_count);
  1539. }
  1540. for (int32_t j=0; j<numAudioOutputBuses; ++j)
  1541. {
  1542. v3_bus_info busInfo = {};
  1543. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_OUTPUT, j, &busInfo) == V3_OK);
  1544. CARLA_SAFE_ASSERT_BREAK(busInfo.channel_count >= 0);
  1545. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  1546. cvOuts += static_cast<uint32_t>(busInfo.channel_count);
  1547. else
  1548. aOuts += static_cast<uint32_t>(busInfo.channel_count);
  1549. }
  1550. for (int32_t j=0; j<numParameters; ++j)
  1551. {
  1552. v3_param_info paramInfo = {};
  1553. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller, j, &paramInfo) == V3_OK);
  1554. if ((paramInfo.flags & (V3_PARAM_IS_BYPASS|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE)) == 0x0)
  1555. ++params;
  1556. }
  1557. if (aIns > 0)
  1558. {
  1559. pData->audioIn.createNew(aIns);
  1560. }
  1561. if (aOuts > 0)
  1562. {
  1563. pData->audioOut.createNew(aOuts);
  1564. needsCtrlIn = true;
  1565. }
  1566. if (cvIns > 0)
  1567. pData->cvIn.createNew(cvIns);
  1568. if (cvOuts > 0)
  1569. pData->cvOut.createNew(cvOuts);
  1570. if (numEventInputBuses > 0)
  1571. needsCtrlIn = true;
  1572. if (numEventOutputBuses > 0)
  1573. needsCtrlOut = true;
  1574. if (params > 0)
  1575. {
  1576. pData->param.createNew(params, false);
  1577. needsCtrlIn = true;
  1578. }
  1579. if (aOuts + cvIns > 0)
  1580. {
  1581. fAudioAndCvOutBuffers = new float*[aOuts + cvIns];
  1582. for (uint32_t i=0; i < aOuts + cvIns; ++i)
  1583. fAudioAndCvOutBuffers[i] = nullptr;
  1584. }
  1585. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1586. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1587. CarlaString portName;
  1588. // Audio Ins
  1589. for (uint32_t j=0; j < aIns; ++j)
  1590. {
  1591. portName.clear();
  1592. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1593. {
  1594. portName = pData->name;
  1595. portName += ":";
  1596. }
  1597. if (aIns > 1)
  1598. {
  1599. portName += "input_";
  1600. portName += CarlaString(j+1);
  1601. }
  1602. else
  1603. portName += "input";
  1604. portName.truncate(portNameSize);
  1605. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, true, j);
  1606. pData->audioIn.ports[j].rindex = j;
  1607. }
  1608. // Audio Outs
  1609. for (uint32_t j=0; j < aOuts; ++j)
  1610. {
  1611. portName.clear();
  1612. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1613. {
  1614. portName = pData->name;
  1615. portName += ":";
  1616. }
  1617. if (aOuts > 1)
  1618. {
  1619. portName += "output_";
  1620. portName += CarlaString(j+1);
  1621. }
  1622. else
  1623. portName += "output";
  1624. portName.truncate(portNameSize);
  1625. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio, portName, false, j);
  1626. pData->audioOut.ports[j].rindex = j;
  1627. }
  1628. // CV Ins
  1629. for (uint32_t j=0; j < cvIns; ++j)
  1630. {
  1631. portName.clear();
  1632. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1633. {
  1634. portName = pData->name;
  1635. portName += ":";
  1636. }
  1637. if (cvIns > 1)
  1638. {
  1639. portName += "cv_input_";
  1640. portName += CarlaString(j+1);
  1641. }
  1642. else
  1643. portName += "cv_input";
  1644. portName.truncate(portNameSize);
  1645. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, true, j);
  1646. pData->cvIn.ports[j].rindex = j;
  1647. }
  1648. // CV Outs
  1649. for (uint32_t j=0; j < cvOuts; ++j)
  1650. {
  1651. portName.clear();
  1652. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1653. {
  1654. portName = pData->name;
  1655. portName += ":";
  1656. }
  1657. if (cvOuts > 1)
  1658. {
  1659. portName += "cv_output_";
  1660. portName += CarlaString(j+1);
  1661. }
  1662. else
  1663. portName += "cv_output";
  1664. portName.truncate(portNameSize);
  1665. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV, portName, false, j);
  1666. pData->cvOut.ports[j].rindex = j;
  1667. }
  1668. for (uint32_t j=0; j < params; ++j)
  1669. {
  1670. v3_param_info paramInfo = {};
  1671. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller, j, &paramInfo) == V3_OK);
  1672. const v3_param_id v3id = paramInfo.param_id;
  1673. pData->param.data[j].index = j;
  1674. pData->param.data[j].rindex = v3id;
  1675. if (paramInfo.flags & (V3_PARAM_IS_BYPASS|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  1676. continue;
  1677. double min, max, def, step, stepSmall, stepLarge;
  1678. min = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, v3id, 0.0);
  1679. max = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, v3id, 1.0);
  1680. def = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, v3id,
  1681. paramInfo.default_normalised_value);
  1682. if (min >= max)
  1683. max = min + 0.1;
  1684. if (def < min)
  1685. def = min;
  1686. else if (def > max)
  1687. def = max;
  1688. if (paramInfo.flags & V3_PARAM_READ_ONLY)
  1689. pData->param.data[j].type = PARAMETER_OUTPUT;
  1690. else
  1691. pData->param.data[j].type = PARAMETER_INPUT;
  1692. if (paramInfo.step_count == 1)
  1693. {
  1694. step = max - min;
  1695. stepSmall = step;
  1696. stepLarge = step;
  1697. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  1698. }
  1699. /*
  1700. else if (paramInfo.step_count != 0 && (paramInfo.flags & V3_PARAM_IS_LIST) != 0x0)
  1701. {
  1702. step = 1.0;
  1703. stepSmall = 1.0;
  1704. stepLarge = std::min(max - min, 10.0);
  1705. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  1706. }
  1707. */
  1708. else
  1709. {
  1710. float range = max - min;
  1711. step = range/100.0;
  1712. stepSmall = range/1000.0;
  1713. stepLarge = range/10.0;
  1714. }
  1715. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  1716. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1717. if (paramInfo.flags & V3_PARAM_CAN_AUTOMATE)
  1718. {
  1719. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  1720. if ((paramInfo.flags & V3_PARAM_IS_LIST) == 0x0)
  1721. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1722. }
  1723. pData->param.ranges[j].min = min;
  1724. pData->param.ranges[j].max = max;
  1725. pData->param.ranges[j].def = def;
  1726. pData->param.ranges[j].step = step;
  1727. pData->param.ranges[j].stepSmall = stepSmall;
  1728. pData->param.ranges[j].stepLarge = stepLarge;
  1729. }
  1730. if (params > 0)
  1731. {
  1732. fEvents.paramInputs = new carla_v3_input_param_changes(pData->param);
  1733. fEvents.paramOutputs = new carla_v3_output_param_changes;
  1734. }
  1735. if (needsCtrlIn)
  1736. {
  1737. portName.clear();
  1738. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1739. {
  1740. portName = pData->name;
  1741. portName += ":";
  1742. }
  1743. portName += "events-in";
  1744. portName.truncate(portNameSize);
  1745. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, true, 0);
  1746. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1747. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1748. #endif
  1749. fEvents.eventInputs = new carla_v3_input_event_list;
  1750. }
  1751. if (needsCtrlOut)
  1752. {
  1753. portName.clear();
  1754. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1755. {
  1756. portName = pData->name;
  1757. portName += ":";
  1758. }
  1759. portName += "events-out";
  1760. portName.truncate(portNameSize);
  1761. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent, portName, false, 0);
  1762. fEvents.eventOutputs = new carla_v3_output_event_list;
  1763. }
  1764. // plugin hints
  1765. const PluginCategory v3category = getPluginCategoryFromV3SubCategories(fV3ClassInfo.v2.sub_categories);
  1766. pData->hints = 0x0;
  1767. if (v3category == PLUGIN_CATEGORY_SYNTH)
  1768. pData->hints |= PLUGIN_IS_SYNTH;
  1769. if (fV3.view != nullptr &&
  1770. v3_cpp_obj(fV3.view)->is_platform_type_supported(fV3.view, V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_TRUE)
  1771. {
  1772. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1773. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1774. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1775. }
  1776. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1777. pData->hints |= PLUGIN_CAN_DRYWET;
  1778. if (aOuts > 0)
  1779. pData->hints |= PLUGIN_CAN_VOLUME;
  1780. if (aOuts >= 2 && aOuts % 2 == 0)
  1781. pData->hints |= PLUGIN_CAN_BALANCE;
  1782. // extra plugin hints
  1783. pData->extraHints = 0x0;
  1784. if (numEventInputBuses > 0)
  1785. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1786. if (numEventOutputBuses > 0)
  1787. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1788. // check initial latency
  1789. if ((fLastKnownLatency = v3_cpp_obj(fV3.processor)->get_latency_samples(fV3.processor)) != 0)
  1790. {
  1791. pData->client->setLatency(fLastKnownLatency);
  1792. #ifndef BUILD_BRIDGE
  1793. pData->latency.recreateBuffers(std::max(aIns+cvIns, aOuts+cvOuts), fLastKnownLatency);
  1794. #endif
  1795. }
  1796. // initial audio setup
  1797. v3_process_setup setup = {
  1798. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  1799. V3_SAMPLE_32,
  1800. static_cast<int32_t>(pData->engine->getBufferSize()),
  1801. pData->engine->getSampleRate()
  1802. };
  1803. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  1804. // activate all buses
  1805. for (int32_t j=0; j<numAudioInputBuses; ++j)
  1806. {
  1807. v3_bus_info busInfo = {};
  1808. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_INPUT, j, &busInfo) == V3_OK);
  1809. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1810. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component, V3_AUDIO, V3_INPUT, j, true) == V3_OK);
  1811. }
  1812. }
  1813. for (int32_t j=0; j<numAudioOutputBuses; ++j)
  1814. {
  1815. v3_bus_info busInfo = {};
  1816. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component, V3_AUDIO, V3_OUTPUT, j, &busInfo) == V3_OK);
  1817. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1818. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component, V3_AUDIO, V3_OUTPUT, j, true) == V3_OK);
  1819. }
  1820. }
  1821. bufferSizeChanged(pData->engine->getBufferSize());
  1822. reloadPrograms(true);
  1823. if (pData->active)
  1824. activate();
  1825. else
  1826. runIdleCallbacksAsNeeded(false);
  1827. carla_debug("CarlaPluginVST3::reload() - end");
  1828. }
  1829. // -------------------------------------------------------------------
  1830. // Plugin processing
  1831. void activate() noexcept override
  1832. {
  1833. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1834. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1835. try {
  1836. v3_cpp_obj(fV3.component)->set_active(fV3.component, true);
  1837. } CARLA_SAFE_EXCEPTION("set_active on");
  1838. try {
  1839. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, true);
  1840. } CARLA_SAFE_EXCEPTION("set_processing on");
  1841. fFirstActive = true;
  1842. runIdleCallbacksAsNeeded(false);
  1843. }
  1844. void deactivate() noexcept override
  1845. {
  1846. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1847. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1848. try {
  1849. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, false);
  1850. } CARLA_SAFE_EXCEPTION("set_processing off");
  1851. try {
  1852. v3_cpp_obj(fV3.component)->set_active(fV3.component, false);
  1853. } CARLA_SAFE_EXCEPTION("set_active off");
  1854. runIdleCallbacksAsNeeded(false);
  1855. }
  1856. void process(const float* const* const audioIn, float** const audioOut,
  1857. const float* const* const cvIn, float** const cvOut, const uint32_t frames) override
  1858. {
  1859. // --------------------------------------------------------------------------------------------------------
  1860. // Check if active
  1861. if (! pData->active)
  1862. {
  1863. // disable any output sound
  1864. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  1865. carla_zeroFloats(audioOut[i], frames);
  1866. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  1867. carla_zeroFloats(cvOut[i], frames);
  1868. return;
  1869. }
  1870. fEvents.init();
  1871. // --------------------------------------------------------------------------------------------------------
  1872. // Check if needs reset
  1873. if (pData->needsReset)
  1874. {
  1875. /*
  1876. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  1877. {
  1878. }
  1879. else
  1880. */
  1881. if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS && fEvents.eventInputs != nullptr)
  1882. {
  1883. fEvents.eventInputs->numEvents = MAX_MIDI_NOTE;
  1884. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  1885. {
  1886. v3_event& event(fEvents.eventInputs->events[i]);
  1887. carla_zeroStruct(event);
  1888. event.type = V3_EVENT_NOTE_OFF;
  1889. event.note_off.channel = (pData->ctrlChannel & MIDI_CHANNEL_BIT);
  1890. event.note_off.pitch = i;
  1891. }
  1892. }
  1893. pData->needsReset = false;
  1894. }
  1895. // --------------------------------------------------------------------------------------------------------
  1896. // Set TimeInfo
  1897. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  1898. fV3TimeContext.state = V3_PROCESS_CTX_PROJECT_TIME_VALID | V3_PROCESS_CTX_CONT_TIME_VALID;
  1899. fV3TimeContext.sample_rate = pData->engine->getSampleRate();
  1900. fV3TimeContext.project_time_in_samples = fV3TimeContext.continuous_time_in_samples
  1901. = static_cast<int64_t>(timeInfo.frame);
  1902. if (fFirstActive || ! fLastTimeInfo.compareIgnoringRollingFrames(timeInfo, frames))
  1903. fLastTimeInfo = timeInfo;
  1904. if (timeInfo.playing)
  1905. fV3TimeContext.state |= V3_PROCESS_CTX_PLAYING;
  1906. if (timeInfo.usecs != 0)
  1907. {
  1908. fV3TimeContext.system_time_ns = static_cast<int64_t>(timeInfo.usecs / 1000);
  1909. fV3TimeContext.state |= V3_PROCESS_CTX_SYSTEM_TIME_VALID;
  1910. }
  1911. if (timeInfo.bbt.valid)
  1912. {
  1913. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  1914. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  1915. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  1916. // const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  1917. // const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  1918. // PPQ Pos
  1919. fV3TimeContext.project_time_quarters = static_cast<double>(timeInfo.frame) / (fV3TimeContext.sample_rate * 60 / timeInfo.bbt.beatsPerMinute);
  1920. // fTimeInfo.project_time_quarters = ppqBar + ppqBeat + ppqTick;
  1921. fV3TimeContext.state |= V3_PROCESS_CTX_PROJECT_TIME_VALID;
  1922. // Tempo
  1923. fV3TimeContext.bpm = timeInfo.bbt.beatsPerMinute;
  1924. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  1925. // Bars
  1926. fV3TimeContext.bar_position_quarters = ppqBar;
  1927. fV3TimeContext.state |= V3_PROCESS_CTX_BAR_POSITION_VALID;
  1928. // Time Signature
  1929. fV3TimeContext.time_sig_numerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  1930. fV3TimeContext.time_sig_denom = static_cast<int32_t>(timeInfo.bbt.beatType + 0.5f);
  1931. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  1932. }
  1933. else
  1934. {
  1935. // Tempo
  1936. fV3TimeContext.bpm = 120.0;
  1937. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  1938. // Time Signature
  1939. fV3TimeContext.time_sig_numerator = 4;
  1940. fV3TimeContext.time_sig_denom = 4;
  1941. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  1942. // Missing info
  1943. fV3TimeContext.project_time_quarters = 0.0;
  1944. fV3TimeContext.bar_position_quarters = 0.0;
  1945. }
  1946. // --------------------------------------------------------------------------------------------------------
  1947. // Event Input and Processing
  1948. if (pData->event.portIn != nullptr)
  1949. {
  1950. // ----------------------------------------------------------------------------------------------------
  1951. // MIDI Input (External)
  1952. if (fEvents.eventInputs != nullptr && pData->extNotes.mutex.tryLock())
  1953. {
  1954. ExternalMidiNote note = { 0, 0, 0 };
  1955. uint16_t numEvents = fEvents.eventInputs->numEvents;
  1956. for (; numEvents < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  1957. {
  1958. note = pData->extNotes.data.getFirst(note, true);
  1959. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  1960. v3_event& event(fEvents.eventInputs->events[numEvents++]);
  1961. carla_zeroStruct(event);
  1962. if (note.velo > 0)
  1963. {
  1964. event.type = V3_EVENT_NOTE_ON;
  1965. event.note_on.channel = (note.channel & MIDI_CHANNEL_BIT);
  1966. event.note_on.pitch = note.note;
  1967. event.note_on.velocity = static_cast<float>(note.velo) / 127.f;
  1968. }
  1969. else
  1970. {
  1971. event.type = V3_EVENT_NOTE_OFF;
  1972. event.note_off.channel = (note.channel & MIDI_CHANNEL_BIT);
  1973. event.note_off.pitch = note.note;
  1974. }
  1975. }
  1976. pData->extNotes.mutex.unlock();
  1977. fEvents.eventInputs->numEvents = numEvents;
  1978. } // End of MIDI Input (External)
  1979. // ----------------------------------------------------------------------------------------------------
  1980. // Event Input (System)
  1981. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1982. bool allNotesOffSent = false;
  1983. #endif
  1984. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  1985. uint32_t startTime = 0;
  1986. uint32_t timeOffset = 0;
  1987. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1988. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  1989. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, isSampleAccurate, pData->event.portIn);
  1990. #endif
  1991. for (uint32_t i=0, numEvents = pData->event.portIn->getEventCount(); i < numEvents; ++i)
  1992. {
  1993. EngineEvent& event(pData->event.portIn->getEvent(i));
  1994. uint32_t eventTime = event.time;
  1995. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  1996. if (eventTime < timeOffset)
  1997. {
  1998. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  1999. eventTime, timeOffset, pData->name);
  2000. eventTime = timeOffset;
  2001. }
  2002. if (isSampleAccurate && eventTime > timeOffset)
  2003. {
  2004. if (processSingle(audioIn, audioOut, eventTime - timeOffset, timeOffset))
  2005. {
  2006. startTime = 0;
  2007. timeOffset = eventTime;
  2008. // TODO
  2009. }
  2010. else
  2011. {
  2012. startTime += timeOffset;
  2013. }
  2014. }
  2015. switch (event.type)
  2016. {
  2017. case kEngineEventTypeNull:
  2018. break;
  2019. case kEngineEventTypeControl: {
  2020. EngineControlEvent& ctrlEvent(event.ctrl);
  2021. switch (ctrlEvent.type)
  2022. {
  2023. case kEngineControlEventTypeNull:
  2024. break;
  2025. case kEngineControlEventTypeParameter: {
  2026. float value;
  2027. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2028. // non-midi
  2029. if (event.channel == kEngineEventNonMidiChannel)
  2030. {
  2031. const uint32_t k = ctrlEvent.param;
  2032. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  2033. ctrlEvent.handled = true;
  2034. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  2035. setParameterValueRT(k, value, event.time, true);
  2036. continue;
  2037. }
  2038. // Control backend stuff
  2039. if (event.channel == pData->ctrlChannel)
  2040. {
  2041. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  2042. {
  2043. ctrlEvent.handled = true;
  2044. value = ctrlEvent.normalizedValue;
  2045. setDryWetRT(value, true);
  2046. }
  2047. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  2048. {
  2049. ctrlEvent.handled = true;
  2050. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  2051. setVolumeRT(value, true);
  2052. }
  2053. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  2054. {
  2055. float left, right;
  2056. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  2057. if (value < 0.0f)
  2058. {
  2059. left = -1.0f;
  2060. right = (value*2.0f)+1.0f;
  2061. }
  2062. else if (value > 0.0f)
  2063. {
  2064. left = (value*2.0f)-1.0f;
  2065. right = 1.0f;
  2066. }
  2067. else
  2068. {
  2069. left = -1.0f;
  2070. right = 1.0f;
  2071. }
  2072. ctrlEvent.handled = true;
  2073. setBalanceLeftRT(left, true);
  2074. setBalanceRightRT(right, true);
  2075. }
  2076. }
  2077. #endif
  2078. // Control plugin parameters
  2079. uint32_t k;
  2080. for (k=0; k < pData->param.count; ++k)
  2081. {
  2082. if (pData->param.data[k].midiChannel != event.channel)
  2083. continue;
  2084. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  2085. continue;
  2086. if (pData->param.data[k].type != PARAMETER_INPUT)
  2087. continue;
  2088. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  2089. continue;
  2090. ctrlEvent.handled = true;
  2091. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  2092. setParameterValueRT(k, value, event.time, true);
  2093. }
  2094. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  2095. {
  2096. // TODO
  2097. }
  2098. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2099. if (! ctrlEvent.handled)
  2100. checkForMidiLearn(event);
  2101. #endif
  2102. break;
  2103. } // case kEngineControlEventTypeParameter
  2104. case kEngineControlEventTypeMidiBank:
  2105. if ((pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) != 0)
  2106. {
  2107. // TODO
  2108. }
  2109. break;
  2110. case kEngineControlEventTypeMidiProgram:
  2111. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  2112. {
  2113. if (ctrlEvent.param < pData->prog.count)
  2114. {
  2115. setProgramRT(ctrlEvent.param, true);
  2116. break;
  2117. }
  2118. }
  2119. else if (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES)
  2120. {
  2121. // TODO
  2122. }
  2123. break;
  2124. case kEngineControlEventTypeAllSoundOff:
  2125. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2126. {
  2127. // TODO
  2128. }
  2129. break;
  2130. case kEngineControlEventTypeAllNotesOff:
  2131. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2132. {
  2133. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2134. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  2135. {
  2136. allNotesOffSent = true;
  2137. postponeRtAllNotesOff();
  2138. }
  2139. #endif
  2140. // TODO
  2141. }
  2142. break;
  2143. } // switch (ctrlEvent.type)
  2144. break;
  2145. } // case kEngineEventTypeControl
  2146. case kEngineEventTypeMidi: {
  2147. const EngineMidiEvent& midiEvent(event.midi);
  2148. if (midiEvent.size > 3)
  2149. continue;
  2150. #ifdef CARLA_PROPER_CPP11_SUPPORT
  2151. static_assert(3 <= EngineMidiEvent::kDataSize, "Incorrect data");
  2152. #endif
  2153. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  2154. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2155. continue;
  2156. if (status == MIDI_STATUS_CHANNEL_PRESSURE && (pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0)
  2157. continue;
  2158. if (status == MIDI_STATUS_CONTROL_CHANGE && (pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0)
  2159. continue;
  2160. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  2161. continue;
  2162. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && (pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0)
  2163. continue;
  2164. // Fix bad note-off
  2165. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  2166. status = MIDI_STATUS_NOTE_OFF;
  2167. // TODO
  2168. if (status == MIDI_STATUS_NOTE_ON)
  2169. {
  2170. pData->postponeNoteOnRtEvent(true, event.channel, midiEvent.data[1], midiEvent.data[2]);
  2171. }
  2172. else if (status == MIDI_STATUS_NOTE_OFF)
  2173. {
  2174. pData->postponeNoteOffRtEvent(true, event.channel, midiEvent.data[1]);
  2175. }
  2176. } break;
  2177. } // switch (event.type)
  2178. }
  2179. pData->postRtEvents.trySplice();
  2180. if (frames > timeOffset)
  2181. processSingle(audioIn, audioOut, frames - timeOffset, timeOffset);
  2182. } // End of Event Input and Processing
  2183. // --------------------------------------------------------------------------------------------------------
  2184. // Plugin processing (no events)
  2185. else
  2186. {
  2187. processSingle(audioIn, audioOut, frames, 0);
  2188. } // End of Plugin processing (no events)
  2189. // --------------------------------------------------------------------------------------------------------
  2190. // MIDI Output
  2191. if (pData->event.portOut != nullptr)
  2192. {
  2193. // TODO
  2194. } // End of MIDI Output
  2195. fFirstActive = false;
  2196. // --------------------------------------------------------------------------------------------------------
  2197. }
  2198. bool processSingle(const float* const* const inBuffer, float** const outBuffer, const uint32_t frames, const uint32_t timeOffset)
  2199. {
  2200. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  2201. if (pData->audioIn.count > 0)
  2202. {
  2203. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  2204. }
  2205. if (pData->audioOut.count > 0)
  2206. {
  2207. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  2208. CARLA_SAFE_ASSERT_RETURN(fAudioAndCvOutBuffers != nullptr, false);
  2209. }
  2210. // --------------------------------------------------------------------------------------------------------
  2211. // Try lock, silence otherwise
  2212. #ifndef STOAT_TEST_BUILD
  2213. if (pData->engine->isOffline())
  2214. {
  2215. pData->singleMutex.lock();
  2216. }
  2217. else
  2218. #endif
  2219. if (! pData->singleMutex.tryLock())
  2220. {
  2221. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2222. {
  2223. for (uint32_t k=0; k < frames; ++k)
  2224. outBuffer[i][k+timeOffset] = 0.0f;
  2225. }
  2226. return false;
  2227. }
  2228. // --------------------------------------------------------------------------------------------------------
  2229. // Set audio buffers
  2230. float* bufferAudioIn[96]; // std::max(1u, pData->audioIn.count + pData->cvIn.count)
  2231. float* bufferAudioOut[96]; // std::max(1u, pData->audioOut.count + pData->cvOut.count)
  2232. {
  2233. uint32_t i=0;
  2234. for (; i < pData->audioIn.count; ++i)
  2235. bufferAudioIn[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  2236. for (; i < pData->cvIn.count; ++i)
  2237. bufferAudioIn[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  2238. }
  2239. {
  2240. uint32_t i=0;
  2241. for (; i < pData->audioOut.count; ++i)
  2242. bufferAudioOut[i] = fAudioAndCvOutBuffers[i]+timeOffset;
  2243. for (; i < pData->cvOut.count; ++i)
  2244. bufferAudioOut[i] = fAudioAndCvOutBuffers[i]+timeOffset;
  2245. }
  2246. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2247. carla_zeroFloats(fAudioAndCvOutBuffers[i], frames);
  2248. // --------------------------------------------------------------------------------------------------------
  2249. // Set MIDI events
  2250. // TODO
  2251. // --------------------------------------------------------------------------------------------------------
  2252. // Run plugin
  2253. fEvents.prepare();
  2254. v3_audio_bus_buffers processInputs = {
  2255. static_cast<int32_t>(pData->audioIn.count + pData->cvIn.count),
  2256. 0, { bufferAudioIn }
  2257. };
  2258. v3_audio_bus_buffers processOutputs = {
  2259. static_cast<int32_t>(pData->audioOut.count + pData->cvOut.count),
  2260. 0, { bufferAudioOut }
  2261. };
  2262. v3_process_data processData = {
  2263. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2264. V3_SAMPLE_32,
  2265. static_cast<int32_t>(frames),
  2266. static_cast<int32_t>(pData->audioIn.count + pData->cvIn.count),
  2267. static_cast<int32_t>(pData->audioOut.count + pData->cvOut.count),
  2268. &processInputs,
  2269. &processOutputs,
  2270. fEvents.paramInputs != nullptr ? (v3_param_changes**)&fEvents.paramInputs : nullptr,
  2271. fEvents.paramOutputs != nullptr ? (v3_param_changes**)&fEvents.paramOutputs : nullptr,
  2272. fEvents.eventInputs != nullptr ? (v3_event_list**)&fEvents.eventInputs : nullptr,
  2273. fEvents.eventOutputs != nullptr ? (v3_event_list**)&fEvents.eventOutputs : nullptr,
  2274. &fV3TimeContext
  2275. };
  2276. try {
  2277. v3_cpp_obj(fV3.processor)->process(fV3.processor, &processData);
  2278. } CARLA_SAFE_EXCEPTION("process");
  2279. fEvents.init();
  2280. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2281. // --------------------------------------------------------------------------------------------------------
  2282. // Post-processing (dry/wet, volume and balance)
  2283. {
  2284. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0 && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  2285. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0 && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f) && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  2286. const bool isMono = (pData->audioIn.count == 1);
  2287. bool isPair;
  2288. float bufValue;
  2289. float* const oldBufLeft = pData->postProc.extraBuffer;
  2290. uint32_t i=0;
  2291. for (; i < pData->audioOut.count; ++i)
  2292. {
  2293. // Dry/Wet
  2294. if (doDryWet)
  2295. {
  2296. const uint32_t c = isMono ? 0 : i;
  2297. for (uint32_t k=0; k < frames; ++k)
  2298. {
  2299. bufValue = inBuffer[c][k+timeOffset];
  2300. fAudioAndCvOutBuffers[i][k] = (fAudioAndCvOutBuffers[i][k] * pData->postProc.dryWet) + (bufValue * (1.0f - pData->postProc.dryWet));
  2301. }
  2302. }
  2303. // Balance
  2304. if (doBalance)
  2305. {
  2306. isPair = (i % 2 == 0);
  2307. if (isPair)
  2308. {
  2309. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2310. carla_copyFloats(oldBufLeft, fAudioAndCvOutBuffers[i], frames);
  2311. }
  2312. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2313. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2314. for (uint32_t k=0; k < frames; ++k)
  2315. {
  2316. if (isPair)
  2317. {
  2318. // left
  2319. fAudioAndCvOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2320. fAudioAndCvOutBuffers[i][k] += fAudioAndCvOutBuffers[i+1][k] * (1.0f - balRangeR);
  2321. }
  2322. else
  2323. {
  2324. // right
  2325. fAudioAndCvOutBuffers[i][k] = fAudioAndCvOutBuffers[i][k] * balRangeR;
  2326. fAudioAndCvOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2327. }
  2328. }
  2329. }
  2330. // Volume (and buffer copy)
  2331. {
  2332. for (uint32_t k=0; k < frames; ++k)
  2333. outBuffer[i][k+timeOffset] = fAudioAndCvOutBuffers[i][k] * pData->postProc.volume;
  2334. }
  2335. }
  2336. for (; i < pData->cvOut.count; ++i)
  2337. carla_copyFloats(outBuffer[i] + timeOffset, fAudioAndCvOutBuffers[i] + timeOffset, frames);
  2338. } // End of Post-processing
  2339. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2340. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2341. carla_copyFloats(outBuffer[i] + timeOffset, fAudioAndCvOutBuffers[i] + timeOffset, frames);
  2342. #endif
  2343. // --------------------------------------------------------------------------------------------------------
  2344. pData->singleMutex.unlock();
  2345. return true;
  2346. }
  2347. void bufferSizeChanged(const uint32_t newBufferSize) override
  2348. {
  2349. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2350. carla_debug("CarlaPluginVST3::bufferSizeChanged(%i)", newBufferSize);
  2351. if (pData->active)
  2352. deactivate();
  2353. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2354. {
  2355. if (fAudioAndCvOutBuffers[i] != nullptr)
  2356. delete[] fAudioAndCvOutBuffers[i];
  2357. fAudioAndCvOutBuffers[i] = new float[newBufferSize];
  2358. }
  2359. v3_process_setup setup = {
  2360. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2361. V3_SAMPLE_32,
  2362. static_cast<int32_t>(newBufferSize),
  2363. pData->engine->getSampleRate()
  2364. };
  2365. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2366. if (pData->active)
  2367. activate();
  2368. CarlaPlugin::bufferSizeChanged(newBufferSize);
  2369. }
  2370. void sampleRateChanged(const double newSampleRate) override
  2371. {
  2372. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  2373. carla_debug("CarlaPluginVST3::sampleRateChanged(%g)", newSampleRate);
  2374. if (pData->active)
  2375. deactivate();
  2376. v3_process_setup setup = {
  2377. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2378. V3_SAMPLE_32,
  2379. static_cast<int32_t>(pData->engine->getBufferSize()),
  2380. newSampleRate
  2381. };
  2382. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2383. if (pData->active)
  2384. activate();
  2385. }
  2386. void offlineModeChanged(const bool isOffline) override
  2387. {
  2388. carla_debug("CarlaPluginVST3::offlineModeChanged(%d)", isOffline);
  2389. if (pData->active)
  2390. deactivate();
  2391. v3_process_setup setup = {
  2392. isOffline ? V3_OFFLINE : V3_REALTIME,
  2393. V3_SAMPLE_32,
  2394. static_cast<int32_t>(pData->engine->getBufferSize()),
  2395. pData->engine->getSampleRate()
  2396. };
  2397. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2398. if (pData->active)
  2399. activate();
  2400. }
  2401. // -------------------------------------------------------------------
  2402. // Plugin buffers
  2403. void clearBuffers() noexcept override
  2404. {
  2405. carla_debug("CarlaPluginVST3::clearBuffers() - start");
  2406. if (fAudioAndCvOutBuffers != nullptr)
  2407. {
  2408. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2409. {
  2410. if (fAudioAndCvOutBuffers[i] != nullptr)
  2411. {
  2412. delete[] fAudioAndCvOutBuffers[i];
  2413. fAudioAndCvOutBuffers[i] = nullptr;
  2414. }
  2415. }
  2416. delete[] fAudioAndCvOutBuffers;
  2417. fAudioAndCvOutBuffers = nullptr;
  2418. }
  2419. CarlaPlugin::clearBuffers();
  2420. carla_debug("CarlaPluginVST3::clearBuffers() - end");
  2421. }
  2422. // -------------------------------------------------------------------
  2423. // Post-poned UI Stuff
  2424. void uiParameterChange(const uint32_t index, const float value) noexcept override
  2425. {
  2426. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  2427. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  2428. const v3_param_id v3id = pData->param.data[index].rindex;
  2429. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  2430. v3id, value);
  2431. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, v3id, normalized);
  2432. }
  2433. // ----------------------------------------------------------------------------------------------------------------
  2434. const void* getNativeDescriptor() const noexcept override
  2435. {
  2436. return fV3.component;
  2437. }
  2438. const void* getExtraStuff() const noexcept override
  2439. {
  2440. return fV3.controller;
  2441. }
  2442. // ----------------------------------------------------------------------------------------------------------------
  2443. bool init(const CarlaPluginPtr plugin,
  2444. const char* const filename,
  2445. const char* name,
  2446. const char* /*const label*/,
  2447. const uint options)
  2448. {
  2449. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2450. // ------------------------------------------------------------------------------------------------------------
  2451. // first checks
  2452. if (pData->client != nullptr)
  2453. {
  2454. pData->engine->setLastError("Plugin client is already registered");
  2455. return false;
  2456. }
  2457. if (filename == nullptr || filename[0] == '\0')
  2458. {
  2459. pData->engine->setLastError("null filename");
  2460. return false;
  2461. }
  2462. V3_ENTRYFN v3_entry;
  2463. V3_EXITFN v3_exit;
  2464. V3_GETFN v3_get;
  2465. // filename is full path to binary
  2466. if (water::File(filename).existsAsFile())
  2467. {
  2468. if (! pData->libOpen(filename))
  2469. {
  2470. pData->engine->setLastError(pData->libError(filename));
  2471. return false;
  2472. }
  2473. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  2474. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  2475. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  2476. }
  2477. // assume filename is a vst3 bundle
  2478. else
  2479. {
  2480. #ifdef CARLA_OS_MAC
  2481. if (! fMacBundleLoader.load(filename))
  2482. {
  2483. pData->engine->setLastError("Failed to load VST3 bundle executable");
  2484. return false;
  2485. }
  2486. v3_entry = fMacBundleLoader.getSymbol<V3_ENTRYFN>(CFSTR(V3_ENTRYFNNAME));
  2487. v3_exit = fMacBundleLoader.getSymbol<V3_EXITFN>(CFSTR(V3_EXITFNNAME));
  2488. v3_get = fMacBundleLoader.getSymbol<V3_GETFN>(CFSTR(V3_GETFNNAME));
  2489. #else
  2490. water::String binaryfilename = filename;
  2491. if (!binaryfilename.endsWithChar(CARLA_OS_SEP))
  2492. binaryfilename += CARLA_OS_SEP_STR;
  2493. binaryfilename += "Contents" CARLA_OS_SEP_STR V3_CONTENT_DIR CARLA_OS_SEP_STR;
  2494. binaryfilename += water::File(filename).getFileNameWithoutExtension();
  2495. #ifdef CARLA_OS_WIN
  2496. binaryfilename += ".vst3";
  2497. #else
  2498. binaryfilename += ".so";
  2499. #endif
  2500. if (! water::File(binaryfilename).existsAsFile())
  2501. {
  2502. pData->engine->setLastError("Failed to find a suitable VST3 bundle binary");
  2503. return false;
  2504. }
  2505. if (! pData->libOpen(binaryfilename.toRawUTF8()))
  2506. {
  2507. pData->engine->setLastError(pData->libError(binaryfilename.toRawUTF8()));
  2508. return false;
  2509. }
  2510. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  2511. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  2512. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  2513. #endif
  2514. }
  2515. // ------------------------------------------------------------------------------------------------------------
  2516. // ensure entry and exit points are available
  2517. if (v3_entry == nullptr || v3_exit == nullptr || v3_get == nullptr)
  2518. {
  2519. pData->engine->setLastError("Not a VST3 plugin");
  2520. return false;
  2521. }
  2522. // ------------------------------------------------------------------------------------------------------------
  2523. // call entry point
  2524. #if defined(CARLA_OS_MAC)
  2525. v3_entry(pData->lib == nullptr ? fMacBundleLoader.getRef() : nullptr);
  2526. #elif defined(CARLA_OS_WIN)
  2527. v3_entry();
  2528. #else
  2529. v3_entry(pData->lib);
  2530. #endif
  2531. // ------------------------------------------------------------------------------------------------------------
  2532. // fetch initial factory
  2533. v3_plugin_factory** const factory = v3_get();
  2534. if (factory == nullptr)
  2535. {
  2536. pData->engine->setLastError("VST3 factory failed to create a valid instance");
  2537. return false;
  2538. }
  2539. // ------------------------------------------------------------------------------------------------------------
  2540. // initialize and find requested plugin
  2541. fV3.exitfn = v3_exit;
  2542. fV3.factory1 = factory;
  2543. v3_funknown** const hostContext = (v3_funknown**)&fV3ApplicationPtr;
  2544. if (! fV3.queryFactories(hostContext))
  2545. {
  2546. pData->engine->setLastError("VST3 plugin failed to properly create factories");
  2547. return false;
  2548. }
  2549. if (! fV3.findPlugin(fV3ClassInfo))
  2550. {
  2551. pData->engine->setLastError("Failed to find the requested plugin in the VST3 bundle");
  2552. return false;
  2553. }
  2554. if (! fV3.initializePlugin(fV3ClassInfo.v1.class_id,
  2555. hostContext,
  2556. (v3_component_handler**)&fComponentHandlerPtr))
  2557. {
  2558. pData->engine->setLastError("VST3 plugin failed to initialize");
  2559. return false;
  2560. }
  2561. // ------------------------------------------------------------------------------------------------------------
  2562. // do some basic safety checks
  2563. if (v3_cpp_obj(fV3.processor)->can_process_sample_size(fV3.processor, V3_SAMPLE_32) != V3_OK)
  2564. {
  2565. pData->engine->setLastError("VST3 plugin does not support 32bit audio, cannot continue");
  2566. return false;
  2567. }
  2568. // ------------------------------------------------------------------------------------------------------------
  2569. // get info
  2570. if (name != nullptr && name[0] != '\0')
  2571. {
  2572. pData->name = pData->engine->getUniquePluginName(name);
  2573. }
  2574. else
  2575. {
  2576. if (fV3ClassInfo.v1.name[0] != '\0')
  2577. pData->name = pData->engine->getUniquePluginName(fV3ClassInfo.v1.name);
  2578. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  2579. pData->name = pData->engine->getUniquePluginName(shortname+1);
  2580. else
  2581. pData->name = pData->engine->getUniquePluginName("unknown");
  2582. }
  2583. pData->filename = carla_strdup(filename);
  2584. // ------------------------------------------------------------------------------------------------------------
  2585. // register client
  2586. pData->client = pData->engine->addClient(plugin);
  2587. if (pData->client == nullptr || ! pData->client->isOk())
  2588. {
  2589. pData->engine->setLastError("Failed to register plugin client");
  2590. return false;
  2591. }
  2592. // ------------------------------------------------------------------------------------------------------------
  2593. // set default options
  2594. pData->options = 0x0;
  2595. if (fLastKnownLatency != 0 /*|| hasMidiOutput()*/ || isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2596. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2597. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2598. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2599. /*
  2600. if (hasMidiInput())
  2601. {
  2602. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2603. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2604. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2605. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2606. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2607. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2608. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2609. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2610. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2611. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2612. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PROGRAM_CHANGES))
  2613. pData->options |= PLUGIN_OPTION_SEND_PROGRAM_CHANGES;
  2614. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2615. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2616. }
  2617. */
  2618. /*
  2619. if (numPrograms > 1 && (pData->options & PLUGIN_OPTION_SEND_PROGRAM_CHANGES) == 0)
  2620. if (isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2621. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2622. */
  2623. // ------------------------------------------------------------------------------------------------------------
  2624. return true;
  2625. }
  2626. protected:
  2627. v3_result v3BeginEdit(const v3_param_id paramId) override
  2628. {
  2629. for (uint32_t i=0; i < pData->param.count; ++i)
  2630. {
  2631. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2632. {
  2633. pData->engine->touchPluginParameter(pData->id, i, true);
  2634. return V3_OK;
  2635. }
  2636. }
  2637. return V3_INVALID_ARG;
  2638. }
  2639. v3_result v3PerformEdit(const v3_param_id paramId, const double value) override
  2640. {
  2641. for (uint32_t i=0; i < pData->param.count; ++i)
  2642. {
  2643. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2644. {
  2645. // report value to component (next process call)
  2646. fEvents.paramInputs->setParamValue(paramId, static_cast<float>(value));
  2647. const double plain = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller,
  2648. paramId,
  2649. value);
  2650. const float fixedValue = pData->param.getFixedValue(i, plain);
  2651. CarlaPlugin::setParameterValue(i, fixedValue, false, true, true);
  2652. return V3_OK;
  2653. }
  2654. }
  2655. return V3_INVALID_ARG;
  2656. }
  2657. v3_result v3EndEdit(const v3_param_id paramId) override
  2658. {
  2659. for (uint32_t i=0; i < pData->param.count; ++i)
  2660. {
  2661. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2662. {
  2663. pData->engine->touchPluginParameter(pData->id, i, false);
  2664. return V3_OK;
  2665. }
  2666. }
  2667. return V3_INVALID_ARG;
  2668. }
  2669. v3_result v3RestartComponent(const int32_t flags) override
  2670. {
  2671. fRestartFlags |= flags;
  2672. return V3_OK;
  2673. }
  2674. void handlePluginUIClosed() override
  2675. {
  2676. // CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2677. carla_debug("CarlaPluginVST3::handlePluginUIClosed()");
  2678. showCustomUI(false);
  2679. pData->engine->callback(true, true,
  2680. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2681. pData->id,
  2682. 0,
  2683. 0, 0, 0.0f, nullptr);
  2684. }
  2685. void handlePluginUIResized(const uint width, const uint height) override
  2686. {
  2687. // CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2688. carla_debug("CarlaPluginVST3::handlePluginUIResized(%u, %u)", width, height);
  2689. return; // unused
  2690. (void)width; (void)height;
  2691. }
  2692. private:
  2693. #ifdef CARLA_OS_MAC
  2694. BundleLoader fMacBundleLoader;
  2695. #endif
  2696. const bool kEngineHasIdleOnMainThread;
  2697. bool fFirstActive; // first process() call after activate()
  2698. float** fAudioAndCvOutBuffers;
  2699. uint32_t fLastKnownLatency;
  2700. int32_t fRestartFlags;
  2701. EngineTimeInfo fLastTimeInfo;
  2702. v3_process_context fV3TimeContext;
  2703. carla_v3_host_application fV3Application;
  2704. carla_v3_host_application* const fV3ApplicationPtr;
  2705. carla_v3_component_handler fComponentHandler;
  2706. carla_v3_component_handler* const fComponentHandlerPtr;
  2707. carla_v3_plugin_frame fPluginFrame;
  2708. carla_v3_plugin_frame* const fPluginFramePtr;
  2709. // v3_class_info_2 is ABI compatible with v3_class_info
  2710. union ClassInfo {
  2711. v3_class_info v1;
  2712. v3_class_info_2 v2;
  2713. } fV3ClassInfo;
  2714. struct PluginPointers {
  2715. V3_EXITFN exitfn;
  2716. v3_plugin_factory** factory1;
  2717. v3_plugin_factory_2** factory2;
  2718. v3_plugin_factory_3** factory3;
  2719. v3_component** component;
  2720. v3_edit_controller** controller;
  2721. v3_audio_processor** processor;
  2722. v3_connection_point** connComponent;
  2723. v3_connection_point** connController;
  2724. v3_plugin_view** view;
  2725. bool shouldTerminateComponent;
  2726. bool shouldTerminateController;
  2727. PluginPointers()
  2728. : exitfn(nullptr),
  2729. factory1(nullptr),
  2730. factory2(nullptr),
  2731. factory3(nullptr),
  2732. component(nullptr),
  2733. controller(nullptr),
  2734. processor(nullptr),
  2735. connComponent(nullptr),
  2736. connController(nullptr),
  2737. view(nullptr),
  2738. shouldTerminateComponent(false),
  2739. shouldTerminateController(false) {}
  2740. ~PluginPointers()
  2741. {
  2742. // must have been cleaned up by now
  2743. CARLA_SAFE_ASSERT(exitfn == nullptr);
  2744. }
  2745. // must have exitfn and factory1 set
  2746. bool queryFactories(v3_funknown** const hostContext)
  2747. {
  2748. // query 2nd factory
  2749. if (v3_cpp_obj_query_interface(factory1, v3_plugin_factory_2_iid, &factory2) == V3_OK)
  2750. {
  2751. CARLA_SAFE_ASSERT_RETURN(factory2 != nullptr, exit());
  2752. }
  2753. else
  2754. {
  2755. CARLA_SAFE_ASSERT(factory2 == nullptr);
  2756. factory2 = nullptr;
  2757. }
  2758. // query 3rd factory
  2759. if (factory2 != nullptr && v3_cpp_obj_query_interface(factory2, v3_plugin_factory_3_iid, &factory3) == V3_OK)
  2760. {
  2761. CARLA_SAFE_ASSERT_RETURN(factory3 != nullptr, exit());
  2762. }
  2763. else
  2764. {
  2765. CARLA_SAFE_ASSERT(factory3 == nullptr);
  2766. factory3 = nullptr;
  2767. }
  2768. // set host context (application) if 3rd factory provided
  2769. if (factory3 != nullptr)
  2770. v3_cpp_obj(factory3)->set_host_context(factory3, hostContext);
  2771. return true;
  2772. }
  2773. // must have all possible factories and exitfn set
  2774. bool findPlugin(ClassInfo& classInfo)
  2775. {
  2776. // get factory info
  2777. v3_factory_info factoryInfo = {};
  2778. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->get_factory_info(factory1, &factoryInfo) == V3_OK, exit());
  2779. // get num classes
  2780. const int32_t numClasses = v3_cpp_obj(factory1)->num_classes(factory1);
  2781. CARLA_SAFE_ASSERT_RETURN(numClasses > 0, exit());
  2782. // go through all relevant classes
  2783. for (int32_t i=0; i<numClasses; ++i)
  2784. {
  2785. carla_zeroStruct(classInfo);
  2786. if (factory2 != nullptr)
  2787. v3_cpp_obj(factory2)->get_class_info_2(factory2, i, &classInfo.v2);
  2788. else
  2789. v3_cpp_obj(factory1)->get_class_info(factory1, i, &classInfo.v1);
  2790. // safety check
  2791. CARLA_SAFE_ASSERT_CONTINUE(classInfo.v1.cardinality == 0x7FFFFFFF);
  2792. // only check for audio plugins
  2793. if (std::strcmp(classInfo.v1.category, "Audio Module Class") != 0)
  2794. continue;
  2795. // FIXME multi-plugin bundle
  2796. break;
  2797. }
  2798. return true;
  2799. }
  2800. bool initializePlugin(const v3_tuid uid,
  2801. v3_funknown** const hostContext,
  2802. v3_component_handler** const handler)
  2803. {
  2804. // create instance
  2805. void* instance = nullptr;
  2806. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->create_instance(factory1, uid, v3_component_iid,
  2807. &instance) == V3_OK,
  2808. exit());
  2809. CARLA_SAFE_ASSERT_RETURN(instance != nullptr, exit());
  2810. component = static_cast<v3_component**>(instance);
  2811. // initialize instance
  2812. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(component, hostContext) == V3_OK, exit());
  2813. shouldTerminateComponent = true;
  2814. // create edit controller
  2815. if (v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller) != V3_OK)
  2816. controller = nullptr;
  2817. // if we cannot cast from component, try to create edit controller from factory
  2818. if (controller == nullptr)
  2819. {
  2820. v3_tuid cuid = {};
  2821. if (v3_cpp_obj(component)->get_controller_class_id(component, cuid) == V3_OK)
  2822. {
  2823. instance = nullptr;
  2824. if (v3_cpp_obj(factory1)->create_instance(factory1, cuid,
  2825. v3_edit_controller_iid, &instance) == V3_OK)
  2826. controller = static_cast<v3_edit_controller**>(instance);
  2827. }
  2828. CARLA_SAFE_ASSERT_RETURN(controller != nullptr, exit());
  2829. // component is separate from controller, needs its dedicated initialize and terminate
  2830. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(controller, hostContext) == V3_OK, exit());
  2831. shouldTerminateController = true;
  2832. }
  2833. v3_cpp_obj(controller)->set_component_handler(controller, handler);
  2834. // create processor
  2835. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_query_interface(component, v3_audio_processor_iid,
  2836. &processor) == V3_OK, exit());
  2837. CARLA_SAFE_ASSERT_RETURN(processor != nullptr, exit());
  2838. // connect component to controller
  2839. if (v3_cpp_obj_query_interface(component, v3_connection_point_iid, &connComponent) != V3_OK)
  2840. connComponent = nullptr;
  2841. if (v3_cpp_obj_query_interface(controller, v3_connection_point_iid, &connController) != V3_OK)
  2842. connController = nullptr;
  2843. if (connComponent != nullptr && connController != nullptr)
  2844. {
  2845. v3_cpp_obj(connComponent)->connect(connComponent, connController);
  2846. v3_cpp_obj(connController)->connect(connController, connComponent);
  2847. }
  2848. // create view
  2849. view = v3_cpp_obj(controller)->create_view(controller, "editor");
  2850. carla_stdout("has view %p", view);
  2851. return true;
  2852. }
  2853. bool exit()
  2854. {
  2855. // must be deleted by now
  2856. CARLA_SAFE_ASSERT(view == nullptr);
  2857. if (connComponent != nullptr && connController != nullptr)
  2858. {
  2859. v3_cpp_obj(connComponent)->disconnect(connComponent, connController);
  2860. v3_cpp_obj(connController)->disconnect(connController, connComponent);
  2861. }
  2862. if (connComponent != nullptr)
  2863. {
  2864. v3_cpp_obj_unref(connComponent);
  2865. connComponent = nullptr;
  2866. }
  2867. if (connController != nullptr)
  2868. {
  2869. v3_cpp_obj_unref(connController);
  2870. connController = nullptr;
  2871. }
  2872. if (processor != nullptr)
  2873. {
  2874. v3_cpp_obj_unref(processor);
  2875. processor = nullptr;
  2876. }
  2877. if (controller != nullptr)
  2878. {
  2879. if (shouldTerminateController)
  2880. {
  2881. v3_cpp_obj_terminate(controller);
  2882. shouldTerminateController = false;
  2883. }
  2884. v3_cpp_obj_unref(controller);
  2885. component = nullptr;
  2886. }
  2887. if (component != nullptr)
  2888. {
  2889. if (shouldTerminateComponent)
  2890. {
  2891. v3_cpp_obj_terminate(component);
  2892. shouldTerminateComponent = false;
  2893. }
  2894. v3_cpp_obj_unref(component);
  2895. component = nullptr;
  2896. }
  2897. if (factory3 != nullptr)
  2898. {
  2899. v3_cpp_obj_unref(factory3);
  2900. factory3 = nullptr;
  2901. }
  2902. if (factory2 != nullptr)
  2903. {
  2904. v3_cpp_obj_unref(factory2);
  2905. factory2 = nullptr;
  2906. }
  2907. if (factory1 != nullptr)
  2908. {
  2909. v3_cpp_obj_unref(factory1);
  2910. factory1 = nullptr;
  2911. }
  2912. if (exitfn != nullptr)
  2913. {
  2914. exitfn();
  2915. exitfn = nullptr;
  2916. }
  2917. // return false so it can be used as error/fail condition
  2918. return false;
  2919. }
  2920. CARLA_DECLARE_NON_COPYABLE(PluginPointers)
  2921. } fV3;
  2922. struct Events {
  2923. carla_v3_input_param_changes* paramInputs;
  2924. carla_v3_output_param_changes* paramOutputs;
  2925. carla_v3_input_event_list* eventInputs;
  2926. carla_v3_output_event_list* eventOutputs;
  2927. Events() noexcept
  2928. : paramInputs(nullptr),
  2929. paramOutputs(nullptr),
  2930. eventInputs(nullptr),
  2931. eventOutputs(nullptr) {}
  2932. ~Events()
  2933. {
  2934. delete paramInputs;
  2935. delete paramOutputs;
  2936. delete eventInputs;
  2937. delete eventOutputs;
  2938. }
  2939. void init()
  2940. {
  2941. if (paramInputs != nullptr)
  2942. paramInputs->init();
  2943. if (eventInputs != nullptr)
  2944. eventInputs->numEvents = 0;
  2945. }
  2946. void prepare()
  2947. {
  2948. if (paramInputs != nullptr)
  2949. paramInputs->prepare();
  2950. }
  2951. CARLA_DECLARE_NON_COPYABLE(Events)
  2952. } fEvents;
  2953. struct UI {
  2954. bool isAttached;
  2955. bool isEmbed;
  2956. bool isVisible;
  2957. CarlaPluginUI* window;
  2958. UI() noexcept
  2959. : isAttached(false),
  2960. isEmbed(false),
  2961. isVisible(false),
  2962. window(nullptr) {}
  2963. ~UI()
  2964. {
  2965. CARLA_ASSERT(isEmbed || ! isVisible);
  2966. if (window != nullptr)
  2967. {
  2968. delete window;
  2969. window = nullptr;
  2970. }
  2971. }
  2972. CARLA_DECLARE_NON_COPYABLE(UI)
  2973. } fUI;
  2974. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST3)
  2975. };
  2976. // --------------------------------------------------------------------------------------------------------------------
  2977. CarlaPluginPtr CarlaPlugin::newVST3(const Initializer& init)
  2978. {
  2979. carla_debug("CarlaPlugin::newVST3({%p, \"%s\", \"%s\", \"%s\"})",
  2980. init.engine, init.filename, init.name, init.label);
  2981. #ifdef USE_JUCE_FOR_VST3
  2982. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST3") == nullptr)
  2983. return newJuce(init, "VST3");
  2984. #endif
  2985. std::shared_ptr<CarlaPluginVST3> plugin(new CarlaPluginVST3(init.engine, init.id));
  2986. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  2987. return nullptr;
  2988. return plugin;
  2989. }
  2990. // -------------------------------------------------------------------------------------------------------------------
  2991. CARLA_BACKEND_END_NAMESPACE