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.

3804 lines
132KB

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