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.

4317 lines
152KB

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