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.

4341 lines
153KB

  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. options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  1162. options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  1163. }
  1164. return options;
  1165. }
  1166. float getParameterValue(const uint32_t paramIndex) const noexcept override
  1167. {
  1168. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, 0.0f);
  1169. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count, 0.0f);
  1170. // FIXME use pending RT value?
  1171. const v3_param_id paramId = pData->param.data[paramIndex].rindex;
  1172. const double normalized = v3_cpp_obj(fV3.controller)->get_parameter_normalised(fV3.controller, paramId);
  1173. return static_cast<float>(
  1174. v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId, normalized));
  1175. }
  1176. /* TODO
  1177. float getParameterScalePointValue(uint32_t paramIndex, uint32_t scalePointId) const noexcept override
  1178. {
  1179. }
  1180. */
  1181. bool getLabel(char* const strBuf) const noexcept override
  1182. {
  1183. std::strncpy(strBuf, fV3ClassInfo.v1.name, STR_MAX);
  1184. return true;
  1185. }
  1186. bool getMaker(char* const strBuf) const noexcept override
  1187. {
  1188. std::strncpy(strBuf, fV3ClassInfo.v2.vendor, STR_MAX);
  1189. return true;
  1190. }
  1191. bool getCopyright(char* const strBuf) const noexcept override
  1192. {
  1193. return getMaker(strBuf);
  1194. }
  1195. bool getRealName(char* const strBuf) const noexcept override
  1196. {
  1197. std::strncpy(strBuf, fV3ClassInfo.v1.name, STR_MAX);
  1198. return true;
  1199. }
  1200. bool getParameterName(const uint32_t paramIndex, char* const strBuf) const noexcept override
  1201. {
  1202. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, 0.0f);
  1203. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count, false);
  1204. v3_param_info paramInfo = {};
  1205. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller,
  1206. static_cast<int32_t>(paramIndex),
  1207. &paramInfo) == V3_OK, false);
  1208. strncpy_utf8(strBuf, paramInfo.title, STR_MAX);
  1209. return true;
  1210. }
  1211. bool getParameterSymbol(const uint32_t paramIndex, char* strBuf) const noexcept override
  1212. {
  1213. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count, false);
  1214. std::snprintf(strBuf, STR_MAX, "%d", pData->param.data[paramIndex].rindex);
  1215. return true;
  1216. }
  1217. bool getParameterText(const uint32_t paramIndex, char* const strBuf) noexcept override
  1218. {
  1219. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, false);
  1220. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count, false);
  1221. const v3_param_id paramId = pData->param.data[paramIndex].rindex;
  1222. const double normalized = v3_cpp_obj(fV3.controller)->get_parameter_normalised(fV3.controller, paramId);
  1223. v3_str_128 paramText;
  1224. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_string_for_value(fV3.controller,
  1225. paramId,
  1226. normalized,
  1227. paramText) == V3_OK, false);
  1228. if (paramText[0] != '\0')
  1229. strncpy_utf8(strBuf, paramText, STR_MAX);
  1230. else
  1231. std::snprintf(strBuf, STR_MAX, "%.12g",
  1232. v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId, normalized));
  1233. return true;
  1234. }
  1235. bool getParameterUnit(const uint32_t paramIndex, char* const strBuf) const noexcept override
  1236. {
  1237. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr, false);
  1238. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count, false);
  1239. v3_param_info paramInfo = {};
  1240. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller,
  1241. static_cast<int32_t>(paramIndex),
  1242. &paramInfo) == V3_OK, false);
  1243. strncpy_utf8(strBuf, paramInfo.units, STR_MAX);
  1244. return true;
  1245. }
  1246. /* TODO
  1247. bool getParameterGroupName(const uint32_t paramIndex, char* const strBuf) const noexcept override
  1248. {
  1249. }
  1250. bool getParameterScalePointLabel(const uint32_t paramIndex,
  1251. const uint32_t scalePointId, char* const strBuf) const noexcept override
  1252. {
  1253. }
  1254. */
  1255. // ----------------------------------------------------------------------------------------------------------------
  1256. // Set data (state)
  1257. /* TODO
  1258. void prepareForSave(const bool temporary) override
  1259. {
  1260. // component to edit controller state or vice-versa here
  1261. }
  1262. */
  1263. // ----------------------------------------------------------------------------------------------------------------
  1264. // Set data (internal stuff)
  1265. /* TODO
  1266. void setName(const char* newName) override
  1267. {
  1268. }
  1269. */
  1270. // ----------------------------------------------------------------------------------------------------------------
  1271. // Set data (plugin-specific stuff)
  1272. void setParameterValue(const uint32_t paramIndex, const float value,
  1273. const bool sendGui, const bool sendOsc, const bool sendCallback) noexcept override
  1274. {
  1275. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1276. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count,);
  1277. CARLA_SAFE_ASSERT_RETURN(fEvents.paramInputs != nullptr,);
  1278. const v3_param_id paramId = pData->param.data[paramIndex].rindex;
  1279. const float fixedValue = pData->param.getFixedValue(paramIndex, value);
  1280. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  1281. paramId,
  1282. fixedValue);
  1283. // report value to component (next process call)
  1284. fEvents.paramInputs->setParamValue(paramIndex, static_cast<float>(normalized));
  1285. // report value to edit controller
  1286. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, paramId, normalized);
  1287. CarlaPlugin::setParameterValue(paramIndex, fixedValue, sendGui, sendOsc, sendCallback);
  1288. }
  1289. void setParameterValueRT(const uint32_t paramIndex, const float value, const uint32_t frameOffset,
  1290. const bool sendCallbackLater) noexcept override
  1291. {
  1292. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1293. CARLA_SAFE_ASSERT_RETURN(paramIndex < pData->param.count,);
  1294. CARLA_SAFE_ASSERT_RETURN(fEvents.paramInputs != nullptr,);
  1295. const v3_param_id paramId = pData->param.data[paramIndex].rindex;
  1296. const float fixedValue = pData->param.getFixedValue(paramIndex, value);
  1297. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  1298. paramId,
  1299. fixedValue);
  1300. // report value to component (next process call)
  1301. fEvents.paramInputs->setParamValueRT(paramIndex, frameOffset, static_cast<float>(normalized));
  1302. CarlaPlugin::setParameterValueRT(paramIndex, fixedValue, frameOffset, sendCallbackLater);
  1303. }
  1304. void setChunkData(const void* data, std::size_t dataSize) override
  1305. {
  1306. CARLA_SAFE_ASSERT_RETURN(pData->options & PLUGIN_OPTION_USE_CHUNKS,);
  1307. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1308. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1309. CARLA_SAFE_ASSERT_RETURN(data != nullptr,);
  1310. CARLA_SAFE_ASSERT_RETURN(dataSize > 0,);
  1311. carla_v3_bstream stream;
  1312. carla_v3_bstream* const streamPtr = &stream;
  1313. v3_bstream** const v3stream = (v3_bstream**)&streamPtr;
  1314. stream.buffer = const_cast<void*>(data);
  1315. stream.size = dataSize;
  1316. stream.canRead = true;
  1317. if (v3_cpp_obj(fV3.component)->set_state(fV3.component, v3stream) == V3_OK)
  1318. {
  1319. v3_cpp_obj(fV3.controller)->set_state(fV3.controller, v3stream);
  1320. pData->updateParameterValues(this, true, true, false);
  1321. }
  1322. runIdleCallbacksAsNeeded(false);
  1323. }
  1324. // ----------------------------------------------------------------------------------------------------------------
  1325. // Set ui stuff
  1326. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  1327. void setCustomUITitle(const char* const title) noexcept override
  1328. {
  1329. if (fUI.window != nullptr)
  1330. {
  1331. try {
  1332. fUI.window->setTitle(title);
  1333. } CARLA_SAFE_EXCEPTION("set custom ui title");
  1334. }
  1335. CarlaPlugin::setCustomUITitle(title);
  1336. }
  1337. void showCustomUI(const bool yesNo) override
  1338. {
  1339. if (fUI.isVisible == yesNo)
  1340. return;
  1341. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr,);
  1342. if (yesNo)
  1343. {
  1344. CarlaString uiTitle;
  1345. if (pData->uiTitle.isNotEmpty())
  1346. {
  1347. uiTitle = pData->uiTitle;
  1348. }
  1349. else
  1350. {
  1351. uiTitle = pData->name;
  1352. uiTitle += " (GUI)";
  1353. }
  1354. if (fUI.window == nullptr)
  1355. {
  1356. const EngineOptions& opts(pData->engine->getOptions());
  1357. const bool isStandalone = opts.pluginsAreStandalone;
  1358. const bool isResizable = v3_cpp_obj(fV3.view)->can_resize(fV3.view) == V3_TRUE;
  1359. #if defined(CARLA_OS_MAC)
  1360. fUI.window = CarlaPluginUI::newCocoa(this, opts.frontendWinId, isStandalone, isResizable);
  1361. #elif defined(CARLA_OS_WIN)
  1362. fUI.window = CarlaPluginUI::newWindows(this, opts.frontendWinId, isStandalone, isResizable);
  1363. #elif defined(HAVE_X11)
  1364. fUI.window = CarlaPluginUI::newX11(this, opts.frontendWinId, isStandalone, isResizable, false);
  1365. #else
  1366. pData->engine->callback(true, true,
  1367. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1368. pData->id,
  1369. -1,
  1370. 0, 0, 0.0f,
  1371. "Unsupported UI type");
  1372. return;
  1373. #endif
  1374. fUI.window->setTitle(uiTitle.buffer());
  1375. #ifndef CARLA_OS_MAC
  1376. if (carla_isNotZero(opts.uiScale))
  1377. {
  1378. // TODO inform plugin of what UI scale we use
  1379. }
  1380. #endif
  1381. v3_cpp_obj(fV3.view)->set_frame(fV3.view, (v3_plugin_frame**)&fPluginFramePtr);
  1382. if (v3_cpp_obj(fV3.view)->attached(fV3.view, fUI.window->getPtr(),
  1383. V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_OK)
  1384. {
  1385. v3_view_rect rect = {};
  1386. if (v3_cpp_obj(fV3.view)->get_size(fV3.view, &rect) == V3_OK)
  1387. {
  1388. const int32_t width = rect.right - rect.left;
  1389. const int32_t height = rect.bottom - rect.top;
  1390. carla_stdout("view attached ok, size %i %i", width, height);
  1391. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  1392. if (width > 1 && height > 1)
  1393. {
  1394. fUI.isResizingFromInit = true;
  1395. fUI.width = width;
  1396. fUI.height = height;
  1397. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true, true);
  1398. }
  1399. }
  1400. else
  1401. {
  1402. carla_stdout("view attached ok, size failed");
  1403. }
  1404. if (isResizable)
  1405. {
  1406. carla_zeroStruct(rect);
  1407. if (v3_cpp_obj(fV3.view)->check_size_constraint(fV3.view, &rect) == V3_OK)
  1408. {
  1409. const int32_t width = rect.right - rect.left;
  1410. const int32_t height = rect.bottom - rect.top;
  1411. carla_stdout("size constraint ok %i %i", width, height);
  1412. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  1413. if (width > 1 && height > 1)
  1414. fUI.window->setMinimumSize(static_cast<uint>(width), static_cast<uint>(height));
  1415. else if (fUI.width > 1 && fUI.height > 1)
  1416. fUI.window->setMinimumSize(fUI.width, fUI.height);
  1417. }
  1418. else
  1419. {
  1420. carla_stdout("view attached ok, size constraint failed");
  1421. }
  1422. }
  1423. }
  1424. else
  1425. {
  1426. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1427. delete fUI.window;
  1428. fUI.window = nullptr;
  1429. carla_stderr2("Plugin refused to open its own UI");
  1430. return pData->engine->callback(true, true,
  1431. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1432. pData->id,
  1433. -1,
  1434. 0, 0, 0.0f,
  1435. "Plugin refused to open its own UI");
  1436. }
  1437. }
  1438. fUI.window->show();
  1439. fUI.isVisible = true;
  1440. }
  1441. else
  1442. {
  1443. fUI.isVisible = false;
  1444. if (fUI.window != nullptr)
  1445. fUI.window->hide();
  1446. if (fUI.isEmbed)
  1447. {
  1448. fUI.isAttached = false;
  1449. fUI.isEmbed = false;
  1450. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1451. v3_cpp_obj(fV3.view)->removed(fV3.view);
  1452. }
  1453. }
  1454. runIdleCallbacksAsNeeded(true);
  1455. }
  1456. void* embedCustomUI(void* const ptr) override
  1457. {
  1458. CARLA_SAFE_ASSERT_RETURN(fUI.window == nullptr, nullptr);
  1459. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr, nullptr);
  1460. v3_cpp_obj(fV3.view)->set_frame(fV3.view, (v3_plugin_frame**)&fPluginFramePtr);
  1461. #ifndef CARLA_OS_MAC
  1462. const EngineOptions& opts(pData->engine->getOptions());
  1463. if (carla_isNotZero(opts.uiScale))
  1464. {
  1465. // TODO
  1466. }
  1467. #endif
  1468. if (v3_cpp_obj(fV3.view)->attached(fV3.view, ptr, V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_OK)
  1469. {
  1470. fUI.isAttached = true;
  1471. fUI.isEmbed = true;
  1472. fUI.isVisible = true;
  1473. v3_view_rect rect = {};
  1474. if (v3_cpp_obj(fV3.view)->get_size(fV3.view, &rect) == V3_OK)
  1475. {
  1476. const int32_t width = rect.right - rect.left;
  1477. const int32_t height = rect.bottom - rect.top;
  1478. carla_stdout("view attached ok, size %i %i", width, height);
  1479. CARLA_SAFE_ASSERT_INT2(width > 1 && height > 1, width, height);
  1480. if (width > 1 && height > 1)
  1481. {
  1482. fUI.isResizingFromInit = true;
  1483. fUI.width = width;
  1484. fUI.height = height;
  1485. pData->engine->callback(true, true,
  1486. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  1487. pData->id, width, height,
  1488. 0, 0.0f, nullptr);
  1489. }
  1490. }
  1491. else
  1492. {
  1493. carla_stdout("view attached ok, size failed");
  1494. }
  1495. }
  1496. else
  1497. {
  1498. fUI.isVisible = false;
  1499. v3_cpp_obj(fV3.view)->set_frame(fV3.view, nullptr);
  1500. carla_stderr2("Plugin refused to open its own UI");
  1501. pData->engine->callback(true, true,
  1502. ENGINE_CALLBACK_UI_STATE_CHANGED,
  1503. pData->id,
  1504. -1,
  1505. 0, 0, 0.0f,
  1506. "Plugin refused to open its own UI");
  1507. }
  1508. return nullptr;
  1509. }
  1510. #endif // V3_VIEW_PLATFORM_TYPE_NATIVE
  1511. void runIdleCallbacksAsNeeded(const bool isIdleCallback)
  1512. {
  1513. int32_t flags = fRestartFlags;
  1514. if (isIdleCallback)
  1515. {
  1516. }
  1517. fRestartFlags = flags;
  1518. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  1519. #ifdef _POSIX_VERSION
  1520. LinkedList<HostPosixFileDescriptor>& posixfds(fPluginFrame.loop.posixfds);
  1521. if (posixfds.isNotEmpty())
  1522. {
  1523. for (LinkedList<HostPosixFileDescriptor>::Itenerator it = posixfds.begin2(); it.valid(); it.next())
  1524. {
  1525. HostPosixFileDescriptor& posixfd(it.getValue(kPosixFileDescriptorFallbackNC));
  1526. #ifdef CARLA_VST3_POSIX_EPOLL
  1527. struct ::epoll_event event;
  1528. #else
  1529. const int16_t filter = EVFILT_WRITE;
  1530. struct ::kevent kev = {}, event;
  1531. struct ::timespec timeout = {};
  1532. EV_SET(&kev, posixfd.pluginfd, filter, EV_ADD|EV_ENABLE, 0, 0, nullptr);
  1533. #endif
  1534. for (int i=0; i<50; ++i)
  1535. {
  1536. #ifdef CARLA_VST3_POSIX_EPOLL
  1537. switch (::epoll_wait(posixfd.hostfd, &event, 1, 0))
  1538. #else
  1539. switch (::kevent(posixfd.hostfd, &kev, 1, &event, 1, &timeout))
  1540. #endif
  1541. {
  1542. case 1:
  1543. v3_cpp_obj(posixfd.handler)->on_fd_is_set(posixfd.handler, posixfd.pluginfd);
  1544. break;
  1545. case -1:
  1546. // fall through
  1547. case 0:
  1548. i = 50;
  1549. break;
  1550. default:
  1551. carla_safe_exception("posix fd received abnormal value", __FILE__, __LINE__);
  1552. i = 50;
  1553. break;
  1554. }
  1555. }
  1556. }
  1557. }
  1558. #endif // _POSIX_VERSION
  1559. LinkedList<HostTimer>& timers(fPluginFrame.loop.timers);
  1560. if (timers.isNotEmpty())
  1561. {
  1562. for (LinkedList<HostTimer>::Itenerator it = timers.begin2(); it.valid(); it.next())
  1563. {
  1564. HostTimer& timer(it.getValue(kTimerFallbackNC));
  1565. const uint32_t currentTimeInMs = water::Time::getMillisecondCounter();
  1566. if (currentTimeInMs > timer.lastCallTimeInMs + timer.periodInMs)
  1567. {
  1568. timer.lastCallTimeInMs = currentTimeInMs;
  1569. v3_cpp_obj(timer.handler)->on_timer(timer.handler);
  1570. }
  1571. }
  1572. }
  1573. #endif // V3_VIEW_PLATFORM_TYPE_NATIVE
  1574. }
  1575. void idle() override
  1576. {
  1577. if (kEngineHasIdleOnMainThread)
  1578. runIdleCallbacksAsNeeded(true);
  1579. CarlaPlugin::idle();
  1580. }
  1581. void uiIdle() override
  1582. {
  1583. if (!kEngineHasIdleOnMainThread)
  1584. runIdleCallbacksAsNeeded(true);
  1585. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  1586. if (fUI.window != nullptr)
  1587. fUI.window->idle();
  1588. if (fUI.isResizingFromHost)
  1589. {
  1590. fUI.isResizingFromHost = false;
  1591. // if (!fUI.isResizingFromPlugin && !fUI.isResizingFromInit)
  1592. {
  1593. carla_stdout("Host resize stopped");
  1594. // v3_view_rect rect = { 0, 0, static_cast<int32_t>(fUI.width), static_cast<int32_t>(fUI.height) };
  1595. // v3_cpp_obj(fV3.view)->on_size(fV3.view, &rect);
  1596. }
  1597. }
  1598. if (fUI.isResizingFromPlugin)
  1599. {
  1600. fUI.isResizingFromPlugin = false;
  1601. carla_stdout("Plugin resize stopped");
  1602. }
  1603. #endif
  1604. CarlaPlugin::uiIdle();
  1605. }
  1606. // ----------------------------------------------------------------------------------------------------------------
  1607. // Plugin state
  1608. void reload() override
  1609. {
  1610. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr,);
  1611. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1612. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  1613. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1614. carla_debug("CarlaPluginVST3::reload() - start");
  1615. // Safely disable plugin for reload
  1616. const ScopedDisabler sd(this);
  1617. if (pData->active)
  1618. deactivate();
  1619. clearBuffers();
  1620. const int32_t numAudioInputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_AUDIO, V3_INPUT);
  1621. const int32_t numAudioOutputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_AUDIO, V3_OUTPUT);
  1622. const int32_t numEventInputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_INPUT);
  1623. const int32_t numEventOutputBuses = v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_OUTPUT);
  1624. const int32_t numParameters = v3_cpp_obj(fV3.controller)->get_parameter_count(fV3.controller);
  1625. CARLA_SAFE_ASSERT(numAudioInputBuses >= 0);
  1626. CARLA_SAFE_ASSERT(numAudioOutputBuses >= 0);
  1627. CARLA_SAFE_ASSERT(numEventInputBuses >= 0);
  1628. CARLA_SAFE_ASSERT(numEventOutputBuses >= 0);
  1629. CARLA_SAFE_ASSERT(numParameters >= 0);
  1630. uint32_t aIns, aOuts, cvIns, cvOuts;
  1631. aIns = aOuts = cvIns = cvOuts = 0;
  1632. bool needsCtrlIn, needsCtrlOut;
  1633. needsCtrlIn = needsCtrlOut = false;
  1634. fBuses.createNew(numAudioInputBuses, numAudioOutputBuses);
  1635. for (int32_t b=0; b<numAudioInputBuses; ++b)
  1636. {
  1637. carla_zeroStruct(fBuses.inputs[b]);
  1638. carla_zeroStruct(fBuses.inputInfo[b]);
  1639. fBuses.inputInfo[b].offset = aIns + cvIns;
  1640. v3_bus_info busInfo = {};
  1641. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1642. V3_AUDIO, V3_INPUT, b, &busInfo) == V3_OK);
  1643. const int32_t numChannels = busInfo.channel_count;
  1644. CARLA_SAFE_ASSERT_BREAK(numChannels >= 0);
  1645. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1646. V3_AUDIO, V3_INPUT, b, true) == V3_OK);
  1647. fBuses.inputs[b].num_channels = numChannels;
  1648. fBuses.inputInfo[b].bus_type = busInfo.bus_type;
  1649. fBuses.inputInfo[b].flags = busInfo.flags;
  1650. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  1651. cvIns += static_cast<uint32_t>(numChannels);
  1652. else
  1653. aIns += static_cast<uint32_t>(numChannels);
  1654. }
  1655. for (int32_t b=0; b<numAudioOutputBuses; ++b)
  1656. {
  1657. carla_zeroStruct(fBuses.outputs[b]);
  1658. carla_zeroStruct(fBuses.outputInfo[b]);
  1659. fBuses.outputInfo[b].offset = aOuts + cvOuts;
  1660. v3_bus_info busInfo = {};
  1661. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1662. V3_AUDIO, V3_OUTPUT, b, &busInfo) == V3_OK);
  1663. const int32_t numChannels = busInfo.channel_count;
  1664. CARLA_SAFE_ASSERT_BREAK(numChannels >= 0);
  1665. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1666. V3_AUDIO, V3_OUTPUT, b, true) == V3_OK);
  1667. fBuses.outputs[b].num_channels = numChannels;
  1668. fBuses.outputInfo[b].bus_type = busInfo.bus_type;
  1669. fBuses.outputInfo[b].flags = busInfo.flags;
  1670. if (busInfo.flags & V3_IS_CONTROL_VOLTAGE)
  1671. cvOuts += static_cast<uint32_t>(numChannels);
  1672. else
  1673. aOuts += static_cast<uint32_t>(numChannels);
  1674. }
  1675. if (aIns > 0)
  1676. {
  1677. pData->audioIn.createNew(aIns);
  1678. }
  1679. if (aOuts > 0)
  1680. {
  1681. pData->audioOut.createNew(aOuts);
  1682. needsCtrlIn = true;
  1683. }
  1684. if (cvIns > 0)
  1685. pData->cvIn.createNew(cvIns);
  1686. if (cvOuts > 0)
  1687. pData->cvOut.createNew(cvOuts);
  1688. if (numEventInputBuses > 0)
  1689. needsCtrlIn = true;
  1690. if (numEventOutputBuses > 0)
  1691. needsCtrlOut = true;
  1692. if (numParameters > 0)
  1693. {
  1694. pData->param.createNew(numParameters, false);
  1695. needsCtrlIn = true;
  1696. }
  1697. if (aOuts + cvOuts > 0)
  1698. {
  1699. fAudioAndCvOutBuffers = new float*[aOuts + cvOuts];
  1700. for (uint32_t i=0; i < aOuts + cvOuts; ++i)
  1701. fAudioAndCvOutBuffers[i] = nullptr;
  1702. }
  1703. const EngineProcessMode processMode = pData->engine->getProccessMode();
  1704. const uint portNameSize = pData->engine->getMaxPortNameSize();
  1705. CarlaString portName;
  1706. // Audio Ins
  1707. for (uint32_t j=0; j < aIns; ++j)
  1708. {
  1709. portName.clear();
  1710. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1711. {
  1712. portName = pData->name;
  1713. portName += ":";
  1714. }
  1715. if (aIns > 1)
  1716. {
  1717. portName += "input_";
  1718. portName += CarlaString(j+1);
  1719. }
  1720. else
  1721. portName += "input";
  1722. portName.truncate(portNameSize);
  1723. pData->audioIn.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio,
  1724. portName, true, j);
  1725. pData->audioIn.ports[j].rindex = j;
  1726. }
  1727. // Audio Outs
  1728. for (uint32_t j=0; j < aOuts; ++j)
  1729. {
  1730. portName.clear();
  1731. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1732. {
  1733. portName = pData->name;
  1734. portName += ":";
  1735. }
  1736. if (aOuts > 1)
  1737. {
  1738. portName += "output_";
  1739. portName += CarlaString(j+1);
  1740. }
  1741. else
  1742. portName += "output";
  1743. portName.truncate(portNameSize);
  1744. pData->audioOut.ports[j].port = (CarlaEngineAudioPort*)pData->client->addPort(kEnginePortTypeAudio,
  1745. portName, false, j);
  1746. pData->audioOut.ports[j].rindex = j;
  1747. }
  1748. // CV Ins
  1749. for (uint32_t j=0; j < cvIns; ++j)
  1750. {
  1751. portName.clear();
  1752. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1753. {
  1754. portName = pData->name;
  1755. portName += ":";
  1756. }
  1757. if (cvIns > 1)
  1758. {
  1759. portName += "cv_input_";
  1760. portName += CarlaString(j+1);
  1761. }
  1762. else
  1763. portName += "cv_input";
  1764. portName.truncate(portNameSize);
  1765. pData->cvIn.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV,
  1766. portName, true, j);
  1767. pData->cvIn.ports[j].rindex = j;
  1768. }
  1769. // CV Outs
  1770. for (uint32_t j=0; j < cvOuts; ++j)
  1771. {
  1772. portName.clear();
  1773. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1774. {
  1775. portName = pData->name;
  1776. portName += ":";
  1777. }
  1778. if (cvOuts > 1)
  1779. {
  1780. portName += "cv_output_";
  1781. portName += CarlaString(j+1);
  1782. }
  1783. else
  1784. portName += "cv_output";
  1785. portName.truncate(portNameSize);
  1786. pData->cvOut.ports[j].port = (CarlaEngineCVPort*)pData->client->addPort(kEnginePortTypeCV,
  1787. portName, false, j);
  1788. pData->cvOut.ports[j].rindex = j;
  1789. }
  1790. for (int32_t j=0; j < numParameters; ++j)
  1791. {
  1792. v3_param_info paramInfo = {};
  1793. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.controller)->get_parameter_info(fV3.controller,
  1794. j, &paramInfo) == V3_OK);
  1795. char strBuf[200];
  1796. strncpy_utf8(strBuf, paramInfo.title, 128);
  1797. const v3_param_id paramId = paramInfo.param_id;
  1798. pData->param.data[j].index = static_cast<uint32_t>(j);
  1799. pData->param.data[j].rindex = paramId;
  1800. if (paramInfo.flags & (V3_PARAM_IS_BYPASS|V3_PARAM_IS_HIDDEN|V3_PARAM_PROGRAM_CHANGE))
  1801. continue;
  1802. double min, max, def, step, stepSmall, stepLarge;
  1803. min = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId, 0.0);
  1804. max = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId, 1.0);
  1805. def = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller, paramId,
  1806. paramInfo.default_normalised_value);
  1807. if (min >= max)
  1808. max = min + 0.1;
  1809. if (def < min)
  1810. def = min;
  1811. else if (def > max)
  1812. def = max;
  1813. if (paramInfo.flags & V3_PARAM_READ_ONLY)
  1814. pData->param.data[j].type = PARAMETER_OUTPUT;
  1815. else
  1816. pData->param.data[j].type = PARAMETER_INPUT;
  1817. if (paramInfo.step_count == 1)
  1818. {
  1819. step = max - min;
  1820. stepSmall = step;
  1821. stepLarge = step;
  1822. pData->param.data[j].hints |= PARAMETER_IS_BOOLEAN;
  1823. }
  1824. /*
  1825. else if (paramInfo.step_count != 0 && (paramInfo.flags & V3_PARAM_IS_LIST) != 0x0)
  1826. {
  1827. step = 1.0;
  1828. stepSmall = 1.0;
  1829. stepLarge = std::min(max - min, 10.0);
  1830. pData->param.data[j].hints |= PARAMETER_IS_INTEGER;
  1831. }
  1832. */
  1833. else
  1834. {
  1835. float range = max - min;
  1836. step = range/100.0;
  1837. stepSmall = range/1000.0;
  1838. stepLarge = range/10.0;
  1839. }
  1840. pData->param.data[j].hints |= PARAMETER_IS_ENABLED;
  1841. pData->param.data[j].hints |= PARAMETER_USES_CUSTOM_TEXT;
  1842. if (paramInfo.flags & V3_PARAM_CAN_AUTOMATE)
  1843. {
  1844. pData->param.data[j].hints |= PARAMETER_IS_AUTOMATABLE;
  1845. if ((paramInfo.flags & V3_PARAM_IS_LIST) == 0x0)
  1846. pData->param.data[j].hints |= PARAMETER_CAN_BE_CV_CONTROLLED;
  1847. }
  1848. pData->param.ranges[j].min = min;
  1849. pData->param.ranges[j].max = max;
  1850. pData->param.ranges[j].def = def;
  1851. pData->param.ranges[j].step = step;
  1852. pData->param.ranges[j].stepSmall = stepSmall;
  1853. pData->param.ranges[j].stepLarge = stepLarge;
  1854. }
  1855. if (numParameters > 0)
  1856. {
  1857. fEvents.paramInputs = new carla_v3_input_param_changes(pData->param);
  1858. fEvents.paramOutputs = new carla_v3_output_param_changes(pData->param);
  1859. }
  1860. if (needsCtrlIn)
  1861. {
  1862. portName.clear();
  1863. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1864. {
  1865. portName = pData->name;
  1866. portName += ":";
  1867. }
  1868. portName += "events-in";
  1869. portName.truncate(portNameSize);
  1870. pData->event.portIn = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1871. portName, true, 0);
  1872. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  1873. pData->event.cvSourcePorts = pData->client->createCVSourcePorts();
  1874. #endif
  1875. fEvents.eventInputs = new carla_v3_input_event_list;
  1876. }
  1877. if (needsCtrlOut)
  1878. {
  1879. portName.clear();
  1880. if (processMode == ENGINE_PROCESS_MODE_SINGLE_CLIENT)
  1881. {
  1882. portName = pData->name;
  1883. portName += ":";
  1884. }
  1885. portName += "events-out";
  1886. portName.truncate(portNameSize);
  1887. pData->event.portOut = (CarlaEngineEventPort*)pData->client->addPort(kEnginePortTypeEvent,
  1888. portName, false, 0);
  1889. fEvents.eventOutputs = new carla_v3_output_event_list;
  1890. }
  1891. // plugin hints
  1892. const PluginCategory v3category = getPluginCategoryFromV3SubCategories(fV3ClassInfo.v2.sub_categories);
  1893. pData->hints = 0x0;
  1894. if (v3category == PLUGIN_CATEGORY_SYNTH)
  1895. pData->hints |= PLUGIN_IS_SYNTH;
  1896. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  1897. if (fV3.view != nullptr &&
  1898. v3_cpp_obj(fV3.view)->is_platform_type_supported(fV3.view, V3_VIEW_PLATFORM_TYPE_NATIVE) == V3_TRUE)
  1899. {
  1900. pData->hints |= PLUGIN_HAS_CUSTOM_UI;
  1901. pData->hints |= PLUGIN_HAS_CUSTOM_EMBED_UI;
  1902. pData->hints |= PLUGIN_NEEDS_UI_MAIN_THREAD;
  1903. }
  1904. #endif
  1905. if (aOuts > 0 && (aIns == aOuts || aIns == 1))
  1906. pData->hints |= PLUGIN_CAN_DRYWET;
  1907. if (aOuts > 0)
  1908. pData->hints |= PLUGIN_CAN_VOLUME;
  1909. if (aOuts >= 2 && aOuts % 2 == 0)
  1910. pData->hints |= PLUGIN_CAN_BALANCE;
  1911. // extra plugin hints
  1912. pData->extraHints = 0x0;
  1913. if (numEventInputBuses > 0)
  1914. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_IN;
  1915. if (numEventOutputBuses > 0)
  1916. pData->extraHints |= PLUGIN_EXTRA_HINT_HAS_MIDI_OUT;
  1917. // check initial latency
  1918. if ((fLastKnownLatency = v3_cpp_obj(fV3.processor)->get_latency_samples(fV3.processor)) != 0)
  1919. {
  1920. pData->client->setLatency(fLastKnownLatency);
  1921. #ifndef BUILD_BRIDGE
  1922. pData->latency.recreateBuffers(std::max(aIns+cvIns, aOuts+cvOuts), fLastKnownLatency);
  1923. #endif
  1924. }
  1925. // initial audio setup
  1926. v3_process_setup setup = {
  1927. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  1928. V3_SAMPLE_32,
  1929. static_cast<int32_t>(pData->engine->getBufferSize()),
  1930. pData->engine->getSampleRate()
  1931. };
  1932. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  1933. // activate all buses
  1934. for (int32_t j=0; j<numAudioInputBuses; ++j)
  1935. {
  1936. v3_bus_info busInfo = {};
  1937. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1938. V3_AUDIO, V3_INPUT, j, &busInfo) == V3_OK);
  1939. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1940. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1941. V3_AUDIO, V3_INPUT, j, true) == V3_OK);
  1942. }
  1943. }
  1944. for (int32_t j=0; j<numAudioOutputBuses; ++j)
  1945. {
  1946. v3_bus_info busInfo = {};
  1947. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->get_bus_info(fV3.component,
  1948. V3_AUDIO, V3_OUTPUT, j, &busInfo) == V3_OK);
  1949. if ((busInfo.flags & V3_DEFAULT_ACTIVE) == 0x0) {
  1950. CARLA_SAFE_ASSERT_BREAK(v3_cpp_obj(fV3.component)->activate_bus(fV3.component,
  1951. V3_AUDIO, V3_OUTPUT, j, true) == V3_OK);
  1952. }
  1953. }
  1954. if (fEvents.paramInputs != nullptr && fV3.midiMapping != nullptr)
  1955. fMidiControllerAssignments.init(fV3.midiMapping, numEventInputBuses);
  1956. bufferSizeChanged(pData->engine->getBufferSize());
  1957. reloadPrograms(true);
  1958. if (pData->active)
  1959. activate();
  1960. else
  1961. runIdleCallbacksAsNeeded(false);
  1962. carla_debug("CarlaPluginVST3::reload() - end");
  1963. }
  1964. // ----------------------------------------------------------------------------------------------------------------
  1965. // Plugin processing
  1966. void activate() noexcept override
  1967. {
  1968. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1969. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1970. try {
  1971. v3_cpp_obj(fV3.component)->set_active(fV3.component, true);
  1972. } CARLA_SAFE_EXCEPTION("set_active on");
  1973. try {
  1974. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, true);
  1975. } CARLA_SAFE_EXCEPTION("set_processing on");
  1976. fFirstActive = true;
  1977. runIdleCallbacksAsNeeded(false);
  1978. }
  1979. void deactivate() noexcept override
  1980. {
  1981. CARLA_SAFE_ASSERT_RETURN(fV3.component != nullptr,);
  1982. CARLA_SAFE_ASSERT_RETURN(fV3.processor != nullptr,);
  1983. try {
  1984. v3_cpp_obj(fV3.processor)->set_processing(fV3.processor, false);
  1985. } CARLA_SAFE_EXCEPTION("set_processing off");
  1986. try {
  1987. v3_cpp_obj(fV3.component)->set_active(fV3.component, false);
  1988. } CARLA_SAFE_EXCEPTION("set_active off");
  1989. runIdleCallbacksAsNeeded(false);
  1990. }
  1991. void process(const float* const* const audioIn, float** const audioOut,
  1992. const float* const* const cvIn, float** const cvOut, const uint32_t frames) override
  1993. {
  1994. // ------------------------------------------------------------------------------------------------------------
  1995. // Check if active
  1996. if (! pData->active)
  1997. {
  1998. // disable any output sound
  1999. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2000. carla_zeroFloats(audioOut[i], frames);
  2001. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2002. carla_zeroFloats(cvOut[i], frames);
  2003. return;
  2004. }
  2005. fEvents.init();
  2006. // ------------------------------------------------------------------------------------------------------------
  2007. // Check if needs reset
  2008. if (pData->needsReset)
  2009. {
  2010. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2011. {
  2012. for (uint8_t c=0; c<MAX_MIDI_CHANNELS; ++c)
  2013. {
  2014. v3_param_id paramId;
  2015. if (fMidiControllerAssignments.get(0, c, MIDI_CONTROL_ALL_NOTES_OFF, paramId))
  2016. {
  2017. // TODO create mapping between paramId -> index
  2018. uint32_t index = UINT32_MAX;
  2019. for (uint32_t i=0; i < pData->param.count; ++i)
  2020. {
  2021. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2022. {
  2023. index = i;
  2024. break;
  2025. }
  2026. }
  2027. if (index == UINT32_MAX)
  2028. break;
  2029. fEvents.paramInputs->setParamValueRT(index, 0, 0.f);
  2030. }
  2031. }
  2032. }
  2033. else if (pData->ctrlChannel >= 0 && pData->ctrlChannel < MAX_MIDI_CHANNELS && fEvents.eventInputs != nullptr)
  2034. {
  2035. fEvents.eventInputs->numEvents = MAX_MIDI_NOTE;
  2036. for (uint8_t i=0; i < MAX_MIDI_NOTE; ++i)
  2037. {
  2038. v3_event& event(fEvents.eventInputs->events[i]);
  2039. carla_zeroStruct(event);
  2040. event.type = V3_EVENT_NOTE_OFF;
  2041. event.note_off.channel = (pData->ctrlChannel & MIDI_CHANNEL_BIT);
  2042. event.note_off.pitch = i;
  2043. }
  2044. }
  2045. pData->needsReset = false;
  2046. }
  2047. // ------------------------------------------------------------------------------------------------------------
  2048. // Set TimeInfo
  2049. const EngineTimeInfo timeInfo(pData->engine->getTimeInfo());
  2050. fV3TimeContext.state = V3_PROCESS_CTX_PROJECT_TIME_VALID | V3_PROCESS_CTX_CONT_TIME_VALID;
  2051. fV3TimeContext.sample_rate = pData->engine->getSampleRate();
  2052. fV3TimeContext.project_time_in_samples = fV3TimeContext.continuous_time_in_samples
  2053. = static_cast<int64_t>(timeInfo.frame);
  2054. if (fFirstActive || ! fLastTimeInfo.compareIgnoringRollingFrames(timeInfo, frames))
  2055. fLastTimeInfo = timeInfo;
  2056. if (timeInfo.playing)
  2057. fV3TimeContext.state |= V3_PROCESS_CTX_PLAYING;
  2058. if (timeInfo.usecs != 0)
  2059. {
  2060. fV3TimeContext.system_time_ns = static_cast<int64_t>(timeInfo.usecs / 1000);
  2061. fV3TimeContext.state |= V3_PROCESS_CTX_SYSTEM_TIME_VALID;
  2062. }
  2063. if (timeInfo.bbt.valid)
  2064. {
  2065. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.bar > 0, timeInfo.bbt.bar);
  2066. CARLA_SAFE_ASSERT_INT(timeInfo.bbt.beat > 0, timeInfo.bbt.beat);
  2067. const double ppqBar = static_cast<double>(timeInfo.bbt.beatsPerBar) * (timeInfo.bbt.bar - 1);
  2068. // const double ppqBeat = static_cast<double>(timeInfo.bbt.beat - 1);
  2069. // const double ppqTick = timeInfo.bbt.tick / timeInfo.bbt.ticksPerBeat;
  2070. // PPQ Pos
  2071. fV3TimeContext.project_time_quarters = static_cast<double>(timeInfo.frame) / (fV3TimeContext.sample_rate * 60 / timeInfo.bbt.beatsPerMinute);
  2072. // fTimeInfo.project_time_quarters = ppqBar + ppqBeat + ppqTick;
  2073. fV3TimeContext.state |= V3_PROCESS_CTX_PROJECT_TIME_VALID;
  2074. // Tempo
  2075. fV3TimeContext.bpm = timeInfo.bbt.beatsPerMinute;
  2076. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  2077. // Bars
  2078. fV3TimeContext.bar_position_quarters = ppqBar;
  2079. fV3TimeContext.state |= V3_PROCESS_CTX_BAR_POSITION_VALID;
  2080. // Time Signature
  2081. fV3TimeContext.time_sig_numerator = static_cast<int32_t>(timeInfo.bbt.beatsPerBar + 0.5f);
  2082. fV3TimeContext.time_sig_denom = static_cast<int32_t>(timeInfo.bbt.beatType + 0.5f);
  2083. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  2084. }
  2085. else
  2086. {
  2087. // Tempo
  2088. fV3TimeContext.bpm = 120.0;
  2089. fV3TimeContext.state |= V3_PROCESS_CTX_TEMPO_VALID;
  2090. // Time Signature
  2091. fV3TimeContext.time_sig_numerator = 4;
  2092. fV3TimeContext.time_sig_denom = 4;
  2093. fV3TimeContext.state |= V3_PROCESS_CTX_TIME_SIG_VALID;
  2094. // Missing info
  2095. fV3TimeContext.project_time_quarters = 0.0;
  2096. fV3TimeContext.bar_position_quarters = 0.0;
  2097. }
  2098. // ------------------------------------------------------------------------------------------------------------
  2099. // Event Input and Processing
  2100. if (pData->event.portIn != nullptr && fEvents.eventInputs != nullptr)
  2101. {
  2102. // --------------------------------------------------------------------------------------------------------
  2103. // MIDI Input (External)
  2104. if (pData->extNotes.mutex.tryLock())
  2105. {
  2106. ExternalMidiNote note = { 0, 0, 0 };
  2107. uint16_t numEvents = fEvents.eventInputs->numEvents;
  2108. for (; numEvents < kPluginMaxMidiEvents && ! pData->extNotes.data.isEmpty();)
  2109. {
  2110. note = pData->extNotes.data.getFirst(note, true);
  2111. CARLA_SAFE_ASSERT_CONTINUE(note.channel >= 0 && note.channel < MAX_MIDI_CHANNELS);
  2112. v3_event& event(fEvents.eventInputs->events[numEvents++]);
  2113. carla_zeroStruct(event);
  2114. if (note.velo > 0)
  2115. {
  2116. event.type = V3_EVENT_NOTE_ON;
  2117. event.note_on.channel = (note.channel & MIDI_CHANNEL_BIT);
  2118. event.note_on.pitch = note.note;
  2119. event.note_on.velocity = static_cast<float>(note.velo) / 127.f;
  2120. }
  2121. else
  2122. {
  2123. event.type = V3_EVENT_NOTE_OFF;
  2124. event.note_off.channel = (note.channel & MIDI_CHANNEL_BIT);
  2125. event.note_off.pitch = note.note;
  2126. }
  2127. }
  2128. pData->extNotes.mutex.unlock();
  2129. fEvents.eventInputs->numEvents = numEvents;
  2130. } // End of MIDI Input (External)
  2131. // --------------------------------------------------------------------------------------------------------
  2132. // Event Input (System)
  2133. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2134. bool allNotesOffSent = false;
  2135. #endif
  2136. bool isSampleAccurate = (pData->options & PLUGIN_OPTION_FIXED_BUFFERS) == 0;
  2137. uint32_t startTime = 0;
  2138. uint32_t timeOffset = 0;
  2139. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2140. if (cvIn != nullptr && pData->event.cvSourcePorts != nullptr)
  2141. pData->event.cvSourcePorts->initPortBuffers(cvIn, frames, isSampleAccurate, pData->event.portIn);
  2142. #endif
  2143. for (uint32_t i=0, numEvents = pData->event.portIn->getEventCount(); i < numEvents; ++i)
  2144. {
  2145. EngineEvent& event(pData->event.portIn->getEvent(i));
  2146. uint32_t eventTime = event.time;
  2147. CARLA_SAFE_ASSERT_UINT2_CONTINUE(eventTime < frames, eventTime, frames);
  2148. if (eventTime < timeOffset)
  2149. {
  2150. carla_stderr2("Timing error, eventTime:%u < timeOffset:%u for '%s'",
  2151. eventTime, timeOffset, pData->name);
  2152. eventTime = timeOffset;
  2153. }
  2154. if (isSampleAccurate && eventTime > timeOffset)
  2155. {
  2156. if (processSingle(audioIn, audioOut, cvIn, cvOut, eventTime - timeOffset, timeOffset))
  2157. {
  2158. startTime = 0;
  2159. timeOffset = eventTime;
  2160. // TODO
  2161. }
  2162. else
  2163. {
  2164. startTime += timeOffset;
  2165. }
  2166. }
  2167. switch (event.type)
  2168. {
  2169. case kEngineEventTypeNull:
  2170. break;
  2171. case kEngineEventTypeControl: {
  2172. EngineControlEvent& ctrlEvent(event.ctrl);
  2173. switch (ctrlEvent.type)
  2174. {
  2175. case kEngineControlEventTypeNull:
  2176. break;
  2177. case kEngineControlEventTypeParameter: {
  2178. float value;
  2179. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2180. // non-midi
  2181. if (event.channel == kEngineEventNonMidiChannel)
  2182. {
  2183. const uint32_t k = ctrlEvent.param;
  2184. CARLA_SAFE_ASSERT_CONTINUE(k < pData->param.count);
  2185. ctrlEvent.handled = true;
  2186. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  2187. setParameterValueRT(k, value, event.time, true);
  2188. continue;
  2189. }
  2190. // Control backend stuff
  2191. if (event.channel == pData->ctrlChannel)
  2192. {
  2193. if (MIDI_IS_CONTROL_BREATH_CONTROLLER(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_DRYWET) != 0)
  2194. {
  2195. ctrlEvent.handled = true;
  2196. value = ctrlEvent.normalizedValue;
  2197. setDryWetRT(value, true);
  2198. }
  2199. else if (MIDI_IS_CONTROL_CHANNEL_VOLUME(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_VOLUME) != 0)
  2200. {
  2201. ctrlEvent.handled = true;
  2202. value = ctrlEvent.normalizedValue*127.0f/100.0f;
  2203. setVolumeRT(value, true);
  2204. }
  2205. else if (MIDI_IS_CONTROL_BALANCE(ctrlEvent.param) && (pData->hints & PLUGIN_CAN_BALANCE) != 0)
  2206. {
  2207. float left, right;
  2208. value = ctrlEvent.normalizedValue/0.5f - 1.0f;
  2209. if (value < 0.0f)
  2210. {
  2211. left = -1.0f;
  2212. right = (value*2.0f)+1.0f;
  2213. }
  2214. else if (value > 0.0f)
  2215. {
  2216. left = (value*2.0f)-1.0f;
  2217. right = 1.0f;
  2218. }
  2219. else
  2220. {
  2221. left = -1.0f;
  2222. right = 1.0f;
  2223. }
  2224. ctrlEvent.handled = true;
  2225. setBalanceLeftRT(left, true);
  2226. setBalanceRightRT(right, true);
  2227. }
  2228. }
  2229. #endif
  2230. // Control plugin parameters
  2231. uint32_t k;
  2232. for (k=0; k < pData->param.count; ++k)
  2233. {
  2234. if (pData->param.data[k].midiChannel != event.channel)
  2235. continue;
  2236. if (pData->param.data[k].mappedControlIndex != ctrlEvent.param)
  2237. continue;
  2238. if (pData->param.data[k].type != PARAMETER_INPUT)
  2239. continue;
  2240. if ((pData->param.data[k].hints & PARAMETER_IS_AUTOMATABLE) == 0)
  2241. continue;
  2242. ctrlEvent.handled = true;
  2243. value = pData->param.getFinalUnnormalizedValue(k, ctrlEvent.normalizedValue);
  2244. setParameterValueRT(k, value, event.time, true);
  2245. }
  2246. if ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) != 0 && ctrlEvent.param < MAX_MIDI_VALUE)
  2247. {
  2248. v3_param_id paramId;
  2249. if (fMidiControllerAssignments.get(0, event.channel, ctrlEvent.param, paramId))
  2250. {
  2251. // TODO create mapping between paramId -> index
  2252. uint32_t index = UINT32_MAX;
  2253. for (uint32_t i=0; i < pData->param.count; ++i)
  2254. {
  2255. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2256. {
  2257. index = i;
  2258. break;
  2259. }
  2260. }
  2261. if (index == UINT32_MAX)
  2262. break;
  2263. fEvents.paramInputs->setParamValueRT(index, event.time, ctrlEvent.normalizedValue);
  2264. }
  2265. }
  2266. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2267. if (! ctrlEvent.handled)
  2268. checkForMidiLearn(event);
  2269. #endif
  2270. break;
  2271. } // case kEngineControlEventTypeParameter
  2272. case kEngineControlEventTypeMidiBank:
  2273. break;
  2274. case kEngineControlEventTypeMidiProgram:
  2275. if (event.channel == pData->ctrlChannel && (pData->options & PLUGIN_OPTION_MAP_PROGRAM_CHANGES) != 0)
  2276. {
  2277. if (ctrlEvent.param < pData->prog.count)
  2278. {
  2279. setProgramRT(ctrlEvent.param, true);
  2280. break;
  2281. }
  2282. }
  2283. break;
  2284. case kEngineControlEventTypeAllSoundOff:
  2285. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2286. {
  2287. v3_param_id paramId;
  2288. if (fMidiControllerAssignments.get(0, event.channel, MIDI_CONTROL_ALL_SOUND_OFF, paramId))
  2289. {
  2290. // TODO create mapping between paramId -> index
  2291. uint32_t index = UINT32_MAX;
  2292. for (uint32_t i=0; i < pData->param.count; ++i)
  2293. {
  2294. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2295. {
  2296. index = i;
  2297. break;
  2298. }
  2299. }
  2300. if (index == UINT32_MAX)
  2301. break;
  2302. fEvents.paramInputs->setParamValueRT(index, event.time, 0.f);
  2303. }
  2304. }
  2305. break;
  2306. case kEngineControlEventTypeAllNotesOff:
  2307. if (pData->options & PLUGIN_OPTION_SEND_ALL_SOUND_OFF)
  2308. {
  2309. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2310. if (event.channel == pData->ctrlChannel && ! allNotesOffSent)
  2311. {
  2312. allNotesOffSent = true;
  2313. postponeRtAllNotesOff();
  2314. }
  2315. #endif
  2316. v3_param_id paramId;
  2317. if (fMidiControllerAssignments.get(0, event.channel, MIDI_CONTROL_ALL_NOTES_OFF, paramId))
  2318. {
  2319. // TODO create mapping between paramId -> index
  2320. uint32_t index = UINT32_MAX;
  2321. for (uint32_t i=0; i < pData->param.count; ++i)
  2322. {
  2323. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2324. {
  2325. index = i;
  2326. break;
  2327. }
  2328. }
  2329. if (index == UINT32_MAX)
  2330. break;
  2331. fEvents.paramInputs->setParamValueRT(index, event.time, 0.f);
  2332. }
  2333. }
  2334. break;
  2335. } // switch (ctrlEvent.type)
  2336. break;
  2337. } // case kEngineEventTypeControl
  2338. case kEngineEventTypeMidi: {
  2339. const EngineMidiEvent& midiEvent(event.midi);
  2340. if (midiEvent.size > 3)
  2341. continue;
  2342. #ifdef CARLA_PROPER_CPP11_SUPPORT
  2343. static_assert(3 <= EngineMidiEvent::kDataSize, "Incorrect data");
  2344. #endif
  2345. uint8_t status = uint8_t(MIDI_GET_STATUS_FROM_DATA(midiEvent.data));
  2346. if ((status == MIDI_STATUS_NOTE_OFF || status == MIDI_STATUS_NOTE_ON) && (pData->options & PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2347. continue;
  2348. if (status == MIDI_STATUS_POLYPHONIC_AFTERTOUCH && (pData->options & PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH) == 0)
  2349. continue;
  2350. if (status == MIDI_STATUS_CONTROL_CHANGE && ((pData->options & PLUGIN_OPTION_SEND_CONTROL_CHANGES) == 0 || fEvents.paramInputs == nullptr || fV3.midiMapping == nullptr))
  2351. continue;
  2352. if (status == MIDI_STATUS_CHANNEL_PRESSURE && ((pData->options & PLUGIN_OPTION_SEND_CHANNEL_PRESSURE) == 0 || fEvents.paramInputs == nullptr || fV3.midiMapping == nullptr))
  2353. continue;
  2354. if (status == MIDI_STATUS_PITCH_WHEEL_CONTROL && ((pData->options & PLUGIN_OPTION_SEND_PITCHBEND) == 0 || fEvents.paramInputs == nullptr || fV3.midiMapping == nullptr))
  2355. continue;
  2356. // Fix bad note-off
  2357. if (status == MIDI_STATUS_NOTE_ON && midiEvent.data[2] == 0)
  2358. status = MIDI_STATUS_NOTE_OFF;
  2359. switch (status)
  2360. {
  2361. case MIDI_STATUS_NOTE_OFF:
  2362. if (fEvents.eventInputs->numEvents < kPluginMaxMidiEvents)
  2363. {
  2364. const uint8_t note = midiEvent.data[1];
  2365. v3_event& v3event(fEvents.eventInputs->events[fEvents.eventInputs->numEvents++]);
  2366. carla_zeroStruct(v3event);
  2367. v3event.type = V3_EVENT_NOTE_OFF;
  2368. v3event.note_off.channel = event.channel & MIDI_CHANNEL_BIT;
  2369. v3event.note_off.pitch = note;
  2370. pData->postponeNoteOffRtEvent(true, event.channel, note);
  2371. }
  2372. break;
  2373. case MIDI_STATUS_NOTE_ON:
  2374. if (fEvents.eventInputs->numEvents < kPluginMaxMidiEvents)
  2375. {
  2376. const uint8_t note = midiEvent.data[1];
  2377. const uint8_t velo = midiEvent.data[2];
  2378. v3_event& v3event(fEvents.eventInputs->events[fEvents.eventInputs->numEvents++]);
  2379. carla_zeroStruct(v3event);
  2380. v3event.type = V3_EVENT_NOTE_ON;
  2381. v3event.note_on.channel = event.channel & MIDI_CHANNEL_BIT;
  2382. v3event.note_on.pitch = note;
  2383. v3event.note_on.velocity = static_cast<float>(velo) / 127.f;
  2384. pData->postponeNoteOnRtEvent(true, event.channel, note, velo);
  2385. }
  2386. break;
  2387. case MIDI_STATUS_POLYPHONIC_AFTERTOUCH:
  2388. if (fEvents.eventInputs->numEvents < kPluginMaxMidiEvents)
  2389. {
  2390. const uint8_t note = midiEvent.data[1];
  2391. const uint8_t pressure = midiEvent.data[2];
  2392. v3_event& v3event(fEvents.eventInputs->events[fEvents.eventInputs->numEvents++]);
  2393. carla_zeroStruct(v3event);
  2394. v3event.type = V3_EVENT_POLY_PRESSURE;
  2395. v3event.poly_pressure.channel = event.channel;
  2396. v3event.poly_pressure.pitch = note;
  2397. v3event.poly_pressure.pressure = static_cast<float>(pressure) / 127.f;
  2398. }
  2399. break;
  2400. case MIDI_STATUS_CONTROL_CHANGE:
  2401. {
  2402. const uint8_t control = midiEvent.data[1];
  2403. const uint8_t value = midiEvent.data[2];
  2404. v3_param_id paramId;
  2405. if (fMidiControllerAssignments.get(midiEvent.port, event.channel, control, paramId))
  2406. {
  2407. // TODO create mapping between paramId -> index
  2408. uint32_t index = UINT32_MAX;
  2409. for (uint32_t i=0; i < pData->param.count; ++i)
  2410. {
  2411. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2412. {
  2413. index = i;
  2414. break;
  2415. }
  2416. }
  2417. if (index == UINT32_MAX)
  2418. break;
  2419. fEvents.paramInputs->setParamValueRT(index,
  2420. event.time,
  2421. static_cast<float>(value) / 127.f);
  2422. }
  2423. }
  2424. break;
  2425. case MIDI_STATUS_CHANNEL_PRESSURE:
  2426. {
  2427. const uint8_t pressure = midiEvent.data[1];
  2428. v3_param_id paramId;
  2429. if (fMidiControllerAssignments.get(midiEvent.port, event.channel, 128, paramId))
  2430. {
  2431. // TODO create mapping between paramId -> index
  2432. uint32_t index = UINT32_MAX;
  2433. for (uint32_t i=0; i < pData->param.count; ++i)
  2434. {
  2435. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2436. {
  2437. index = i;
  2438. break;
  2439. }
  2440. }
  2441. if (index == UINT32_MAX)
  2442. break;
  2443. fEvents.paramInputs->setParamValueRT(index,
  2444. event.time,
  2445. static_cast<float>(pressure) / 127.f);
  2446. }
  2447. }
  2448. break;
  2449. case MIDI_STATUS_PITCH_WHEEL_CONTROL:
  2450. {
  2451. const uint16_t pitchbend = (midiEvent.data[2] << 7) | midiEvent.data[1];
  2452. v3_param_id paramId;
  2453. if (fMidiControllerAssignments.get(midiEvent.port, event.channel, 129, paramId))
  2454. {
  2455. // TODO create mapping between paramId -> index
  2456. uint32_t index = UINT32_MAX;
  2457. for (uint32_t i=0; i < pData->param.count; ++i)
  2458. {
  2459. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2460. {
  2461. index = i;
  2462. break;
  2463. }
  2464. }
  2465. if (index == UINT32_MAX)
  2466. break;
  2467. fEvents.paramInputs->setParamValueRT(index,
  2468. event.time,
  2469. static_cast<float>(pitchbend) / 16384.f);
  2470. }
  2471. }
  2472. break;
  2473. } // switch (status)
  2474. } break;
  2475. } // switch (event.type)
  2476. }
  2477. pData->postRtEvents.trySplice();
  2478. if (frames > timeOffset)
  2479. processSingle(audioIn, audioOut, cvIn, cvOut, frames - timeOffset, timeOffset);
  2480. } // End of Event Input and Processing
  2481. // ------------------------------------------------------------------------------------------------------------
  2482. // Plugin processing (no events)
  2483. else
  2484. {
  2485. processSingle(audioIn, audioOut, cvIn, cvOut, frames, 0);
  2486. } // End of Plugin processing (no events)
  2487. // ------------------------------------------------------------------------------------------------------------
  2488. // MIDI Output
  2489. if (pData->event.portOut != nullptr)
  2490. {
  2491. // TODO
  2492. } // End of MIDI Output
  2493. fFirstActive = false;
  2494. // ------------------------------------------------------------------------------------------------------------
  2495. }
  2496. bool processSingle(const float* const* const inBuffer, float** const outBuffer,
  2497. const float* const* const cvIn, float** const cvOut,
  2498. const uint32_t frames, const uint32_t timeOffset)
  2499. {
  2500. CARLA_SAFE_ASSERT_RETURN(frames > 0, false);
  2501. if (pData->audioIn.count > 0)
  2502. {
  2503. CARLA_SAFE_ASSERT_RETURN(inBuffer != nullptr, false);
  2504. }
  2505. if (pData->audioOut.count > 0)
  2506. {
  2507. CARLA_SAFE_ASSERT_RETURN(outBuffer != nullptr, false);
  2508. CARLA_SAFE_ASSERT_RETURN(fAudioAndCvOutBuffers != nullptr, false);
  2509. }
  2510. // ------------------------------------------------------------------------------------------------------------
  2511. // Try lock, silence otherwise
  2512. #ifndef STOAT_TEST_BUILD
  2513. if (pData->engine->isOffline())
  2514. {
  2515. pData->singleMutex.lock();
  2516. }
  2517. else
  2518. #endif
  2519. if (! pData->singleMutex.tryLock())
  2520. {
  2521. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2522. {
  2523. for (uint32_t k=0; k < frames; ++k)
  2524. outBuffer[i][k+timeOffset] = 0.0f;
  2525. }
  2526. for (uint32_t i=0; i < pData->cvOut.count; ++i)
  2527. {
  2528. for (uint32_t k=0; k < frames; ++k)
  2529. cvOut[i][k+timeOffset] = 0.0f;
  2530. }
  2531. return false;
  2532. }
  2533. // ------------------------------------------------------------------------------------------------------------
  2534. // Set audio buffers
  2535. float* bufferAudioIn[96]; // std::max(1u, pData->audioIn.count + pData->cvIn.count)
  2536. float* bufferAudioOut[96]; // std::max(1u, pData->audioOut.count + pData->cvOut.count)
  2537. for (uint32_t i=0; i < pData->audioIn.count; ++i)
  2538. bufferAudioIn[i] = const_cast<float*>(inBuffer[i]+timeOffset);
  2539. for (uint32_t i=0, j=pData->audioIn.count; i < pData->cvIn.count; ++i, ++j)
  2540. bufferAudioIn[j] = const_cast<float*>(cvIn[i]+timeOffset);
  2541. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2542. {
  2543. bufferAudioOut[i] = fAudioAndCvOutBuffers[i]+timeOffset;
  2544. carla_zeroFloats(bufferAudioOut[i], frames);
  2545. }
  2546. // ------------------------------------------------------------------------------------------------------------
  2547. // Set MIDI events
  2548. // TODO
  2549. // ------------------------------------------------------------------------------------------------------------
  2550. // Run plugin
  2551. fEvents.prepare();
  2552. for (int32_t b = 0, j = 0; b < fBuses.numInputs; ++b)
  2553. {
  2554. fBuses.inputs[b].channel_buffers_32 = const_cast<float**>(bufferAudioIn + j);
  2555. j += fBuses.inputs[b].num_channels;
  2556. }
  2557. for (int32_t b = 0, j = 0; b < fBuses.numOutputs; ++b)
  2558. {
  2559. fBuses.outputs[b].channel_buffers_32 = bufferAudioOut + j;
  2560. j += fBuses.outputs[b].num_channels;
  2561. }
  2562. v3_process_data processData = {
  2563. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2564. V3_SAMPLE_32,
  2565. static_cast<int32_t>(frames),
  2566. fBuses.numInputs,
  2567. fBuses.numOutputs,
  2568. fBuses.inputs,
  2569. fBuses.outputs,
  2570. fEvents.paramInputs != nullptr ? (v3_param_changes**)&fEvents.paramInputs : nullptr,
  2571. fEvents.paramOutputs != nullptr ? (v3_param_changes**)&fEvents.paramOutputs : nullptr,
  2572. fEvents.eventInputs != nullptr ? (v3_event_list**)&fEvents.eventInputs : nullptr,
  2573. fEvents.eventOutputs != nullptr ? (v3_event_list**)&fEvents.eventOutputs : nullptr,
  2574. &fV3TimeContext
  2575. };
  2576. try {
  2577. v3_cpp_obj(fV3.processor)->process(fV3.processor, &processData);
  2578. } CARLA_SAFE_EXCEPTION("process");
  2579. // ------------------------------------------------------------------------------------------------------------
  2580. // Handle parameter outputs
  2581. if (fEvents.paramOutputs != nullptr && fEvents.paramOutputs->numParametersUsed != 0)
  2582. {
  2583. uint8_t channel;
  2584. uint16_t param;
  2585. for (uint32_t i=0; i < pData->param.count; ++i)
  2586. {
  2587. if (fEvents.paramOutputs->parametersUsed[i])
  2588. {
  2589. carla_v3_output_param_value_queue* const queue = fEvents.paramOutputs->queue[i];
  2590. const v3_param_id paramId = pData->param.data[i].rindex;
  2591. const float value = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller,
  2592. paramId,
  2593. queue->value);
  2594. pData->postponeParameterChangeRtEvent(true, static_cast<int32_t>(i), value);
  2595. if (pData->param.data[i].type == PARAMETER_OUTPUT && pData->param.data[i].mappedControlIndex > 0)
  2596. {
  2597. channel = pData->param.data[i].midiChannel;
  2598. param = static_cast<uint16_t>(pData->param.data[i].mappedControlIndex);
  2599. pData->event.portOut->writeControlEvent(queue->offset,
  2600. channel,
  2601. kEngineControlEventTypeParameter,
  2602. param,
  2603. -1,
  2604. queue->value);
  2605. }
  2606. }
  2607. }
  2608. }
  2609. pData->postRtEvents.trySplice();
  2610. fEvents.init();
  2611. #ifndef BUILD_BRIDGE_ALTERNATIVE_ARCH
  2612. // ------------------------------------------------------------------------------------------------------------
  2613. // Post-processing (dry/wet, volume and balance)
  2614. {
  2615. const bool doDryWet = (pData->hints & PLUGIN_CAN_DRYWET) != 0
  2616. && carla_isNotEqual(pData->postProc.dryWet, 1.0f);
  2617. const bool doBalance = (pData->hints & PLUGIN_CAN_BALANCE) != 0
  2618. && ! (carla_isEqual(pData->postProc.balanceLeft, -1.0f)
  2619. && carla_isEqual(pData->postProc.balanceRight, 1.0f));
  2620. const bool isMono = (pData->audioIn.count == 1);
  2621. bool isPair;
  2622. float bufValue;
  2623. float* const oldBufLeft = pData->postProc.extraBuffer;
  2624. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2625. {
  2626. // Dry/Wet
  2627. if (doDryWet)
  2628. {
  2629. const uint32_t c = isMono ? 0 : i;
  2630. for (uint32_t k=0; k < frames; ++k)
  2631. {
  2632. bufValue = inBuffer[c][k+timeOffset];
  2633. fAudioAndCvOutBuffers[i][k] = (fAudioAndCvOutBuffers[i][k] * pData->postProc.dryWet)
  2634. + (bufValue * (1.0f - pData->postProc.dryWet));
  2635. }
  2636. }
  2637. // Balance
  2638. if (doBalance)
  2639. {
  2640. isPair = (i % 2 == 0);
  2641. if (isPair)
  2642. {
  2643. CARLA_ASSERT(i+1 < pData->audioOut.count);
  2644. carla_copyFloats(oldBufLeft, fAudioAndCvOutBuffers[i], frames);
  2645. }
  2646. float balRangeL = (pData->postProc.balanceLeft + 1.0f)/2.0f;
  2647. float balRangeR = (pData->postProc.balanceRight + 1.0f)/2.0f;
  2648. for (uint32_t k=0; k < frames; ++k)
  2649. {
  2650. if (isPair)
  2651. {
  2652. // left
  2653. fAudioAndCvOutBuffers[i][k] = oldBufLeft[k] * (1.0f - balRangeL);
  2654. fAudioAndCvOutBuffers[i][k] += fAudioAndCvOutBuffers[i+1][k] * (1.0f - balRangeR);
  2655. }
  2656. else
  2657. {
  2658. // right
  2659. fAudioAndCvOutBuffers[i][k] = fAudioAndCvOutBuffers[i][k] * balRangeR;
  2660. fAudioAndCvOutBuffers[i][k] += oldBufLeft[k] * balRangeL;
  2661. }
  2662. }
  2663. }
  2664. // Volume (and buffer copy)
  2665. {
  2666. for (uint32_t k=0; k < frames; ++k)
  2667. outBuffer[i][k+timeOffset] = fAudioAndCvOutBuffers[i][k] * pData->postProc.volume;
  2668. }
  2669. }
  2670. for (uint32_t i=0, j=pData->audioOut.count; i < pData->cvOut.count; ++i, ++j)
  2671. carla_copyFloats(cvOut[i] + timeOffset, fAudioAndCvOutBuffers[j] + timeOffset, frames);
  2672. } // End of Post-processing
  2673. #else // BUILD_BRIDGE_ALTERNATIVE_ARCH
  2674. for (uint32_t i=0; i < pData->audioOut.count; ++i)
  2675. carla_copyFloats(outBuffer[i] + timeOffset, fAudioAndCvOutBuffers[i] + timeOffset, frames);
  2676. for (uint32_t i=0, j=pData->audioOut.count; i < pData->cvOut.count; ++i, ++j)
  2677. carla_copyFloats(cvOut[i] + timeOffset, fAudioAndCvOutBuffers[j] + timeOffset, frames);
  2678. #endif
  2679. // ------------------------------------------------------------------------------------------------------------
  2680. pData->singleMutex.unlock();
  2681. return true;
  2682. }
  2683. void bufferSizeChanged(const uint32_t newBufferSize) override
  2684. {
  2685. CARLA_ASSERT_INT(newBufferSize > 0, newBufferSize);
  2686. carla_debug("CarlaPluginVST3::bufferSizeChanged(%i)", newBufferSize);
  2687. if (pData->active)
  2688. deactivate();
  2689. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2690. {
  2691. if (fAudioAndCvOutBuffers[i] != nullptr)
  2692. delete[] fAudioAndCvOutBuffers[i];
  2693. fAudioAndCvOutBuffers[i] = new float[newBufferSize];
  2694. }
  2695. v3_process_setup setup = {
  2696. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2697. V3_SAMPLE_32,
  2698. static_cast<int32_t>(newBufferSize),
  2699. pData->engine->getSampleRate()
  2700. };
  2701. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2702. if (pData->active)
  2703. activate();
  2704. CarlaPlugin::bufferSizeChanged(newBufferSize);
  2705. }
  2706. void sampleRateChanged(const double newSampleRate) override
  2707. {
  2708. CARLA_ASSERT_INT(newSampleRate > 0.0, newSampleRate);
  2709. carla_debug("CarlaPluginVST3::sampleRateChanged(%g)", newSampleRate);
  2710. if (pData->active)
  2711. deactivate();
  2712. v3_process_setup setup = {
  2713. pData->engine->isOffline() ? V3_OFFLINE : V3_REALTIME,
  2714. V3_SAMPLE_32,
  2715. static_cast<int32_t>(pData->engine->getBufferSize()),
  2716. newSampleRate
  2717. };
  2718. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2719. if (pData->active)
  2720. activate();
  2721. }
  2722. void offlineModeChanged(const bool isOffline) override
  2723. {
  2724. carla_debug("CarlaPluginVST3::offlineModeChanged(%d)", isOffline);
  2725. if (pData->active)
  2726. deactivate();
  2727. v3_process_setup setup = {
  2728. isOffline ? V3_OFFLINE : V3_REALTIME,
  2729. V3_SAMPLE_32,
  2730. static_cast<int32_t>(pData->engine->getBufferSize()),
  2731. pData->engine->getSampleRate()
  2732. };
  2733. v3_cpp_obj(fV3.processor)->setup_processing(fV3.processor, &setup);
  2734. if (pData->active)
  2735. activate();
  2736. }
  2737. // ----------------------------------------------------------------------------------------------------------------
  2738. // Plugin buffers
  2739. void clearBuffers() noexcept override
  2740. {
  2741. carla_debug("CarlaPluginVST3::clearBuffers() - start");
  2742. if (fAudioAndCvOutBuffers != nullptr)
  2743. {
  2744. for (uint32_t i=0; i < pData->audioOut.count + pData->cvOut.count; ++i)
  2745. {
  2746. if (fAudioAndCvOutBuffers[i] != nullptr)
  2747. {
  2748. delete[] fAudioAndCvOutBuffers[i];
  2749. fAudioAndCvOutBuffers[i] = nullptr;
  2750. }
  2751. }
  2752. delete[] fAudioAndCvOutBuffers;
  2753. fAudioAndCvOutBuffers = nullptr;
  2754. }
  2755. CarlaPlugin::clearBuffers();
  2756. carla_debug("CarlaPluginVST3::clearBuffers() - end");
  2757. }
  2758. // ----------------------------------------------------------------------------------------------------------------
  2759. // Post-poned UI Stuff
  2760. void uiParameterChange(const uint32_t index, const float value) noexcept override
  2761. {
  2762. CARLA_SAFE_ASSERT_RETURN(fV3.controller != nullptr,);
  2763. CARLA_SAFE_ASSERT_RETURN(index < pData->param.count,);
  2764. const v3_param_id paramId = pData->param.data[index].rindex;
  2765. const double normalized = v3_cpp_obj(fV3.controller)->plain_parameter_to_normalised(fV3.controller,
  2766. paramId, value);
  2767. v3_cpp_obj(fV3.controller)->set_parameter_normalised(fV3.controller, paramId, normalized);
  2768. }
  2769. // ----------------------------------------------------------------------------------------------------------------
  2770. bool hasMidiInput() const noexcept
  2771. {
  2772. return pData->extraHints & PLUGIN_EXTRA_HINT_HAS_MIDI_IN ||
  2773. std::strstr(fV3ClassInfo.v2.sub_categories, "Instrument") != nullptr ||
  2774. v3_cpp_obj(fV3.component)->get_bus_count(fV3.component, V3_EVENT, V3_INPUT) > 0;
  2775. }
  2776. // ----------------------------------------------------------------------------------------------------------------
  2777. const void* getNativeDescriptor() const noexcept override
  2778. {
  2779. return fV3.component;
  2780. }
  2781. const void* getExtraStuff() const noexcept override
  2782. {
  2783. return fV3.controller;
  2784. }
  2785. // ----------------------------------------------------------------------------------------------------------------
  2786. bool init(const CarlaPluginPtr plugin,
  2787. const char* const filename,
  2788. const char* name,
  2789. const char* /*const label*/,
  2790. const uint options)
  2791. {
  2792. CARLA_SAFE_ASSERT_RETURN(pData->engine != nullptr, false);
  2793. // ------------------------------------------------------------------------------------------------------------
  2794. // first checks
  2795. if (pData->client != nullptr)
  2796. {
  2797. pData->engine->setLastError("Plugin client is already registered");
  2798. return false;
  2799. }
  2800. if (filename == nullptr || filename[0] == '\0')
  2801. {
  2802. pData->engine->setLastError("null filename");
  2803. return false;
  2804. }
  2805. V3_ENTRYFN v3_entry;
  2806. V3_EXITFN v3_exit;
  2807. V3_GETFN v3_get;
  2808. // filename is full path to binary
  2809. if (water::File(filename).existsAsFile())
  2810. {
  2811. if (! pData->libOpen(filename))
  2812. {
  2813. pData->engine->setLastError(pData->libError(filename));
  2814. return false;
  2815. }
  2816. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  2817. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  2818. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  2819. }
  2820. // assume filename is a vst3 bundle
  2821. else
  2822. {
  2823. #ifdef CARLA_OS_MAC
  2824. if (! fMacBundleLoader.load(filename))
  2825. {
  2826. pData->engine->setLastError("Failed to load VST3 bundle executable");
  2827. return false;
  2828. }
  2829. v3_entry = fMacBundleLoader.getSymbol<V3_ENTRYFN>(CFSTR(V3_ENTRYFNNAME));
  2830. v3_exit = fMacBundleLoader.getSymbol<V3_EXITFN>(CFSTR(V3_EXITFNNAME));
  2831. v3_get = fMacBundleLoader.getSymbol<V3_GETFN>(CFSTR(V3_GETFNNAME));
  2832. #else
  2833. water::String binaryfilename = filename;
  2834. if (!binaryfilename.endsWithChar(CARLA_OS_SEP))
  2835. binaryfilename += CARLA_OS_SEP_STR;
  2836. binaryfilename += "Contents" CARLA_OS_SEP_STR V3_CONTENT_DIR CARLA_OS_SEP_STR;
  2837. binaryfilename += water::File(filename).getFileNameWithoutExtension();
  2838. #ifdef CARLA_OS_WIN
  2839. binaryfilename += ".vst3";
  2840. #else
  2841. binaryfilename += ".so";
  2842. #endif
  2843. if (! water::File(binaryfilename).existsAsFile())
  2844. {
  2845. pData->engine->setLastError("Failed to find a suitable VST3 bundle binary");
  2846. return false;
  2847. }
  2848. if (! pData->libOpen(binaryfilename.toRawUTF8()))
  2849. {
  2850. pData->engine->setLastError(pData->libError(binaryfilename.toRawUTF8()));
  2851. return false;
  2852. }
  2853. v3_entry = pData->libSymbol<V3_ENTRYFN>(V3_ENTRYFNNAME);
  2854. v3_exit = pData->libSymbol<V3_EXITFN>(V3_EXITFNNAME);
  2855. v3_get = pData->libSymbol<V3_GETFN>(V3_GETFNNAME);
  2856. #endif
  2857. }
  2858. // ------------------------------------------------------------------------------------------------------------
  2859. // ensure entry and exit points are available
  2860. if (v3_entry == nullptr || v3_exit == nullptr || v3_get == nullptr)
  2861. {
  2862. pData->engine->setLastError("Not a VST3 plugin");
  2863. return false;
  2864. }
  2865. // ------------------------------------------------------------------------------------------------------------
  2866. // call entry point
  2867. #if defined(CARLA_OS_MAC)
  2868. v3_entry(pData->lib == nullptr ? fMacBundleLoader.getRef() : nullptr);
  2869. #elif defined(CARLA_OS_WIN)
  2870. v3_entry();
  2871. #else
  2872. v3_entry(pData->lib);
  2873. #endif
  2874. // ------------------------------------------------------------------------------------------------------------
  2875. // fetch initial factory
  2876. v3_plugin_factory** const factory = v3_get();
  2877. if (factory == nullptr)
  2878. {
  2879. pData->engine->setLastError("VST3 factory failed to create a valid instance");
  2880. return false;
  2881. }
  2882. // ------------------------------------------------------------------------------------------------------------
  2883. // initialize and find requested plugin
  2884. fV3.exitfn = v3_exit;
  2885. fV3.factory1 = factory;
  2886. v3_funknown** const hostContext = (v3_funknown**)&fV3ApplicationPtr;
  2887. if (! fV3.queryFactories(hostContext))
  2888. {
  2889. pData->engine->setLastError("VST3 plugin failed to properly create factories");
  2890. return false;
  2891. }
  2892. if (! fV3.findPlugin(fV3ClassInfo))
  2893. {
  2894. pData->engine->setLastError("Failed to find the requested plugin in the VST3 bundle");
  2895. return false;
  2896. }
  2897. if (! fV3.initializePlugin(fV3ClassInfo.v1.class_id,
  2898. hostContext,
  2899. (v3_component_handler**)&fComponentHandlerPtr))
  2900. {
  2901. pData->engine->setLastError("VST3 plugin failed to initialize");
  2902. return false;
  2903. }
  2904. // ------------------------------------------------------------------------------------------------------------
  2905. // do some basic safety checks
  2906. if (v3_cpp_obj(fV3.processor)->can_process_sample_size(fV3.processor, V3_SAMPLE_32) != V3_OK)
  2907. {
  2908. pData->engine->setLastError("VST3 plugin does not support 32bit audio, cannot continue");
  2909. return false;
  2910. }
  2911. // ------------------------------------------------------------------------------------------------------------
  2912. // get info
  2913. if (name != nullptr && name[0] != '\0')
  2914. {
  2915. pData->name = pData->engine->getUniquePluginName(name);
  2916. }
  2917. else
  2918. {
  2919. if (fV3ClassInfo.v1.name[0] != '\0')
  2920. pData->name = pData->engine->getUniquePluginName(fV3ClassInfo.v1.name);
  2921. else if (const char* const shortname = std::strrchr(filename, CARLA_OS_SEP))
  2922. pData->name = pData->engine->getUniquePluginName(shortname+1);
  2923. else
  2924. pData->name = pData->engine->getUniquePluginName("unknown");
  2925. }
  2926. pData->filename = carla_strdup(filename);
  2927. // ------------------------------------------------------------------------------------------------------------
  2928. // register client
  2929. pData->client = pData->engine->addClient(plugin);
  2930. if (pData->client == nullptr || ! pData->client->isOk())
  2931. {
  2932. pData->engine->setLastError("Failed to register plugin client");
  2933. return false;
  2934. }
  2935. // ------------------------------------------------------------------------------------------------------------
  2936. // set default options
  2937. pData->options = 0x0;
  2938. if (fLastKnownLatency != 0 /*|| hasMidiOutput()*/ || isPluginOptionEnabled(options, PLUGIN_OPTION_FIXED_BUFFERS))
  2939. pData->options |= PLUGIN_OPTION_FIXED_BUFFERS;
  2940. if (isPluginOptionEnabled(options, PLUGIN_OPTION_USE_CHUNKS))
  2941. pData->options |= PLUGIN_OPTION_USE_CHUNKS;
  2942. if (hasMidiInput())
  2943. {
  2944. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CONTROL_CHANGES))
  2945. pData->options |= PLUGIN_OPTION_SEND_CONTROL_CHANGES;
  2946. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_CHANNEL_PRESSURE))
  2947. pData->options |= PLUGIN_OPTION_SEND_CHANNEL_PRESSURE;
  2948. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH))
  2949. pData->options |= PLUGIN_OPTION_SEND_NOTE_AFTERTOUCH;
  2950. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_PITCHBEND))
  2951. pData->options |= PLUGIN_OPTION_SEND_PITCHBEND;
  2952. if (isPluginOptionEnabled(options, PLUGIN_OPTION_SEND_ALL_SOUND_OFF))
  2953. pData->options |= PLUGIN_OPTION_SEND_ALL_SOUND_OFF;
  2954. if (isPluginOptionInverseEnabled(options, PLUGIN_OPTION_SKIP_SENDING_NOTES))
  2955. pData->options |= PLUGIN_OPTION_SKIP_SENDING_NOTES;
  2956. }
  2957. /*
  2958. if (numPrograms > 1 && isPluginOptionEnabled(options, PLUGIN_OPTION_MAP_PROGRAM_CHANGES))
  2959. pData->options |= PLUGIN_OPTION_MAP_PROGRAM_CHANGES;
  2960. */
  2961. // ------------------------------------------------------------------------------------------------------------
  2962. return true;
  2963. }
  2964. protected:
  2965. v3_result v3BeginEdit(const v3_param_id paramId) override
  2966. {
  2967. for (uint32_t i=0; i < pData->param.count; ++i)
  2968. {
  2969. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2970. {
  2971. pData->engine->touchPluginParameter(pData->id, i, true);
  2972. return V3_OK;
  2973. }
  2974. }
  2975. return V3_INVALID_ARG;
  2976. }
  2977. v3_result v3PerformEdit(const v3_param_id paramId, const double value) override
  2978. {
  2979. CARLA_SAFE_ASSERT_RETURN(fEvents.paramInputs != nullptr, V3_INTERNAL_ERR);
  2980. for (uint32_t i=0; i < pData->param.count; ++i)
  2981. {
  2982. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  2983. {
  2984. // report value to component (next process call)
  2985. fEvents.paramInputs->setParamValue(i, static_cast<float>(value));
  2986. const double plain = v3_cpp_obj(fV3.controller)->normalised_parameter_to_plain(fV3.controller,
  2987. paramId,
  2988. value);
  2989. const float fixedValue = pData->param.getFixedValue(i, plain);
  2990. CarlaPlugin::setParameterValue(i, fixedValue, false, true, true);
  2991. return V3_OK;
  2992. }
  2993. }
  2994. return V3_INVALID_ARG;
  2995. }
  2996. v3_result v3EndEdit(const v3_param_id paramId) override
  2997. {
  2998. for (uint32_t i=0; i < pData->param.count; ++i)
  2999. {
  3000. if (static_cast<v3_param_id>(pData->param.data[i].rindex) == paramId)
  3001. {
  3002. pData->engine->touchPluginParameter(pData->id, i, false);
  3003. return V3_OK;
  3004. }
  3005. }
  3006. return V3_INVALID_ARG;
  3007. }
  3008. v3_result v3RestartComponent(const int32_t flags) override
  3009. {
  3010. fRestartFlags |= flags;
  3011. return V3_OK;
  3012. }
  3013. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3014. v3_result v3ResizeView(struct v3_plugin_view** const view, struct v3_view_rect* const rect) override
  3015. {
  3016. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr, V3_INVALID_ARG);
  3017. CARLA_SAFE_ASSERT_RETURN(fV3.view == view, V3_INVALID_ARG);
  3018. const int32_t width = rect->right - rect->left;
  3019. const int32_t height = rect->bottom - rect->top;
  3020. CARLA_SAFE_ASSERT_INT_RETURN(width > 0, width, V3_INVALID_ARG);
  3021. CARLA_SAFE_ASSERT_INT_RETURN(height > 0, height, V3_INVALID_ARG);
  3022. carla_stdout("v3ResizeView %d %d", width, height);
  3023. fUI.isResizingFromPlugin = true;
  3024. fUI.width = width;
  3025. fUI.height = height;
  3026. if (fUI.isEmbed)
  3027. {
  3028. pData->engine->callback(true, true,
  3029. ENGINE_CALLBACK_EMBED_UI_RESIZED,
  3030. pData->id,
  3031. width, height,
  3032. 0, 0.0f, nullptr);
  3033. }
  3034. else
  3035. {
  3036. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr, V3_NOT_INITIALIZED);
  3037. fUI.window->setSize(static_cast<uint>(width), static_cast<uint>(height), true, false);
  3038. }
  3039. return V3_OK;
  3040. }
  3041. void handlePluginUIClosed() override
  3042. {
  3043. // CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  3044. carla_debug("CarlaPluginVST3::handlePluginUIClosed()");
  3045. fUI.isResizingFromHost = fUI.isResizingFromInit = false;
  3046. fUI.isResizingFromPlugin = false;
  3047. showCustomUI(false);
  3048. pData->engine->callback(true, true,
  3049. ENGINE_CALLBACK_UI_STATE_CHANGED,
  3050. pData->id,
  3051. 0,
  3052. 0, 0, 0.0f, nullptr);
  3053. }
  3054. void handlePluginUIResized(const uint width, const uint height) override
  3055. {
  3056. CARLA_SAFE_ASSERT_RETURN(fV3.view != nullptr,);
  3057. CARLA_SAFE_ASSERT_RETURN(fUI.window != nullptr,);
  3058. carla_stdout("CarlaPluginVST3::handlePluginUIResized(%u, %u | vs %u %u) %s %s %s",
  3059. width, height,
  3060. fUI.width, fUI.height,
  3061. bool2str(fUI.isResizingFromPlugin),
  3062. bool2str(fUI.isResizingFromInit),
  3063. bool2str(fUI.isResizingFromHost));
  3064. if (fUI.isResizingFromInit)
  3065. {
  3066. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  3067. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  3068. fUI.isResizingFromInit = false;
  3069. return;
  3070. }
  3071. if (fUI.isResizingFromPlugin)
  3072. {
  3073. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  3074. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  3075. fUI.isResizingFromPlugin = false;
  3076. return;
  3077. }
  3078. if (fUI.isResizingFromHost)
  3079. {
  3080. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.width == width, fUI.width, width,);
  3081. CARLA_SAFE_ASSERT_UINT2_RETURN(fUI.height == height, fUI.height, height,);
  3082. fUI.isResizingFromHost = false;
  3083. return;
  3084. }
  3085. if (fUI.width != width || fUI.height != height)
  3086. {
  3087. v3_view_rect rect = { 0, 0, static_cast<int32_t>(width), static_cast<int32_t>(height) };
  3088. if (v3_cpp_obj(fV3.view)->check_size_constraint(fV3.view, &rect) == V3_OK)
  3089. {
  3090. const uint width2 = rect.right - rect.left;
  3091. const uint height2 = rect.bottom - rect.top;
  3092. if (width2 != width || height2 != height)
  3093. {
  3094. fUI.isResizingFromHost = true;
  3095. fUI.width = width2;
  3096. fUI.height = height2;
  3097. fUI.window->setSize(width2, height2, true, false);
  3098. }
  3099. else
  3100. {
  3101. v3_cpp_obj(fV3.view)->on_size(fV3.view, &rect);
  3102. }
  3103. }
  3104. }
  3105. }
  3106. #endif // V3_VIEW_PLATFORM_TYPE_NATIVE
  3107. private:
  3108. #ifdef CARLA_OS_MAC
  3109. BundleLoader fMacBundleLoader;
  3110. #endif
  3111. const bool kEngineHasIdleOnMainThread;
  3112. bool fFirstActive; // first process() call after activate()
  3113. float** fAudioAndCvOutBuffers;
  3114. uint32_t fLastKnownLatency;
  3115. int32_t fRestartFlags;
  3116. void* fLastChunk;
  3117. EngineTimeInfo fLastTimeInfo;
  3118. v3_process_context fV3TimeContext;
  3119. carla_v3_host_application fV3Application;
  3120. carla_v3_host_application* const fV3ApplicationPtr;
  3121. carla_v3_component_handler fComponentHandler;
  3122. carla_v3_component_handler* const fComponentHandlerPtr;
  3123. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3124. carla_v3_plugin_frame fPluginFrame;
  3125. carla_v3_plugin_frame* const fPluginFramePtr;
  3126. #endif
  3127. // v3_class_info_2 is ABI compatible with v3_class_info
  3128. union ClassInfo {
  3129. v3_class_info v1;
  3130. v3_class_info_2 v2;
  3131. } fV3ClassInfo;
  3132. struct PluginPointers {
  3133. V3_EXITFN exitfn;
  3134. v3_plugin_factory** factory1;
  3135. v3_plugin_factory_2** factory2;
  3136. v3_plugin_factory_3** factory3;
  3137. v3_component** component;
  3138. v3_edit_controller** controller;
  3139. v3_audio_processor** processor;
  3140. v3_connection_point** connComponent;
  3141. v3_connection_point** connController;
  3142. v3_midi_mapping** midiMapping;
  3143. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3144. v3_plugin_view** view;
  3145. #endif
  3146. bool shouldTerminateComponent;
  3147. bool shouldTerminateController;
  3148. PluginPointers()
  3149. : exitfn(nullptr),
  3150. factory1(nullptr),
  3151. factory2(nullptr),
  3152. factory3(nullptr),
  3153. component(nullptr),
  3154. controller(nullptr),
  3155. processor(nullptr),
  3156. connComponent(nullptr),
  3157. connController(nullptr),
  3158. midiMapping(nullptr),
  3159. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3160. view(nullptr),
  3161. #endif
  3162. shouldTerminateComponent(false),
  3163. shouldTerminateController(false) {}
  3164. ~PluginPointers()
  3165. {
  3166. // must have been cleaned up by now
  3167. CARLA_SAFE_ASSERT(exitfn == nullptr);
  3168. }
  3169. // must have exitfn and factory1 set
  3170. bool queryFactories(v3_funknown** const hostContext)
  3171. {
  3172. // query 2nd factory
  3173. if (v3_cpp_obj_query_interface(factory1, v3_plugin_factory_2_iid, &factory2) == V3_OK)
  3174. {
  3175. CARLA_SAFE_ASSERT_RETURN(factory2 != nullptr, exit());
  3176. }
  3177. else
  3178. {
  3179. CARLA_SAFE_ASSERT(factory2 == nullptr);
  3180. factory2 = nullptr;
  3181. }
  3182. // query 3rd factory
  3183. if (factory2 != nullptr && v3_cpp_obj_query_interface(factory2, v3_plugin_factory_3_iid, &factory3) == V3_OK)
  3184. {
  3185. CARLA_SAFE_ASSERT_RETURN(factory3 != nullptr, exit());
  3186. }
  3187. else
  3188. {
  3189. CARLA_SAFE_ASSERT(factory3 == nullptr);
  3190. factory3 = nullptr;
  3191. }
  3192. // set host context (application) if 3rd factory provided
  3193. if (factory3 != nullptr)
  3194. v3_cpp_obj(factory3)->set_host_context(factory3, hostContext);
  3195. return true;
  3196. }
  3197. // must have all possible factories and exitfn set
  3198. bool findPlugin(ClassInfo& classInfo)
  3199. {
  3200. // get factory info
  3201. v3_factory_info factoryInfo = {};
  3202. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->get_factory_info(factory1, &factoryInfo) == V3_OK, exit());
  3203. // get num classes
  3204. const int32_t numClasses = v3_cpp_obj(factory1)->num_classes(factory1);
  3205. CARLA_SAFE_ASSERT_RETURN(numClasses > 0, exit());
  3206. // go through all relevant classes
  3207. for (int32_t i=0; i<numClasses; ++i)
  3208. {
  3209. carla_zeroStruct(classInfo);
  3210. if (factory2 != nullptr)
  3211. v3_cpp_obj(factory2)->get_class_info_2(factory2, i, &classInfo.v2);
  3212. else
  3213. v3_cpp_obj(factory1)->get_class_info(factory1, i, &classInfo.v1);
  3214. // safety check
  3215. CARLA_SAFE_ASSERT_CONTINUE(classInfo.v1.cardinality == 0x7FFFFFFF);
  3216. // only check for audio plugins
  3217. if (std::strcmp(classInfo.v1.category, "Audio Module Class") != 0)
  3218. continue;
  3219. // FIXME multi-plugin bundle
  3220. break;
  3221. }
  3222. return true;
  3223. }
  3224. bool initializePlugin(const v3_tuid uid,
  3225. v3_funknown** const hostContext,
  3226. v3_component_handler** const handler)
  3227. {
  3228. // create instance
  3229. void* instance = nullptr;
  3230. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj(factory1)->create_instance(factory1, uid, v3_component_iid,
  3231. &instance) == V3_OK,
  3232. exit());
  3233. CARLA_SAFE_ASSERT_RETURN(instance != nullptr, exit());
  3234. component = static_cast<v3_component**>(instance);
  3235. // initialize instance
  3236. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(component, hostContext) == V3_OK, exit());
  3237. shouldTerminateComponent = true;
  3238. // create edit controller
  3239. if (v3_cpp_obj_query_interface(component, v3_edit_controller_iid, &controller) != V3_OK)
  3240. controller = nullptr;
  3241. // if we cannot cast from component, try to create edit controller from factory
  3242. if (controller == nullptr)
  3243. {
  3244. v3_tuid cuid = {};
  3245. if (v3_cpp_obj(component)->get_controller_class_id(component, cuid) == V3_OK)
  3246. {
  3247. instance = nullptr;
  3248. if (v3_cpp_obj(factory1)->create_instance(factory1, cuid,
  3249. v3_edit_controller_iid, &instance) == V3_OK)
  3250. controller = static_cast<v3_edit_controller**>(instance);
  3251. }
  3252. CARLA_SAFE_ASSERT_RETURN(controller != nullptr, exit());
  3253. // component is separate from controller, needs its dedicated initialize and terminate
  3254. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_initialize(controller, hostContext) == V3_OK, exit());
  3255. shouldTerminateController = true;
  3256. }
  3257. v3_cpp_obj(controller)->set_component_handler(controller, handler);
  3258. // create processor
  3259. CARLA_SAFE_ASSERT_RETURN(v3_cpp_obj_query_interface(component, v3_audio_processor_iid,
  3260. &processor) == V3_OK, exit());
  3261. CARLA_SAFE_ASSERT_RETURN(processor != nullptr, exit());
  3262. // connect component to controller
  3263. if (v3_cpp_obj_query_interface(component, v3_connection_point_iid, &connComponent) != V3_OK)
  3264. connComponent = nullptr;
  3265. if (v3_cpp_obj_query_interface(controller, v3_connection_point_iid, &connController) != V3_OK)
  3266. connController = nullptr;
  3267. if (connComponent != nullptr && connController != nullptr)
  3268. {
  3269. v3_cpp_obj(connComponent)->connect(connComponent, connController);
  3270. v3_cpp_obj(connController)->connect(connController, connComponent);
  3271. }
  3272. // get midi mapping interface
  3273. if (v3_cpp_obj_query_interface(component, v3_midi_mapping_iid, &midiMapping) != V3_OK)
  3274. {
  3275. midiMapping = nullptr;
  3276. if (v3_cpp_obj_query_interface(controller, v3_midi_mapping_iid, &midiMapping) != V3_OK)
  3277. midiMapping = nullptr;
  3278. }
  3279. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3280. // create view
  3281. view = v3_cpp_obj(controller)->create_view(controller, "editor");
  3282. #endif
  3283. return true;
  3284. }
  3285. bool exit()
  3286. {
  3287. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3288. // must be deleted by now
  3289. CARLA_SAFE_ASSERT(view == nullptr);
  3290. #endif
  3291. if (midiMapping != nullptr)
  3292. {
  3293. v3_cpp_obj_unref(midiMapping);
  3294. midiMapping = nullptr;
  3295. }
  3296. if (connComponent != nullptr && connController != nullptr)
  3297. {
  3298. v3_cpp_obj(connComponent)->disconnect(connComponent, connController);
  3299. v3_cpp_obj(connController)->disconnect(connController, connComponent);
  3300. }
  3301. if (connComponent != nullptr)
  3302. {
  3303. v3_cpp_obj_unref(connComponent);
  3304. connComponent = nullptr;
  3305. }
  3306. if (connController != nullptr)
  3307. {
  3308. v3_cpp_obj_unref(connController);
  3309. connController = nullptr;
  3310. }
  3311. if (processor != nullptr)
  3312. {
  3313. v3_cpp_obj_unref(processor);
  3314. processor = nullptr;
  3315. }
  3316. if (controller != nullptr)
  3317. {
  3318. if (shouldTerminateController)
  3319. {
  3320. v3_cpp_obj_terminate(controller);
  3321. shouldTerminateController = false;
  3322. }
  3323. v3_cpp_obj_unref(controller);
  3324. controller = nullptr;
  3325. }
  3326. if (component != nullptr)
  3327. {
  3328. if (shouldTerminateComponent)
  3329. {
  3330. v3_cpp_obj_terminate(component);
  3331. shouldTerminateComponent = false;
  3332. }
  3333. v3_cpp_obj_unref(component);
  3334. component = nullptr;
  3335. }
  3336. if (factory3 != nullptr)
  3337. {
  3338. v3_cpp_obj_unref(factory3);
  3339. factory3 = nullptr;
  3340. }
  3341. if (factory2 != nullptr)
  3342. {
  3343. v3_cpp_obj_unref(factory2);
  3344. factory2 = nullptr;
  3345. }
  3346. if (factory1 != nullptr)
  3347. {
  3348. v3_cpp_obj_unref(factory1);
  3349. factory1 = nullptr;
  3350. }
  3351. if (exitfn != nullptr)
  3352. {
  3353. exitfn();
  3354. exitfn = nullptr;
  3355. }
  3356. // return false so it can be used as error/fail condition
  3357. return false;
  3358. }
  3359. CARLA_DECLARE_NON_COPYABLE(PluginPointers)
  3360. } fV3;
  3361. struct Buses {
  3362. int32_t numInputs;
  3363. int32_t numOutputs;
  3364. v3_audio_bus_buffers* inputs;
  3365. v3_audio_bus_buffers* outputs;
  3366. v3_bus_mini_info* inputInfo;
  3367. v3_bus_mini_info* outputInfo;
  3368. Buses()
  3369. : numInputs(0),
  3370. numOutputs(0),
  3371. inputs(nullptr),
  3372. outputs(nullptr),
  3373. inputInfo(nullptr),
  3374. outputInfo(nullptr) {}
  3375. ~Buses()
  3376. {
  3377. delete[] inputs;
  3378. delete[] outputs;
  3379. delete[] inputInfo;
  3380. delete[] outputInfo;
  3381. }
  3382. void createNew(const int32_t numAudioInputBuses, const int32_t numAudioOutputBuses)
  3383. {
  3384. delete[] inputs;
  3385. delete[] outputs;
  3386. delete[] inputInfo;
  3387. delete[] outputInfo;
  3388. numInputs = numAudioInputBuses;
  3389. numOutputs = numAudioOutputBuses;
  3390. if (numAudioInputBuses > 0)
  3391. {
  3392. inputs = new v3_audio_bus_buffers[numAudioInputBuses];
  3393. inputInfo = new v3_bus_mini_info[numAudioInputBuses];
  3394. }
  3395. else
  3396. {
  3397. inputs = nullptr;
  3398. inputInfo = nullptr;
  3399. }
  3400. if (numAudioOutputBuses > 0)
  3401. {
  3402. outputs = new v3_audio_bus_buffers[numAudioOutputBuses];
  3403. outputInfo = new v3_bus_mini_info[numAudioOutputBuses];
  3404. }
  3405. else
  3406. {
  3407. outputs = nullptr;
  3408. outputInfo = nullptr;
  3409. }
  3410. }
  3411. CARLA_DECLARE_NON_COPYABLE(Buses)
  3412. } fBuses;
  3413. struct Events {
  3414. carla_v3_input_param_changes* paramInputs;
  3415. carla_v3_output_param_changes* paramOutputs;
  3416. carla_v3_input_event_list* eventInputs;
  3417. carla_v3_output_event_list* eventOutputs;
  3418. Events() noexcept
  3419. : paramInputs(nullptr),
  3420. paramOutputs(nullptr),
  3421. eventInputs(nullptr),
  3422. eventOutputs(nullptr) {}
  3423. ~Events()
  3424. {
  3425. delete paramInputs;
  3426. delete paramOutputs;
  3427. delete eventInputs;
  3428. delete eventOutputs;
  3429. }
  3430. void init()
  3431. {
  3432. if (paramInputs != nullptr)
  3433. paramInputs->init();
  3434. if (eventInputs != nullptr)
  3435. eventInputs->numEvents = 0;
  3436. }
  3437. void prepare()
  3438. {
  3439. if (paramInputs != nullptr)
  3440. paramInputs->prepare();
  3441. if (paramOutputs != nullptr)
  3442. paramOutputs->prepare();
  3443. }
  3444. CARLA_DECLARE_NON_COPYABLE(Events)
  3445. } fEvents;
  3446. struct MidiControllerAssignments {
  3447. v3_param_id* mappings;
  3448. bool* used;
  3449. MidiControllerAssignments() noexcept
  3450. : mappings(nullptr),
  3451. used(nullptr) {}
  3452. ~MidiControllerAssignments() noexcept
  3453. {
  3454. clear();
  3455. }
  3456. void init(v3_midi_mapping** const midiMapping, const uint32_t numPorts)
  3457. {
  3458. clear();
  3459. if (numPorts == 0)
  3460. return;
  3461. const uint32_t dataPoints = numPorts * MAX_MIDI_CHANNELS * 130;
  3462. mappings = new v3_param_id[dataPoints];
  3463. used = new bool[dataPoints];
  3464. carla_zeroStructs(mappings, dataPoints);
  3465. carla_zeroStructs(used, dataPoints);
  3466. v3_param_id paramId;
  3467. for (uint32_t p=0; p<numPorts; ++p)
  3468. {
  3469. for (uint8_t ch=0; ch<MAX_MIDI_CHANNELS; ++ch)
  3470. {
  3471. for (uint16_t cc=0; cc<130; ++cc)
  3472. {
  3473. if (v3_cpp_obj(midiMapping)->get_midi_controller_assignment(midiMapping, p,
  3474. ch, cc, &paramId) == V3_OK)
  3475. {
  3476. const uint32_t index = p * (130 + MAX_MIDI_CHANNELS) + cc * MAX_MIDI_CHANNELS + ch;
  3477. mappings[index] = paramId;
  3478. used[index] = true;
  3479. }
  3480. }
  3481. }
  3482. }
  3483. }
  3484. void clear() noexcept
  3485. {
  3486. delete[] mappings;
  3487. delete[] used;
  3488. mappings = nullptr;
  3489. used = nullptr;
  3490. }
  3491. bool get(const uint8_t port, const uint8_t channel, const uint8_t cc, v3_param_id& paramId) noexcept
  3492. {
  3493. CARLA_SAFE_ASSERT_UINT_RETURN(channel < MAX_MIDI_CHANNELS, channel, false);
  3494. CARLA_SAFE_ASSERT_UINT_RETURN(cc < 130, cc, false);
  3495. if (used == nullptr)
  3496. return false;
  3497. const uint32_t index = port * (130 + MAX_MIDI_CHANNELS) + cc * MAX_MIDI_CHANNELS + channel;
  3498. if (used[index])
  3499. {
  3500. paramId = mappings[index];
  3501. return true;
  3502. }
  3503. return false;
  3504. }
  3505. } fMidiControllerAssignments;
  3506. #ifdef V3_VIEW_PLATFORM_TYPE_NATIVE
  3507. struct UI {
  3508. bool isAttached;
  3509. bool isEmbed;
  3510. bool isResizingFromHost;
  3511. bool isResizingFromInit;
  3512. bool isResizingFromPlugin;
  3513. bool isVisible;
  3514. uint32_t width, height;
  3515. CarlaPluginUI* window;
  3516. UI() noexcept
  3517. : isAttached(false),
  3518. isEmbed(false),
  3519. isResizingFromHost(false),
  3520. isResizingFromInit(false),
  3521. isResizingFromPlugin(false),
  3522. isVisible(false),
  3523. width(0),
  3524. height(0),
  3525. window(nullptr) {}
  3526. ~UI()
  3527. {
  3528. CARLA_ASSERT(isEmbed || ! isVisible);
  3529. if (window != nullptr)
  3530. {
  3531. delete window;
  3532. window = nullptr;
  3533. }
  3534. }
  3535. CARLA_DECLARE_NON_COPYABLE(UI)
  3536. } fUI;
  3537. #endif
  3538. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaPluginVST3)
  3539. };
  3540. // --------------------------------------------------------------------------------------------------------------------
  3541. CarlaPluginPtr CarlaPlugin::newVST3(const Initializer& init)
  3542. {
  3543. carla_debug("CarlaPlugin::newVST3({%p, \"%s\", \"%s\", \"%s\"})",
  3544. init.engine, init.filename, init.name, init.label);
  3545. #ifdef USE_JUCE_FOR_VST3
  3546. if (std::getenv("CARLA_DO_NOT_USE_JUCE_FOR_VST3") == nullptr)
  3547. return newJuce(init, "VST3");
  3548. #endif
  3549. std::shared_ptr<CarlaPluginVST3> plugin(new CarlaPluginVST3(init.engine, init.id));
  3550. if (! plugin->init(plugin, init.filename, init.name, init.label, init.options))
  3551. return nullptr;
  3552. return plugin;
  3553. }
  3554. // -------------------------------------------------------------------------------------------------------------------
  3555. CARLA_BACKEND_END_NAMESPACE