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.

4203 lines
149KB

  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. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1648. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1649. V3_AUDIO, V3_INPUT, b, true) == V3_OK);
  1650. }
  1651. fBuses.inputs[b].num_channels = numChannels;
  1652. fBuses.inputInfo[b].bus_type = busInfo.bus_type;
  1653. fBuses.inputInfo[b].flags = busInfo.flags;
  1654. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  1655. cvIns += static_cast<uint32_t>(numChannels);
  1656. else
  1657. aIns += static_cast<uint32_t>(numChannels);
  1658. }
  1659. for (int32_t b=0; b<numAudioOutputBuses; ++b)
  1660. {
  1661. carla_zeroStruct(fBuses.outputs[b]);
  1662. carla_zeroStruct(fBuses.outputInfo[b]);
  1663. fBuses.outputInfo[b].offset = aOuts + cvOuts;
  1664. v3_bus_info busInfo = {};
  1665. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1666. V3_AUDIO, V3_OUTPUT, b, &busInfo) == V3_OK);
  1667. const int32_t numChannels = busInfo.channel_count;
  1668. CARLA_SAFE_ASSERT_BREAK(numChannels >= 0);
  1669. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1670. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1671. V3_AUDIO, V3_OUTPUT, b, true) == V3_OK);
  1672. }
  1673. fBuses.outputs[b].num_channels = numChannels;
  1674. fBuses.outputInfo[b].bus_type = busInfo.bus_type;
  1675. fBuses.outputInfo[b].flags = busInfo.flags;
  1676. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  1677. cvOuts += static_cast<uint32_t>(numChannels);
  1678. else
  1679. aOuts += static_cast<uint32_t>(numChannels);
  1680. }
  1681. if (aIns > 0)
  1682. {
  1683. pData->audioIn.createNew(aIns);
  1684. }
  1685. if (aOuts > 0)
  1686. {
  1687. pData->audioOut.createNew(aOuts);
  1688. needsCtrlIn = true;
  1689. }
  1690. if (cvIns > 0)
  1691. pData->cvIn.createNew(cvIns);
  1692. if (cvOuts > 0)
  1693. pData->cvOut.createNew(cvOuts);
  1694. if (numEventInputBuses > 0)
  1695. needsCtrlIn = true;
  1696. if (numEventOutputBuses > 0)
  1697. needsCtrlOut = true;
  1698. if (numParameters > 0)
  1699. {
  1700. pData->param.createNew(numParameters, false);
  1701. needsCtrlIn = true;
  1702. }
  1703. if (aOuts + cvOuts > 0)
  1704. {
  1705. fAudioAndCvOutBuffers = new float*[aOuts + cvOuts];
  1706. for (uint32_t i=0; i < aOuts + cvOuts; ++i)
  1707. fAudioAndCvOutBuffers[i] = nullptr;
  1708. }
  1709. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1710. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1711. CarlaString portName;
  1712. // Audio Ins
  1713. for (uint32_t j=0; j < aIns; ++j)
  1714. {
  1715. portName.clear();
  1716. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1717. {
  1718. portName = pData->name;
  1719. portName += ":";
  1720. }
  1721. if (aIns > 1)
  1722. {
  1723. portName += "input_";
  1724. portName += CarlaString(j+1);
  1725. }
  1726. else
  1727. portName += "input";
  1728. portName.truncate(portNameSize);
  1729. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio,
  1730. portName, true, j);
  1731. pData->audioIn.ports[j].rindex = j;
  1732. }
  1733. // Audio Outs
  1734. for (uint32_t j=0; j < aOuts; ++j)
  1735. {
  1736. portName.clear();
  1737. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1738. {
  1739. portName = pData->name;
  1740. portName += ":";
  1741. }
  1742. if (aOuts > 1)
  1743. {
  1744. portName += "output_";
  1745. portName += CarlaString(j+1);
  1746. }
  1747. else
  1748. portName += "output";
  1749. portName.truncate(portNameSize);
  1750. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio,
  1751. portName, false, j);
  1752. pData->audioOut.ports[j].rindex = j;
  1753. }
  1754. // CV Ins
  1755. for (uint32_t j=0; j < cvIns; ++j)
  1756. {
  1757. portName.clear();
  1758. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1759. {
  1760. portName = pData->name;
  1761. portName += ":";
  1762. }
  1763. if (cvIns > 1)
  1764. {
  1765. portName += "cv_input_";
  1766. portName += CarlaString(j+1);
  1767. }
  1768. else
  1769. portName += "cv_input";
  1770. portName.truncate(portNameSize);
  1771. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV,
  1772. portName, true, j);
  1773. pData->cvIn.ports[j].rindex = j;
  1774. }
  1775. // CV Outs
  1776. for (uint32_t j=0; j < cvOuts; ++j)
  1777. {
  1778. portName.clear();
  1779. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1780. {
  1781. portName = pData->name;
  1782. portName += ":";
  1783. }
  1784. if (cvOuts > 1)
  1785. {
  1786. portName += "cv_output_";
  1787. portName += CarlaString(j+1);
  1788. }
  1789. else
  1790. portName += "cv_output";
  1791. portName.truncate(portNameSize);
  1792. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV,
  1793. portName, false, j);
  1794. pData->cvOut.ports[j].rindex = j;
  1795. }
  1796. for (int32_t j=0; j < numParameters; ++j)
  1797. {
  1798. v3_param_info paramInfo = {};
  1799. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller,
  1800. j, &paramInfo) == V3_OK);
  1801. char strBuf[200];
  1802. strncpy_utf8(strBuf, paramInfo.title, 128);
  1803. const v3_param_id paramId = paramInfo.param_id;
  1804. pData->param.data[j].index = static_cast<uint32_t>(j);
  1805. pData->param.data[j].rindex = paramId;
  1806. if (paramInfo.flags & (V3_PARAM_IS_BYPASS|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  1807. continue;
  1808. double min, max, def, step, stepSmall, stepLarge;
  1809. min = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId, 0.0);
  1810. max = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId, 1.0);
  1811. def = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId,
  1812. paramInfo.default_normalised_value);
  1813. if (min >= max)
  1814. max = min + 0.1;
  1815. if (def < min)
  1816. def = min;
  1817. else if (def > max)
  1818. def = max;
  1819. if (paramInfo.flags & V3_PARAM_READ_ONLY)
  1820. pData->param.data[j].type = PARAMETER_OUTPUT;
  1821. else
  1822. pData->param.data[j].type = PARAMETER_INPUT;
  1823. if (paramInfo.step_count == 1)
  1824. {
  1825. step = max - min;
  1826. stepSmall = step;
  1827. stepLarge = step;
  1828. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  1829. }
  1830. /*
  1831. else if (paramInfo.step_count != 0 && (paramInfo.flags & V3_PARAM_IS_LIST) != 0x0)
  1832. {
  1833. step = 1.0;
  1834. stepSmall = 1.0;
  1835. stepLarge = std::min(max - min, 10.0);
  1836. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  1837. }
  1838. */
  1839. else
  1840. {
  1841. float range = max - min;
  1842. step = range/100.0;
  1843. stepSmall = range/1000.0;
  1844. stepLarge = range/10.0;
  1845. }
  1846. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  1847. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1848. if (paramInfo.flags & V3_PARAM_CAN_AUTOMATE)
  1849. {
  1850. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  1851. if ((paramInfo.flags & V3_PARAM_IS_LIST) == 0x0)
  1852. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1853. }
  1854. pData->param.ranges[j].min = min;
  1855. pData->param.ranges[j].max = max;
  1856. pData->param.ranges[j].def = def;
  1857. pData->param.ranges[j].step = step;
  1858. pData->param.ranges[j].stepSmall = stepSmall;
  1859. pData->param.ranges[j].stepLarge = stepLarge;
  1860. }
  1861. if (numParameters > 0)
  1862. {
  1863. fEvents.paramInputs = new carla_v3_input_param_changes(pData->param);
  1864. fEvents.paramOutputs = new carla_v3_output_param_changes(pData->param);
  1865. }
  1866. if (needsCtrlIn)
  1867. {
  1868. portName.clear();
  1869. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1870. {
  1871. portName = pData->name;
  1872. portName += ":";
  1873. }
  1874. portName += "events-in";
  1875. portName.truncate(portNameSize);
  1876. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1877. portName, true, 0);
  1878. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1879. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1880. #endif
  1881. fEvents.eventInputs = new carla_v3_input_event_list;
  1882. }
  1883. if (needsCtrlOut)
  1884. {
  1885. portName.clear();
  1886. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1887. {
  1888. portName = pData->name;
  1889. portName += ":";
  1890. }
  1891. portName += "events-out";
  1892. portName.truncate(portNameSize);
  1893. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1894. portName, false, 0);
  1895. fEvents.eventOutputs = new carla_v3_output_event_list;
  1896. }
  1897. // plugin hints
  1898. const PluginCategory v3category = getPluginCategoryFromV3SubCategories(fV3ClassInfo.v2.sub_categories);
  1899. pData->hints = 0x0;
  1900. if (v3category == PLUGIN_CATEGORY_SYNTH)
  1901. pData->hints |= PLUGIN_IS_SYNTH;
  1902. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  1903. if (fV3.view != nullptr &&
  1904. v3_cpp_obj(fV3.view)->is_platform_type_supported(fV3.view, V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_TRUE)
  1905. {
  1906. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1907. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1908. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1909. }
  1910. #endif
  1911. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1912. pData->hints |= PLUGIN_CAN_DRYWET;
  1913. if (aOuts > 0)
  1914. pData->hints |= PLUGIN_CAN_VOLUME;
  1915. if (aOuts >= 2 && aOuts % 2 == 0)
  1916. pData->hints |= PLUGIN_CAN_BALANCE;
  1917. // extra plugin hints
  1918. pData->extraHints = 0x0;
  1919. if (numEventInputBuses > 0)
  1920. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1921. if (numEventOutputBuses > 0)
  1922. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1923. // check initial latency
  1924. if ((fLastKnownLatency = v3_cpp_obj(fV3.processor)->get_latency_samples(fV3.processor)) != 0)
  1925. {
  1926. pData->client->setLatency(fLastKnownLatency);
  1927. #ifndef BUILD_BRIDGE
  1928. pData->latency.recreateBuffers(std::max(aIns+cvIns, aOuts+cvOuts), fLastKnownLatency);
  1929. #endif
  1930. }
  1931. // initial audio setup
  1932. v3_process_setup setup = {
  1933. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  1934. V3_SAMPLE_32,
  1935. static_cast<int32_t>(pData->engine->getBufferSize()),
  1936. pData->engine->getSampleRate()
  1937. };
  1938. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  1939. // activate all buses
  1940. for (int32_t j=0; j<numAudioInputBuses; ++j)
  1941. {
  1942. v3_bus_info busInfo = {};
  1943. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1944. V3_AUDIO, V3_INPUT, j, &busInfo) == V3_OK);
  1945. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1946. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1947. V3_AUDIO, V3_INPUT, j, true) == V3_OK);
  1948. }
  1949. }
  1950. for (int32_t j=0; j<numAudioOutputBuses; ++j)
  1951. {
  1952. v3_bus_info busInfo = {};
  1953. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1954. V3_AUDIO, V3_OUTPUT, j, &busInfo) == V3_OK);
  1955. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1956. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1957. V3_AUDIO, V3_OUTPUT, j, true) == V3_OK);
  1958. }
  1959. }
  1960. bufferSizeChanged(pData->engine->getBufferSize());
  1961. reloadPrograms(true);
  1962. if (pData->active)
  1963. activate();
  1964. else
  1965. runIdleCallbacksAsNeeded(false);
  1966. carla_debug("CarlaPluginVST3::reload() - end");
  1967. }
  1968. // ----------------------------------------------------------------------------------------------------------------
  1969. // Plugin processing
  1970. void activate() noexcept override
  1971. {
  1972. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1973. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1974. try {
  1975. v3_cpp_obj(fV3.component)->set_active(fV3.component, true);
  1976. } CARLA_SAFE_EXCEPTION("set_active on");
  1977. try {
  1978. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, true);
  1979. } CARLA_SAFE_EXCEPTION("set_processing on");
  1980. fFirstActive = true;
  1981. runIdleCallbacksAsNeeded(false);
  1982. }
  1983. void deactivate() noexcept override
  1984. {
  1985. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1986. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1987. try {
  1988. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, false);
  1989. } CARLA_SAFE_EXCEPTION("set_processing off");
  1990. try {
  1991. v3_cpp_obj(fV3.component)->set_active(fV3.component, false);
  1992. } CARLA_SAFE_EXCEPTION("set_active off");
  1993. runIdleCallbacksAsNeeded(false);
  1994. }
  1995. void process(const float* const* const audioIn, float** const audioOut,
  1996. const float* const* const cvIn, float** const cvOut, const uint32_t frames) override
  1997. {
  1998. // ------------------------------------------------------------------------------------------------------------
  1999. // Check if active
  2000. if (! pData->active)
  2001. {
  2002. // disable any output sound
  2003. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2004. carla_zeroFloats(audioOut[i], frames);
  2005. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2006. carla_zeroFloats(cvOut[i], frames);
  2007. return;
  2008. }
  2009. fEvents.init();
  2010. // ------------------------------------------------------------------------------------------------------------
  2011. // Check if needs reset
  2012. if (pData->needsReset)
  2013. {
  2014. if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS && fEvents.eventInputs != nullptr)
  2015. {
  2016. fEvents.eventInputs->numEvents = MAX_MIDI_NOTE;
  2017. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  2018. {
  2019. v3_event& event(fEvents.eventInputs->events[i]);
  2020. carla_zeroStruct(event);
  2021. event.type = V3_EVENT_NOTE_OFF;
  2022. event.note_off.channel = (pData->ctrlChannel & MIDI_CHANNEL_BIT);
  2023. event.note_off.pitch = i;
  2024. }
  2025. }
  2026. pData->needsReset = false;
  2027. }
  2028. // ------------------------------------------------------------------------------------------------------------
  2029. // Set TimeInfo
  2030. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  2031. fV3TimeContext.state = V3_PROCESS_CTX_PROJECT_TIME_VALID | V3_PROCESS_CTX_CONT_TIME_VALID;
  2032. fV3TimeContext.sample_rate = pData->engine->getSampleRate();
  2033. fV3TimeContext.project_time_in_samples = fV3TimeContext.continuous_time_in_samples
  2034. = static_cast<int64_t>(timeInfo.frame);
  2035. if (fFirstActive || ! fLastTimeInfo.compareIgnoringRollingFrames(timeInfo, frames))
  2036. fLastTimeInfo = timeInfo;
  2037. if (timeInfo.playing)
  2038. fV3TimeContext.state |= V3_PROCESS_CTX_PLAYING;
  2039. if (timeInfo.usecs != 0)
  2040. {
  2041. fV3TimeContext.system_time_ns = static_cast<int64_t>(timeInfo.usecs / 1000);
  2042. fV3TimeContext.state |= V3_PROCESS_CTX_SYSTEM_TIME_VALID;
  2043. }
  2044. if (timeInfo.bbt.valid)
  2045. {
  2046. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  2047. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  2048. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  2049. // const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  2050. // const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  2051. // PPQ Pos
  2052. fV3TimeContext.project_time_quarters = static_cast<double>(timeInfo.frame) / (fV3TimeContext.sample_rate * 60 / timeInfo.bbt.beatsPerMinute);
  2053. // fTimeInfo.project_time_quarters = ppqBar + ppqBeat + ppqTick;
  2054. fV3TimeContext.state |= V3_PROCESS_CTX_PROJECT_TIME_VALID;
  2055. // Tempo
  2056. fV3TimeContext.bpm = timeInfo.bbt.beatsPerMinute;
  2057. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  2058. // Bars
  2059. fV3TimeContext.bar_position_quarters = ppqBar;
  2060. fV3TimeContext.state |= V3_PROCESS_CTX_BAR_POSITION_VALID;
  2061. // Time Signature
  2062. fV3TimeContext.time_sig_numerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  2063. fV3TimeContext.time_sig_denom = static_cast<int32_t>(timeInfo.bbt.beatType + 0.5f);
  2064. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  2065. }
  2066. else
  2067. {
  2068. // Tempo
  2069. fV3TimeContext.bpm = 120.0;
  2070. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  2071. // Time Signature
  2072. fV3TimeContext.time_sig_numerator = 4;
  2073. fV3TimeContext.time_sig_denom = 4;
  2074. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  2075. // Missing info
  2076. fV3TimeContext.project_time_quarters = 0.0;
  2077. fV3TimeContext.bar_position_quarters = 0.0;
  2078. }
  2079. // ------------------------------------------------------------------------------------------------------------
  2080. // Event Input and Processing
  2081. if (pData->event.portIn != nullptr && fEvents.eventInputs != nullptr)
  2082. {
  2083. // --------------------------------------------------------------------------------------------------------
  2084. // MIDI Input (External)
  2085. if (pData->extNotes.mutex.tryLock())
  2086. {
  2087. ExternalMidiNote note = { 0, 0, 0 };
  2088. uint16_t numEvents = fEvents.eventInputs->numEvents;
  2089. for (; numEvents < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  2090. {
  2091. note = pData->extNotes.data.getFirst(note, true);
  2092. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  2093. v3_event& event(fEvents.eventInputs->events[numEvents++]);
  2094. carla_zeroStruct(event);
  2095. if (note.velo > 0)
  2096. {
  2097. event.type = V3_EVENT_NOTE_ON;
  2098. event.note_on.channel = (note.channel & MIDI_CHANNEL_BIT);
  2099. event.note_on.pitch = note.note;
  2100. event.note_on.velocity = static_cast<float>(note.velo) / 127.f;
  2101. }
  2102. else
  2103. {
  2104. event.type = V3_EVENT_NOTE_OFF;
  2105. event.note_off.channel = (note.channel & MIDI_CHANNEL_BIT);
  2106. event.note_off.pitch = note.note;
  2107. }
  2108. }
  2109. pData->extNotes.mutex.unlock();
  2110. fEvents.eventInputs->numEvents = numEvents;
  2111. } // End of MIDI Input (External)
  2112. // --------------------------------------------------------------------------------------------------------
  2113. // Event Input (System)
  2114. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  2115. uint32_t startTime = 0;
  2116. uint32_t timeOffset = 0;
  2117. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2118. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  2119. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, isSampleAccurate, pData->event.portIn);
  2120. #endif
  2121. for (uint32_t i=0, numEvents = pData->event.portIn->getEventCount(); i < numEvents; ++i)
  2122. {
  2123. EngineEvent& event(pData->event.portIn->getEvent(i));
  2124. uint32_t eventTime = event.time;
  2125. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  2126. if (eventTime < timeOffset)
  2127. {
  2128. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  2129. eventTime, timeOffset, pData->name);
  2130. eventTime = timeOffset;
  2131. }
  2132. if (isSampleAccurate && eventTime > timeOffset)
  2133. {
  2134. if (processSingle(audioIn, audioOut, cvIn, cvOut, eventTime - timeOffset, timeOffset))
  2135. {
  2136. startTime = 0;
  2137. timeOffset = eventTime;
  2138. // TODO
  2139. }
  2140. else
  2141. {
  2142. startTime += timeOffset;
  2143. }
  2144. }
  2145. switch (event.type)
  2146. {
  2147. case kEngineEventTypeNull:
  2148. break;
  2149. case kEngineEventTypeControl: {
  2150. EngineControlEvent& ctrlEvent(event.ctrl);
  2151. switch (ctrlEvent.type)
  2152. {
  2153. case kEngineControlEventTypeNull:
  2154. break;
  2155. case kEngineControlEventTypeParameter: {
  2156. float value;
  2157. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2158. // non-midi
  2159. if (event.channel == kEngineEventNonMidiChannel)
  2160. {
  2161. const uint32_t k = ctrlEvent.param;
  2162. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  2163. ctrlEvent.handled = true;
  2164. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  2165. setParameterValueRT(k, value, event.time, true);
  2166. continue;
  2167. }
  2168. // Control backend stuff
  2169. if (event.channel == pData->ctrlChannel)
  2170. {
  2171. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  2172. {
  2173. ctrlEvent.handled = true;
  2174. value = ctrlEvent.normalizedValue;
  2175. setDryWetRT(value, true);
  2176. }
  2177. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  2178. {
  2179. ctrlEvent.handled = true;
  2180. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  2181. setVolumeRT(value, true);
  2182. }
  2183. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  2184. {
  2185. float left, right;
  2186. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  2187. if (value < 0.0f)
  2188. {
  2189. left = -1.0f;
  2190. right = (value*2.0f)+1.0f;
  2191. }
  2192. else if (value > 0.0f)
  2193. {
  2194. left = (value*2.0f)-1.0f;
  2195. right = 1.0f;
  2196. }
  2197. else
  2198. {
  2199. left = -1.0f;
  2200. right = 1.0f;
  2201. }
  2202. ctrlEvent.handled = true;
  2203. setBalanceLeftRT(left, true);
  2204. setBalanceRightRT(right, true);
  2205. }
  2206. }
  2207. #endif
  2208. // Control plugin parameters
  2209. uint32_t k;
  2210. for (k=0; k < pData->param.count; ++k)
  2211. {
  2212. if (pData->param.data[k].midiChannel != event.channel)
  2213. continue;
  2214. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  2215. continue;
  2216. if (pData->param.data[k].type != PARAMETER_INPUT)
  2217. continue;
  2218. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  2219. continue;
  2220. ctrlEvent.handled = true;
  2221. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  2222. setParameterValueRT(k, value, event.time, true);
  2223. }
  2224. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  2225. {
  2226. v3_param_id paramId = 0;
  2227. if (v3_cpp_obj(fV3.midiMapping)->get_midi_controller_assignment(fV3.midiMapping,
  2228. 0,
  2229. event.channel,
  2230. ctrlEvent.param,
  2231. &paramId) == V3_OK)
  2232. {
  2233. uint32_t index = UINT32_MAX;
  2234. for (uint32_t i=0; i < pData->param.count; ++i)
  2235. {
  2236. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2237. {
  2238. index = i;
  2239. break;
  2240. }
  2241. }
  2242. if (index == UINT32_MAX)
  2243. break;
  2244. fEvents.paramInputs->setParamValueRT(index, event.time, ctrlEvent.normalizedValue);
  2245. }
  2246. }
  2247. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2248. if (! ctrlEvent.handled)
  2249. checkForMidiLearn(event);
  2250. #endif
  2251. break;
  2252. } // case kEngineControlEventTypeParameter
  2253. case kEngineControlEventTypeMidiBank:
  2254. break;
  2255. case kEngineControlEventTypeMidiProgram:
  2256. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  2257. {
  2258. if (ctrlEvent.param < pData->prog.count)
  2259. {
  2260. setProgramRT(ctrlEvent.param, true);
  2261. break;
  2262. }
  2263. }
  2264. break;
  2265. case kEngineControlEventTypeAllSoundOff:
  2266. case kEngineControlEventTypeAllNotesOff:
  2267. // TODO map to CC
  2268. break;
  2269. } // switch (ctrlEvent.type)
  2270. break;
  2271. } // case kEngineEventTypeControl
  2272. case kEngineEventTypeMidi: {
  2273. const EngineMidiEvent& midiEvent(event.midi);
  2274. if (midiEvent.size > 3)
  2275. continue;
  2276. #ifdef CARLA_PROPER_CPP11_SUPPORT
  2277. static_assert(3 <= EngineMidiEvent::kDataSize, "Incorrect data");
  2278. #endif
  2279. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  2280. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2281. continue;
  2282. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  2283. continue;
  2284. if (status == MIDI_STATUS_CONTROL_CHANGE && ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0 || fEvents.paramInputs == nullptr || fV3.midiMapping == nullptr))
  2285. continue;
  2286. if (status == MIDI_STATUS_CHANNEL_PRESSURE && ((pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0 || fEvents.paramInputs == nullptr || fV3.midiMapping == nullptr))
  2287. continue;
  2288. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && ((pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0 || fEvents.paramInputs == nullptr || fV3.midiMapping == nullptr))
  2289. continue;
  2290. // Fix bad note-off
  2291. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  2292. status = MIDI_STATUS_NOTE_OFF;
  2293. switch (status)
  2294. {
  2295. case MIDI_STATUS_NOTE_OFF:
  2296. if (fEvents.eventInputs->numEvents < kPluginMaxMidiEvents)
  2297. {
  2298. const uint8_t note = midiEvent.data[1];
  2299. v3_event& v3event(fEvents.eventInputs->events[fEvents.eventInputs->numEvents++]);
  2300. carla_zeroStruct(v3event);
  2301. v3event.type = V3_EVENT_NOTE_OFF;
  2302. v3event.note_off.channel = event.channel & MIDI_CHANNEL_BIT;
  2303. v3event.note_off.pitch = note;
  2304. pData->postponeNoteOffRtEvent(true, event.channel, note);
  2305. }
  2306. break;
  2307. case MIDI_STATUS_NOTE_ON:
  2308. if (fEvents.eventInputs->numEvents < kPluginMaxMidiEvents)
  2309. {
  2310. const uint8_t note = midiEvent.data[1];
  2311. const uint8_t velo = midiEvent.data[2];
  2312. v3_event& v3event(fEvents.eventInputs->events[fEvents.eventInputs->numEvents++]);
  2313. carla_zeroStruct(v3event);
  2314. v3event.type = V3_EVENT_NOTE_ON;
  2315. v3event.note_on.channel = event.channel & MIDI_CHANNEL_BIT;
  2316. v3event.note_on.pitch = note;
  2317. v3event.note_on.velocity = static_cast<float>(velo) / 127.f;
  2318. pData->postponeNoteOnRtEvent(true, event.channel, note, velo);
  2319. }
  2320. break;
  2321. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  2322. if (fEvents.eventInputs->numEvents < kPluginMaxMidiEvents)
  2323. {
  2324. const uint8_t note = midiEvent.data[1];
  2325. const uint8_t pressure = midiEvent.data[2];
  2326. v3_event& v3event(fEvents.eventInputs->events[fEvents.eventInputs->numEvents++]);
  2327. carla_zeroStruct(v3event);
  2328. v3event.type = V3_EVENT_POLY_PRESSURE;
  2329. v3event.poly_pressure.channel = event.channel;
  2330. v3event.poly_pressure.pitch = note;
  2331. v3event.poly_pressure.pressure = static_cast<float>(pressure) / 127.f;
  2332. }
  2333. break;
  2334. case MIDI_STATUS_CONTROL_CHANGE:
  2335. {
  2336. const uint8_t control = midiEvent.data[1];
  2337. const uint8_t value = midiEvent.data[2];
  2338. v3_param_id paramId = 0;
  2339. if (v3_cpp_obj(fV3.midiMapping)->get_midi_controller_assignment(fV3.midiMapping,
  2340. midiEvent.port,
  2341. event.channel,
  2342. control,
  2343. &paramId) == V3_OK)
  2344. {
  2345. uint32_t index = UINT32_MAX;
  2346. for (uint32_t i=0; i < pData->param.count; ++i)
  2347. {
  2348. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2349. {
  2350. index = i;
  2351. break;
  2352. }
  2353. }
  2354. if (index == UINT32_MAX)
  2355. break;
  2356. fEvents.paramInputs->setParamValueRT(index,
  2357. event.time,
  2358. static_cast<float>(value) / 127.f);
  2359. }
  2360. }
  2361. break;
  2362. case MIDI_STATUS_CHANNEL_PRESSURE:
  2363. {
  2364. const uint8_t pressure = midiEvent.data[1];
  2365. v3_param_id paramId = 0;
  2366. if (v3_cpp_obj(fV3.midiMapping)->get_midi_controller_assignment(fV3.midiMapping,
  2367. midiEvent.port,
  2368. event.channel,
  2369. 128,
  2370. &paramId) == V3_OK)
  2371. {
  2372. uint32_t index = UINT32_MAX;
  2373. for (uint32_t i=0; i < pData->param.count; ++i)
  2374. {
  2375. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2376. {
  2377. index = i;
  2378. break;
  2379. }
  2380. }
  2381. if (index == UINT32_MAX)
  2382. break;
  2383. fEvents.paramInputs->setParamValueRT(index,
  2384. event.time,
  2385. static_cast<float>(pressure) / 127.f);
  2386. }
  2387. }
  2388. break;
  2389. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  2390. {
  2391. const uint16_t pitchbend = (midiEvent.data[2] << 7) | midiEvent.data[1];
  2392. v3_param_id paramId = 0;
  2393. if (v3_cpp_obj(fV3.midiMapping)->get_midi_controller_assignment(fV3.midiMapping,
  2394. midiEvent.port,
  2395. event.channel,
  2396. 129,
  2397. &paramId) == V3_OK)
  2398. {
  2399. uint32_t index = UINT32_MAX;
  2400. for (uint32_t i=0; i < pData->param.count; ++i)
  2401. {
  2402. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2403. {
  2404. index = i;
  2405. break;
  2406. }
  2407. }
  2408. if (index == UINT32_MAX)
  2409. break;
  2410. fEvents.paramInputs->setParamValueRT(index,
  2411. event.time,
  2412. static_cast<float>(pitchbend) / 16384.f);
  2413. }
  2414. }
  2415. break;
  2416. } // switch (status)
  2417. } break;
  2418. } // switch (event.type)
  2419. }
  2420. pData->postRtEvents.trySplice();
  2421. if (frames > timeOffset)
  2422. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset);
  2423. } // End of Event Input and Processing
  2424. // ------------------------------------------------------------------------------------------------------------
  2425. // Plugin processing (no events)
  2426. else
  2427. {
  2428. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0);
  2429. } // End of Plugin processing (no events)
  2430. // ------------------------------------------------------------------------------------------------------------
  2431. // MIDI Output
  2432. if (pData->event.portOut != nullptr)
  2433. {
  2434. // TODO
  2435. } // End of MIDI Output
  2436. fFirstActive = false;
  2437. // ------------------------------------------------------------------------------------------------------------
  2438. }
  2439. bool processSingle(const float* const* const inBuffer, float** const outBuffer,
  2440. const float* const* const cvIn, float** const cvOut,
  2441. const uint32_t frames, const uint32_t timeOffset)
  2442. {
  2443. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  2444. if (pData->audioIn.count > 0)
  2445. {
  2446. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  2447. }
  2448. if (pData->audioOut.count > 0)
  2449. {
  2450. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  2451. CARLA_SAFE_ASSERT_RETURN(fAudioAndCvOutBuffers != nullptr, false);
  2452. }
  2453. // ------------------------------------------------------------------------------------------------------------
  2454. // Try lock, silence otherwise
  2455. #ifndef STOAT_TEST_BUILD
  2456. if (pData->engine->isOffline())
  2457. {
  2458. pData->singleMutex.lock();
  2459. }
  2460. else
  2461. #endif
  2462. if (! pData->singleMutex.tryLock())
  2463. {
  2464. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2465. {
  2466. for (uint32_t k=0; k < frames; ++k)
  2467. outBuffer[i][k+timeOffset] = 0.0f;
  2468. }
  2469. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2470. {
  2471. for (uint32_t k=0; k < frames; ++k)
  2472. cvOut[i][k+timeOffset] = 0.0f;
  2473. }
  2474. return false;
  2475. }
  2476. // ------------------------------------------------------------------------------------------------------------
  2477. // Set audio buffers
  2478. float* bufferAudioIn[96]; // std::max(1u, pData->audioIn.count + pData->cvIn.count)
  2479. float* bufferAudioOut[96]; // std::max(1u, pData->audioOut.count + pData->cvOut.count)
  2480. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  2481. bufferAudioIn[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  2482. for (uint32_t i=0, j=pData->audioIn.count; i < pData->cvIn.count; ++i, ++j)
  2483. bufferAudioIn[j] = const_cast<float*>(cvIn[i]+timeOffset);
  2484. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2485. {
  2486. bufferAudioOut[i] = fAudioAndCvOutBuffers[i]+timeOffset;
  2487. carla_zeroFloats(bufferAudioOut[i], frames);
  2488. }
  2489. // ------------------------------------------------------------------------------------------------------------
  2490. // Set MIDI events
  2491. // TODO
  2492. // ------------------------------------------------------------------------------------------------------------
  2493. // Run plugin
  2494. fEvents.prepare();
  2495. for (int32_t b = 0, j = 0; b < fBuses.numInputs; ++b)
  2496. {
  2497. fBuses.inputs[b].channel_buffers_32 = const_cast<float**>(bufferAudioIn + j);
  2498. j += fBuses.inputs[b].num_channels;
  2499. }
  2500. for (int32_t b = 0, j = 0; b < fBuses.numOutputs; ++b)
  2501. {
  2502. fBuses.outputs[b].channel_buffers_32 = bufferAudioOut + j;
  2503. j += fBuses.outputs[b].num_channels;
  2504. }
  2505. v3_process_data processData = {
  2506. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2507. V3_SAMPLE_32,
  2508. static_cast<int32_t>(frames),
  2509. fBuses.numInputs,
  2510. fBuses.numOutputs,
  2511. fBuses.inputs,
  2512. fBuses.outputs,
  2513. fEvents.paramInputs != nullptr ? (v3_param_changes**)&fEvents.paramInputs : nullptr,
  2514. fEvents.paramOutputs != nullptr ? (v3_param_changes**)&fEvents.paramOutputs : nullptr,
  2515. fEvents.eventInputs != nullptr ? (v3_event_list**)&fEvents.eventInputs : nullptr,
  2516. fEvents.eventOutputs != nullptr ? (v3_event_list**)&fEvents.eventOutputs : nullptr,
  2517. &fV3TimeContext
  2518. };
  2519. try {
  2520. v3_cpp_obj(fV3.processor)->process(fV3.processor, &processData);
  2521. } CARLA_SAFE_EXCEPTION("process");
  2522. // ------------------------------------------------------------------------------------------------------------
  2523. // Handle parameter outputs
  2524. if (fEvents.paramOutputs != nullptr && fEvents.paramOutputs->numParametersUsed != 0)
  2525. {
  2526. uint8_t channel;
  2527. uint16_t param;
  2528. for (uint32_t i=0; i < pData->param.count; ++i)
  2529. {
  2530. if (fEvents.paramOutputs->parametersUsed[i])
  2531. {
  2532. carla_v3_output_param_value_queue* const queue = fEvents.paramOutputs->queue[i];
  2533. const v3_param_id paramId = pData->param.data[i].rindex;
  2534. const float value = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller,
  2535. paramId,
  2536. queue->value);
  2537. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(i), value);
  2538. if (pData->param.data[i].type == PARAMETER_OUTPUT && pData->param.data[i].mappedControlIndex > 0)
  2539. {
  2540. channel = pData->param.data[i].midiChannel;
  2541. param = static_cast<uint16_t>(pData->param.data[i].mappedControlIndex);
  2542. pData->event.portOut->writeControlEvent(queue->offset,
  2543. channel,
  2544. kEngineControlEventTypeParameter,
  2545. param,
  2546. -1,
  2547. queue->value);
  2548. }
  2549. }
  2550. }
  2551. }
  2552. pData->postRtEvents.trySplice();
  2553. fEvents.init();
  2554. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2555. // ------------------------------------------------------------------------------------------------------------
  2556. // Post-processing (dry/wet, volume and balance)
  2557. {
  2558. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0
  2559. && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  2560. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0
  2561. && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f)
  2562. && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  2563. const bool isMono = (pData->audioIn.count == 1);
  2564. bool isPair;
  2565. float bufValue;
  2566. float* const oldBufLeft = pData->postProc.extraBuffer;
  2567. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2568. {
  2569. // Dry/Wet
  2570. if (doDryWet)
  2571. {
  2572. const uint32_t c = isMono ? 0 : i;
  2573. for (uint32_t k=0; k < frames; ++k)
  2574. {
  2575. bufValue = inBuffer[c][k+timeOffset];
  2576. fAudioAndCvOutBuffers[i][k] = (fAudioAndCvOutBuffers[i][k] * pData->postProc.dryWet)
  2577. + (bufValue * (1.0f - pData->postProc.dryWet));
  2578. }
  2579. }
  2580. // Balance
  2581. if (doBalance)
  2582. {
  2583. isPair = (i % 2 == 0);
  2584. if (isPair)
  2585. {
  2586. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2587. carla_copyFloats(oldBufLeft, fAudioAndCvOutBuffers[i], frames);
  2588. }
  2589. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2590. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2591. for (uint32_t k=0; k < frames; ++k)
  2592. {
  2593. if (isPair)
  2594. {
  2595. // left
  2596. fAudioAndCvOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2597. fAudioAndCvOutBuffers[i][k] += fAudioAndCvOutBuffers[i+1][k] * (1.0f - balRangeR);
  2598. }
  2599. else
  2600. {
  2601. // right
  2602. fAudioAndCvOutBuffers[i][k] = fAudioAndCvOutBuffers[i][k] * balRangeR;
  2603. fAudioAndCvOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2604. }
  2605. }
  2606. }
  2607. // Volume (and buffer copy)
  2608. {
  2609. for (uint32_t k=0; k < frames; ++k)
  2610. outBuffer[i][k+timeOffset] = fAudioAndCvOutBuffers[i][k] * pData->postProc.volume;
  2611. }
  2612. }
  2613. for (uint32_t i=0, j=pData->audioOut.count; i < pData->cvOut.count; ++i, ++j)
  2614. carla_copyFloats(cvOut[i] + timeOffset, fAudioAndCvOutBuffers[j] + timeOffset, frames);
  2615. } // End of Post-processing
  2616. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2617. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2618. carla_copyFloats(outBuffer[i] + timeOffset, fAudioAndCvOutBuffers[i] + timeOffset, frames);
  2619. for (uint32_t i=0, j=pData->audioOut.count; i < pData->cvOut.count; ++i, ++j)
  2620. carla_copyFloats(cvOut[i] + timeOffset, fAudioAndCvOutBuffers[j] + timeOffset, frames);
  2621. #endif
  2622. // ------------------------------------------------------------------------------------------------------------
  2623. pData->singleMutex.unlock();
  2624. return true;
  2625. }
  2626. void bufferSizeChanged(const uint32_t newBufferSize) override
  2627. {
  2628. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2629. carla_debug("CarlaPluginVST3::bufferSizeChanged(%i)", newBufferSize);
  2630. if (pData->active)
  2631. deactivate();
  2632. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2633. {
  2634. if (fAudioAndCvOutBuffers[i] != nullptr)
  2635. delete[] fAudioAndCvOutBuffers[i];
  2636. fAudioAndCvOutBuffers[i] = new float[newBufferSize];
  2637. }
  2638. v3_process_setup setup = {
  2639. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2640. V3_SAMPLE_32,
  2641. static_cast<int32_t>(newBufferSize),
  2642. pData->engine->getSampleRate()
  2643. };
  2644. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2645. if (pData->active)
  2646. activate();
  2647. CarlaPlugin::bufferSizeChanged(newBufferSize);
  2648. }
  2649. void sampleRateChanged(const double newSampleRate) override
  2650. {
  2651. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  2652. carla_debug("CarlaPluginVST3::sampleRateChanged(%g)", newSampleRate);
  2653. if (pData->active)
  2654. deactivate();
  2655. v3_process_setup setup = {
  2656. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2657. V3_SAMPLE_32,
  2658. static_cast<int32_t>(pData->engine->getBufferSize()),
  2659. newSampleRate
  2660. };
  2661. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2662. if (pData->active)
  2663. activate();
  2664. }
  2665. void offlineModeChanged(const bool isOffline) override
  2666. {
  2667. carla_debug("CarlaPluginVST3::offlineModeChanged(%d)", isOffline);
  2668. if (pData->active)
  2669. deactivate();
  2670. v3_process_setup setup = {
  2671. isOffline ? V3_OFFLINE : V3_REALTIME,
  2672. V3_SAMPLE_32,
  2673. static_cast<int32_t>(pData->engine->getBufferSize()),
  2674. pData->engine->getSampleRate()
  2675. };
  2676. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2677. if (pData->active)
  2678. activate();
  2679. }
  2680. // ----------------------------------------------------------------------------------------------------------------
  2681. // Plugin buffers
  2682. void clearBuffers() noexcept override
  2683. {
  2684. carla_debug("CarlaPluginVST3::clearBuffers() - start");
  2685. if (fAudioAndCvOutBuffers != nullptr)
  2686. {
  2687. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2688. {
  2689. if (fAudioAndCvOutBuffers[i] != nullptr)
  2690. {
  2691. delete[] fAudioAndCvOutBuffers[i];
  2692. fAudioAndCvOutBuffers[i] = nullptr;
  2693. }
  2694. }
  2695. delete[] fAudioAndCvOutBuffers;
  2696. fAudioAndCvOutBuffers = nullptr;
  2697. }
  2698. CarlaPlugin::clearBuffers();
  2699. carla_debug("CarlaPluginVST3::clearBuffers() - end");
  2700. }
  2701. // ----------------------------------------------------------------------------------------------------------------
  2702. // Post-poned UI Stuff
  2703. void uiParameterChange(const uint32_t index, const float value) noexcept override
  2704. {
  2705. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  2706. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  2707. const v3_param_id paramId = pData->param.data[index].rindex;
  2708. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  2709. paramId, value);
  2710. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, paramId, normalized);
  2711. }
  2712. // ----------------------------------------------------------------------------------------------------------------
  2713. bool hasMidiInput() const noexcept
  2714. {
  2715. return pData->extraHints & PLUGIN_EXTRA_HINT_HAS_MIDI_IN ||
  2716. std::strstr(fV3ClassInfo.v2.sub_categories, "Instrument") != nullptr ||
  2717. v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_INPUT) > 0;
  2718. }
  2719. // ----------------------------------------------------------------------------------------------------------------
  2720. const void* getNativeDescriptor() const noexcept override
  2721. {
  2722. return fV3.component;
  2723. }
  2724. const void* getExtraStuff() const noexcept override
  2725. {
  2726. return fV3.controller;
  2727. }
  2728. // ----------------------------------------------------------------------------------------------------------------
  2729. bool init(const CarlaPluginPtr plugin,
  2730. const char* const filename,
  2731. const char* name,
  2732. const char* /*const label*/,
  2733. const uint options)
  2734. {
  2735. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2736. // ------------------------------------------------------------------------------------------------------------
  2737. // first checks
  2738. if (pData->client != nullptr)
  2739. {
  2740. pData->engine->setLastError("Plugin client is already registered");
  2741. return false;
  2742. }
  2743. if (filename == nullptr || filename[0] == '\0')
  2744. {
  2745. pData->engine->setLastError("null filename");
  2746. return false;
  2747. }
  2748. V3_ENTRYFN v3_entry;
  2749. V3_EXITFN v3_exit;
  2750. V3_GETFN v3_get;
  2751. // filename is full path to binary
  2752. if (water::File(filename).existsAsFile())
  2753. {
  2754. if (! pData->libOpen(filename))
  2755. {
  2756. pData->engine->setLastError(pData->libError(filename));
  2757. return false;
  2758. }
  2759. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  2760. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  2761. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  2762. }
  2763. // assume filename is a vst3 bundle
  2764. else
  2765. {
  2766. #ifdef CARLA_OS_MAC
  2767. if (! fMacBundleLoader.load(filename))
  2768. {
  2769. pData->engine->setLastError("Failed to load VST3 bundle executable");
  2770. return false;
  2771. }
  2772. v3_entry = fMacBundleLoader.getSymbol<V3_ENTRYFN>(CFSTR(V3_ENTRYFNNAME));
  2773. v3_exit = fMacBundleLoader.getSymbol<V3_EXITFN>(CFSTR(V3_EXITFNNAME));
  2774. v3_get = fMacBundleLoader.getSymbol<V3_GETFN>(CFSTR(V3_GETFNNAME));
  2775. #else
  2776. water::String binaryfilename = filename;
  2777. if (!binaryfilename.endsWithChar(CARLA_OS_SEP))
  2778. binaryfilename += CARLA_OS_SEP_STR;
  2779. binaryfilename += "Contents" CARLA_OS_SEP_STR V3_CONTENT_DIR CARLA_OS_SEP_STR;
  2780. binaryfilename += water::File(filename).getFileNameWithoutExtension();
  2781. #ifdef CARLA_OS_WIN
  2782. binaryfilename += ".vst3";
  2783. #else
  2784. binaryfilename += ".so";
  2785. #endif
  2786. if (! water::File(binaryfilename).existsAsFile())
  2787. {
  2788. pData->engine->setLastError("Failed to find a suitable VST3 bundle binary");
  2789. return false;
  2790. }
  2791. if (! pData->libOpen(binaryfilename.toRawUTF8()))
  2792. {
  2793. pData->engine->setLastError(pData->libError(binaryfilename.toRawUTF8()));
  2794. return false;
  2795. }
  2796. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  2797. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  2798. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  2799. #endif
  2800. }
  2801. // ------------------------------------------------------------------------------------------------------------
  2802. // ensure entry and exit points are available
  2803. if (v3_entry == nullptr || v3_exit == nullptr || v3_get == nullptr)
  2804. {
  2805. pData->engine->setLastError("Not a VST3 plugin");
  2806. return false;
  2807. }
  2808. // ------------------------------------------------------------------------------------------------------------
  2809. // call entry point
  2810. #if defined(CARLA_OS_MAC)
  2811. v3_entry(pData->lib == nullptr ? fMacBundleLoader.getRef() : nullptr);
  2812. #elif defined(CARLA_OS_WIN)
  2813. v3_entry();
  2814. #else
  2815. v3_entry(pData->lib);
  2816. #endif
  2817. // ------------------------------------------------------------------------------------------------------------
  2818. // fetch initial factory
  2819. v3_plugin_factory** const factory = v3_get();
  2820. if (factory == nullptr)
  2821. {
  2822. pData->engine->setLastError("VST3 factory failed to create a valid instance");
  2823. return false;
  2824. }
  2825. // ------------------------------------------------------------------------------------------------------------
  2826. // initialize and find requested plugin
  2827. fV3.exitfn = v3_exit;
  2828. fV3.factory1 = factory;
  2829. v3_funknown** const hostContext = (v3_funknown**)&fV3ApplicationPtr;
  2830. if (! fV3.queryFactories(hostContext))
  2831. {
  2832. pData->engine->setLastError("VST3 plugin failed to properly create factories");
  2833. return false;
  2834. }
  2835. if (! fV3.findPlugin(fV3ClassInfo))
  2836. {
  2837. pData->engine->setLastError("Failed to find the requested plugin in the VST3 bundle");
  2838. return false;
  2839. }
  2840. if (! fV3.initializePlugin(fV3ClassInfo.v1.class_id,
  2841. hostContext,
  2842. (v3_component_handler**)&fComponentHandlerPtr))
  2843. {
  2844. pData->engine->setLastError("VST3 plugin failed to initialize");
  2845. return false;
  2846. }
  2847. // ------------------------------------------------------------------------------------------------------------
  2848. // do some basic safety checks
  2849. if (v3_cpp_obj(fV3.processor)->can_process_sample_size(fV3.processor, V3_SAMPLE_32) != V3_OK)
  2850. {
  2851. pData->engine->setLastError("VST3 plugin does not support 32bit audio, cannot continue");
  2852. return false;
  2853. }
  2854. // ------------------------------------------------------------------------------------------------------------
  2855. // get info
  2856. if (name != nullptr && name[0] != '\0')
  2857. {
  2858. pData->name = pData->engine->getUniquePluginName(name);
  2859. }
  2860. else
  2861. {
  2862. if (fV3ClassInfo.v1.name[0] != '\0')
  2863. pData->name = pData->engine->getUniquePluginName(fV3ClassInfo.v1.name);
  2864. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  2865. pData->name = pData->engine->getUniquePluginName(shortname+1);
  2866. else
  2867. pData->name = pData->engine->getUniquePluginName("unknown");
  2868. }
  2869. pData->filename = carla_strdup(filename);
  2870. // ------------------------------------------------------------------------------------------------------------
  2871. // register client
  2872. pData->client = pData->engine->addClient(plugin);
  2873. if (pData->client == nullptr || ! pData->client->isOk())
  2874. {
  2875. pData->engine->setLastError("Failed to register plugin client");
  2876. return false;
  2877. }
  2878. // ------------------------------------------------------------------------------------------------------------
  2879. // set default options
  2880. pData->options = 0x0;
  2881. if (fLastKnownLatency != 0 /*|| hasMidiOutput()*/ || isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2882. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2883. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2884. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2885. if (hasMidiInput())
  2886. {
  2887. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2888. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2889. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2890. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2891. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2892. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2893. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2894. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2895. /* TODO
  2896. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2897. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2898. */
  2899. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2900. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2901. }
  2902. /*
  2903. if (numPrograms > 1 && isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2904. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2905. */
  2906. // ------------------------------------------------------------------------------------------------------------
  2907. return true;
  2908. }
  2909. protected:
  2910. v3_result v3BeginEdit(const v3_param_id paramId) override
  2911. {
  2912. for (uint32_t i=0; i < pData->param.count; ++i)
  2913. {
  2914. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2915. {
  2916. pData->engine->touchPluginParameter(pData->id, i, true);
  2917. return V3_OK;
  2918. }
  2919. }
  2920. return V3_INVALID_ARG;
  2921. }
  2922. v3_result v3PerformEdit(const v3_param_id paramId, const double value) override
  2923. {
  2924. CARLA_SAFE_ASSERT_RETURN(fEvents.paramInputs != nullptr, V3_INTERNAL_ERR);
  2925. for (uint32_t i=0; i < pData->param.count; ++i)
  2926. {
  2927. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2928. {
  2929. // report value to component (next process call)
  2930. fEvents.paramInputs->setParamValue(i, static_cast<float>(value));
  2931. const double plain = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller,
  2932. paramId,
  2933. value);
  2934. const float fixedValue = pData->param.getFixedValue(i, plain);
  2935. CarlaPlugin::setParameterValue(i, fixedValue, false, true, true);
  2936. return V3_OK;
  2937. }
  2938. }
  2939. return V3_INVALID_ARG;
  2940. }
  2941. v3_result v3EndEdit(const v3_param_id paramId) override
  2942. {
  2943. for (uint32_t i=0; i < pData->param.count; ++i)
  2944. {
  2945. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2946. {
  2947. pData->engine->touchPluginParameter(pData->id, i, false);
  2948. return V3_OK;
  2949. }
  2950. }
  2951. return V3_INVALID_ARG;
  2952. }
  2953. v3_result v3RestartComponent(const int32_t flags) override
  2954. {
  2955. fRestartFlags |= flags;
  2956. return V3_OK;
  2957. }
  2958. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  2959. v3_result v3ResizeView(struct v3_plugin_view** const view, struct v3_view_rect* const rect) override
  2960. {
  2961. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr, V3_INVALID_ARG);
  2962. CARLA_SAFE_ASSERT_RETURN(fV3.view == view, V3_INVALID_ARG);
  2963. const int32_t width = rect->right - rect->left;
  2964. const int32_t height = rect->bottom - rect->top;
  2965. CARLA_SAFE_ASSERT_INT_RETURN(width > 0, width, V3_INVALID_ARG);
  2966. CARLA_SAFE_ASSERT_INT_RETURN(height > 0, height, V3_INVALID_ARG);
  2967. carla_stdout("v3ResizeView %d %d", width, height);
  2968. fUI.isResizingFromPlugin = true;
  2969. fUI.width = width;
  2970. fUI.height = height;
  2971. if (fUI.isEmbed)
  2972. {
  2973. pData->engine->callback(true, true,
  2974. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  2975. pData->id,
  2976. width, height,
  2977. 0, 0.0f, nullptr);
  2978. }
  2979. else
  2980. {
  2981. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, V3_NOT_INITIALIZED);
  2982. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true, false);
  2983. }
  2984. return V3_OK;
  2985. }
  2986. void handlePluginUIClosed() override
  2987. {
  2988. // CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  2989. carla_debug("CarlaPluginVST3::handlePluginUIClosed()");
  2990. fUI.isResizingFromHost = fUI.isResizingFromInit = false;
  2991. fUI.isResizingFromPlugin = false;
  2992. showCustomUI(false);
  2993. pData->engine->callback(true, true,
  2994. ENGINE_CALLBACK_UI_STATE_CHANGED,
  2995. pData->id,
  2996. 0,
  2997. 0, 0, 0.0f, nullptr);
  2998. }
  2999. void handlePluginUIResized(const uint width, const uint height) override
  3000. {
  3001. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr,);
  3002. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  3003. carla_stdout("CarlaPluginVST3::handlePluginUIResized(%u, %u | vs %u %u) %s %s %s",
  3004. width, height,
  3005. fUI.width, fUI.height,
  3006. bool2str(fUI.isResizingFromPlugin),
  3007. bool2str(fUI.isResizingFromInit),
  3008. bool2str(fUI.isResizingFromHost));
  3009. if (fUI.isResizingFromInit)
  3010. {
  3011. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  3012. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  3013. fUI.isResizingFromInit = false;
  3014. return;
  3015. }
  3016. if (fUI.isResizingFromPlugin)
  3017. {
  3018. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  3019. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  3020. fUI.isResizingFromPlugin = false;
  3021. return;
  3022. }
  3023. if (fUI.isResizingFromHost)
  3024. {
  3025. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  3026. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  3027. fUI.isResizingFromHost = false;
  3028. return;
  3029. }
  3030. if (fUI.width != width || fUI.height != height)
  3031. {
  3032. v3_view_rect rect = { 0, 0, static_cast<int32_t>(width), static_cast<int32_t>(height) };
  3033. if (v3_cpp_obj(fV3.view)->check_size_constraint(fV3.view, &rect) == V3_OK)
  3034. {
  3035. const uint width2 = rect.right - rect.left;
  3036. const uint height2 = rect.bottom - rect.top;
  3037. if (width2 != width || height2 != height)
  3038. {
  3039. fUI.isResizingFromHost = true;
  3040. fUI.width = width2;
  3041. fUI.height = height2;
  3042. fUI.window->setSize(width2, height2, true, false);
  3043. }
  3044. else
  3045. {
  3046. v3_cpp_obj(fV3.view)->on_size(fV3.view, &rect);
  3047. }
  3048. }
  3049. }
  3050. }
  3051. #endif // V3_VIEW_PLATFORM_TYPE_NATIVE
  3052. private:
  3053. #ifdef CARLA_OS_MAC
  3054. BundleLoader fMacBundleLoader;
  3055. #endif
  3056. const bool kEngineHasIdleOnMainThread;
  3057. bool fFirstActive; // first process() call after activate()
  3058. float** fAudioAndCvOutBuffers;
  3059. uint32_t fLastKnownLatency;
  3060. int32_t fRestartFlags;
  3061. void* fLastChunk;
  3062. EngineTimeInfo fLastTimeInfo;
  3063. v3_process_context fV3TimeContext;
  3064. carla_v3_host_application fV3Application;
  3065. carla_v3_host_application* const fV3ApplicationPtr;
  3066. carla_v3_component_handler fComponentHandler;
  3067. carla_v3_component_handler* const fComponentHandlerPtr;
  3068. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3069. carla_v3_plugin_frame fPluginFrame;
  3070. carla_v3_plugin_frame* const fPluginFramePtr;
  3071. #endif
  3072. // v3_class_info_2 is ABI compatible with v3_class_info
  3073. union ClassInfo {
  3074. v3_class_info v1;
  3075. v3_class_info_2 v2;
  3076. } fV3ClassInfo;
  3077. struct PluginPointers {
  3078. V3_EXITFN exitfn;
  3079. v3_plugin_factory** factory1;
  3080. v3_plugin_factory_2** factory2;
  3081. v3_plugin_factory_3** factory3;
  3082. v3_component** component;
  3083. v3_edit_controller** controller;
  3084. v3_audio_processor** processor;
  3085. v3_connection_point** connComponent;
  3086. v3_connection_point** connController;
  3087. v3_midi_mapping** midiMapping;
  3088. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3089. v3_plugin_view** view;
  3090. #endif
  3091. bool shouldTerminateComponent;
  3092. bool shouldTerminateController;
  3093. PluginPointers()
  3094. : exitfn(nullptr),
  3095. factory1(nullptr),
  3096. factory2(nullptr),
  3097. factory3(nullptr),
  3098. component(nullptr),
  3099. controller(nullptr),
  3100. processor(nullptr),
  3101. connComponent(nullptr),
  3102. connController(nullptr),
  3103. midiMapping(nullptr),
  3104. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3105. view(nullptr),
  3106. #endif
  3107. shouldTerminateComponent(false),
  3108. shouldTerminateController(false) {}
  3109. ~PluginPointers()
  3110. {
  3111. // must have been cleaned up by now
  3112. CARLA_SAFE_ASSERT(exitfn == nullptr);
  3113. }
  3114. // must have exitfn and factory1 set
  3115. bool queryFactories(v3_funknown** const hostContext)
  3116. {
  3117. // query 2nd factory
  3118. if (v3_cpp_obj_query_interface(factory1, v3_plugin_factory_2_iid, &factory2) == V3_OK)
  3119. {
  3120. CARLA_SAFE_ASSERT_RETURN(factory2 != nullptr, exit());
  3121. }
  3122. else
  3123. {
  3124. CARLA_SAFE_ASSERT(factory2 == nullptr);
  3125. factory2 = nullptr;
  3126. }
  3127. // query 3rd factory
  3128. if (factory2 != nullptr && v3_cpp_obj_query_interface(factory2, v3_plugin_factory_3_iid, &factory3) == V3_OK)
  3129. {
  3130. CARLA_SAFE_ASSERT_RETURN(factory3 != nullptr, exit());
  3131. }
  3132. else
  3133. {
  3134. CARLA_SAFE_ASSERT(factory3 == nullptr);
  3135. factory3 = nullptr;
  3136. }
  3137. // set host context (application) if 3rd factory provided
  3138. if (factory3 != nullptr)
  3139. v3_cpp_obj(factory3)->set_host_context(factory3, hostContext);
  3140. return true;
  3141. }
  3142. // must have all possible factories and exitfn set
  3143. bool findPlugin(ClassInfo& classInfo)
  3144. {
  3145. // get factory info
  3146. v3_factory_info factoryInfo = {};
  3147. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->get_factory_info(factory1, &factoryInfo) == V3_OK, exit());
  3148. // get num classes
  3149. const int32_t numClasses = v3_cpp_obj(factory1)->num_classes(factory1);
  3150. CARLA_SAFE_ASSERT_RETURN(numClasses > 0, exit());
  3151. // go through all relevant classes
  3152. for (int32_t i=0; i<numClasses; ++i)
  3153. {
  3154. carla_zeroStruct(classInfo);
  3155. if (factory2 != nullptr)
  3156. v3_cpp_obj(factory2)->get_class_info_2(factory2, i, &classInfo.v2);
  3157. else
  3158. v3_cpp_obj(factory1)->get_class_info(factory1, i, &classInfo.v1);
  3159. // safety check
  3160. CARLA_SAFE_ASSERT_CONTINUE(classInfo.v1.cardinality == 0x7FFFFFFF);
  3161. // only check for audio plugins
  3162. if (std::strcmp(classInfo.v1.category, "Audio Module Class") != 0)
  3163. continue;
  3164. // FIXME multi-plugin bundle
  3165. break;
  3166. }
  3167. return true;
  3168. }
  3169. bool initializePlugin(const v3_tuid uid,
  3170. v3_funknown** const hostContext,
  3171. v3_component_handler** const handler)
  3172. {
  3173. // create instance
  3174. void* instance = nullptr;
  3175. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->create_instance(factory1, uid, v3_component_iid,
  3176. &instance) == V3_OK,
  3177. exit());
  3178. CARLA_SAFE_ASSERT_RETURN(instance != nullptr, exit());
  3179. component = static_cast<v3_component**>(instance);
  3180. // initialize instance
  3181. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(component, hostContext) == V3_OK, exit());
  3182. shouldTerminateComponent = true;
  3183. // create edit controller
  3184. if (v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller) != V3_OK)
  3185. controller = nullptr;
  3186. // if we cannot cast from component, try to create edit controller from factory
  3187. if (controller == nullptr)
  3188. {
  3189. v3_tuid cuid = {};
  3190. if (v3_cpp_obj(component)->get_controller_class_id(component, cuid) == V3_OK)
  3191. {
  3192. instance = nullptr;
  3193. if (v3_cpp_obj(factory1)->create_instance(factory1, cuid,
  3194. v3_edit_controller_iid, &instance) == V3_OK)
  3195. controller = static_cast<v3_edit_controller**>(instance);
  3196. }
  3197. CARLA_SAFE_ASSERT_RETURN(controller != nullptr, exit());
  3198. // component is separate from controller, needs its dedicated initialize and terminate
  3199. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(controller, hostContext) == V3_OK, exit());
  3200. shouldTerminateController = true;
  3201. }
  3202. v3_cpp_obj(controller)->set_component_handler(controller, handler);
  3203. // create processor
  3204. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_query_interface(component, v3_audio_processor_iid,
  3205. &processor) == V3_OK, exit());
  3206. CARLA_SAFE_ASSERT_RETURN(processor != nullptr, exit());
  3207. // connect component to controller
  3208. if (v3_cpp_obj_query_interface(component, v3_connection_point_iid, &connComponent) != V3_OK)
  3209. connComponent = nullptr;
  3210. if (v3_cpp_obj_query_interface(controller, v3_connection_point_iid, &connController) != V3_OK)
  3211. connController = nullptr;
  3212. if (connComponent != nullptr && connController != nullptr)
  3213. {
  3214. v3_cpp_obj(connComponent)->connect(connComponent, connController);
  3215. v3_cpp_obj(connController)->connect(connController, connComponent);
  3216. }
  3217. // get midi mapping interface
  3218. if (v3_cpp_obj_query_interface(component, v3_midi_mapping_iid, &midiMapping) != V3_OK)
  3219. {
  3220. midiMapping = nullptr;
  3221. if (v3_cpp_obj_query_interface(controller, v3_midi_mapping_iid, &midiMapping) != V3_OK)
  3222. midiMapping = nullptr;
  3223. }
  3224. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3225. // create view
  3226. view = v3_cpp_obj(controller)->create_view(controller, "editor");
  3227. #endif
  3228. return true;
  3229. }
  3230. bool exit()
  3231. {
  3232. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3233. // must be deleted by now
  3234. CARLA_SAFE_ASSERT(view == nullptr);
  3235. #endif
  3236. if (midiMapping != nullptr)
  3237. {
  3238. v3_cpp_obj_unref(midiMapping);
  3239. midiMapping = nullptr;
  3240. }
  3241. if (connComponent != nullptr && connController != nullptr)
  3242. {
  3243. v3_cpp_obj(connComponent)->disconnect(connComponent, connController);
  3244. v3_cpp_obj(connController)->disconnect(connController, connComponent);
  3245. }
  3246. if (connComponent != nullptr)
  3247. {
  3248. v3_cpp_obj_unref(connComponent);
  3249. connComponent = nullptr;
  3250. }
  3251. if (connController != nullptr)
  3252. {
  3253. v3_cpp_obj_unref(connController);
  3254. connController = nullptr;
  3255. }
  3256. if (processor != nullptr)
  3257. {
  3258. v3_cpp_obj_unref(processor);
  3259. processor = nullptr;
  3260. }
  3261. if (controller != nullptr)
  3262. {
  3263. if (shouldTerminateController)
  3264. {
  3265. v3_cpp_obj_terminate(controller);
  3266. shouldTerminateController = false;
  3267. }
  3268. v3_cpp_obj_unref(controller);
  3269. controller = nullptr;
  3270. }
  3271. if (component != nullptr)
  3272. {
  3273. if (shouldTerminateComponent)
  3274. {
  3275. v3_cpp_obj_terminate(component);
  3276. shouldTerminateComponent = false;
  3277. }
  3278. v3_cpp_obj_unref(component);
  3279. component = nullptr;
  3280. }
  3281. if (factory3 != nullptr)
  3282. {
  3283. v3_cpp_obj_unref(factory3);
  3284. factory3 = nullptr;
  3285. }
  3286. if (factory2 != nullptr)
  3287. {
  3288. v3_cpp_obj_unref(factory2);
  3289. factory2 = nullptr;
  3290. }
  3291. if (factory1 != nullptr)
  3292. {
  3293. v3_cpp_obj_unref(factory1);
  3294. factory1 = nullptr;
  3295. }
  3296. if (exitfn != nullptr)
  3297. {
  3298. exitfn();
  3299. exitfn = nullptr;
  3300. }
  3301. // return false so it can be used as error/fail condition
  3302. return false;
  3303. }
  3304. CARLA_DECLARE_NON_COPYABLE(PluginPointers)
  3305. } fV3;
  3306. struct Buses {
  3307. int32_t numInputs;
  3308. int32_t numOutputs;
  3309. v3_audio_bus_buffers* inputs;
  3310. v3_audio_bus_buffers* outputs;
  3311. v3_bus_mini_info* inputInfo;
  3312. v3_bus_mini_info* outputInfo;
  3313. Buses()
  3314. : numInputs(0),
  3315. numOutputs(0),
  3316. inputs(nullptr),
  3317. outputs(nullptr),
  3318. inputInfo(nullptr),
  3319. outputInfo(nullptr) {}
  3320. ~Buses()
  3321. {
  3322. delete[] inputs;
  3323. delete[] outputs;
  3324. delete[] inputInfo;
  3325. delete[] outputInfo;
  3326. }
  3327. void createNew(const int32_t numAudioInputBuses, const int32_t numAudioOutputBuses)
  3328. {
  3329. delete[] inputs;
  3330. delete[] outputs;
  3331. delete[] inputInfo;
  3332. delete[] outputInfo;
  3333. numInputs = numAudioInputBuses;
  3334. numOutputs = numAudioOutputBuses;
  3335. if (numAudioInputBuses > 0)
  3336. {
  3337. inputs = new v3_audio_bus_buffers[numAudioInputBuses];
  3338. inputInfo = new v3_bus_mini_info[numAudioInputBuses];
  3339. }
  3340. else
  3341. {
  3342. inputs = nullptr;
  3343. inputInfo = nullptr;
  3344. }
  3345. if (numAudioOutputBuses > 0)
  3346. {
  3347. outputs = new v3_audio_bus_buffers[numAudioOutputBuses];
  3348. outputInfo = new v3_bus_mini_info[numAudioOutputBuses];
  3349. }
  3350. else
  3351. {
  3352. outputs = nullptr;
  3353. outputInfo = nullptr;
  3354. }
  3355. }
  3356. CARLA_DECLARE_NON_COPYABLE(Buses)
  3357. } fBuses;
  3358. struct Events {
  3359. carla_v3_input_param_changes* paramInputs;
  3360. carla_v3_output_param_changes* paramOutputs;
  3361. carla_v3_input_event_list* eventInputs;
  3362. carla_v3_output_event_list* eventOutputs;
  3363. Events() noexcept
  3364. : paramInputs(nullptr),
  3365. paramOutputs(nullptr),
  3366. eventInputs(nullptr),
  3367. eventOutputs(nullptr) {}
  3368. ~Events()
  3369. {
  3370. delete paramInputs;
  3371. delete paramOutputs;
  3372. delete eventInputs;
  3373. delete eventOutputs;
  3374. }
  3375. void init()
  3376. {
  3377. if (paramInputs != nullptr)
  3378. paramInputs->init();
  3379. if (eventInputs != nullptr)
  3380. eventInputs->numEvents = 0;
  3381. }
  3382. void prepare()
  3383. {
  3384. if (paramInputs != nullptr)
  3385. paramInputs->prepare();
  3386. if (paramOutputs != nullptr)
  3387. paramOutputs->prepare();
  3388. }
  3389. CARLA_DECLARE_NON_COPYABLE(Events)
  3390. } fEvents;
  3391. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3392. struct UI {
  3393. bool isAttached;
  3394. bool isEmbed;
  3395. bool isResizingFromHost;
  3396. bool isResizingFromInit;
  3397. bool isResizingFromPlugin;
  3398. bool isVisible;
  3399. uint32_t width, height;
  3400. CarlaPluginUI* window;
  3401. UI() noexcept
  3402. : isAttached(false),
  3403. isEmbed(false),
  3404. isResizingFromHost(false),
  3405. isResizingFromInit(false),
  3406. isResizingFromPlugin(false),
  3407. isVisible(false),
  3408. width(0),
  3409. height(0),
  3410. window(nullptr) {}
  3411. ~UI()
  3412. {
  3413. CARLA_ASSERT(isEmbed || ! isVisible);
  3414. if (window != nullptr)
  3415. {
  3416. delete window;
  3417. window = nullptr;
  3418. }
  3419. }
  3420. CARLA_DECLARE_NON_COPYABLE(UI)
  3421. } fUI;
  3422. #endif
  3423. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST3)
  3424. };
  3425. // --------------------------------------------------------------------------------------------------------------------
  3426. CarlaPluginPtr CarlaPlugin::newVST3(const Initializer& init)
  3427. {
  3428. carla_debug("CarlaPlugin::newVST3({%p, \"%s\", \"%s\", \"%s\"})",
  3429. init.engine, init.filename, init.name, init.label);
  3430. #ifdef USE_JUCE_FOR_VST3
  3431. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST3") == nullptr)
  3432. return newJuce(init, "VST3");
  3433. #endif
  3434. std::shared_ptr<CarlaPluginVST3> plugin(new CarlaPluginVST3(init.engine, init.id));
  3435. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  3436. return nullptr;
  3437. return plugin;
  3438. }
  3439. // -------------------------------------------------------------------------------------------------------------------
  3440. CARLA_BACKEND_END_NAMESPACE