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.

1260 lines
42KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2020 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. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  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. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  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. const LV2_URID urid = ((const LV2_Atom_URID*)property)->body;
  236. /* */ if (std::strcmp(fDescriptor->label, "audiofile") == 0) {
  237. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFileAudio);
  238. } else if (std::strcmp(fDescriptor->label, "midifile") == 0) {
  239. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFileMIDI);
  240. } else {
  241. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFile);
  242. }
  243. // Get value.
  244. const LV2_Atom* fileobj = NULL;
  245. lv2_atom_object_get(obj, fURIs.patchValue, &fileobj, 0);
  246. CARLA_SAFE_ASSERT_CONTINUE(fileobj != nullptr);
  247. CARLA_SAFE_ASSERT_CONTINUE(fileobj->type == fURIs.atomPath);
  248. const char* const filepath((const char*)(fileobj + 1));
  249. fWorker->schedule_work(fWorker->handle,
  250. static_cast<uint32_t>(std::strlen(filepath) + 1U),
  251. filepath);
  252. }
  253. continue;
  254. }
  255. if (event->body.type != fURIs.midiEvent)
  256. continue;
  257. if (event->body.size > 4)
  258. continue;
  259. if (event->time.frames >= frames)
  260. break;
  261. const uint8_t* const data((const uint8_t*)(event + 1));
  262. NativeMidiEvent& nativeEvent(fMidiEvents[fMidiEventCount++]);
  263. nativeEvent.port = (uint8_t)i;
  264. nativeEvent.size = (uint8_t)event->body.size;
  265. nativeEvent.time = (uint32_t)event->time.frames;
  266. uint32_t j=0;
  267. for (uint32_t size=event->body.size; j<size; ++j)
  268. nativeEvent.data[j] = data[j];
  269. for (; j<4; ++j)
  270. nativeEvent.data[j] = 0;
  271. if (fMidiEventCount >= kMaxMidiEvents)
  272. break;
  273. }
  274. }
  275. }
  276. fDescriptor->process(fHandle, fPorts.audioCVIns, fPorts.audioCVOuts, frames, fMidiEvents, fMidiEventCount);
  277. if (fWorkerUISignal == -1 && fPorts.hasUI)
  278. {
  279. const char* const msg = "quit";
  280. const size_t msgSize = 5;
  281. LV2_Atom_Sequence* const seq(fPorts.eventsOut[0]);
  282. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  283. if (sizeof(LV2_Atom_Event) + msgSize <= mData.capacity - mData.offset)
  284. {
  285. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  286. aev->time.frames = 0;
  287. aev->body.size = msgSize;
  288. aev->body.type = fURIs.uiEvents;
  289. std::memcpy(LV2_ATOM_BODY(&aev->body), msg, msgSize);
  290. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + msgSize));
  291. mData.offset += size;
  292. seq->atom.size += size;
  293. fWorkerUISignal = 0;
  294. }
  295. }
  296. lv2_post_run(frames);
  297. updateParameterOutputs();
  298. }
  299. // ----------------------------------------------------------------------------------------------------------------
  300. const LV2_Program_Descriptor* lv2_get_program(const uint32_t index)
  301. {
  302. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  303. return nullptr;
  304. if (fDescriptor->get_midi_program_count == nullptr)
  305. return nullptr;
  306. if (fDescriptor->get_midi_program_info == nullptr)
  307. return nullptr;
  308. if (index >= fDescriptor->get_midi_program_count(fHandle))
  309. return nullptr;
  310. const NativeMidiProgram* const midiProg(fDescriptor->get_midi_program_info(fHandle, index));
  311. if (midiProg == nullptr)
  312. return nullptr;
  313. fProgramDesc.bank = midiProg->bank;
  314. fProgramDesc.program = midiProg->program;
  315. fProgramDesc.name = midiProg->name;
  316. return &fProgramDesc;
  317. }
  318. void lv2_select_program(uint32_t bank, uint32_t program)
  319. {
  320. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  321. return;
  322. if (fDescriptor->set_midi_program == nullptr)
  323. return;
  324. fDescriptor->set_midi_program(fHandle, 0, bank, program);
  325. for (uint32_t i=0; i < fPorts.numParams; ++i)
  326. {
  327. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  328. if (fPorts.paramsPtr[i] != nullptr)
  329. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  330. }
  331. }
  332. // ----------------------------------------------------------------------------------------------------------------
  333. LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle,
  334. const uint32_t /*flags*/, const LV2_Feature* const* const /*features*/) const
  335. {
  336. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  337. {
  338. store(handle,
  339. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  340. fLoadedFile.buffer(),
  341. fLoadedFile.length()+1,
  342. fURIs.atomPath,
  343. LV2_STATE_IS_POD);
  344. return LV2_STATE_SUCCESS;
  345. }
  346. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->get_state == nullptr)
  347. return LV2_STATE_ERR_NO_FEATURE;
  348. if (char* const state = fDescriptor->get_state(fHandle))
  349. {
  350. 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);
  351. std::free(state);
  352. return LV2_STATE_SUCCESS;
  353. }
  354. return LV2_STATE_ERR_UNKNOWN;
  355. }
  356. LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve, const LV2_State_Handle handle,
  357. uint32_t flags, const LV2_Feature* const* const /*features*/)
  358. {
  359. size_t size = 0;
  360. uint32_t type = 0;
  361. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  362. {
  363. size = type = 0;
  364. const void* const data = retrieve(handle,
  365. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  366. &size, &type, &flags);
  367. CARLA_SAFE_ASSERT_RETURN(type == fURIs.atomPath, LV2_STATE_ERR_UNKNOWN);
  368. const char* const filename = (const char*)data;
  369. fLoadedFile = filename;
  370. fDescriptor->set_custom_data(fHandle, "file", filename);
  371. return LV2_STATE_SUCCESS;
  372. }
  373. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->set_state == nullptr)
  374. return LV2_STATE_ERR_NO_FEATURE;
  375. size = type = 0;
  376. const void* const data = retrieve(handle, fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"), &size, &type, &flags);
  377. if (size == 0)
  378. return LV2_STATE_ERR_UNKNOWN;
  379. if (type == 0)
  380. return LV2_STATE_ERR_UNKNOWN;
  381. if (data == nullptr)
  382. return LV2_STATE_ERR_UNKNOWN;
  383. if (type != fURIs.atomString)
  384. return LV2_STATE_ERR_BAD_TYPE;
  385. fDescriptor->set_state(fHandle, (const char*)data);
  386. return LV2_STATE_SUCCESS;
  387. }
  388. // ----------------------------------------------------------------------------------------------------------------
  389. LV2_Worker_Status lv2_work(LV2_Worker_Respond_Function, LV2_Worker_Respond_Handle, uint32_t, const void* data)
  390. {
  391. const char* const msg = (const char*)data;
  392. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  393. {
  394. fLoadedFile = msg;
  395. fDescriptor->set_custom_data(fHandle, "file", msg);
  396. return LV2_WORKER_SUCCESS;
  397. }
  398. /**/ if (std::strncmp(msg, "control ", 8) == 0)
  399. {
  400. if (fDescriptor->ui_set_parameter_value == nullptr)
  401. return LV2_WORKER_SUCCESS;
  402. if (const char* const msgSplit = std::strstr(msg+8, " "))
  403. {
  404. const char* const msgIndex = msg+8;
  405. CARLA_SAFE_ASSERT_RETURN(msgSplit - msgIndex < 8, LV2_WORKER_ERR_UNKNOWN);
  406. CARLA_SAFE_ASSERT_RETURN(msgSplit[0] != '\0', LV2_WORKER_ERR_UNKNOWN);
  407. char strBufIndex[8];
  408. carla_zeroChars(strBufIndex, 8);
  409. std::strncpy(strBufIndex, msgIndex, static_cast<size_t>(msgSplit - msgIndex));
  410. const int index = std::atoi(msgIndex) - static_cast<int>(fPorts.indexOffset);
  411. CARLA_SAFE_ASSERT_RETURN(index >= 0, LV2_WORKER_ERR_UNKNOWN);
  412. float value;
  413. {
  414. const CarlaScopedLocale csl;
  415. value = static_cast<float>(std::atof(msgSplit+1));
  416. }
  417. fDescriptor->ui_set_parameter_value(fHandle, static_cast<uint32_t>(index), value);
  418. }
  419. }
  420. else if (std::strcmp(msg, "show") == 0)
  421. {
  422. handleUiShow();
  423. }
  424. else if (std::strcmp(msg, "hide") == 0)
  425. {
  426. handleUiHide();
  427. }
  428. else if (std::strcmp(msg, "idle") == 0)
  429. {
  430. handleUiRun();
  431. }
  432. else if (std::strcmp(msg, "quit") == 0)
  433. {
  434. handleUiClosed();
  435. }
  436. else
  437. {
  438. carla_stdout("lv2_work unknown msg '%s'", msg);
  439. return LV2_WORKER_ERR_UNKNOWN;
  440. }
  441. return LV2_WORKER_SUCCESS;
  442. }
  443. LV2_Worker_Status lv2_work_resp(uint32_t /*size*/, const void* /*body*/)
  444. {
  445. return LV2_WORKER_SUCCESS;
  446. }
  447. // ----------------------------------------------------------------------------------------------------------------
  448. void lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  449. LV2UI_Widget* widget, const LV2_Feature* const* features)
  450. {
  451. fUI.writeFunction = writeFunction;
  452. fUI.controller = controller;
  453. if (fHost.uiName != nullptr)
  454. {
  455. delete[] fHost.uiName;
  456. fHost.uiName = nullptr;
  457. }
  458. // ---------------------------------------------------------------
  459. // see if the host supports external-ui
  460. for (int i=0; features[i] != nullptr; ++i)
  461. {
  462. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  463. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  464. {
  465. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  466. }
  467. if (std::strcmp(features[i]->URI, LV2_UI__touch) == 0)
  468. {
  469. fUI.touch = (const LV2UI_Touch*)features[i]->data;
  470. }
  471. }
  472. if (fUI.host != nullptr)
  473. {
  474. fHost.uiName = carla_strdup(fUI.host->plugin_human_id);
  475. *widget = (LV2_External_UI_Widget_Compat*)this;
  476. return;
  477. }
  478. // ---------------------------------------------------------------
  479. // no external-ui support, use showInterface
  480. for (int i=0; features[i] != nullptr; ++i)
  481. {
  482. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) != 0)
  483. continue;
  484. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  485. CARLA_SAFE_ASSERT_BREAK(options != nullptr);
  486. for (int j=0; options[j].key != 0; ++j)
  487. {
  488. if (options[j].key != fUridMap->map(fUridMap->handle, LV2_UI__windowTitle))
  489. continue;
  490. const char* const title((const char*)options[j].value);
  491. CARLA_SAFE_ASSERT_BREAK(title != nullptr && title[0] != '\0');
  492. fHost.uiName = carla_strdup(title);
  493. break;
  494. }
  495. break;
  496. }
  497. if (fHost.uiName == nullptr)
  498. fHost.uiName = carla_strdup(fDescriptor->name);
  499. *widget = nullptr;
  500. return;
  501. }
  502. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  503. {
  504. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  505. return;
  506. if (portIndex < fPorts.indexOffset || ! fUI.isVisible)
  507. return;
  508. if (fDescriptor->ui_set_parameter_value == nullptr)
  509. return;
  510. const float value(*(const float*)buffer);
  511. fDescriptor->ui_set_parameter_value(fHandle, portIndex-fPorts.indexOffset, value);
  512. }
  513. // ----------------------------------------------------------------------------------------------------------------
  514. void lv2ui_select_program(uint32_t bank, uint32_t program) const
  515. {
  516. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  517. return;
  518. if (fDescriptor->ui_set_midi_program == nullptr)
  519. return;
  520. fDescriptor->ui_set_midi_program(fHandle, 0, bank, program);
  521. }
  522. // ----------------------------------------------------------------------------------------------------------------
  523. protected:
  524. void handleUiRun() const override
  525. {
  526. if (fDescriptor->ui_idle != nullptr)
  527. fDescriptor->ui_idle(fHandle);
  528. }
  529. void handleUiShow() override
  530. {
  531. if (fDescriptor->ui_show != nullptr)
  532. fDescriptor->ui_show(fHandle, true);
  533. fUI.isVisible = true;
  534. }
  535. void handleUiHide() override
  536. {
  537. if (fDescriptor->ui_show != nullptr)
  538. fDescriptor->ui_show(fHandle, false);
  539. fUI.isVisible = false;
  540. }
  541. // ----------------------------------------------------------------------------------------------------------------
  542. void handleParameterValueChanged(const uint32_t index, const float value) override
  543. {
  544. fDescriptor->set_parameter_value(fHandle, index, value);
  545. }
  546. void handleBufferSizeChanged(const uint32_t bufferSize) override
  547. {
  548. if (fDescriptor->dispatcher == nullptr)
  549. return;
  550. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, bufferSize, nullptr, 0.0f);
  551. }
  552. void handleSampleRateChanged(const double sampleRate) override
  553. {
  554. if (fDescriptor->dispatcher == nullptr)
  555. return;
  556. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)sampleRate);
  557. }
  558. // ----------------------------------------------------------------------------------------------------------------
  559. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  560. {
  561. CARLA_SAFE_ASSERT_RETURN(fPorts.numMidiOuts > 0, false);
  562. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  563. CARLA_SAFE_ASSERT_RETURN(event->size > 0, false);
  564. const uint8_t port(event->port);
  565. CARLA_SAFE_ASSERT_RETURN(port < fPorts.numMidiOuts, false);
  566. LV2_Atom_Sequence* const seq(fPorts.eventsOut[port]);
  567. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  568. Ports::EventsOutData& mData(fPorts.eventsOutData[port]);
  569. if (sizeof(LV2_Atom_Event) + event->size > mData.capacity - mData.offset)
  570. return false;
  571. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  572. aev->time.frames = event->time;
  573. aev->body.size = event->size;
  574. aev->body.type = fURIs.midiEvent;
  575. std::memcpy(LV2_ATOM_BODY(&aev->body), event->data, event->size);
  576. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + event->size));
  577. mData.offset += size;
  578. seq->atom.size += size;
  579. return true;
  580. }
  581. void handleUiParameterChanged(const uint32_t index, const float value) const
  582. {
  583. if (kIgnoreParameters || fWorkerUISignal)
  584. return;
  585. if (fUI.writeFunction != nullptr && fUI.controller != nullptr)
  586. fUI.writeFunction(fUI.controller, index+fPorts.indexOffset, sizeof(float), 0, &value);
  587. }
  588. void handleUiParameterTouch(const uint32_t index, const bool touch) const
  589. {
  590. if (kIgnoreParameters)
  591. return;
  592. if (fUI.touch != nullptr && fUI.touch->touch != nullptr)
  593. fUI.touch->touch(fUI.touch->handle, index+fPorts.indexOffset, touch);
  594. }
  595. void handleUiResize(const uint32_t, const uint32_t) const
  596. {
  597. // nothing here
  598. }
  599. void handleUiCustomDataChanged(const char* const key, const char* const value) const
  600. {
  601. carla_stdout("TODO: handleUiCustomDataChanged %s %s", key, value);
  602. //storeCustomData(key, value);
  603. if (fUI.writeFunction == nullptr || fUI.controller == nullptr)
  604. return;
  605. }
  606. void handleUiClosed()
  607. {
  608. fUI.isVisible = false;
  609. if (fWorkerUISignal)
  610. fWorkerUISignal = -1;
  611. if (fUI.host != nullptr && fUI.host->ui_closed != nullptr && fUI.controller != nullptr)
  612. fUI.host->ui_closed(fUI.controller);
  613. fUI.host = nullptr;
  614. fUI.touch = nullptr;
  615. fUI.writeFunction = nullptr;
  616. fUI.controller = nullptr;
  617. }
  618. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  619. {
  620. // TODO
  621. return nullptr;
  622. }
  623. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  624. {
  625. // TODO
  626. return nullptr;
  627. }
  628. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  629. {
  630. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)",
  631. opcode, index, value, ptr, static_cast<double>(opt));
  632. intptr_t ret = 0;
  633. switch (opcode)
  634. {
  635. case NATIVE_HOST_OPCODE_NULL:
  636. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  637. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  638. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  639. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  640. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  641. case NATIVE_HOST_OPCODE_HOST_IDLE:
  642. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  643. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  644. case NATIVE_HOST_OPCODE_REQUEST_IDLE:
  645. case NATIVE_HOST_OPCODE_GET_FILE_PATH:
  646. // nothing
  647. break;
  648. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  649. handleUiClosed();
  650. break;
  651. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  652. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  653. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  654. break;
  655. case NATIVE_HOST_OPCODE_UI_RESIZE:
  656. CARLA_SAFE_ASSERT_RETURN(index > 0, 0);
  657. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  658. handleUiResize(static_cast<uint32_t>(index), static_cast<uint32_t>(value));
  659. break;
  660. }
  661. return ret;
  662. // unused for now
  663. (void)index;
  664. (void)value;
  665. (void)ptr;
  666. (void)opt;
  667. }
  668. void updateParameterOutputs()
  669. {
  670. float value;
  671. for (uint32_t i=0; i < fPorts.numParams; ++i)
  672. {
  673. if (! fPorts.paramsOut[i])
  674. continue;
  675. fPorts.paramsLast[i] = value = fDescriptor->get_parameter_value(fHandle, i);
  676. if (fPorts.paramsPtr[i] != nullptr)
  677. *fPorts.paramsPtr[i] = value;
  678. }
  679. }
  680. // -------------------------------------------------------------------
  681. private:
  682. // Native data
  683. NativePluginHandle fHandle;
  684. NativeHostDescriptor fHost;
  685. const NativePluginDescriptor* const fDescriptor;
  686. LV2_Program_Descriptor fProgramDesc;
  687. // carla as plugin does not implement lv2 parameter API yet, needed for feedback
  688. const bool kIgnoreParameters;
  689. uint32_t fMidiEventCount;
  690. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  691. #if defined(USING_JUCE) && (defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN))
  692. juce::SharedResourcePointer<juce::ScopedJuceInitialiser_GUI> fJuceInitialiser;
  693. #endif
  694. CarlaString fLoadedFile;
  695. int fWorkerUISignal;
  696. // -------------------------------------------------------------------
  697. #define handlePtr ((NativePlugin*)handle)
  698. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  699. {
  700. return handlePtr->fBufferSize;
  701. }
  702. static double host_get_sample_rate(NativeHostHandle handle)
  703. {
  704. return handlePtr->fSampleRate;
  705. }
  706. static bool host_is_offline(NativeHostHandle handle)
  707. {
  708. return handlePtr->fIsOffline;
  709. }
  710. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  711. {
  712. return &(handlePtr->fTimeInfo);
  713. }
  714. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  715. {
  716. return handlePtr->handleWriteMidiEvent(event);
  717. }
  718. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  719. {
  720. handlePtr->handleUiParameterChanged(index, value);
  721. }
  722. static void host_ui_parameter_touch(NativeHostHandle handle, uint32_t index, bool touch)
  723. {
  724. handlePtr->handleUiParameterTouch(index, touch);
  725. }
  726. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  727. {
  728. handlePtr->handleUiCustomDataChanged(key, value);
  729. }
  730. static void host_ui_closed(NativeHostHandle handle)
  731. {
  732. handlePtr->handleUiClosed();
  733. }
  734. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  735. {
  736. return handlePtr->handleUiOpenFile(isDir, title, filter);
  737. }
  738. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  739. {
  740. return handlePtr->handleUiSaveFile(isDir, title, filter);
  741. }
  742. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  743. {
  744. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  745. }
  746. #undef handlePtr
  747. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  748. };
  749. // -----------------------------------------------------------------------
  750. // LV2 plugin descriptor functions
  751. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  752. {
  753. carla_debug("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  754. const NativePluginDescriptor* pluginDesc = nullptr;
  755. const char* pluginLabel = nullptr;
  756. if (std::strncmp(lv2Descriptor->URI, "http://kxstudio.sf.net/carla/plugins/", 37) == 0)
  757. pluginLabel = lv2Descriptor->URI+37;
  758. if (pluginLabel == nullptr)
  759. {
  760. carla_stderr("Failed to find carla native plugin with URI \"%s\"", lv2Descriptor->URI);
  761. return nullptr;
  762. }
  763. carla_debug("lv2_instantiate() - looking up label \"%s\"", pluginLabel);
  764. PluginListManager& plm(PluginListManager::getInstance());
  765. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  766. {
  767. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  768. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  769. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  770. {
  771. pluginDesc = tmpDesc;
  772. break;
  773. }
  774. }
  775. if (pluginDesc == nullptr)
  776. {
  777. carla_stderr("Failed to find carla native plugin with label \"%s\"", pluginLabel);
  778. return nullptr;
  779. }
  780. NativePlugin* const plugin(new NativePlugin(pluginDesc, sampleRate, bundlePath, features));
  781. if (! plugin->init())
  782. {
  783. carla_stderr("Failed to init plugin");
  784. delete plugin;
  785. return nullptr;
  786. }
  787. return (LV2_Handle)plugin;
  788. }
  789. #define instancePtr ((NativePlugin*)instance)
  790. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  791. {
  792. instancePtr->lv2_connect_port(port, dataLocation);
  793. }
  794. static void lv2_activate(LV2_Handle instance)
  795. {
  796. carla_debug("lv2_activate(%p)", instance);
  797. instancePtr->lv2_activate();
  798. }
  799. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  800. {
  801. instancePtr->lv2_run(sampleCount);
  802. }
  803. static void lv2_deactivate(LV2_Handle instance)
  804. {
  805. carla_debug("lv2_deactivate(%p)", instance);
  806. instancePtr->lv2_deactivate();
  807. }
  808. static void lv2_cleanup(LV2_Handle instance)
  809. {
  810. carla_debug("lv2_cleanup(%p)", instance);
  811. instancePtr->lv2_cleanup();
  812. delete instancePtr;
  813. }
  814. static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options)
  815. {
  816. carla_debug("lv2_get_options(%p, %p)", instance, options);
  817. return instancePtr->lv2_get_options(options);
  818. }
  819. static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options)
  820. {
  821. carla_debug("lv2_set_options(%p, %p)", instance, options);
  822. return instancePtr->lv2_set_options(options);
  823. }
  824. static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index)
  825. {
  826. carla_debug("lv2_get_program(%p, %i)", instance, index);
  827. return instancePtr->lv2_get_program(index);
  828. }
  829. static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program)
  830. {
  831. carla_debug("lv2_select_program(%p, %i, %i)", instance, bank, program);
  832. return instancePtr->lv2_select_program(bank, program);
  833. }
  834. 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)
  835. {
  836. carla_debug("lv2_save(%p, %p, %p, %i, %p)", instance, store, handle, flags, features);
  837. return instancePtr->lv2_save(store, handle, flags, features);
  838. }
  839. 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)
  840. {
  841. carla_debug("lv2_restore(%p, %p, %p, %i, %p)", instance, retrieve, handle, flags, features);
  842. return instancePtr->lv2_restore(retrieve, handle, flags, features);
  843. }
  844. 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)
  845. {
  846. carla_debug("work(%p, %p, %p, %u, %p)", instance, respond, handle, size, data);
  847. return instancePtr->lv2_work(respond, handle, size, data);
  848. }
  849. static LV2_Worker_Status lv2_work_resp(LV2_Handle instance, uint32_t size, const void* body)
  850. {
  851. carla_debug("work_resp(%p, %u, %p)", instance, size, body);
  852. return instancePtr->lv2_work_resp(size, body);
  853. }
  854. static const void* lv2_extension_data(const char* uri)
  855. {
  856. carla_debug("lv2_extension_data(\"%s\")", uri);
  857. static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options };
  858. static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program };
  859. static const LV2_State_Interface state = { lv2_save, lv2_restore };
  860. static const LV2_Worker_Interface worker = { lv2_work, lv2_work_resp, nullptr };
  861. if (std::strcmp(uri, LV2_OPTIONS__interface) == 0)
  862. return &options;
  863. if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0)
  864. return &programs;
  865. if (std::strcmp(uri, LV2_STATE__interface) == 0)
  866. return &state;
  867. if (std::strcmp(uri, LV2_WORKER__interface) == 0)
  868. return &worker;
  869. return nullptr;
  870. }
  871. #undef instancePtr
  872. #ifdef HAVE_PYQT
  873. // -----------------------------------------------------------------------
  874. // LV2 UI descriptor functions
  875. static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char*, const char*,
  876. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  877. LV2UI_Widget* widget, const LV2_Feature* const* features)
  878. {
  879. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  880. NativePlugin* plugin = nullptr;
  881. for (int i=0; features[i] != nullptr; ++i)
  882. {
  883. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  884. {
  885. plugin = (NativePlugin*)features[i]->data;
  886. break;
  887. }
  888. }
  889. if (plugin == nullptr)
  890. {
  891. carla_stderr("Host doesn't support instance-access, cannot show UI");
  892. return nullptr;
  893. }
  894. plugin->lv2ui_instantiate(writeFunction, controller, widget, features);
  895. return (LV2UI_Handle)plugin;
  896. }
  897. #define uiPtr ((NativePlugin*)ui)
  898. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  899. {
  900. carla_debug("lv2ui_port_eventxx(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  901. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  902. }
  903. static void lv2ui_cleanup(LV2UI_Handle ui)
  904. {
  905. carla_debug("lv2ui_cleanup(%p)", ui);
  906. uiPtr->lv2ui_cleanup();
  907. }
  908. static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program)
  909. {
  910. carla_debug("lv2ui_select_program(%p, %i, %i)", ui, bank, program);
  911. uiPtr->lv2ui_select_program(bank, program);
  912. }
  913. static int lv2ui_idle(LV2UI_Handle ui)
  914. {
  915. return uiPtr->lv2ui_idle();
  916. }
  917. static int lv2ui_show(LV2UI_Handle ui)
  918. {
  919. carla_debug("lv2ui_show(%p)", ui);
  920. return uiPtr->lv2ui_show();
  921. }
  922. static int lv2ui_hide(LV2UI_Handle ui)
  923. {
  924. carla_debug("lv2ui_hide(%p)", ui);
  925. return uiPtr->lv2ui_hide();
  926. }
  927. static const void* lv2ui_extension_data(const char* uri)
  928. {
  929. carla_stdout("lv2ui_extension_data(\"%s\")", uri);
  930. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  931. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  932. static const LV2_Programs_UI_Interface uiprograms = { lv2ui_select_program };
  933. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  934. return &uiidle;
  935. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  936. return &uishow;
  937. if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0)
  938. return &uiprograms;
  939. return nullptr;
  940. }
  941. #endif
  942. #undef uiPtr
  943. // -----------------------------------------------------------------------
  944. // Startup code
  945. CARLA_EXPORT
  946. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  947. {
  948. carla_debug("lv2_descriptor(%i)", index);
  949. PluginListManager& plm(PluginListManager::getInstance());
  950. if (index >= plm.descs.count())
  951. {
  952. carla_debug("lv2_descriptor(%i) - out of bounds", index);
  953. return nullptr;
  954. }
  955. if (index < plm.lv2Descs.count())
  956. {
  957. carla_debug("lv2_descriptor(%i) - found previously allocated", index);
  958. return plm.lv2Descs.getAt(index, nullptr);
  959. }
  960. const NativePluginDescriptor* const pluginDesc(plm.descs.getAt(index, nullptr));
  961. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, nullptr);
  962. CarlaString tmpURI;
  963. tmpURI = "http://kxstudio.sf.net/carla/plugins/";
  964. tmpURI += pluginDesc->label;
  965. carla_debug("lv2_descriptor(%i) - not found, allocating new with uri \"%s\"", index, (const char*)tmpURI);
  966. const LV2_Descriptor lv2DescTmp = {
  967. /* URI */ carla_strdup(tmpURI),
  968. /* instantiate */ lv2_instantiate,
  969. /* connect_port */ lv2_connect_port,
  970. /* activate */ lv2_activate,
  971. /* run */ lv2_run,
  972. /* deactivate */ lv2_deactivate,
  973. /* cleanup */ lv2_cleanup,
  974. /* extension_data */ lv2_extension_data
  975. };
  976. LV2_Descriptor* lv2Desc;
  977. try {
  978. lv2Desc = new LV2_Descriptor;
  979. } CARLA_SAFE_EXCEPTION_RETURN("new LV2_Descriptor", nullptr);
  980. std::memcpy(lv2Desc, &lv2DescTmp, sizeof(LV2_Descriptor));
  981. plm.lv2Descs.append(lv2Desc);
  982. return lv2Desc;
  983. }
  984. #ifdef HAVE_PYQT
  985. CARLA_EXPORT
  986. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  987. {
  988. carla_debug("lv2ui_descriptor(%i)", index);
  989. static const LV2UI_Descriptor lv2UiExtDesc = {
  990. /* URI */ "http://kxstudio.sf.net/carla/ui-ext",
  991. /* instantiate */ lv2ui_instantiate,
  992. /* cleanup */ lv2ui_cleanup,
  993. /* port_event */ lv2ui_port_event,
  994. /* extension_data */ lv2ui_extension_data
  995. };
  996. return (index == 0) ? &lv2UiExtDesc : nullptr;
  997. }
  998. #endif
  999. // -----------------------------------------------------------------------