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.

1242 lines
41KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2019 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. #define CARLA_NATIVE_PLUGIN_LV2
  18. #include "carla-base.cpp"
  19. #include "CarlaLv2Utils.hpp"
  20. #include "CarlaMathUtils.hpp"
  21. #include "CarlaPipeUtils.hpp"
  22. #include "CarlaString.hpp"
  23. #ifdef USING_JUCE
  24. # if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  25. # pragma GCC diagnostic push
  26. # pragma GCC diagnostic ignored "-Wconversion"
  27. # pragma GCC diagnostic ignored "-Weffc++"
  28. # pragma GCC diagnostic ignored "-Wsign-conversion"
  29. # pragma GCC diagnostic ignored "-Wundef"
  30. # pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
  31. # endif
  32. # include "AppConfig.h"
  33. # include "juce_events/juce_events.h"
  34. # if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  35. # pragma GCC diagnostic pop
  36. # endif
  37. #endif
  38. #include "water/files/File.h"
  39. template<>
  40. void Lv2PluginBaseClass<NativeTimeInfo>::clearTimeData() noexcept
  41. {
  42. fLastPositionData.clear();
  43. carla_zeroStruct(fTimeInfo);
  44. }
  45. // --------------------------------------------------------------------------------------------------------------------
  46. // Carla Internal Plugin API exposed as LV2 plugin
  47. class NativePlugin : public Lv2PluginBaseClass<NativeTimeInfo>
  48. {
  49. public:
  50. static const uint32_t kMaxMidiEvents = 512;
  51. NativePlugin(const NativePluginDescriptor* const desc,
  52. const double sampleRate,
  53. const char* const bundlePath,
  54. const LV2_Feature* const* const features)
  55. : Lv2PluginBaseClass<NativeTimeInfo>(sampleRate, features),
  56. fHandle(nullptr),
  57. fHost(),
  58. fDescriptor(desc),
  59. #ifdef CARLA_PROPER_CPP11_SUPPORT
  60. fProgramDesc({0, 0, nullptr}),
  61. #endif
  62. kIgnoreParameters(std::strncmp(desc->label, "carla", 5) == 0),
  63. fMidiEventCount(0),
  64. #ifdef USING_JUCE
  65. fJuceInitialiser(),
  66. #endif
  67. fLoadedFile(),
  68. fWorkerUISignal(0)
  69. {
  70. carla_zeroStruct(fHost);
  71. #ifndef CARLA_PROPER_CPP11_SUPPORT
  72. carla_zeroStruct(fProgramDesc);
  73. #endif
  74. if (! loadedInProperHost())
  75. return;
  76. using water::File;
  77. using water::String;
  78. String resourceDir(water::File(bundlePath).getChildFile("resources").getFullPathName());
  79. fHost.handle = this;
  80. fHost.resourceDir = carla_strdup(resourceDir.toRawUTF8());
  81. fHost.uiName = nullptr;
  82. fHost.uiParentId = 0;
  83. fHost.get_buffer_size = host_get_buffer_size;
  84. fHost.get_sample_rate = host_get_sample_rate;
  85. fHost.is_offline = host_is_offline;
  86. fHost.get_time_info = host_get_time_info;
  87. fHost.write_midi_event = host_write_midi_event;
  88. fHost.ui_parameter_changed = host_ui_parameter_changed;
  89. fHost.ui_custom_data_changed = host_ui_custom_data_changed;
  90. fHost.ui_closed = host_ui_closed;
  91. fHost.ui_open_file = host_ui_open_file;
  92. fHost.ui_save_file = host_ui_save_file;
  93. fHost.dispatcher = host_dispatcher;
  94. }
  95. ~NativePlugin()
  96. {
  97. CARLA_SAFE_ASSERT(fHandle == nullptr);
  98. if (fHost.resourceDir != nullptr)
  99. {
  100. delete[] fHost.resourceDir;
  101. fHost.resourceDir = nullptr;
  102. }
  103. if (fHost.uiName != nullptr)
  104. {
  105. delete[] fHost.uiName;
  106. fHost.uiName = nullptr;
  107. }
  108. }
  109. // ----------------------------------------------------------------------------------------------------------------
  110. bool init()
  111. {
  112. if (fHost.resourceDir == nullptr)
  113. return false;
  114. if (fDescriptor->instantiate == nullptr || fDescriptor->process == nullptr)
  115. {
  116. carla_stderr("Plugin is missing something...");
  117. return false;
  118. }
  119. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  120. fHandle = fDescriptor->instantiate(&fHost);
  121. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, false);
  122. fPorts.hasUI = fDescriptor->hints & NATIVE_PLUGIN_HAS_UI;
  123. fPorts.usesTime = fDescriptor->hints & NATIVE_PLUGIN_USES_TIME;
  124. fPorts.numAudioIns = fDescriptor->audioIns;
  125. fPorts.numAudioOuts = fDescriptor->audioOuts;
  126. fPorts.numCVIns = fDescriptor->cvIns;
  127. fPorts.numCVOuts = fDescriptor->cvOuts;
  128. fPorts.numMidiIns = fDescriptor->midiIns;
  129. fPorts.numMidiOuts = fDescriptor->midiOuts;
  130. if (fDescriptor->get_parameter_count != nullptr &&
  131. fDescriptor->get_parameter_info != nullptr &&
  132. fDescriptor->get_parameter_value != nullptr &&
  133. fDescriptor->set_parameter_value != nullptr &&
  134. ! kIgnoreParameters)
  135. {
  136. fPorts.numParams = fDescriptor->get_parameter_count(fHandle);
  137. }
  138. fPorts.init();
  139. if (fPorts.numParams > 0)
  140. {
  141. for (uint32_t i=0; i < fPorts.numParams; ++i)
  142. {
  143. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  144. fPorts.paramsOut [i] = fDescriptor->get_parameter_info(fHandle, i)->hints & NATIVE_PARAMETER_IS_OUTPUT;
  145. }
  146. }
  147. return true;
  148. }
  149. // ----------------------------------------------------------------------------------------------------------------
  150. // LV2 functions
  151. void lv2_activate()
  152. {
  153. CARLA_SAFE_ASSERT_RETURN(! fIsActive,);
  154. resetTimeInfo();
  155. if (fDescriptor->activate != nullptr)
  156. fDescriptor->activate(fHandle);
  157. fIsActive = true;
  158. }
  159. void lv2_deactivate()
  160. {
  161. CARLA_SAFE_ASSERT_RETURN(fIsActive,);
  162. fIsActive = false;
  163. if (fDescriptor->deactivate != nullptr)
  164. fDescriptor->deactivate(fHandle);
  165. }
  166. void lv2_cleanup()
  167. {
  168. if (fIsActive)
  169. {
  170. carla_stderr("Warning: Host forgot to call deactivate!");
  171. fIsActive = false;
  172. if (fDescriptor->deactivate != nullptr)
  173. fDescriptor->deactivate(fHandle);
  174. }
  175. if (fDescriptor->cleanup != nullptr)
  176. fDescriptor->cleanup(fHandle);
  177. fHandle = nullptr;
  178. }
  179. // ----------------------------------------------------------------------------------------------------------------
  180. void lv2_run(const uint32_t frames)
  181. {
  182. if (! lv2_pre_run(frames))
  183. {
  184. updateParameterOutputs();
  185. return;
  186. }
  187. if (fPorts.numMidiIns > 0 || fPorts.hasUI)
  188. {
  189. uint32_t numEventsIn;
  190. if (fPorts.numMidiIns > 0)
  191. {
  192. numEventsIn = fPorts.numMidiIns;
  193. fMidiEventCount = 0;
  194. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  195. }
  196. else
  197. {
  198. numEventsIn = 1;
  199. }
  200. for (uint32_t i=0; i < numEventsIn; ++i)
  201. {
  202. const LV2_Atom_Sequence* const eventsIn(fPorts.eventsIn[i]);
  203. CARLA_SAFE_ASSERT_CONTINUE(eventsIn != nullptr);
  204. LV2_ATOM_SEQUENCE_FOREACH(eventsIn, event)
  205. {
  206. if (event == nullptr)
  207. continue;
  208. if (event->body.type == fURIs.uiEvents && fWorkerUISignal != -1)
  209. {
  210. CARLA_SAFE_ASSERT_CONTINUE((fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE) == 0);
  211. if (fWorker != nullptr)
  212. {
  213. // worker is supported by the host, we can continue
  214. fWorkerUISignal = 1;
  215. const char* const msg((const char*)(event + 1));
  216. const size_t msgSize = std::strlen(msg);
  217. fWorker->schedule_work(fWorker->handle, static_cast<uint32_t>(msgSize + 1U), msg);
  218. }
  219. else
  220. {
  221. // worker is not supported, cancel
  222. fWorkerUISignal = -1;
  223. }
  224. continue;
  225. }
  226. if (event->body.type == fURIs.atomObject)
  227. {
  228. const LV2_Atom_Object* const obj = (const LV2_Atom_Object*)(&event->body);
  229. if (obj->body.otype == fURIs.patchSet) {
  230. // Get property URI.
  231. const LV2_Atom* property = NULL;
  232. lv2_atom_object_get(obj, fURIs.patchProperty, &property, 0);
  233. CARLA_SAFE_ASSERT_CONTINUE(property != nullptr);
  234. CARLA_SAFE_ASSERT_CONTINUE(property->type == fURIs.atomURID);
  235. CARLA_SAFE_ASSERT_CONTINUE(((const LV2_Atom_URID*)property)->body == fURIs.carlaFile);
  236. // Get value.
  237. const LV2_Atom* fileobj = NULL;
  238. lv2_atom_object_get(obj, fURIs.patchValue, &fileobj, 0);
  239. CARLA_SAFE_ASSERT_CONTINUE(fileobj != nullptr);
  240. CARLA_SAFE_ASSERT_CONTINUE(fileobj->type == fURIs.atomPath);
  241. const char* const filepath((const char*)(fileobj + 1));
  242. fWorker->schedule_work(fWorker->handle,
  243. static_cast<uint32_t>(std::strlen(filepath) + 1U),
  244. filepath);
  245. }
  246. continue;
  247. }
  248. if (event->body.type != fURIs.midiEvent)
  249. continue;
  250. if (event->body.size > 4)
  251. continue;
  252. if (event->time.frames >= frames)
  253. break;
  254. const uint8_t* const data((const uint8_t*)(event + 1));
  255. NativeMidiEvent& nativeEvent(fMidiEvents[fMidiEventCount++]);
  256. nativeEvent.port = (uint8_t)i;
  257. nativeEvent.size = (uint8_t)event->body.size;
  258. nativeEvent.time = (uint32_t)event->time.frames;
  259. uint32_t j=0;
  260. for (uint32_t size=event->body.size; j<size; ++j)
  261. nativeEvent.data[j] = data[j];
  262. for (; j<4; ++j)
  263. nativeEvent.data[j] = 0;
  264. if (fMidiEventCount >= kMaxMidiEvents)
  265. break;
  266. }
  267. }
  268. }
  269. fDescriptor->process(fHandle, fPorts.audioCVIns, fPorts.audioCVOuts, frames, fMidiEvents, fMidiEventCount);
  270. if (fWorkerUISignal == -1 && fPorts.hasUI)
  271. {
  272. const char* const msg = "quit";
  273. const size_t msgSize = 5;
  274. LV2_Atom_Sequence* const seq(fPorts.eventsOut[0]);
  275. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  276. if (sizeof(LV2_Atom_Event) + msgSize <= mData.capacity - mData.offset)
  277. {
  278. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  279. aev->time.frames = 0;
  280. aev->body.size = msgSize;
  281. aev->body.type = fURIs.uiEvents;
  282. std::memcpy(LV2_ATOM_BODY(&aev->body), msg, msgSize);
  283. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + msgSize));
  284. mData.offset += size;
  285. seq->atom.size += size;
  286. fWorkerUISignal = 0;
  287. }
  288. }
  289. lv2_post_run(frames);
  290. updateParameterOutputs();
  291. }
  292. // ----------------------------------------------------------------------------------------------------------------
  293. const LV2_Program_Descriptor* lv2_get_program(const uint32_t index)
  294. {
  295. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  296. return nullptr;
  297. if (fDescriptor->get_midi_program_count == nullptr)
  298. return nullptr;
  299. if (fDescriptor->get_midi_program_info == nullptr)
  300. return nullptr;
  301. if (index >= fDescriptor->get_midi_program_count(fHandle))
  302. return nullptr;
  303. const NativeMidiProgram* const midiProg(fDescriptor->get_midi_program_info(fHandle, index));
  304. if (midiProg == nullptr)
  305. return nullptr;
  306. fProgramDesc.bank = midiProg->bank;
  307. fProgramDesc.program = midiProg->program;
  308. fProgramDesc.name = midiProg->name;
  309. return &fProgramDesc;
  310. }
  311. void lv2_select_program(uint32_t bank, uint32_t program)
  312. {
  313. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  314. return;
  315. if (fDescriptor->set_midi_program == nullptr)
  316. return;
  317. fDescriptor->set_midi_program(fHandle, 0, bank, program);
  318. for (uint32_t i=0; i < fPorts.numParams; ++i)
  319. {
  320. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  321. if (fPorts.paramsPtr[i] != nullptr)
  322. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  323. }
  324. }
  325. // ----------------------------------------------------------------------------------------------------------------
  326. LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle,
  327. const uint32_t /*flags*/, const LV2_Feature* const* const /*features*/) const
  328. {
  329. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  330. {
  331. store(handle,
  332. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  333. fLoadedFile.buffer(),
  334. fLoadedFile.length()+1,
  335. fURIs.atomPath,
  336. LV2_STATE_IS_POD);
  337. return LV2_STATE_SUCCESS;
  338. }
  339. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->get_state == nullptr)
  340. return LV2_STATE_ERR_NO_FEATURE;
  341. if (char* const state = fDescriptor->get_state(fHandle))
  342. {
  343. store(handle, fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"), state, std::strlen(state)+1, fURIs.atomString, LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  344. std::free(state);
  345. return LV2_STATE_SUCCESS;
  346. }
  347. return LV2_STATE_ERR_UNKNOWN;
  348. }
  349. LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve, const LV2_State_Handle handle,
  350. uint32_t flags, const LV2_Feature* const* const /*features*/)
  351. {
  352. size_t size = 0;
  353. uint32_t type = 0;
  354. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  355. {
  356. size = type = 0;
  357. const void* const data = retrieve(handle,
  358. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  359. &size, &type, &flags);
  360. CARLA_SAFE_ASSERT_RETURN(type == fURIs.atomPath, LV2_STATE_ERR_UNKNOWN);
  361. const char* const filename = (const char*)data;
  362. fLoadedFile = filename;
  363. fDescriptor->set_custom_data(fHandle, "file", filename);
  364. return LV2_STATE_SUCCESS;
  365. }
  366. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->set_state == nullptr)
  367. return LV2_STATE_ERR_NO_FEATURE;
  368. size = type = 0;
  369. const void* const data = retrieve(handle, fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"), &size, &type, &flags);
  370. if (size == 0)
  371. return LV2_STATE_ERR_UNKNOWN;
  372. if (type == 0)
  373. return LV2_STATE_ERR_UNKNOWN;
  374. if (data == nullptr)
  375. return LV2_STATE_ERR_UNKNOWN;
  376. if (type != fURIs.atomString)
  377. return LV2_STATE_ERR_BAD_TYPE;
  378. fDescriptor->set_state(fHandle, (const char*)data);
  379. return LV2_STATE_SUCCESS;
  380. }
  381. // ----------------------------------------------------------------------------------------------------------------
  382. LV2_Worker_Status lv2_work(LV2_Worker_Respond_Function, LV2_Worker_Respond_Handle, uint32_t, const void* data)
  383. {
  384. const char* const msg = (const char*)data;
  385. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  386. {
  387. fLoadedFile = msg;
  388. fDescriptor->set_custom_data(fHandle, "file", msg);
  389. return LV2_WORKER_SUCCESS;
  390. }
  391. /**/ if (std::strncmp(msg, "control ", 8) == 0)
  392. {
  393. if (fDescriptor->ui_set_parameter_value == nullptr)
  394. return LV2_WORKER_SUCCESS;
  395. if (const char* const msgSplit = std::strstr(msg+8, " "))
  396. {
  397. const char* const msgIndex = msg+8;
  398. CARLA_SAFE_ASSERT_RETURN(msgSplit - msgIndex < 8, LV2_WORKER_ERR_UNKNOWN);
  399. CARLA_SAFE_ASSERT_RETURN(msgSplit[0] != '\0', LV2_WORKER_ERR_UNKNOWN);
  400. char strBufIndex[8];
  401. carla_zeroChars(strBufIndex, 8);
  402. std::strncpy(strBufIndex, msgIndex, static_cast<size_t>(msgSplit - msgIndex));
  403. const int index = std::atoi(msgIndex) - static_cast<int>(fPorts.indexOffset);
  404. CARLA_SAFE_ASSERT_RETURN(index >= 0, LV2_WORKER_ERR_UNKNOWN);
  405. float value;
  406. {
  407. const CarlaScopedLocale csl;
  408. value = static_cast<float>(std::atof(msgSplit+1));
  409. }
  410. fDescriptor->ui_set_parameter_value(fHandle, static_cast<uint32_t>(index), value);
  411. }
  412. }
  413. else if (std::strcmp(msg, "show") == 0)
  414. {
  415. handleUiShow();
  416. }
  417. else if (std::strcmp(msg, "hide") == 0)
  418. {
  419. handleUiHide();
  420. }
  421. else if (std::strcmp(msg, "idle") == 0)
  422. {
  423. handleUiRun();
  424. }
  425. else if (std::strcmp(msg, "quit") == 0)
  426. {
  427. handleUiClosed();
  428. }
  429. else
  430. {
  431. carla_stdout("lv2_work unknown msg '%s'", msg);
  432. return LV2_WORKER_ERR_UNKNOWN;
  433. }
  434. return LV2_WORKER_SUCCESS;
  435. }
  436. LV2_Worker_Status lv2_work_resp(uint32_t /*size*/, const void* /*body*/)
  437. {
  438. return LV2_WORKER_SUCCESS;
  439. }
  440. // ----------------------------------------------------------------------------------------------------------------
  441. void lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  442. LV2UI_Widget* widget, const LV2_Feature* const* features)
  443. {
  444. fUI.writeFunction = writeFunction;
  445. fUI.controller = controller;
  446. if (fHost.uiName != nullptr)
  447. {
  448. delete[] fHost.uiName;
  449. fHost.uiName = nullptr;
  450. }
  451. // ---------------------------------------------------------------
  452. // see if the host supports external-ui
  453. for (int i=0; features[i] != nullptr; ++i)
  454. {
  455. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  456. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  457. {
  458. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  459. break;
  460. }
  461. if (std::strcmp(features[i]->URI, LV2_UI__touch) == 0)
  462. {
  463. fUI.touch = (const LV2UI_Touch*)features[i]->data;
  464. break;
  465. }
  466. }
  467. if (fUI.host != nullptr)
  468. {
  469. fHost.uiName = carla_strdup(fUI.host->plugin_human_id);
  470. *widget = (LV2_External_UI_Widget_Compat*)this;
  471. return;
  472. }
  473. // ---------------------------------------------------------------
  474. // no external-ui support, use showInterface
  475. for (int i=0; features[i] != nullptr; ++i)
  476. {
  477. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) != 0)
  478. continue;
  479. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  480. CARLA_SAFE_ASSERT_BREAK(options != nullptr);
  481. for (int j=0; options[j].key != 0; ++j)
  482. {
  483. if (options[j].key != fUridMap->map(fUridMap->handle, LV2_UI__windowTitle))
  484. continue;
  485. const char* const title((const char*)options[j].value);
  486. CARLA_SAFE_ASSERT_BREAK(title != nullptr && title[0] != '\0');
  487. fHost.uiName = carla_strdup(title);
  488. break;
  489. }
  490. break;
  491. }
  492. if (fHost.uiName == nullptr)
  493. fHost.uiName = carla_strdup(fDescriptor->name);
  494. *widget = nullptr;
  495. return;
  496. }
  497. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  498. {
  499. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  500. return;
  501. if (portIndex < fPorts.indexOffset || ! fUI.isVisible)
  502. return;
  503. if (fDescriptor->ui_set_parameter_value == nullptr)
  504. return;
  505. const float value(*(const float*)buffer);
  506. fDescriptor->ui_set_parameter_value(fHandle, portIndex-fPorts.indexOffset, value);
  507. }
  508. // ----------------------------------------------------------------------------------------------------------------
  509. void lv2ui_select_program(uint32_t bank, uint32_t program) const
  510. {
  511. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  512. return;
  513. if (fDescriptor->ui_set_midi_program == nullptr)
  514. return;
  515. fDescriptor->ui_set_midi_program(fHandle, 0, bank, program);
  516. }
  517. // ----------------------------------------------------------------------------------------------------------------
  518. protected:
  519. void handleUiRun() const override
  520. {
  521. if (fDescriptor->ui_idle != nullptr)
  522. fDescriptor->ui_idle(fHandle);
  523. }
  524. void handleUiShow() override
  525. {
  526. if (fDescriptor->ui_show != nullptr)
  527. fDescriptor->ui_show(fHandle, true);
  528. fUI.isVisible = true;
  529. }
  530. void handleUiHide() override
  531. {
  532. if (fDescriptor->ui_show != nullptr)
  533. fDescriptor->ui_show(fHandle, false);
  534. fUI.isVisible = false;
  535. }
  536. // ----------------------------------------------------------------------------------------------------------------
  537. void handleParameterValueChanged(const uint32_t index, const float value) override
  538. {
  539. fDescriptor->set_parameter_value(fHandle, index, value);
  540. }
  541. void handleBufferSizeChanged(const uint32_t bufferSize) override
  542. {
  543. if (fDescriptor->dispatcher == nullptr)
  544. return;
  545. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, bufferSize, nullptr, 0.0f);
  546. }
  547. void handleSampleRateChanged(const double sampleRate) override
  548. {
  549. if (fDescriptor->dispatcher == nullptr)
  550. return;
  551. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)sampleRate);
  552. }
  553. // ----------------------------------------------------------------------------------------------------------------
  554. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  555. {
  556. CARLA_SAFE_ASSERT_RETURN(fPorts.numMidiOuts > 0, false);
  557. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  558. CARLA_SAFE_ASSERT_RETURN(event->size > 0, false);
  559. const uint8_t port(event->port);
  560. CARLA_SAFE_ASSERT_RETURN(port < fPorts.numMidiOuts, false);
  561. LV2_Atom_Sequence* const seq(fPorts.eventsOut[port]);
  562. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  563. Ports::EventsOutData& mData(fPorts.eventsOutData[port]);
  564. if (sizeof(LV2_Atom_Event) + event->size > mData.capacity - mData.offset)
  565. return false;
  566. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  567. aev->time.frames = event->time;
  568. aev->body.size = event->size;
  569. aev->body.type = fURIs.midiEvent;
  570. std::memcpy(LV2_ATOM_BODY(&aev->body), event->data, event->size);
  571. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + event->size));
  572. mData.offset += size;
  573. seq->atom.size += size;
  574. return true;
  575. }
  576. void handleUiParameterChanged(const uint32_t index, const float value) const
  577. {
  578. if (kIgnoreParameters || fWorkerUISignal)
  579. return;
  580. if (fUI.writeFunction != nullptr && fUI.controller != nullptr)
  581. fUI.writeFunction(fUI.controller, index+fPorts.indexOffset, sizeof(float), 0, &value);
  582. }
  583. void handleUiParameterTouch(const uint32_t index, const bool touch) const
  584. {
  585. if (kIgnoreParameters)
  586. return;
  587. if (fUI.touch != nullptr && fUI.touch->touch != nullptr)
  588. fUI.touch->touch(fUI.touch->handle, index+fPorts.indexOffset, touch);
  589. }
  590. void handleUiCustomDataChanged(const char* const key, const char* const value) const
  591. {
  592. carla_stdout("TODO: handleUiCustomDataChanged %s %s", key, value);
  593. //storeCustomData(key, value);
  594. if (fUI.writeFunction == nullptr || fUI.controller == nullptr)
  595. return;
  596. }
  597. void handleUiClosed()
  598. {
  599. fUI.isVisible = false;
  600. if (fWorkerUISignal)
  601. fWorkerUISignal = -1;
  602. if (fUI.host != nullptr && fUI.host->ui_closed != nullptr && fUI.controller != nullptr)
  603. fUI.host->ui_closed(fUI.controller);
  604. fUI.host = nullptr;
  605. fUI.touch = nullptr;
  606. fUI.writeFunction = nullptr;
  607. fUI.controller = nullptr;
  608. }
  609. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  610. {
  611. // TODO
  612. return nullptr;
  613. }
  614. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  615. {
  616. // TODO
  617. return nullptr;
  618. }
  619. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  620. {
  621. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)",
  622. opcode, index, value, ptr, static_cast<double>(opt));
  623. intptr_t ret = 0;
  624. switch (opcode)
  625. {
  626. case NATIVE_HOST_OPCODE_NULL:
  627. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  628. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  629. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  630. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  631. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  632. case NATIVE_HOST_OPCODE_HOST_IDLE:
  633. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  634. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  635. case NATIVE_HOST_OPCODE_REQUEST_IDLE:
  636. case NATIVE_HOST_OPCODE_GET_FILE_PATH:
  637. // nothing
  638. break;
  639. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  640. handleUiClosed();
  641. break;
  642. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  643. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  644. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  645. break;
  646. }
  647. return ret;
  648. // unused for now
  649. (void)index;
  650. (void)value;
  651. (void)ptr;
  652. (void)opt;
  653. }
  654. void updateParameterOutputs()
  655. {
  656. float value;
  657. for (uint32_t i=0; i < fPorts.numParams; ++i)
  658. {
  659. if (! fPorts.paramsOut[i])
  660. continue;
  661. fPorts.paramsLast[i] = value = fDescriptor->get_parameter_value(fHandle, i);
  662. if (fPorts.paramsPtr[i] != nullptr)
  663. *fPorts.paramsPtr[i] = value;
  664. }
  665. }
  666. // -------------------------------------------------------------------
  667. private:
  668. // Native data
  669. NativePluginHandle fHandle;
  670. NativeHostDescriptor fHost;
  671. const NativePluginDescriptor* const fDescriptor;
  672. LV2_Program_Descriptor fProgramDesc;
  673. // carla as plugin does not implement lv2 parameter API yet, needed for feedback
  674. const bool kIgnoreParameters;
  675. uint32_t fMidiEventCount;
  676. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  677. #ifdef USING_JUCE
  678. juce::SharedResourcePointer<juce::ScopedJuceInitialiser_GUI> fJuceInitialiser;
  679. #endif
  680. CarlaString fLoadedFile;
  681. int fWorkerUISignal;
  682. // -------------------------------------------------------------------
  683. #define handlePtr ((NativePlugin*)handle)
  684. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  685. {
  686. return handlePtr->fBufferSize;
  687. }
  688. static double host_get_sample_rate(NativeHostHandle handle)
  689. {
  690. return handlePtr->fSampleRate;
  691. }
  692. static bool host_is_offline(NativeHostHandle handle)
  693. {
  694. return handlePtr->fIsOffline;
  695. }
  696. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  697. {
  698. return &(handlePtr->fTimeInfo);
  699. }
  700. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  701. {
  702. return handlePtr->handleWriteMidiEvent(event);
  703. }
  704. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  705. {
  706. handlePtr->handleUiParameterChanged(index, value);
  707. }
  708. static void host_ui_parameter_touch(NativeHostHandle handle, uint32_t index, bool touch)
  709. {
  710. handlePtr->handleUiParameterTouch(index, touch);
  711. }
  712. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  713. {
  714. handlePtr->handleUiCustomDataChanged(key, value);
  715. }
  716. static void host_ui_closed(NativeHostHandle handle)
  717. {
  718. handlePtr->handleUiClosed();
  719. }
  720. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  721. {
  722. return handlePtr->handleUiOpenFile(isDir, title, filter);
  723. }
  724. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  725. {
  726. return handlePtr->handleUiSaveFile(isDir, title, filter);
  727. }
  728. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  729. {
  730. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  731. }
  732. #undef handlePtr
  733. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  734. };
  735. // -----------------------------------------------------------------------
  736. // LV2 plugin descriptor functions
  737. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  738. {
  739. carla_debug("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  740. const NativePluginDescriptor* pluginDesc = nullptr;
  741. const char* pluginLabel = nullptr;
  742. if (std::strncmp(lv2Descriptor->URI, "http://kxstudio.sf.net/carla/plugins/", 37) == 0)
  743. pluginLabel = lv2Descriptor->URI+37;
  744. if (pluginLabel == nullptr)
  745. {
  746. carla_stderr("Failed to find carla native plugin with URI \"%s\"", lv2Descriptor->URI);
  747. return nullptr;
  748. }
  749. carla_debug("lv2_instantiate() - looking up label \"%s\"", pluginLabel);
  750. PluginListManager& plm(PluginListManager::getInstance());
  751. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  752. {
  753. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  754. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  755. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  756. {
  757. pluginDesc = tmpDesc;
  758. break;
  759. }
  760. }
  761. if (pluginDesc == nullptr)
  762. {
  763. carla_stderr("Failed to find carla native plugin with label \"%s\"", pluginLabel);
  764. return nullptr;
  765. }
  766. NativePlugin* const plugin(new NativePlugin(pluginDesc, sampleRate, bundlePath, features));
  767. if (! plugin->init())
  768. {
  769. carla_stderr("Failed to init plugin");
  770. delete plugin;
  771. return nullptr;
  772. }
  773. return (LV2_Handle)plugin;
  774. }
  775. #define instancePtr ((NativePlugin*)instance)
  776. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  777. {
  778. instancePtr->lv2_connect_port(port, dataLocation);
  779. }
  780. static void lv2_activate(LV2_Handle instance)
  781. {
  782. carla_debug("lv2_activate(%p)", instance);
  783. instancePtr->lv2_activate();
  784. }
  785. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  786. {
  787. instancePtr->lv2_run(sampleCount);
  788. }
  789. static void lv2_deactivate(LV2_Handle instance)
  790. {
  791. carla_debug("lv2_deactivate(%p)", instance);
  792. instancePtr->lv2_deactivate();
  793. }
  794. static void lv2_cleanup(LV2_Handle instance)
  795. {
  796. carla_debug("lv2_cleanup(%p)", instance);
  797. instancePtr->lv2_cleanup();
  798. delete instancePtr;
  799. }
  800. static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options)
  801. {
  802. carla_debug("lv2_get_options(%p, %p)", instance, options);
  803. return instancePtr->lv2_get_options(options);
  804. }
  805. static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options)
  806. {
  807. carla_debug("lv2_set_options(%p, %p)", instance, options);
  808. return instancePtr->lv2_set_options(options);
  809. }
  810. static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index)
  811. {
  812. carla_debug("lv2_get_program(%p, %i)", instance, index);
  813. return instancePtr->lv2_get_program(index);
  814. }
  815. static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program)
  816. {
  817. carla_debug("lv2_select_program(%p, %i, %i)", instance, bank, program);
  818. return instancePtr->lv2_select_program(bank, program);
  819. }
  820. static LV2_State_Status lv2_save(LV2_Handle instance, LV2_State_Store_Function store, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features)
  821. {
  822. carla_debug("lv2_save(%p, %p, %p, %i, %p)", instance, store, handle, flags, features);
  823. return instancePtr->lv2_save(store, handle, flags, features);
  824. }
  825. static LV2_State_Status lv2_restore(LV2_Handle instance, LV2_State_Retrieve_Function retrieve, LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* features)
  826. {
  827. carla_debug("lv2_restore(%p, %p, %p, %i, %p)", instance, retrieve, handle, flags, features);
  828. return instancePtr->lv2_restore(retrieve, handle, flags, features);
  829. }
  830. static LV2_Worker_Status lv2_work(LV2_Handle instance, LV2_Worker_Respond_Function respond, LV2_Worker_Respond_Handle handle, uint32_t size, const void* data)
  831. {
  832. carla_debug("work(%p, %p, %p, %u, %p)", instance, respond, handle, size, data);
  833. return instancePtr->lv2_work(respond, handle, size, data);
  834. }
  835. static LV2_Worker_Status lv2_work_resp(LV2_Handle instance, uint32_t size, const void* body)
  836. {
  837. carla_debug("work_resp(%p, %u, %p)", instance, size, body);
  838. return instancePtr->lv2_work_resp(size, body);
  839. }
  840. static const void* lv2_extension_data(const char* uri)
  841. {
  842. carla_debug("lv2_extension_data(\"%s\")", uri);
  843. static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options };
  844. static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program };
  845. static const LV2_State_Interface state = { lv2_save, lv2_restore };
  846. static const LV2_Worker_Interface worker = { lv2_work, lv2_work_resp, nullptr };
  847. if (std::strcmp(uri, LV2_OPTIONS__interface) == 0)
  848. return &options;
  849. if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0)
  850. return &programs;
  851. if (std::strcmp(uri, LV2_STATE__interface) == 0)
  852. return &state;
  853. if (std::strcmp(uri, LV2_WORKER__interface) == 0)
  854. return &worker;
  855. return nullptr;
  856. }
  857. #undef instancePtr
  858. #ifdef HAVE_PYQT
  859. // -----------------------------------------------------------------------
  860. // LV2 UI descriptor functions
  861. static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char*, const char*,
  862. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  863. LV2UI_Widget* widget, const LV2_Feature* const* features)
  864. {
  865. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  866. NativePlugin* plugin = nullptr;
  867. for (int i=0; features[i] != nullptr; ++i)
  868. {
  869. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  870. {
  871. plugin = (NativePlugin*)features[i]->data;
  872. break;
  873. }
  874. }
  875. if (plugin == nullptr)
  876. {
  877. carla_stderr("Host doesn't support instance-access, cannot show UI");
  878. return nullptr;
  879. }
  880. plugin->lv2ui_instantiate(writeFunction, controller, widget, features);
  881. return (LV2UI_Handle)plugin;
  882. }
  883. #define uiPtr ((NativePlugin*)ui)
  884. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  885. {
  886. carla_debug("lv2ui_port_eventxx(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  887. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  888. }
  889. static void lv2ui_cleanup(LV2UI_Handle ui)
  890. {
  891. carla_debug("lv2ui_cleanup(%p)", ui);
  892. uiPtr->lv2ui_cleanup();
  893. }
  894. static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program)
  895. {
  896. carla_debug("lv2ui_select_program(%p, %i, %i)", ui, bank, program);
  897. uiPtr->lv2ui_select_program(bank, program);
  898. }
  899. static int lv2ui_idle(LV2UI_Handle ui)
  900. {
  901. return uiPtr->lv2ui_idle();
  902. }
  903. static int lv2ui_show(LV2UI_Handle ui)
  904. {
  905. carla_debug("lv2ui_show(%p)", ui);
  906. return uiPtr->lv2ui_show();
  907. }
  908. static int lv2ui_hide(LV2UI_Handle ui)
  909. {
  910. carla_debug("lv2ui_hide(%p)", ui);
  911. return uiPtr->lv2ui_hide();
  912. }
  913. static const void* lv2ui_extension_data(const char* uri)
  914. {
  915. carla_stdout("lv2ui_extension_data(\"%s\")", uri);
  916. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  917. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  918. static const LV2_Programs_UI_Interface uiprograms = { lv2ui_select_program };
  919. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  920. return &uiidle;
  921. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  922. return &uishow;
  923. if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0)
  924. return &uiprograms;
  925. return nullptr;
  926. }
  927. #endif
  928. #undef uiPtr
  929. // -----------------------------------------------------------------------
  930. // Startup code
  931. CARLA_EXPORT
  932. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  933. {
  934. carla_debug("lv2_descriptor(%i)", index);
  935. PluginListManager& plm(PluginListManager::getInstance());
  936. if (index >= plm.descs.count())
  937. {
  938. carla_debug("lv2_descriptor(%i) - out of bounds", index);
  939. return nullptr;
  940. }
  941. if (index < plm.lv2Descs.count())
  942. {
  943. carla_debug("lv2_descriptor(%i) - found previously allocated", index);
  944. return plm.lv2Descs.getAt(index, nullptr);
  945. }
  946. const NativePluginDescriptor* const pluginDesc(plm.descs.getAt(index, nullptr));
  947. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, nullptr);
  948. CarlaString tmpURI;
  949. tmpURI = "http://kxstudio.sf.net/carla/plugins/";
  950. tmpURI += pluginDesc->label;
  951. carla_debug("lv2_descriptor(%i) - not found, allocating new with uri \"%s\"", index, (const char*)tmpURI);
  952. const LV2_Descriptor lv2DescTmp = {
  953. /* URI */ carla_strdup(tmpURI),
  954. /* instantiate */ lv2_instantiate,
  955. /* connect_port */ lv2_connect_port,
  956. /* activate */ lv2_activate,
  957. /* run */ lv2_run,
  958. /* deactivate */ lv2_deactivate,
  959. /* cleanup */ lv2_cleanup,
  960. /* extension_data */ lv2_extension_data
  961. };
  962. LV2_Descriptor* lv2Desc;
  963. try {
  964. lv2Desc = new LV2_Descriptor;
  965. } CARLA_SAFE_EXCEPTION_RETURN("new LV2_Descriptor", nullptr);
  966. std::memcpy(lv2Desc, &lv2DescTmp, sizeof(LV2_Descriptor));
  967. plm.lv2Descs.append(lv2Desc);
  968. return lv2Desc;
  969. }
  970. #ifdef HAVE_PYQT
  971. CARLA_EXPORT
  972. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  973. {
  974. carla_debug("lv2ui_descriptor(%i)", index);
  975. static const LV2UI_Descriptor lv2UiExtDesc = {
  976. /* URI */ "http://kxstudio.sf.net/carla/ui-ext",
  977. /* instantiate */ lv2ui_instantiate,
  978. /* cleanup */ lv2ui_cleanup,
  979. /* port_event */ lv2ui_port_event,
  980. /* extension_data */ lv2ui_extension_data
  981. };
  982. return (index == 0) ? &lv2UiExtDesc : nullptr;
  983. }
  984. #endif
  985. // -----------------------------------------------------------------------