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.

4386 lines
155KB

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