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.

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