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.

4033 lines
140KB

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