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.

4199 lines
148KB

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