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.

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