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.

1560 lines
53KB

  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. #include "water/files/File.h"
  24. static const char* const kPathForCarlaFiles = "carlafiles";
  25. template<>
  26. void Lv2PluginBaseClass<NativeTimeInfo>::clearTimeData() noexcept
  27. {
  28. fLastPositionData.clear();
  29. carla_zeroStruct(fTimeInfo);
  30. }
  31. struct PreviewData {
  32. char type;
  33. uint32_t size;
  34. const void* buffer;
  35. bool shouldSend;
  36. PreviewData()
  37. : type(0),
  38. size(0),
  39. buffer(nullptr),
  40. shouldSend(false) {}
  41. };
  42. // --------------------------------------------------------------------------------------------------------------------
  43. // Carla Internal Plugin API exposed as LV2 plugin
  44. class NativePlugin : public Lv2PluginBaseClass<NativeTimeInfo>
  45. {
  46. public:
  47. static const uint32_t kMaxMidiEvents = 512;
  48. NativePlugin(const NativePluginDescriptor* const desc,
  49. const double sampleRate,
  50. const char* const bundlePath,
  51. const LV2_Feature* const* const features)
  52. : Lv2PluginBaseClass<NativeTimeInfo>(sampleRate, features),
  53. fHandle(nullptr),
  54. fHost(),
  55. fDescriptor(desc),
  56. #ifdef CARLA_PROPER_CPP11_SUPPORT
  57. fProgramDesc({0, 0, nullptr}),
  58. #endif
  59. kIgnoreParameters(std::strncmp(desc->label, "carla", 5) == 0),
  60. fAtomForge(),
  61. fMidiEventCount(0),
  62. fLastProjectPath(),
  63. fLoadedFile(),
  64. fPreviewData(),
  65. fNeedsNotifyFileChanged(false),
  66. fPluginNeedsIdle(0),
  67. fWorkerUISignal(0)
  68. {
  69. carla_zeroStruct(fHost);
  70. #ifndef CARLA_PROPER_CPP11_SUPPORT
  71. carla_zeroStruct(fProgramDesc);
  72. #endif
  73. if (! loadedInProperHost())
  74. return;
  75. using water::File;
  76. using water::String;
  77. String resourceDir(water::File(bundlePath).getChildFile("resources").getFullPathName());
  78. fHost.handle = this;
  79. fHost.resourceDir = carla_strdup(resourceDir.toRawUTF8());
  80. fHost.uiName = nullptr;
  81. fHost.uiParentId = 0;
  82. fHost.get_buffer_size = host_get_buffer_size;
  83. fHost.get_sample_rate = host_get_sample_rate;
  84. fHost.is_offline = host_is_offline;
  85. fHost.get_time_info = host_get_time_info;
  86. fHost.write_midi_event = host_write_midi_event;
  87. fHost.ui_parameter_changed = host_ui_parameter_changed;
  88. fHost.ui_custom_data_changed = host_ui_custom_data_changed;
  89. fHost.ui_closed = host_ui_closed;
  90. fHost.ui_open_file = host_ui_open_file;
  91. fHost.ui_save_file = host_ui_save_file;
  92. fHost.dispatcher = host_dispatcher;
  93. carla_zeroStruct(fAtomForge);
  94. lv2_atom_forge_init(&fAtomForge, fUridMap);
  95. }
  96. ~NativePlugin()
  97. {
  98. CARLA_SAFE_ASSERT(fHandle == nullptr);
  99. if (fHost.resourceDir != nullptr)
  100. {
  101. delete[] fHost.resourceDir;
  102. fHost.resourceDir = nullptr;
  103. }
  104. if (fHost.uiName != nullptr)
  105. {
  106. delete[] fHost.uiName;
  107. fHost.uiName = nullptr;
  108. }
  109. }
  110. // ----------------------------------------------------------------------------------------------------------------
  111. bool init()
  112. {
  113. if (fHost.resourceDir == nullptr)
  114. return false;
  115. if (fDescriptor->instantiate == nullptr || fDescriptor->process == nullptr)
  116. {
  117. carla_stderr("Plugin is missing something...");
  118. return false;
  119. }
  120. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  121. fHandle = fDescriptor->instantiate(&fHost);
  122. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, false);
  123. fPorts.hasUI = fDescriptor->hints & NATIVE_PLUGIN_HAS_UI;
  124. fPorts.usesTime = fDescriptor->hints & NATIVE_PLUGIN_USES_TIME;
  125. fPorts.numAudioIns = fDescriptor->audioIns;
  126. fPorts.numAudioOuts = fDescriptor->audioOuts;
  127. fPorts.numCVIns = fDescriptor->cvIns;
  128. fPorts.numCVOuts = fDescriptor->cvOuts;
  129. fPorts.numMidiIns = fDescriptor->midiIns;
  130. fPorts.numMidiOuts = fDescriptor->midiOuts;
  131. if (fDescriptor->get_parameter_count != nullptr &&
  132. fDescriptor->get_parameter_info != nullptr &&
  133. fDescriptor->get_parameter_value != nullptr &&
  134. fDescriptor->set_parameter_value != nullptr &&
  135. ! kIgnoreParameters)
  136. {
  137. fPorts.numParams = fDescriptor->get_parameter_count(fHandle);
  138. }
  139. fPorts.init();
  140. if (fPorts.numParams > 0)
  141. {
  142. for (uint32_t i=0; i < fPorts.numParams; ++i)
  143. {
  144. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  145. fPorts.paramsOut [i] = fDescriptor->get_parameter_info(fHandle, i)->hints & NATIVE_PARAMETER_IS_OUTPUT;
  146. }
  147. }
  148. return true;
  149. }
  150. // ----------------------------------------------------------------------------------------------------------------
  151. // LV2 functions
  152. void lv2_activate()
  153. {
  154. CARLA_SAFE_ASSERT_RETURN(! fIsActive,);
  155. resetTimeInfo();
  156. if (fDescriptor->activate != nullptr)
  157. fDescriptor->activate(fHandle);
  158. fIsActive = true;
  159. }
  160. void lv2_deactivate()
  161. {
  162. CARLA_SAFE_ASSERT_RETURN(fIsActive,);
  163. fIsActive = false;
  164. if (fDescriptor->deactivate != nullptr)
  165. fDescriptor->deactivate(fHandle);
  166. }
  167. void lv2_cleanup()
  168. {
  169. if (fIsActive)
  170. {
  171. carla_stderr("Warning: Host forgot to call deactivate!");
  172. fIsActive = false;
  173. if (fDescriptor->deactivate != nullptr)
  174. fDescriptor->deactivate(fHandle);
  175. }
  176. if (fDescriptor->cleanup != nullptr)
  177. fDescriptor->cleanup(fHandle);
  178. fHandle = nullptr;
  179. }
  180. // ----------------------------------------------------------------------------------------------------------------
  181. void lv2_run(const uint32_t frames)
  182. {
  183. if (! lv2_pre_run(frames))
  184. {
  185. updateParameterOutputs();
  186. return;
  187. }
  188. if (fPorts.numMidiIns > 0 || fPorts.hasUI)
  189. {
  190. uint32_t numEventsIn;
  191. if (fPorts.numMidiIns > 0)
  192. {
  193. numEventsIn = fPorts.numMidiIns;
  194. fMidiEventCount = 0;
  195. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  196. }
  197. else
  198. {
  199. numEventsIn = 1;
  200. }
  201. for (uint32_t i=0; i < numEventsIn; ++i)
  202. {
  203. const LV2_Atom_Sequence* const eventsIn(fPorts.eventsIn[i]);
  204. CARLA_SAFE_ASSERT_CONTINUE(eventsIn != nullptr);
  205. LV2_ATOM_SEQUENCE_FOREACH(eventsIn, event)
  206. {
  207. if (event == nullptr)
  208. continue;
  209. if (event->body.type == fURIs.carlaUiEvents && fWorkerUISignal != -1)
  210. {
  211. CARLA_SAFE_ASSERT_CONTINUE((fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE) == 0);
  212. if (fWorker != nullptr)
  213. {
  214. // worker is supported by the host, we can continue
  215. fWorkerUISignal = 1;
  216. const char* const msg((const char*)(event + 1));
  217. const size_t msgSize = std::strlen(msg);
  218. fWorker->schedule_work(fWorker->handle, static_cast<uint32_t>(msgSize + 1U), msg);
  219. }
  220. else
  221. {
  222. // worker is not supported, cancel
  223. fWorkerUISignal = -1;
  224. }
  225. continue;
  226. }
  227. if (event->body.type == fURIs.atomObject)
  228. {
  229. const LV2_Atom_Object* const obj = (const LV2_Atom_Object*)(&event->body);
  230. if (obj->body.otype == fURIs.patchSet)
  231. {
  232. // Get property URI.
  233. const LV2_Atom* property = nullptr;
  234. lv2_atom_object_get(obj, fURIs.patchProperty, &property, 0);
  235. CARLA_SAFE_ASSERT_CONTINUE(property != nullptr);
  236. CARLA_SAFE_ASSERT_CONTINUE(property->type == fURIs.atomURID);
  237. const LV2_URID urid = ((const LV2_Atom_URID*)property)->body;
  238. /* */ if (std::strcmp(fDescriptor->label, "audiofile") == 0) {
  239. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFileAudio);
  240. } else if (std::strcmp(fDescriptor->label, "midifile") == 0) {
  241. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFileMIDI);
  242. } else {
  243. CARLA_SAFE_ASSERT_CONTINUE(urid == fURIs.carlaFile);
  244. }
  245. // Get value.
  246. const LV2_Atom* fileobj = nullptr;
  247. lv2_atom_object_get(obj, fURIs.patchValue, &fileobj, 0);
  248. CARLA_SAFE_ASSERT_CONTINUE(fileobj != nullptr);
  249. CARLA_SAFE_ASSERT_CONTINUE(fileobj->type == fURIs.atomPath);
  250. const char* const filepath((const char*)(fileobj + 1));
  251. fWorker->schedule_work(fWorker->handle,
  252. static_cast<uint32_t>(std::strlen(filepath) + 1U),
  253. filepath);
  254. }
  255. else if (obj->body.otype == fURIs.patchGet)
  256. {
  257. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  258. fNeedsNotifyFileChanged = true;
  259. if (fPreviewData.buffer != nullptr)
  260. fPreviewData.shouldSend = true;
  261. }
  262. continue;
  263. }
  264. if (event->body.type != fURIs.midiEvent)
  265. continue;
  266. // anything past this point assumes plugin with MIDI input
  267. CARLA_SAFE_ASSERT_CONTINUE(fPorts.numMidiIns > 0);
  268. if (event->body.size > 4)
  269. continue;
  270. if (event->time.frames >= frames)
  271. break;
  272. const uint8_t* const data((const uint8_t*)(event + 1));
  273. NativeMidiEvent& nativeEvent(fMidiEvents[fMidiEventCount++]);
  274. nativeEvent.port = (uint8_t)i;
  275. nativeEvent.size = (uint8_t)event->body.size;
  276. nativeEvent.time = (uint32_t)event->time.frames;
  277. uint32_t j=0;
  278. for (uint32_t size=event->body.size; j<size; ++j)
  279. nativeEvent.data[j] = data[j];
  280. for (; j<4; ++j)
  281. nativeEvent.data[j] = 0;
  282. if (fMidiEventCount >= kMaxMidiEvents)
  283. break;
  284. }
  285. }
  286. if (fNeedsNotifyFileChanged || fPreviewData.shouldSend)
  287. {
  288. uint8_t atomBuf[4096];
  289. LV2_Atom_Forge atomForge = fAtomForge;
  290. lv2_atom_forge_set_buffer(&atomForge, atomBuf, sizeof(atomBuf));
  291. const int numEvents = fNeedsNotifyFileChanged && fPreviewData.shouldSend ? 2 : 1;
  292. if (fNeedsNotifyFileChanged)
  293. {
  294. fNeedsNotifyFileChanged = false;
  295. LV2_Atom_Forge_Frame forgeFrame;
  296. lv2_atom_forge_object(&atomForge, &forgeFrame, 0, fURIs.patchSet);
  297. lv2_atom_forge_key(&atomForge, fURIs.patchProperty);
  298. /* */ if (std::strcmp(fDescriptor->label, "audiofile") == 0) {
  299. lv2_atom_forge_urid(&atomForge, fURIs.carlaFileAudio);
  300. } else if (std::strcmp(fDescriptor->label, "midifile") == 0) {
  301. lv2_atom_forge_urid(&atomForge, fURIs.carlaFileMIDI);
  302. } else {
  303. lv2_atom_forge_urid(&atomForge, fURIs.carlaFile);
  304. }
  305. lv2_atom_forge_key(&atomForge, fURIs.patchValue);
  306. lv2_atom_forge_path(&atomForge,
  307. fLoadedFile.buffer(),
  308. static_cast<uint32_t>(fLoadedFile.length()+1));
  309. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  310. }
  311. if (fPreviewData.shouldSend)
  312. {
  313. const char ptype = fPreviewData.type;
  314. const uint32_t psize = fPreviewData.size;
  315. const void* const pbuffer = fPreviewData.buffer;
  316. fPreviewData.shouldSend = false;
  317. LV2_Atom_Forge_Frame forgeFrame;
  318. lv2_atom_forge_object(&atomForge, &forgeFrame, 0, fURIs.patchSet);
  319. lv2_atom_forge_key(&atomForge, fURIs.patchProperty);
  320. lv2_atom_forge_urid(&atomForge, fURIs.carlaPreview);
  321. lv2_atom_forge_key(&atomForge, fURIs.patchValue);
  322. switch (ptype)
  323. {
  324. case 'f':
  325. lv2_atom_forge_vector(&atomForge, sizeof(float), fURIs.atomFloat, psize, pbuffer);
  326. break;
  327. default:
  328. carla_stderr2("Preview data buffer has wrong type '%c' (and size %u)", ptype, psize);
  329. break;
  330. }
  331. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  332. }
  333. LV2_Atom* atom = (LV2_Atom*)atomBuf;
  334. LV2_Atom_Sequence* const seq = fPorts.eventsOut[0];
  335. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  336. for (int i=0; i<numEvents; ++i)
  337. {
  338. if (sizeof(LV2_Atom_Event) + atom->size <= mData.capacity - mData.offset)
  339. {
  340. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  341. aev->time.frames = 0;
  342. aev->body.size = atom->size;
  343. aev->body.type = atom->type;
  344. std::memcpy(LV2_ATOM_BODY(&aev->body), atom + 1, atom->size);
  345. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + atom->size));
  346. mData.offset += size;
  347. seq->atom.size += size;
  348. }
  349. atom = (LV2_Atom*)(atomBuf + lv2_atom_total_size(atom));
  350. }
  351. }
  352. }
  353. fDescriptor->process(fHandle, fPorts.audioCVIns, fPorts.audioCVOuts, frames, fMidiEvents, fMidiEventCount);
  354. if (fPluginNeedsIdle == 1)
  355. {
  356. fPluginNeedsIdle = 2;
  357. const char* const msg = "_idle_";
  358. const size_t msgSize = std::strlen(msg);
  359. fWorker->schedule_work(fWorker->handle, static_cast<uint32_t>(msgSize + 1U), msg);
  360. }
  361. if (fWorkerUISignal == -1 && fPorts.hasUI)
  362. {
  363. const char* const msg = "quit";
  364. const size_t msgSize = 5;
  365. LV2_Atom_Sequence* const seq(fPorts.eventsOut[0]);
  366. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  367. if (sizeof(LV2_Atom_Event) + msgSize <= mData.capacity - mData.offset)
  368. {
  369. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  370. aev->time.frames = 0;
  371. aev->body.size = msgSize;
  372. aev->body.type = fURIs.carlaUiEvents;
  373. std::memcpy(LV2_ATOM_BODY(&aev->body), msg, msgSize);
  374. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + msgSize));
  375. mData.offset += size;
  376. seq->atom.size += size;
  377. fWorkerUISignal = 0;
  378. }
  379. }
  380. lv2_post_run(frames);
  381. updateParameterOutputs();
  382. }
  383. // ----------------------------------------------------------------------------------------------------------------
  384. const LV2_Program_Descriptor* lv2_get_program(const uint32_t index)
  385. {
  386. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  387. return nullptr;
  388. if (fDescriptor->get_midi_program_count == nullptr)
  389. return nullptr;
  390. if (fDescriptor->get_midi_program_info == nullptr)
  391. return nullptr;
  392. if (index >= fDescriptor->get_midi_program_count(fHandle))
  393. return nullptr;
  394. const NativeMidiProgram* const midiProg(fDescriptor->get_midi_program_info(fHandle, index));
  395. if (midiProg == nullptr)
  396. return nullptr;
  397. fProgramDesc.bank = midiProg->bank;
  398. fProgramDesc.program = midiProg->program;
  399. fProgramDesc.name = midiProg->name;
  400. return &fProgramDesc;
  401. }
  402. void lv2_select_program(uint32_t bank, uint32_t program)
  403. {
  404. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  405. return;
  406. if (fDescriptor->set_midi_program == nullptr)
  407. return;
  408. fDescriptor->set_midi_program(fHandle, 0, bank, program);
  409. for (uint32_t i=0; i < fPorts.numParams; ++i)
  410. {
  411. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  412. if (fPorts.paramsPtr[i] != nullptr)
  413. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  414. }
  415. }
  416. // ----------------------------------------------------------------------------------------------------------------
  417. void cleanupLastProjectPath()
  418. {
  419. fLastProjectPath.clear();
  420. }
  421. void saveLastProjectPathIfPossible(const LV2_Feature* const* const features)
  422. {
  423. if (features == nullptr)
  424. return cleanupLastProjectPath();
  425. const LV2_State_Free_Path* freePath = nullptr;
  426. const LV2_State_Make_Path* makePath = nullptr;
  427. for (int i=0; features[i] != nullptr; ++i)
  428. {
  429. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  430. freePath = (const LV2_State_Free_Path*)features[i]->data;
  431. else if (makePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__makePath) == 0)
  432. makePath = (const LV2_State_Make_Path*)features[i]->data;
  433. }
  434. if (makePath == nullptr || makePath->path == nullptr)
  435. return cleanupLastProjectPath();
  436. if (freePath == nullptr)
  437. freePath = fFreePath;
  438. char* const newpath = makePath->path(makePath->handle, kPathForCarlaFiles);
  439. if (newpath == nullptr)
  440. return cleanupLastProjectPath();
  441. fLastProjectPath = CarlaString(water::File(newpath).getParentDirectory().getFullPathName().toRawUTF8());
  442. if (freePath != nullptr && freePath->free_path != nullptr)
  443. freePath->free_path(freePath->handle, newpath);
  444. #ifndef CARLA_OS_WIN
  445. // this is not safe to call under windows
  446. else
  447. std::free(newpath);
  448. #endif
  449. }
  450. LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle,
  451. const uint32_t /*flags*/, const LV2_Feature* const* const features)
  452. {
  453. saveLastProjectPathIfPossible(features);
  454. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  455. {
  456. if (fLoadedFile.isEmpty())
  457. return LV2_STATE_SUCCESS;
  458. const LV2_State_Free_Path* freePath = nullptr;
  459. const LV2_State_Map_Path* mapPath = nullptr;
  460. if (features != nullptr)
  461. {
  462. for (int i=0; features[i] != nullptr; ++i)
  463. {
  464. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  465. freePath = (const LV2_State_Free_Path*)features[i]->data;
  466. else if (mapPath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__mapPath) == 0)
  467. mapPath = (const LV2_State_Map_Path*)features[i]->data;
  468. }
  469. }
  470. if (mapPath == nullptr || mapPath->abstract_path == nullptr)
  471. return LV2_STATE_ERR_NO_FEATURE;
  472. char* path = mapPath->abstract_path(mapPath->handle, fLoadedFile.buffer());
  473. store(handle,
  474. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  475. path,
  476. std::strlen(path)+1,
  477. fURIs.atomPath,
  478. LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  479. if (freePath != nullptr && freePath->free_path != nullptr)
  480. freePath->free_path(freePath->handle, path);
  481. #ifndef CARLA_OS_WIN
  482. // this is not safe to call under windows
  483. else
  484. std::free(path);
  485. #endif
  486. return LV2_STATE_SUCCESS;
  487. }
  488. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->get_state == nullptr)
  489. return LV2_STATE_ERR_UNKNOWN;
  490. if (char* const state = fDescriptor->get_state(fHandle))
  491. {
  492. store(handle,
  493. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"),
  494. state,
  495. std::strlen(state)+1,
  496. fURIs.atomString,
  497. LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  498. std::free(state);
  499. return LV2_STATE_SUCCESS;
  500. }
  501. return LV2_STATE_ERR_UNKNOWN;
  502. }
  503. LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve,
  504. const LV2_State_Handle handle,
  505. uint32_t flags,
  506. const LV2_Feature* const* const features)
  507. {
  508. saveLastProjectPathIfPossible(features);
  509. size_t size = 0;
  510. uint32_t type = 0;
  511. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  512. {
  513. size = type = 0;
  514. const void* const data = retrieve(handle,
  515. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  516. &size, &type, &flags);
  517. if (size <= 1 || type == 0)
  518. return LV2_STATE_ERR_NO_PROPERTY;
  519. CARLA_SAFE_ASSERT_RETURN(type == fURIs.atomPath, LV2_STATE_ERR_UNKNOWN);
  520. const LV2_State_Free_Path* freePath = nullptr;
  521. const LV2_State_Map_Path* mapPath = nullptr;
  522. if (features != nullptr)
  523. {
  524. for (int i=0; features[i] != nullptr; ++i)
  525. {
  526. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  527. freePath = (const LV2_State_Free_Path*)features[i]->data;
  528. else if (mapPath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__mapPath) == 0)
  529. mapPath = (const LV2_State_Map_Path*)features[i]->data;
  530. }
  531. }
  532. if (mapPath == nullptr || mapPath->absolute_path == nullptr)
  533. return LV2_STATE_ERR_NO_FEATURE;
  534. const char* const filename = (const char*)data;
  535. char* const absolute_filename = mapPath->absolute_path(mapPath->handle, filename);
  536. fLoadedFile = absolute_filename;
  537. if (freePath != nullptr && freePath->free_path != nullptr)
  538. freePath->free_path(freePath->handle, absolute_filename);
  539. #ifndef CARLA_OS_WIN
  540. // this is not safe to call under windows
  541. else
  542. std::free(absolute_filename);
  543. #endif
  544. fNeedsNotifyFileChanged = true;
  545. fDescriptor->set_custom_data(fHandle, "file", fLoadedFile);
  546. return LV2_STATE_SUCCESS;
  547. }
  548. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->set_state == nullptr)
  549. return LV2_STATE_ERR_UNKNOWN;
  550. size = type = 0;
  551. const void* const data = retrieve(handle,
  552. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"),
  553. &size, &type, &flags);
  554. if (size == 0)
  555. return LV2_STATE_ERR_UNKNOWN;
  556. if (type == 0)
  557. return LV2_STATE_ERR_UNKNOWN;
  558. if (data == nullptr)
  559. return LV2_STATE_ERR_UNKNOWN;
  560. if (type != fURIs.atomString)
  561. return LV2_STATE_ERR_BAD_TYPE;
  562. fDescriptor->set_state(fHandle, (const char*)data);
  563. return LV2_STATE_SUCCESS;
  564. }
  565. // ----------------------------------------------------------------------------------------------------------------
  566. LV2_Worker_Status lv2_work(LV2_Worker_Respond_Function, LV2_Worker_Respond_Handle, uint32_t, const void* data)
  567. {
  568. const char* const msg = (const char*)data;
  569. if (std::strcmp(msg, "_idle_") == 0)
  570. {
  571. if (fDescriptor->hints & NATIVE_PLUGIN_REQUESTS_IDLE)
  572. {
  573. fPluginNeedsIdle = 0;
  574. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_IDLE, 0, 0, nullptr, 0.0f);
  575. return LV2_WORKER_SUCCESS;
  576. }
  577. return LV2_WORKER_ERR_UNKNOWN;
  578. }
  579. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  580. {
  581. fLoadedFile = msg;
  582. fDescriptor->set_custom_data(fHandle, "file", msg);
  583. return LV2_WORKER_SUCCESS;
  584. }
  585. /**/ if (std::strncmp(msg, "control ", 8) == 0)
  586. {
  587. if (fDescriptor->ui_set_parameter_value == nullptr)
  588. return LV2_WORKER_SUCCESS;
  589. if (const char* const msgSplit = std::strstr(msg+8, " "))
  590. {
  591. const char* const msgIndex = msg+8;
  592. CARLA_SAFE_ASSERT_RETURN(msgSplit - msgIndex < 8, LV2_WORKER_ERR_UNKNOWN);
  593. CARLA_SAFE_ASSERT_RETURN(msgSplit[0] != '\0', LV2_WORKER_ERR_UNKNOWN);
  594. char strBufIndex[8];
  595. carla_zeroChars(strBufIndex, 8);
  596. std::strncpy(strBufIndex, msgIndex, static_cast<size_t>(msgSplit - msgIndex));
  597. const int index = std::atoi(msgIndex) - static_cast<int>(fPorts.indexOffset);
  598. CARLA_SAFE_ASSERT_RETURN(index >= 0, LV2_WORKER_ERR_UNKNOWN);
  599. float value;
  600. {
  601. const CarlaScopedLocale csl;
  602. value = static_cast<float>(std::atof(msgSplit+1));
  603. }
  604. fDescriptor->ui_set_parameter_value(fHandle, static_cast<uint32_t>(index), value);
  605. }
  606. }
  607. else if (std::strcmp(msg, "show") == 0)
  608. {
  609. handleUiShow();
  610. }
  611. else if (std::strcmp(msg, "hide") == 0)
  612. {
  613. handleUiHide();
  614. }
  615. else if (std::strcmp(msg, "idle") == 0)
  616. {
  617. handleUiRun();
  618. }
  619. else if (std::strcmp(msg, "quit") == 0)
  620. {
  621. handleUiClosed();
  622. }
  623. else
  624. {
  625. carla_stdout("lv2_work unknown msg '%s'", msg);
  626. return LV2_WORKER_ERR_UNKNOWN;
  627. }
  628. return LV2_WORKER_SUCCESS;
  629. }
  630. LV2_Worker_Status lv2_work_resp(uint32_t /*size*/, const void* /*body*/)
  631. {
  632. return LV2_WORKER_SUCCESS;
  633. }
  634. const LV2_Inline_Display_Image_Surface* lv2_idisp_render(const uint32_t width, const uint32_t height)
  635. {
  636. CARLA_SAFE_ASSERT_RETURN(fDescriptor->hints & NATIVE_PLUGIN_HAS_INLINE_DISPLAY, nullptr);
  637. CARLA_SAFE_ASSERT_RETURN(fDescriptor->render_inline_display, nullptr);
  638. CARLA_SAFE_ASSERT_RETURN(width > 0, nullptr);
  639. CARLA_SAFE_ASSERT_RETURN(height > 0, nullptr);
  640. const NativeInlineDisplayImageSurface* nsur = fDescriptor->render_inline_display(fHandle, width, height);
  641. CARLA_SAFE_ASSERT_RETURN(nsur != nullptr, nullptr);
  642. return (const LV2_Inline_Display_Image_Surface*)(nsur);
  643. }
  644. // ----------------------------------------------------------------------------------------------------------------
  645. void lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  646. LV2UI_Widget* widget, const LV2_Feature* const* features)
  647. {
  648. fUI.writeFunction = writeFunction;
  649. fUI.controller = controller;
  650. if (fHost.uiName != nullptr)
  651. {
  652. delete[] fHost.uiName;
  653. fHost.uiName = nullptr;
  654. }
  655. // ---------------------------------------------------------------
  656. // see if the host supports external-ui
  657. for (int i=0; features[i] != nullptr; ++i)
  658. {
  659. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  660. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  661. {
  662. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  663. }
  664. if (std::strcmp(features[i]->URI, LV2_UI__touch) == 0)
  665. {
  666. fUI.touch = (const LV2UI_Touch*)features[i]->data;
  667. }
  668. }
  669. if (fUI.host != nullptr)
  670. {
  671. fHost.uiName = carla_strdup(fUI.host->plugin_human_id);
  672. *widget = (LV2_External_UI_Widget_Compat*)this;
  673. return;
  674. }
  675. // ---------------------------------------------------------------
  676. // no external-ui support, use showInterface
  677. for (int i=0; features[i] != nullptr; ++i)
  678. {
  679. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) != 0)
  680. continue;
  681. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  682. CARLA_SAFE_ASSERT_BREAK(options != nullptr);
  683. for (int j=0; options[j].key != 0; ++j)
  684. {
  685. if (options[j].key != fUridMap->map(fUridMap->handle, LV2_UI__windowTitle))
  686. continue;
  687. const char* const title((const char*)options[j].value);
  688. CARLA_SAFE_ASSERT_BREAK(title != nullptr && title[0] != '\0');
  689. fHost.uiName = carla_strdup(title);
  690. break;
  691. }
  692. break;
  693. }
  694. if (fHost.uiName == nullptr)
  695. fHost.uiName = carla_strdup(fDescriptor->name);
  696. *widget = nullptr;
  697. return;
  698. }
  699. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  700. {
  701. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  702. return;
  703. if (portIndex < fPorts.indexOffset || ! fUI.isVisible)
  704. return;
  705. if (fDescriptor->ui_set_parameter_value == nullptr)
  706. return;
  707. const float value(*(const float*)buffer);
  708. fDescriptor->ui_set_parameter_value(fHandle, portIndex-fPorts.indexOffset, value);
  709. }
  710. // ----------------------------------------------------------------------------------------------------------------
  711. void lv2ui_select_program(uint32_t bank, uint32_t program) const
  712. {
  713. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  714. return;
  715. if (fDescriptor->ui_set_midi_program == nullptr)
  716. return;
  717. fDescriptor->ui_set_midi_program(fHandle, 0, bank, program);
  718. }
  719. // ----------------------------------------------------------------------------------------------------------------
  720. protected:
  721. void handleUiRun() const override
  722. {
  723. if (fDescriptor->ui_idle != nullptr)
  724. fDescriptor->ui_idle(fHandle);
  725. }
  726. void handleUiShow() override
  727. {
  728. if (fDescriptor->ui_show != nullptr)
  729. fDescriptor->ui_show(fHandle, true);
  730. fUI.isVisible = true;
  731. }
  732. void handleUiHide() override
  733. {
  734. if (fDescriptor->ui_show != nullptr)
  735. fDescriptor->ui_show(fHandle, false);
  736. fUI.isVisible = false;
  737. }
  738. // ----------------------------------------------------------------------------------------------------------------
  739. void handleParameterValueChanged(const uint32_t index, const float value) override
  740. {
  741. fDescriptor->set_parameter_value(fHandle, index, value);
  742. }
  743. void handleBufferSizeChanged(const uint32_t bufferSize) override
  744. {
  745. if (fDescriptor->dispatcher == nullptr)
  746. return;
  747. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, bufferSize, nullptr, 0.0f);
  748. }
  749. void handleSampleRateChanged(const double sampleRate) override
  750. {
  751. if (fDescriptor->dispatcher == nullptr)
  752. return;
  753. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)sampleRate);
  754. }
  755. // ----------------------------------------------------------------------------------------------------------------
  756. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  757. {
  758. CARLA_SAFE_ASSERT_RETURN(fPorts.numMidiOuts > 0, false);
  759. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  760. CARLA_SAFE_ASSERT_RETURN(event->size > 0, false);
  761. const uint8_t port(event->port);
  762. CARLA_SAFE_ASSERT_RETURN(port < fPorts.numMidiOuts, false);
  763. LV2_Atom_Sequence* const seq(fPorts.eventsOut[port]);
  764. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  765. Ports::EventsOutData& mData(fPorts.eventsOutData[port]);
  766. if (sizeof(LV2_Atom_Event) + event->size > mData.capacity - mData.offset)
  767. return false;
  768. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  769. aev->time.frames = event->time;
  770. aev->body.size = event->size;
  771. aev->body.type = fURIs.midiEvent;
  772. std::memcpy(LV2_ATOM_BODY(&aev->body), event->data, event->size);
  773. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + event->size));
  774. mData.offset += size;
  775. seq->atom.size += size;
  776. return true;
  777. }
  778. void handleUiParameterChanged(const uint32_t index, const float value) const
  779. {
  780. if (kIgnoreParameters || fWorkerUISignal)
  781. return;
  782. if (fUI.writeFunction != nullptr && fUI.controller != nullptr)
  783. fUI.writeFunction(fUI.controller, index+fPorts.indexOffset, sizeof(float), 0, &value);
  784. }
  785. void handleUiParameterTouch(const uint32_t index, const bool touch) const
  786. {
  787. if (kIgnoreParameters)
  788. return;
  789. if (fUI.touch != nullptr && fUI.touch->touch != nullptr)
  790. fUI.touch->touch(fUI.touch->handle, index+fPorts.indexOffset, touch);
  791. }
  792. void handleUiResize(const uint32_t, const uint32_t) const
  793. {
  794. // nothing here
  795. }
  796. void handlePreviewBufferData(const char type, const uint32_t size, const void* const buffer) noexcept
  797. {
  798. fPreviewData.type = type;
  799. fPreviewData.size = size;
  800. fPreviewData.buffer = buffer;
  801. fPreviewData.shouldSend = true;
  802. }
  803. void handleUiCustomDataChanged(const char* const key, const char* const value) const
  804. {
  805. carla_stdout("TODO: handleUiCustomDataChanged %s %s", key, value);
  806. //storeCustomData(key, value);
  807. if (fUI.writeFunction == nullptr || fUI.controller == nullptr)
  808. return;
  809. }
  810. void handleUiClosed()
  811. {
  812. fUI.isVisible = false;
  813. if (fWorkerUISignal)
  814. fWorkerUISignal = -1;
  815. if (fUI.host != nullptr && fUI.host->ui_closed != nullptr && fUI.controller != nullptr)
  816. fUI.host->ui_closed(fUI.controller);
  817. fUI.host = nullptr;
  818. fUI.touch = nullptr;
  819. fUI.writeFunction = nullptr;
  820. fUI.controller = nullptr;
  821. }
  822. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  823. {
  824. // TODO
  825. return nullptr;
  826. }
  827. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  828. {
  829. // TODO
  830. return nullptr;
  831. }
  832. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  833. {
  834. #ifdef DEBUG
  835. if (opcode != NATIVE_HOST_OPCODE_GET_FILE_PATH)
  836. {
  837. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)",
  838. opcode, index, value, ptr, static_cast<double>(opt));
  839. }
  840. #endif
  841. intptr_t ret = 0;
  842. switch (opcode)
  843. {
  844. case NATIVE_HOST_OPCODE_NULL:
  845. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  846. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  847. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  848. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  849. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  850. case NATIVE_HOST_OPCODE_HOST_IDLE:
  851. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  852. // nothing
  853. break;
  854. case NATIVE_HOST_OPCODE_REQUEST_IDLE:
  855. CARLA_SAFE_ASSERT_RETURN(fDescriptor->hints & NATIVE_PLUGIN_REQUESTS_IDLE, 0);
  856. if (fWorker != nullptr && fPluginNeedsIdle == 0)
  857. {
  858. fPluginNeedsIdle = 1;
  859. return 1;
  860. }
  861. return 0;
  862. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  863. if (fInlineDisplay != nullptr && fInlineDisplay->queue_draw != nullptr)
  864. {
  865. fInlineDisplay->queue_draw(fInlineDisplay->handle);
  866. return 1;
  867. }
  868. return 0;
  869. case NATIVE_HOST_OPCODE_GET_FILE_PATH:
  870. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  871. if (std::strcmp((char*)ptr, "carla") == 0 && fLastProjectPath != nullptr)
  872. return static_cast<intptr_t>((uintptr_t)fLastProjectPath.buffer());
  873. break;
  874. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  875. handleUiClosed();
  876. break;
  877. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  878. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  879. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  880. break;
  881. case NATIVE_HOST_OPCODE_UI_RESIZE:
  882. CARLA_SAFE_ASSERT_RETURN(index > 0, 0);
  883. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  884. handleUiResize(static_cast<uint32_t>(index), static_cast<uint32_t>(value));
  885. break;
  886. case NATIVE_HOST_OPCODE_PREVIEW_BUFFER_DATA:
  887. CARLA_SAFE_ASSERT_RETURN(index != 0, 0);
  888. CARLA_SAFE_ASSERT_RETURN(index >= 'a', 0);
  889. CARLA_SAFE_ASSERT_RETURN(index <= 'z', 0);
  890. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  891. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  892. handlePreviewBufferData(static_cast<char>(index), static_cast<uint32_t>(value), (const void*)ptr);
  893. break;
  894. }
  895. return ret;
  896. // unused for now
  897. (void)opt;
  898. }
  899. void updateParameterOutputs()
  900. {
  901. float value;
  902. for (uint32_t i=0; i < fPorts.numParams; ++i)
  903. {
  904. if (! fPorts.paramsOut[i])
  905. continue;
  906. fPorts.paramsLast[i] = value = fDescriptor->get_parameter_value(fHandle, i);
  907. if (fPorts.paramsPtr[i] != nullptr)
  908. *fPorts.paramsPtr[i] = value;
  909. }
  910. }
  911. // -------------------------------------------------------------------
  912. private:
  913. // Native data
  914. NativePluginHandle fHandle;
  915. NativeHostDescriptor fHost;
  916. const NativePluginDescriptor* const fDescriptor;
  917. LV2_Program_Descriptor fProgramDesc;
  918. // carla as plugin does not implement lv2 parameter API yet, needed for feedback
  919. const bool kIgnoreParameters;
  920. LV2_Atom_Forge fAtomForge;
  921. uint32_t fMidiEventCount;
  922. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  923. CarlaString fLastProjectPath;
  924. CarlaString fLoadedFile;
  925. PreviewData fPreviewData;
  926. volatile bool fNeedsNotifyFileChanged;
  927. volatile int fPluginNeedsIdle;
  928. int fWorkerUISignal;
  929. // -1 needs close, 0 idle, 1 stuff is writing??
  930. // -------------------------------------------------------------------
  931. #define handlePtr ((NativePlugin*)handle)
  932. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  933. {
  934. return handlePtr->fBufferSize;
  935. }
  936. static double host_get_sample_rate(NativeHostHandle handle)
  937. {
  938. return handlePtr->fSampleRate;
  939. }
  940. static bool host_is_offline(NativeHostHandle handle)
  941. {
  942. return handlePtr->fIsOffline;
  943. }
  944. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  945. {
  946. return &(handlePtr->fTimeInfo);
  947. }
  948. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  949. {
  950. return handlePtr->handleWriteMidiEvent(event);
  951. }
  952. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  953. {
  954. handlePtr->handleUiParameterChanged(index, value);
  955. }
  956. static void host_ui_parameter_touch(NativeHostHandle handle, uint32_t index, bool touch)
  957. {
  958. handlePtr->handleUiParameterTouch(index, touch);
  959. }
  960. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  961. {
  962. handlePtr->handleUiCustomDataChanged(key, value);
  963. }
  964. static void host_ui_closed(NativeHostHandle handle)
  965. {
  966. handlePtr->handleUiClosed();
  967. }
  968. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  969. {
  970. return handlePtr->handleUiOpenFile(isDir, title, filter);
  971. }
  972. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  973. {
  974. return handlePtr->handleUiSaveFile(isDir, title, filter);
  975. }
  976. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  977. {
  978. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  979. }
  980. #undef handlePtr
  981. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  982. };
  983. // -----------------------------------------------------------------------
  984. // LV2 plugin descriptor functions
  985. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  986. {
  987. carla_debug("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  988. const NativePluginDescriptor* pluginDesc = nullptr;
  989. const char* pluginLabel = nullptr;
  990. if (std::strncmp(lv2Descriptor->URI, "http://kxstudio.sf.net/carla/plugins/", 37) == 0)
  991. pluginLabel = lv2Descriptor->URI+37;
  992. if (pluginLabel == nullptr)
  993. {
  994. carla_stderr("Failed to find carla native plugin with URI \"%s\"", lv2Descriptor->URI);
  995. return nullptr;
  996. }
  997. carla_debug("lv2_instantiate() - looking up label \"%s\"", pluginLabel);
  998. PluginListManager& plm(PluginListManager::getInstance());
  999. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  1000. {
  1001. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  1002. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  1003. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  1004. {
  1005. pluginDesc = tmpDesc;
  1006. break;
  1007. }
  1008. }
  1009. if (pluginDesc == nullptr)
  1010. {
  1011. carla_stderr("Failed to find carla native plugin with label \"%s\"", pluginLabel);
  1012. return nullptr;
  1013. }
  1014. NativePlugin* const plugin(new NativePlugin(pluginDesc, sampleRate, bundlePath, features));
  1015. if (! plugin->init())
  1016. {
  1017. carla_stderr("Failed to init plugin");
  1018. delete plugin;
  1019. return nullptr;
  1020. }
  1021. return (LV2_Handle)plugin;
  1022. }
  1023. #define instancePtr ((NativePlugin*)instance)
  1024. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  1025. {
  1026. instancePtr->lv2_connect_port(port, dataLocation);
  1027. }
  1028. static void lv2_activate(LV2_Handle instance)
  1029. {
  1030. carla_debug("lv2_activate(%p)", instance);
  1031. instancePtr->lv2_activate();
  1032. }
  1033. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  1034. {
  1035. instancePtr->lv2_run(sampleCount);
  1036. }
  1037. static void lv2_deactivate(LV2_Handle instance)
  1038. {
  1039. carla_debug("lv2_deactivate(%p)", instance);
  1040. instancePtr->lv2_deactivate();
  1041. }
  1042. static void lv2_cleanup(LV2_Handle instance)
  1043. {
  1044. carla_debug("lv2_cleanup(%p)", instance);
  1045. instancePtr->lv2_cleanup();
  1046. delete instancePtr;
  1047. }
  1048. static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options)
  1049. {
  1050. carla_debug("lv2_get_options(%p, %p)", instance, options);
  1051. return instancePtr->lv2_get_options(options);
  1052. }
  1053. static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options)
  1054. {
  1055. carla_debug("lv2_set_options(%p, %p)", instance, options);
  1056. return instancePtr->lv2_set_options(options);
  1057. }
  1058. static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index)
  1059. {
  1060. carla_debug("lv2_get_program(%p, %i)", instance, index);
  1061. return instancePtr->lv2_get_program(index);
  1062. }
  1063. static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program)
  1064. {
  1065. carla_debug("lv2_select_program(%p, %i, %i)", instance, bank, program);
  1066. return instancePtr->lv2_select_program(bank, program);
  1067. }
  1068. 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)
  1069. {
  1070. carla_debug("lv2_save(%p, %p, %p, %i, %p)", instance, store, handle, flags, features);
  1071. return instancePtr->lv2_save(store, handle, flags, features);
  1072. }
  1073. 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)
  1074. {
  1075. carla_debug("lv2_restore(%p, %p, %p, %i, %p)", instance, retrieve, handle, flags, features);
  1076. return instancePtr->lv2_restore(retrieve, handle, flags, features);
  1077. }
  1078. 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)
  1079. {
  1080. carla_debug("work(%p, %p, %p, %u, %p)", instance, respond, handle, size, data);
  1081. return instancePtr->lv2_work(respond, handle, size, data);
  1082. }
  1083. static LV2_Worker_Status lv2_work_resp(LV2_Handle instance, uint32_t size, const void* body)
  1084. {
  1085. carla_debug("work_resp(%p, %u, %p)", instance, size, body);
  1086. return instancePtr->lv2_work_resp(size, body);
  1087. }
  1088. static const LV2_Inline_Display_Image_Surface* lv2_idisp_render(LV2_Handle instance, uint32_t w, uint32_t h)
  1089. {
  1090. // carla_debug("lv2_idisp_render(%p, %u, %u)", instance, w, h);
  1091. return instancePtr->lv2_idisp_render(w, h);
  1092. }
  1093. static const void* lv2_extension_data(const char* uri)
  1094. {
  1095. carla_debug("lv2_extension_data(\"%s\")", uri);
  1096. static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options };
  1097. static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program };
  1098. static const LV2_State_Interface state = { lv2_save, lv2_restore };
  1099. static const LV2_Worker_Interface worker = { lv2_work, lv2_work_resp, nullptr };
  1100. static const LV2_Inline_Display_Interface idisp = { lv2_idisp_render };
  1101. if (std::strcmp(uri, LV2_OPTIONS__interface) == 0)
  1102. return &options;
  1103. if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0)
  1104. return &programs;
  1105. if (std::strcmp(uri, LV2_STATE__interface) == 0)
  1106. return &state;
  1107. if (std::strcmp(uri, LV2_WORKER__interface) == 0)
  1108. return &worker;
  1109. if (std::strcmp(uri, LV2_INLINEDISPLAY__interface) == 0)
  1110. return &idisp;
  1111. return nullptr;
  1112. }
  1113. #undef instancePtr
  1114. #ifdef HAVE_PYQT
  1115. // -----------------------------------------------------------------------
  1116. // LV2 UI descriptor functions
  1117. static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char*, const char*,
  1118. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  1119. LV2UI_Widget* widget, const LV2_Feature* const* features)
  1120. {
  1121. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  1122. NativePlugin* plugin = nullptr;
  1123. for (int i=0; features[i] != nullptr; ++i)
  1124. {
  1125. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  1126. {
  1127. plugin = (NativePlugin*)features[i]->data;
  1128. break;
  1129. }
  1130. }
  1131. if (plugin == nullptr)
  1132. {
  1133. carla_stderr("Host doesn't support instance-access, cannot show UI");
  1134. return nullptr;
  1135. }
  1136. plugin->lv2ui_instantiate(writeFunction, controller, widget, features);
  1137. return (LV2UI_Handle)plugin;
  1138. }
  1139. #define uiPtr ((NativePlugin*)ui)
  1140. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  1141. {
  1142. carla_debug("lv2ui_port_event(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  1143. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  1144. }
  1145. static void lv2ui_cleanup(LV2UI_Handle ui)
  1146. {
  1147. carla_debug("lv2ui_cleanup(%p)", ui);
  1148. uiPtr->lv2ui_cleanup();
  1149. }
  1150. static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program)
  1151. {
  1152. carla_debug("lv2ui_select_program(%p, %i, %i)", ui, bank, program);
  1153. uiPtr->lv2ui_select_program(bank, program);
  1154. }
  1155. static int lv2ui_idle(LV2UI_Handle ui)
  1156. {
  1157. return uiPtr->lv2ui_idle();
  1158. }
  1159. static int lv2ui_show(LV2UI_Handle ui)
  1160. {
  1161. carla_debug("lv2ui_show(%p)", ui);
  1162. return uiPtr->lv2ui_show();
  1163. }
  1164. static int lv2ui_hide(LV2UI_Handle ui)
  1165. {
  1166. carla_debug("lv2ui_hide(%p)", ui);
  1167. return uiPtr->lv2ui_hide();
  1168. }
  1169. static const void* lv2ui_extension_data(const char* uri)
  1170. {
  1171. carla_stdout("lv2ui_extension_data(\"%s\")", uri);
  1172. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  1173. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  1174. static const LV2_Programs_UI_Interface uiprograms = { lv2ui_select_program };
  1175. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  1176. return &uiidle;
  1177. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  1178. return &uishow;
  1179. if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0)
  1180. return &uiprograms;
  1181. return nullptr;
  1182. }
  1183. #endif
  1184. #undef uiPtr
  1185. // -----------------------------------------------------------------------
  1186. // Startup code
  1187. CARLA_EXPORT
  1188. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  1189. {
  1190. carla_debug("lv2_descriptor(%i)", index);
  1191. PluginListManager& plm(PluginListManager::getInstance());
  1192. if (index >= plm.descs.count())
  1193. {
  1194. carla_debug("lv2_descriptor(%i) - out of bounds", index);
  1195. return nullptr;
  1196. }
  1197. if (index < plm.lv2Descs.count())
  1198. {
  1199. carla_debug("lv2_descriptor(%i) - found previously allocated", index);
  1200. return plm.lv2Descs.getAt(index, nullptr);
  1201. }
  1202. const NativePluginDescriptor* const pluginDesc(plm.descs.getAt(index, nullptr));
  1203. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, nullptr);
  1204. CarlaString tmpURI;
  1205. tmpURI = "http://kxstudio.sf.net/carla/plugins/";
  1206. tmpURI += pluginDesc->label;
  1207. carla_debug("lv2_descriptor(%i) - not found, allocating new with uri \"%s\"", index, (const char*)tmpURI);
  1208. const LV2_Descriptor lv2DescTmp = {
  1209. /* URI */ carla_strdup(tmpURI),
  1210. /* instantiate */ lv2_instantiate,
  1211. /* connect_port */ lv2_connect_port,
  1212. /* activate */ lv2_activate,
  1213. /* run */ lv2_run,
  1214. /* deactivate */ lv2_deactivate,
  1215. /* cleanup */ lv2_cleanup,
  1216. /* extension_data */ lv2_extension_data
  1217. };
  1218. LV2_Descriptor* lv2Desc;
  1219. try {
  1220. lv2Desc = new LV2_Descriptor;
  1221. } CARLA_SAFE_EXCEPTION_RETURN("new LV2_Descriptor", nullptr);
  1222. std::memcpy(lv2Desc, &lv2DescTmp, sizeof(LV2_Descriptor));
  1223. plm.lv2Descs.append(lv2Desc);
  1224. return lv2Desc;
  1225. }
  1226. #ifdef HAVE_PYQT
  1227. CARLA_EXPORT
  1228. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  1229. {
  1230. carla_debug("lv2ui_descriptor(%i)", index);
  1231. static const LV2UI_Descriptor lv2UiExtDesc = {
  1232. /* URI */ "http://kxstudio.sf.net/carla/ui-ext",
  1233. /* instantiate */ lv2ui_instantiate,
  1234. /* cleanup */ lv2ui_cleanup,
  1235. /* port_event */ lv2ui_port_event,
  1236. /* extension_data */ lv2ui_extension_data
  1237. };
  1238. return (index == 0) ? &lv2UiExtDesc : nullptr;
  1239. }
  1240. #endif
  1241. // -----------------------------------------------------------------------