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.

1575 lines
54KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2022 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. LV2_Atom_Forge_Frame outerFrame;
  292. lv2_atom_forge_sequence_head(&atomForge, &outerFrame, 0);
  293. const int numEvents = fNeedsNotifyFileChanged && fPreviewData.shouldSend ? 2 : 1;
  294. if (fNeedsNotifyFileChanged)
  295. {
  296. fNeedsNotifyFileChanged = false;
  297. lv2_atom_forge_frame_time(&atomForge, 0);
  298. LV2_Atom_Forge_Frame forgeFrame;
  299. lv2_atom_forge_object(&atomForge, &forgeFrame, 0, fURIs.patchSet);
  300. lv2_atom_forge_key(&atomForge, fURIs.patchProperty);
  301. /* */ if (std::strcmp(fDescriptor->label, "audiofile") == 0) {
  302. lv2_atom_forge_urid(&atomForge, fURIs.carlaFileAudio);
  303. } else if (std::strcmp(fDescriptor->label, "midifile") == 0) {
  304. lv2_atom_forge_urid(&atomForge, fURIs.carlaFileMIDI);
  305. } else {
  306. lv2_atom_forge_urid(&atomForge, fURIs.carlaFile);
  307. }
  308. lv2_atom_forge_key(&atomForge, fURIs.patchValue);
  309. lv2_atom_forge_path(&atomForge,
  310. fLoadedFile.buffer(),
  311. static_cast<uint32_t>(fLoadedFile.length()+1));
  312. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  313. }
  314. if (fPreviewData.shouldSend)
  315. {
  316. const char ptype = fPreviewData.type;
  317. const uint32_t psize = fPreviewData.size;
  318. const void* const pbuffer = fPreviewData.buffer;
  319. fPreviewData.shouldSend = false;
  320. lv2_atom_forge_frame_time(&atomForge, 0);
  321. LV2_Atom_Forge_Frame forgeFrame;
  322. lv2_atom_forge_object(&atomForge, &forgeFrame, 0, fURIs.patchSet);
  323. lv2_atom_forge_key(&atomForge, fURIs.patchProperty);
  324. lv2_atom_forge_urid(&atomForge, fURIs.carlaPreview);
  325. lv2_atom_forge_key(&atomForge, fURIs.patchValue);
  326. switch (ptype)
  327. {
  328. case 'b':
  329. lv2_atom_forge_vector(&atomForge, sizeof(int32_t), fURIs.atomBool, psize, pbuffer);
  330. break;
  331. case 'i':
  332. lv2_atom_forge_vector(&atomForge, sizeof(int32_t), fURIs.atomInt, psize, pbuffer);
  333. break;
  334. case 'f':
  335. lv2_atom_forge_vector(&atomForge, sizeof(float), fURIs.atomFloat, psize, pbuffer);
  336. break;
  337. default:
  338. carla_stderr2("Preview data buffer has wrong type '%c' (and size %u)", ptype, psize);
  339. break;
  340. }
  341. lv2_atom_forge_pop(&atomForge, &forgeFrame);
  342. }
  343. lv2_atom_forge_pop(&atomForge, &outerFrame);
  344. LV2_Atom* atom = (LV2_Atom*)atomBuf;
  345. LV2_Atom_Sequence* const seq = fPorts.eventsOut[0];
  346. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  347. for (int i=0; i<numEvents; ++i)
  348. {
  349. if (sizeof(LV2_Atom_Event) + atom->size <= mData.capacity - mData.offset)
  350. {
  351. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  352. aev->time.frames = 0;
  353. aev->body.size = atom->size;
  354. aev->body.type = atom->type;
  355. std::memcpy(LV2_ATOM_BODY(&aev->body), atom + 1, atom->size);
  356. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + atom->size));
  357. mData.offset += size;
  358. seq->atom.size += size;
  359. }
  360. atom = (LV2_Atom*)(atomBuf + lv2_atom_total_size(atom));
  361. }
  362. }
  363. }
  364. fDescriptor->process(fHandle, fPorts.audioCVIns, fPorts.audioCVOuts, frames, fMidiEvents, fMidiEventCount);
  365. if (fPluginNeedsIdle == 1)
  366. {
  367. fPluginNeedsIdle = 2;
  368. const char* const msg = "_idle_";
  369. const size_t msgSize = std::strlen(msg);
  370. fWorker->schedule_work(fWorker->handle, static_cast<uint32_t>(msgSize + 1U), msg);
  371. }
  372. if (fWorkerUISignal == -1 && fPorts.hasUI)
  373. {
  374. const char* const msg = "quit";
  375. const size_t msgSize = 5;
  376. LV2_Atom_Sequence* const seq(fPorts.eventsOut[0]);
  377. Ports::EventsOutData& mData(fPorts.eventsOutData[0]);
  378. if (sizeof(LV2_Atom_Event) + msgSize <= mData.capacity - mData.offset)
  379. {
  380. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  381. aev->time.frames = 0;
  382. aev->body.size = msgSize;
  383. aev->body.type = fURIs.carlaUiEvents;
  384. std::memcpy(LV2_ATOM_BODY(&aev->body), msg, msgSize);
  385. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + msgSize));
  386. mData.offset += size;
  387. seq->atom.size += size;
  388. fWorkerUISignal = 0;
  389. }
  390. }
  391. lv2_post_run(frames);
  392. updateParameterOutputs();
  393. }
  394. // ----------------------------------------------------------------------------------------------------------------
  395. const LV2_Program_Descriptor* lv2_get_program(const uint32_t index)
  396. {
  397. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  398. return nullptr;
  399. if (fDescriptor->get_midi_program_count == nullptr)
  400. return nullptr;
  401. if (fDescriptor->get_midi_program_info == nullptr)
  402. return nullptr;
  403. if (index >= fDescriptor->get_midi_program_count(fHandle))
  404. return nullptr;
  405. const NativeMidiProgram* const midiProg(fDescriptor->get_midi_program_info(fHandle, index));
  406. if (midiProg == nullptr)
  407. return nullptr;
  408. fProgramDesc.bank = midiProg->bank;
  409. fProgramDesc.program = midiProg->program;
  410. fProgramDesc.name = midiProg->name;
  411. return &fProgramDesc;
  412. }
  413. void lv2_select_program(uint32_t bank, uint32_t program)
  414. {
  415. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  416. return;
  417. if (fDescriptor->set_midi_program == nullptr)
  418. return;
  419. fDescriptor->set_midi_program(fHandle, 0, bank, program);
  420. for (uint32_t i=0; i < fPorts.numParams; ++i)
  421. {
  422. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  423. if (fPorts.paramsPtr[i] != nullptr)
  424. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  425. }
  426. }
  427. // ----------------------------------------------------------------------------------------------------------------
  428. void cleanupLastProjectPath()
  429. {
  430. fLastProjectPath.clear();
  431. }
  432. void saveLastProjectPathIfPossible(const LV2_Feature* const* const features)
  433. {
  434. if (features == nullptr)
  435. return cleanupLastProjectPath();
  436. const LV2_State_Free_Path* freePath = nullptr;
  437. const LV2_State_Make_Path* makePath = nullptr;
  438. for (int i=0; features[i] != nullptr; ++i)
  439. {
  440. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  441. freePath = (const LV2_State_Free_Path*)features[i]->data;
  442. else if (makePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__makePath) == 0)
  443. makePath = (const LV2_State_Make_Path*)features[i]->data;
  444. }
  445. if (makePath == nullptr || makePath->path == nullptr)
  446. return cleanupLastProjectPath();
  447. if (freePath == nullptr)
  448. freePath = fFreePath;
  449. char* const newpath = makePath->path(makePath->handle, kPathForCarlaFiles);
  450. if (newpath == nullptr)
  451. return cleanupLastProjectPath();
  452. fLastProjectPath = CarlaString(water::File(newpath).getParentDirectory().getFullPathName().toRawUTF8());
  453. if (freePath != nullptr && freePath->free_path != nullptr)
  454. freePath->free_path(freePath->handle, newpath);
  455. #ifndef CARLA_OS_WIN
  456. // this is not safe to call under windows
  457. else
  458. std::free(newpath);
  459. #endif
  460. }
  461. LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle,
  462. const uint32_t /*flags*/, const LV2_Feature* const* const features)
  463. {
  464. saveLastProjectPathIfPossible(features);
  465. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  466. {
  467. if (fLoadedFile.isEmpty())
  468. return LV2_STATE_SUCCESS;
  469. const LV2_State_Free_Path* freePath = nullptr;
  470. const LV2_State_Map_Path* mapPath = nullptr;
  471. if (features != nullptr)
  472. {
  473. for (int i=0; features[i] != nullptr; ++i)
  474. {
  475. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  476. freePath = (const LV2_State_Free_Path*)features[i]->data;
  477. else if (mapPath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__mapPath) == 0)
  478. mapPath = (const LV2_State_Map_Path*)features[i]->data;
  479. }
  480. }
  481. if (mapPath == nullptr || mapPath->abstract_path == nullptr)
  482. return LV2_STATE_ERR_NO_FEATURE;
  483. char* path = mapPath->abstract_path(mapPath->handle, fLoadedFile.buffer());
  484. store(handle,
  485. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  486. path,
  487. std::strlen(path)+1,
  488. fURIs.atomPath,
  489. LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  490. if (freePath != nullptr && freePath->free_path != nullptr)
  491. freePath->free_path(freePath->handle, path);
  492. #ifndef CARLA_OS_WIN
  493. // this is not safe to call under windows
  494. else
  495. std::free(path);
  496. #endif
  497. return LV2_STATE_SUCCESS;
  498. }
  499. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->get_state == nullptr)
  500. return LV2_STATE_ERR_UNKNOWN;
  501. if (char* const state = fDescriptor->get_state(fHandle))
  502. {
  503. store(handle,
  504. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"),
  505. state,
  506. std::strlen(state)+1,
  507. fURIs.atomString,
  508. LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  509. std::free(state);
  510. return LV2_STATE_SUCCESS;
  511. }
  512. return LV2_STATE_ERR_UNKNOWN;
  513. }
  514. LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve,
  515. const LV2_State_Handle handle,
  516. uint32_t flags,
  517. const LV2_Feature* const* const features)
  518. {
  519. saveLastProjectPathIfPossible(features);
  520. size_t size = 0;
  521. uint32_t type = 0;
  522. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  523. {
  524. size = type = 0;
  525. const void* const data = retrieve(handle,
  526. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/file"),
  527. &size, &type, &flags);
  528. if (size <= 1 || type == 0)
  529. return LV2_STATE_ERR_NO_PROPERTY;
  530. CARLA_SAFE_ASSERT_RETURN(type == fURIs.atomPath, LV2_STATE_ERR_UNKNOWN);
  531. const LV2_State_Free_Path* freePath = nullptr;
  532. const LV2_State_Map_Path* mapPath = nullptr;
  533. if (features != nullptr)
  534. {
  535. for (int i=0; features[i] != nullptr; ++i)
  536. {
  537. /**/ if (freePath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__freePath) == 0)
  538. freePath = (const LV2_State_Free_Path*)features[i]->data;
  539. else if (mapPath == nullptr && std::strcmp(features[i]->URI, LV2_STATE__mapPath) == 0)
  540. mapPath = (const LV2_State_Map_Path*)features[i]->data;
  541. }
  542. }
  543. if (mapPath == nullptr || mapPath->absolute_path == nullptr)
  544. return LV2_STATE_ERR_NO_FEATURE;
  545. const char* const filename = (const char*)data;
  546. char* const absolute_filename = mapPath->absolute_path(mapPath->handle, filename);
  547. fLoadedFile = absolute_filename;
  548. if (freePath != nullptr && freePath->free_path != nullptr)
  549. freePath->free_path(freePath->handle, absolute_filename);
  550. #ifndef CARLA_OS_WIN
  551. // this is not safe to call under windows
  552. else
  553. std::free(absolute_filename);
  554. #endif
  555. fNeedsNotifyFileChanged = true;
  556. fDescriptor->set_custom_data(fHandle, "file", fLoadedFile);
  557. return LV2_STATE_SUCCESS;
  558. }
  559. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->set_state == nullptr)
  560. return LV2_STATE_ERR_UNKNOWN;
  561. size = type = 0;
  562. const void* const data = retrieve(handle,
  563. fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"),
  564. &size, &type, &flags);
  565. if (size == 0)
  566. return LV2_STATE_ERR_UNKNOWN;
  567. if (type == 0)
  568. return LV2_STATE_ERR_UNKNOWN;
  569. if (data == nullptr)
  570. return LV2_STATE_ERR_UNKNOWN;
  571. if (type != fURIs.atomString)
  572. return LV2_STATE_ERR_BAD_TYPE;
  573. fDescriptor->set_state(fHandle, (const char*)data);
  574. return LV2_STATE_SUCCESS;
  575. }
  576. // ----------------------------------------------------------------------------------------------------------------
  577. LV2_Worker_Status lv2_work(LV2_Worker_Respond_Function, LV2_Worker_Respond_Handle, uint32_t, const void* data)
  578. {
  579. const char* const msg = (const char*)data;
  580. if (std::strcmp(msg, "_idle_") == 0)
  581. {
  582. if (fDescriptor->hints & NATIVE_PLUGIN_REQUESTS_IDLE)
  583. {
  584. fPluginNeedsIdle = 0;
  585. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_IDLE, 0, 0, nullptr, 0.0f);
  586. return LV2_WORKER_SUCCESS;
  587. }
  588. return LV2_WORKER_ERR_UNKNOWN;
  589. }
  590. if (fDescriptor->hints & NATIVE_PLUGIN_NEEDS_UI_OPEN_SAVE)
  591. {
  592. fLoadedFile = msg;
  593. fDescriptor->set_custom_data(fHandle, "file", msg);
  594. return LV2_WORKER_SUCCESS;
  595. }
  596. /**/ if (std::strncmp(msg, "control ", 8) == 0)
  597. {
  598. if (fDescriptor->ui_set_parameter_value == nullptr)
  599. return LV2_WORKER_SUCCESS;
  600. if (const char* const msgSplit = std::strstr(msg+8, " "))
  601. {
  602. const char* const msgIndex = msg+8;
  603. CARLA_SAFE_ASSERT_RETURN(msgSplit - msgIndex < 8, LV2_WORKER_ERR_UNKNOWN);
  604. CARLA_SAFE_ASSERT_RETURN(msgSplit[0] != '\0', LV2_WORKER_ERR_UNKNOWN);
  605. char strBufIndex[8];
  606. carla_zeroChars(strBufIndex, 8);
  607. std::strncpy(strBufIndex, msgIndex, static_cast<size_t>(msgSplit - msgIndex));
  608. const int index = std::atoi(msgIndex) - static_cast<int>(fPorts.indexOffset);
  609. CARLA_SAFE_ASSERT_RETURN(index >= 0, LV2_WORKER_ERR_UNKNOWN);
  610. float value;
  611. {
  612. const CarlaScopedLocale csl;
  613. value = static_cast<float>(std::atof(msgSplit+1));
  614. }
  615. fDescriptor->ui_set_parameter_value(fHandle, static_cast<uint32_t>(index), value);
  616. }
  617. }
  618. else if (std::strcmp(msg, "show") == 0)
  619. {
  620. handleUiShow();
  621. }
  622. else if (std::strcmp(msg, "hide") == 0)
  623. {
  624. handleUiHide();
  625. }
  626. else if (std::strcmp(msg, "idle") == 0)
  627. {
  628. handleUiRun();
  629. }
  630. else if (std::strcmp(msg, "quit") == 0)
  631. {
  632. handleUiClosed();
  633. }
  634. else
  635. {
  636. carla_stdout("lv2_work unknown msg '%s'", msg);
  637. return LV2_WORKER_ERR_UNKNOWN;
  638. }
  639. return LV2_WORKER_SUCCESS;
  640. }
  641. LV2_Worker_Status lv2_work_resp(uint32_t /*size*/, const void* /*body*/)
  642. {
  643. return LV2_WORKER_SUCCESS;
  644. }
  645. const LV2_Inline_Display_Image_Surface* lv2_idisp_render(const uint32_t width, const uint32_t height)
  646. {
  647. CARLA_SAFE_ASSERT_RETURN(fDescriptor->hints & NATIVE_PLUGIN_HAS_INLINE_DISPLAY, nullptr);
  648. CARLA_SAFE_ASSERT_RETURN(fDescriptor->render_inline_display, nullptr);
  649. CARLA_SAFE_ASSERT_RETURN(width > 0, nullptr);
  650. CARLA_SAFE_ASSERT_RETURN(height > 0, nullptr);
  651. const NativeInlineDisplayImageSurface* nsur = fDescriptor->render_inline_display(fHandle, width, height);
  652. CARLA_SAFE_ASSERT_RETURN(nsur != nullptr, nullptr);
  653. return (const LV2_Inline_Display_Image_Surface*)(nsur);
  654. }
  655. // ----------------------------------------------------------------------------------------------------------------
  656. void lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  657. LV2UI_Widget* widget, const LV2_Feature* const* features)
  658. {
  659. fUI.writeFunction = writeFunction;
  660. fUI.controller = controller;
  661. if (fHost.uiName != nullptr)
  662. {
  663. delete[] fHost.uiName;
  664. fHost.uiName = nullptr;
  665. }
  666. // ---------------------------------------------------------------
  667. // see if the host supports external-ui
  668. for (int i=0; features[i] != nullptr; ++i)
  669. {
  670. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  671. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  672. {
  673. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  674. }
  675. if (std::strcmp(features[i]->URI, LV2_UI__touch) == 0)
  676. {
  677. fUI.touch = (const LV2UI_Touch*)features[i]->data;
  678. }
  679. }
  680. if (fUI.host != nullptr)
  681. {
  682. fHost.uiName = carla_strdup(fUI.host->plugin_human_id);
  683. *widget = (LV2_External_UI_Widget_Compat*)this;
  684. return;
  685. }
  686. // ---------------------------------------------------------------
  687. // no external-ui support, use showInterface
  688. for (int i=0; features[i] != nullptr; ++i)
  689. {
  690. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) != 0)
  691. continue;
  692. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  693. CARLA_SAFE_ASSERT_BREAK(options != nullptr);
  694. for (int j=0; options[j].key != 0; ++j)
  695. {
  696. if (options[j].key != fUridMap->map(fUridMap->handle, LV2_UI__windowTitle))
  697. continue;
  698. const char* const title((const char*)options[j].value);
  699. CARLA_SAFE_ASSERT_BREAK(title != nullptr && title[0] != '\0');
  700. fHost.uiName = carla_strdup(title);
  701. break;
  702. }
  703. break;
  704. }
  705. if (fHost.uiName == nullptr)
  706. fHost.uiName = carla_strdup(fDescriptor->name);
  707. *widget = nullptr;
  708. return;
  709. }
  710. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  711. {
  712. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  713. return;
  714. if (portIndex < fPorts.indexOffset || ! fUI.isVisible)
  715. return;
  716. if (fDescriptor->ui_set_parameter_value == nullptr)
  717. return;
  718. const float value(*(const float*)buffer);
  719. fDescriptor->ui_set_parameter_value(fHandle, portIndex-fPorts.indexOffset, value);
  720. }
  721. // ----------------------------------------------------------------------------------------------------------------
  722. void lv2ui_select_program(uint32_t bank, uint32_t program) const
  723. {
  724. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  725. return;
  726. if (fDescriptor->ui_set_midi_program == nullptr)
  727. return;
  728. fDescriptor->ui_set_midi_program(fHandle, 0, bank, program);
  729. }
  730. // ----------------------------------------------------------------------------------------------------------------
  731. protected:
  732. void handleUiRun() const override
  733. {
  734. if (fDescriptor->ui_idle != nullptr)
  735. fDescriptor->ui_idle(fHandle);
  736. }
  737. void handleUiShow() override
  738. {
  739. if (fDescriptor->ui_show != nullptr)
  740. fDescriptor->ui_show(fHandle, true);
  741. fUI.isVisible = true;
  742. }
  743. void handleUiHide() override
  744. {
  745. if (fDescriptor->ui_show != nullptr)
  746. fDescriptor->ui_show(fHandle, false);
  747. fUI.isVisible = false;
  748. }
  749. // ----------------------------------------------------------------------------------------------------------------
  750. void handleParameterValueChanged(const uint32_t index, const float value) override
  751. {
  752. fDescriptor->set_parameter_value(fHandle, index, value);
  753. }
  754. void handleBufferSizeChanged(const uint32_t bufferSize) override
  755. {
  756. if (fDescriptor->dispatcher == nullptr)
  757. return;
  758. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, bufferSize, nullptr, 0.0f);
  759. }
  760. void handleSampleRateChanged(const double sampleRate) override
  761. {
  762. if (fDescriptor->dispatcher == nullptr)
  763. return;
  764. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)sampleRate);
  765. }
  766. // ----------------------------------------------------------------------------------------------------------------
  767. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  768. {
  769. CARLA_SAFE_ASSERT_RETURN(fPorts.numMidiOuts > 0, false);
  770. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  771. CARLA_SAFE_ASSERT_RETURN(event->size > 0, false);
  772. const uint8_t port(event->port);
  773. CARLA_SAFE_ASSERT_RETURN(port < fPorts.numMidiOuts, false);
  774. LV2_Atom_Sequence* const seq(fPorts.eventsOut[port]);
  775. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  776. Ports::EventsOutData& mData(fPorts.eventsOutData[port]);
  777. if (sizeof(LV2_Atom_Event) + event->size > mData.capacity - mData.offset)
  778. return false;
  779. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  780. aev->time.frames = event->time;
  781. aev->body.size = event->size;
  782. aev->body.type = fURIs.midiEvent;
  783. std::memcpy(LV2_ATOM_BODY(&aev->body), event->data, event->size);
  784. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + event->size));
  785. mData.offset += size;
  786. seq->atom.size += size;
  787. return true;
  788. }
  789. void handleUiParameterChanged(const uint32_t index, const float value) const
  790. {
  791. if (kIgnoreParameters || fWorkerUISignal)
  792. return;
  793. if (fUI.writeFunction != nullptr && fUI.controller != nullptr)
  794. fUI.writeFunction(fUI.controller, index+fPorts.indexOffset, sizeof(float), 0, &value);
  795. }
  796. void handleUiParameterTouch(const uint32_t index, const bool touch) const
  797. {
  798. if (kIgnoreParameters)
  799. return;
  800. if (fUI.touch != nullptr && fUI.touch->touch != nullptr)
  801. fUI.touch->touch(fUI.touch->handle, index+fPorts.indexOffset, touch);
  802. }
  803. void handleUiResize(const uint32_t, const uint32_t) const
  804. {
  805. // nothing here
  806. }
  807. void handlePreviewBufferData(const char type, const uint32_t size, const void* const buffer) noexcept
  808. {
  809. fPreviewData.type = type;
  810. fPreviewData.size = size;
  811. fPreviewData.buffer = buffer;
  812. fPreviewData.shouldSend = true;
  813. }
  814. void handleUiCustomDataChanged(const char* const key, const char* const value) const
  815. {
  816. carla_stdout("TODO: handleUiCustomDataChanged %s %s", key, value);
  817. //storeCustomData(key, value);
  818. if (fUI.writeFunction == nullptr || fUI.controller == nullptr)
  819. return;
  820. }
  821. void handleUiClosed()
  822. {
  823. fUI.isVisible = false;
  824. if (fWorkerUISignal)
  825. fWorkerUISignal = -1;
  826. if (fUI.host != nullptr && fUI.host->ui_closed != nullptr && fUI.controller != nullptr)
  827. fUI.host->ui_closed(fUI.controller);
  828. fUI.host = nullptr;
  829. fUI.touch = nullptr;
  830. fUI.writeFunction = nullptr;
  831. fUI.controller = nullptr;
  832. }
  833. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  834. {
  835. // TODO
  836. return nullptr;
  837. }
  838. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  839. {
  840. // TODO
  841. return nullptr;
  842. }
  843. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  844. {
  845. #ifdef DEBUG
  846. if (opcode != NATIVE_HOST_OPCODE_GET_FILE_PATH)
  847. {
  848. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)",
  849. opcode, index, value, ptr, static_cast<double>(opt));
  850. }
  851. #endif
  852. intptr_t ret = 0;
  853. switch (opcode)
  854. {
  855. case NATIVE_HOST_OPCODE_NULL:
  856. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  857. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  858. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  859. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  860. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  861. case NATIVE_HOST_OPCODE_HOST_IDLE:
  862. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  863. // nothing
  864. break;
  865. case NATIVE_HOST_OPCODE_REQUEST_IDLE:
  866. CARLA_SAFE_ASSERT_RETURN(fDescriptor->hints & NATIVE_PLUGIN_REQUESTS_IDLE, 0);
  867. if (fWorker != nullptr && fPluginNeedsIdle == 0)
  868. {
  869. fPluginNeedsIdle = 1;
  870. return 1;
  871. }
  872. return 0;
  873. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  874. if (fInlineDisplay != nullptr && fInlineDisplay->queue_draw != nullptr)
  875. {
  876. fInlineDisplay->queue_draw(fInlineDisplay->handle);
  877. return 1;
  878. }
  879. return 0;
  880. case NATIVE_HOST_OPCODE_GET_FILE_PATH:
  881. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  882. if (std::strcmp((char*)ptr, "carla") == 0 && fLastProjectPath != nullptr)
  883. return static_cast<intptr_t>((uintptr_t)fLastProjectPath.buffer());
  884. break;
  885. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  886. handleUiClosed();
  887. break;
  888. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  889. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  890. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  891. break;
  892. case NATIVE_HOST_OPCODE_UI_RESIZE:
  893. CARLA_SAFE_ASSERT_RETURN(index > 0, 0);
  894. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  895. handleUiResize(static_cast<uint32_t>(index), static_cast<uint32_t>(value));
  896. break;
  897. case NATIVE_HOST_OPCODE_PREVIEW_BUFFER_DATA:
  898. CARLA_SAFE_ASSERT_RETURN(index != 0, 0);
  899. CARLA_SAFE_ASSERT_RETURN(index >= 'a', 0);
  900. CARLA_SAFE_ASSERT_RETURN(index <= 'z', 0);
  901. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  902. CARLA_SAFE_ASSERT_RETURN(ptr != nullptr, 0);
  903. handlePreviewBufferData(static_cast<char>(index), static_cast<uint32_t>(value), (const void*)ptr);
  904. break;
  905. }
  906. return ret;
  907. // unused for now
  908. (void)opt;
  909. }
  910. void updateParameterOutputs()
  911. {
  912. float value;
  913. for (uint32_t i=0; i < fPorts.numParams; ++i)
  914. {
  915. if (! fPorts.paramsOut[i])
  916. continue;
  917. fPorts.paramsLast[i] = value = fDescriptor->get_parameter_value(fHandle, i);
  918. if (fPorts.paramsPtr[i] != nullptr)
  919. *fPorts.paramsPtr[i] = value;
  920. }
  921. }
  922. // -------------------------------------------------------------------
  923. private:
  924. // Native data
  925. NativePluginHandle fHandle;
  926. NativeHostDescriptor fHost;
  927. const NativePluginDescriptor* const fDescriptor;
  928. LV2_Program_Descriptor fProgramDesc;
  929. // carla as plugin does not implement lv2 parameter API yet, needed for feedback
  930. const bool kIgnoreParameters;
  931. LV2_Atom_Forge fAtomForge;
  932. uint32_t fMidiEventCount;
  933. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  934. CarlaString fLastProjectPath;
  935. CarlaString fLoadedFile;
  936. PreviewData fPreviewData;
  937. volatile bool fNeedsNotifyFileChanged;
  938. volatile int fPluginNeedsIdle;
  939. int fWorkerUISignal;
  940. // -1 needs close, 0 idle, 1 stuff is writing??
  941. // -------------------------------------------------------------------
  942. #define handlePtr ((NativePlugin*)handle)
  943. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  944. {
  945. return handlePtr->fBufferSize;
  946. }
  947. static double host_get_sample_rate(NativeHostHandle handle)
  948. {
  949. return handlePtr->fSampleRate;
  950. }
  951. static bool host_is_offline(NativeHostHandle handle)
  952. {
  953. return handlePtr->fIsOffline;
  954. }
  955. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  956. {
  957. return &(handlePtr->fTimeInfo);
  958. }
  959. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  960. {
  961. return handlePtr->handleWriteMidiEvent(event);
  962. }
  963. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  964. {
  965. handlePtr->handleUiParameterChanged(index, value);
  966. }
  967. static void host_ui_parameter_touch(NativeHostHandle handle, uint32_t index, bool touch)
  968. {
  969. handlePtr->handleUiParameterTouch(index, touch);
  970. }
  971. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  972. {
  973. handlePtr->handleUiCustomDataChanged(key, value);
  974. }
  975. static void host_ui_closed(NativeHostHandle handle)
  976. {
  977. handlePtr->handleUiClosed();
  978. }
  979. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  980. {
  981. return handlePtr->handleUiOpenFile(isDir, title, filter);
  982. }
  983. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  984. {
  985. return handlePtr->handleUiSaveFile(isDir, title, filter);
  986. }
  987. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  988. {
  989. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  990. }
  991. #undef handlePtr
  992. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  993. };
  994. // -----------------------------------------------------------------------
  995. // LV2 plugin descriptor functions
  996. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  997. {
  998. carla_debug("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  999. const NativePluginDescriptor* pluginDesc = nullptr;
  1000. const char* pluginLabel = nullptr;
  1001. if (std::strncmp(lv2Descriptor->URI, "http://kxstudio.sf.net/carla/plugins/", 37) == 0)
  1002. pluginLabel = lv2Descriptor->URI+37;
  1003. if (pluginLabel == nullptr)
  1004. {
  1005. carla_stderr("Failed to find carla native plugin with URI \"%s\"", lv2Descriptor->URI);
  1006. return nullptr;
  1007. }
  1008. carla_debug("lv2_instantiate() - looking up label \"%s\"", pluginLabel);
  1009. PluginListManager& plm(PluginListManager::getInstance());
  1010. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  1011. {
  1012. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  1013. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  1014. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  1015. {
  1016. pluginDesc = tmpDesc;
  1017. break;
  1018. }
  1019. }
  1020. if (pluginDesc == nullptr)
  1021. {
  1022. carla_stderr("Failed to find carla native plugin with label \"%s\"", pluginLabel);
  1023. return nullptr;
  1024. }
  1025. NativePlugin* const plugin(new NativePlugin(pluginDesc, sampleRate, bundlePath, features));
  1026. if (! plugin->init())
  1027. {
  1028. carla_stderr("Failed to init plugin");
  1029. delete plugin;
  1030. return nullptr;
  1031. }
  1032. return (LV2_Handle)plugin;
  1033. }
  1034. #define instancePtr ((NativePlugin*)instance)
  1035. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  1036. {
  1037. instancePtr->lv2_connect_port(port, dataLocation);
  1038. }
  1039. static void lv2_activate(LV2_Handle instance)
  1040. {
  1041. carla_debug("lv2_activate(%p)", instance);
  1042. instancePtr->lv2_activate();
  1043. }
  1044. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  1045. {
  1046. instancePtr->lv2_run(sampleCount);
  1047. }
  1048. static void lv2_deactivate(LV2_Handle instance)
  1049. {
  1050. carla_debug("lv2_deactivate(%p)", instance);
  1051. instancePtr->lv2_deactivate();
  1052. }
  1053. static void lv2_cleanup(LV2_Handle instance)
  1054. {
  1055. carla_debug("lv2_cleanup(%p)", instance);
  1056. instancePtr->lv2_cleanup();
  1057. delete instancePtr;
  1058. }
  1059. static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options)
  1060. {
  1061. carla_debug("lv2_get_options(%p, %p)", instance, options);
  1062. return instancePtr->lv2_get_options(options);
  1063. }
  1064. static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options)
  1065. {
  1066. carla_debug("lv2_set_options(%p, %p)", instance, options);
  1067. return instancePtr->lv2_set_options(options);
  1068. }
  1069. static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index)
  1070. {
  1071. carla_debug("lv2_get_program(%p, %i)", instance, index);
  1072. return instancePtr->lv2_get_program(index);
  1073. }
  1074. static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program)
  1075. {
  1076. carla_debug("lv2_select_program(%p, %i, %i)", instance, bank, program);
  1077. return instancePtr->lv2_select_program(bank, program);
  1078. }
  1079. 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)
  1080. {
  1081. carla_debug("lv2_save(%p, %p, %p, %i, %p)", instance, store, handle, flags, features);
  1082. return instancePtr->lv2_save(store, handle, flags, features);
  1083. }
  1084. 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)
  1085. {
  1086. carla_debug("lv2_restore(%p, %p, %p, %i, %p)", instance, retrieve, handle, flags, features);
  1087. return instancePtr->lv2_restore(retrieve, handle, flags, features);
  1088. }
  1089. 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)
  1090. {
  1091. carla_debug("work(%p, %p, %p, %u, %p)", instance, respond, handle, size, data);
  1092. return instancePtr->lv2_work(respond, handle, size, data);
  1093. }
  1094. static LV2_Worker_Status lv2_work_resp(LV2_Handle instance, uint32_t size, const void* body)
  1095. {
  1096. carla_debug("work_resp(%p, %u, %p)", instance, size, body);
  1097. return instancePtr->lv2_work_resp(size, body);
  1098. }
  1099. static const LV2_Inline_Display_Image_Surface* lv2_idisp_render(LV2_Handle instance, uint32_t w, uint32_t h)
  1100. {
  1101. // carla_debug("lv2_idisp_render(%p, %u, %u)", instance, w, h);
  1102. return instancePtr->lv2_idisp_render(w, h);
  1103. }
  1104. static const void* lv2_extension_data(const char* uri)
  1105. {
  1106. carla_debug("lv2_extension_data(\"%s\")", uri);
  1107. static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options };
  1108. static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program };
  1109. static const LV2_State_Interface state = { lv2_save, lv2_restore };
  1110. static const LV2_Worker_Interface worker = { lv2_work, lv2_work_resp, nullptr };
  1111. static const LV2_Inline_Display_Interface idisp = { lv2_idisp_render };
  1112. if (std::strcmp(uri, LV2_OPTIONS__interface) == 0)
  1113. return &options;
  1114. if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0)
  1115. return &programs;
  1116. if (std::strcmp(uri, LV2_STATE__interface) == 0)
  1117. return &state;
  1118. if (std::strcmp(uri, LV2_WORKER__interface) == 0)
  1119. return &worker;
  1120. if (std::strcmp(uri, LV2_INLINEDISPLAY__interface) == 0)
  1121. return &idisp;
  1122. return nullptr;
  1123. }
  1124. #undef instancePtr
  1125. #ifdef HAVE_PYQT
  1126. // -----------------------------------------------------------------------
  1127. // LV2 UI descriptor functions
  1128. static LV2UI_Handle lv2ui_instantiate(const LV2UI_Descriptor*, const char*, const char*,
  1129. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  1130. LV2UI_Widget* widget, const LV2_Feature* const* features)
  1131. {
  1132. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  1133. NativePlugin* plugin = nullptr;
  1134. for (int i=0; features[i] != nullptr; ++i)
  1135. {
  1136. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  1137. {
  1138. plugin = (NativePlugin*)features[i]->data;
  1139. break;
  1140. }
  1141. }
  1142. if (plugin == nullptr)
  1143. {
  1144. carla_stderr("Host doesn't support instance-access, cannot show UI");
  1145. return nullptr;
  1146. }
  1147. plugin->lv2ui_instantiate(writeFunction, controller, widget, features);
  1148. return (LV2UI_Handle)plugin;
  1149. }
  1150. #define uiPtr ((NativePlugin*)ui)
  1151. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  1152. {
  1153. carla_debug("lv2ui_port_event(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  1154. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  1155. }
  1156. static void lv2ui_cleanup(LV2UI_Handle ui)
  1157. {
  1158. carla_debug("lv2ui_cleanup(%p)", ui);
  1159. uiPtr->lv2ui_cleanup();
  1160. }
  1161. static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program)
  1162. {
  1163. carla_debug("lv2ui_select_program(%p, %i, %i)", ui, bank, program);
  1164. uiPtr->lv2ui_select_program(bank, program);
  1165. }
  1166. static int lv2ui_idle(LV2UI_Handle ui)
  1167. {
  1168. return uiPtr->lv2ui_idle();
  1169. }
  1170. static int lv2ui_show(LV2UI_Handle ui)
  1171. {
  1172. carla_debug("lv2ui_show(%p)", ui);
  1173. return uiPtr->lv2ui_show();
  1174. }
  1175. static int lv2ui_hide(LV2UI_Handle ui)
  1176. {
  1177. carla_debug("lv2ui_hide(%p)", ui);
  1178. return uiPtr->lv2ui_hide();
  1179. }
  1180. static const void* lv2ui_extension_data(const char* uri)
  1181. {
  1182. carla_stdout("lv2ui_extension_data(\"%s\")", uri);
  1183. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  1184. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  1185. static const LV2_Programs_UI_Interface uiprograms = { lv2ui_select_program };
  1186. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  1187. return &uiidle;
  1188. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  1189. return &uishow;
  1190. if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0)
  1191. return &uiprograms;
  1192. return nullptr;
  1193. }
  1194. #endif
  1195. #undef uiPtr
  1196. // -----------------------------------------------------------------------
  1197. // Startup code
  1198. CARLA_PLUGIN_EXPORT
  1199. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  1200. {
  1201. carla_debug("lv2_descriptor(%i)", index);
  1202. PluginListManager& plm(PluginListManager::getInstance());
  1203. if (index >= plm.descs.count())
  1204. {
  1205. carla_debug("lv2_descriptor(%i) - out of bounds", index);
  1206. return nullptr;
  1207. }
  1208. if (index < plm.lv2Descs.count())
  1209. {
  1210. carla_debug("lv2_descriptor(%i) - found previously allocated", index);
  1211. return plm.lv2Descs.getAt(index, nullptr);
  1212. }
  1213. const NativePluginDescriptor* const pluginDesc(plm.descs.getAt(index, nullptr));
  1214. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, nullptr);
  1215. CarlaString tmpURI;
  1216. tmpURI = "http://kxstudio.sf.net/carla/plugins/";
  1217. tmpURI += pluginDesc->label;
  1218. carla_debug("lv2_descriptor(%i) - not found, allocating new with uri \"%s\"", index, (const char*)tmpURI);
  1219. const LV2_Descriptor lv2DescTmp = {
  1220. /* URI */ carla_strdup(tmpURI),
  1221. /* instantiate */ lv2_instantiate,
  1222. /* connect_port */ lv2_connect_port,
  1223. /* activate */ lv2_activate,
  1224. /* run */ lv2_run,
  1225. /* deactivate */ lv2_deactivate,
  1226. /* cleanup */ lv2_cleanup,
  1227. /* extension_data */ lv2_extension_data
  1228. };
  1229. LV2_Descriptor* lv2Desc;
  1230. try {
  1231. lv2Desc = new LV2_Descriptor;
  1232. } CARLA_SAFE_EXCEPTION_RETURN("new LV2_Descriptor", nullptr);
  1233. std::memcpy(lv2Desc, &lv2DescTmp, sizeof(LV2_Descriptor));
  1234. plm.lv2Descs.append(lv2Desc);
  1235. return lv2Desc;
  1236. }
  1237. #ifdef HAVE_PYQT
  1238. CARLA_PLUGIN_EXPORT
  1239. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  1240. {
  1241. carla_debug("lv2ui_descriptor(%i)", index);
  1242. static const LV2UI_Descriptor lv2UiExtDesc = {
  1243. /* URI */ "http://kxstudio.sf.net/carla/ui-ext",
  1244. /* instantiate */ lv2ui_instantiate,
  1245. /* cleanup */ lv2ui_cleanup,
  1246. /* port_event */ lv2ui_port_event,
  1247. /* extension_data */ lv2ui_extension_data
  1248. };
  1249. return (index == 0) ? &lv2UiExtDesc : nullptr;
  1250. }
  1251. #endif
  1252. // -----------------------------------------------------------------------