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.

1858 lines
64KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2014 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 "CarlaString.hpp"
  22. // -----------------------------------------------------------------------
  23. // -Weffc++ compat ext widget
  24. extern "C" {
  25. typedef struct _LV2_External_UI_Widget_Compat {
  26. void (*run )(struct _LV2_External_UI_Widget_Compat*);
  27. void (*show)(struct _LV2_External_UI_Widget_Compat*);
  28. void (*hide)(struct _LV2_External_UI_Widget_Compat*);
  29. _LV2_External_UI_Widget_Compat() noexcept
  30. : run(nullptr), show(nullptr), hide(nullptr) {}
  31. } LV2_External_UI_Widget_Compat;
  32. }
  33. // -----------------------------------------------------------------------
  34. // LV2 descriptor functions
  35. #if defined(__clang__)
  36. # pragma clang diagnostic push
  37. # pragma clang diagnostic ignored "-Weffc++"
  38. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  39. # pragma GCC diagnostic push
  40. # pragma GCC diagnostic ignored "-Weffc++"
  41. #endif
  42. class NativePlugin : public LV2_External_UI_Widget_Compat
  43. {
  44. #if defined(__clang__)
  45. # pragma clang diagnostic pop
  46. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  47. # pragma GCC diagnostic pop
  48. #endif
  49. public:
  50. static const uint32_t kMaxMidiEvents = 512;
  51. NativePlugin(const NativePluginDescriptor* const desc, const double sampleRate, const char* const bundlePath, const LV2_Feature* const* features)
  52. : fHandle(nullptr),
  53. fHost(),
  54. fDescriptor(desc),
  55. #ifdef CARLA_PROPER_CPP11_SUPPORT
  56. fProgramDesc({0, 0, nullptr}),
  57. #endif
  58. fMidiEventCount(0),
  59. fTimeInfo(),
  60. fIsOffline(false),
  61. fBufferSize(0),
  62. fSampleRate(sampleRate),
  63. fUsingNominal(false),
  64. fUridMap(nullptr),
  65. fLastPositionData(),
  66. fURIs(),
  67. fUI(),
  68. fPorts()
  69. {
  70. run = extui_run;
  71. show = extui_show;
  72. hide = extui_hide;
  73. CarlaString resourceDir(bundlePath);
  74. resourceDir += CARLA_OS_SEP_STR "resources" CARLA_OS_SEP_STR;
  75. fHost.handle = this;
  76. fHost.resourceDir = resourceDir.dup();
  77. fHost.uiName = nullptr;
  78. fHost.uiParentId = 0;
  79. fHost.get_buffer_size = host_get_buffer_size;
  80. fHost.get_sample_rate = host_get_sample_rate;
  81. fHost.is_offline = host_is_offline;
  82. fHost.get_time_info = host_get_time_info;
  83. fHost.write_midi_event = host_write_midi_event;
  84. fHost.ui_parameter_changed = host_ui_parameter_changed;
  85. fHost.ui_custom_data_changed = host_ui_custom_data_changed;
  86. fHost.ui_closed = host_ui_closed;
  87. fHost.ui_open_file = host_ui_open_file;
  88. fHost.ui_save_file = host_ui_save_file;
  89. fHost.dispatcher = host_dispatcher;
  90. const LV2_Options_Option* options = nullptr;
  91. const LV2_URID_Map* uridMap = nullptr;
  92. const LV2_URID_Unmap* uridUnmap = nullptr;
  93. for (int i=0; features[i] != nullptr; ++i)
  94. {
  95. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) == 0)
  96. options = (const LV2_Options_Option*)features[i]->data;
  97. else if (std::strcmp(features[i]->URI, LV2_URID__map) == 0)
  98. uridMap = (const LV2_URID_Map*)features[i]->data;
  99. else if (std::strcmp(features[i]->URI, LV2_URID__unmap) == 0)
  100. uridUnmap = (const LV2_URID_Unmap*)features[i]->data;
  101. }
  102. if (options == nullptr || uridMap == nullptr)
  103. {
  104. carla_stderr("Host doesn't provide option or urid-map features");
  105. return;
  106. }
  107. for (int i=0; options[i].key != 0; ++i)
  108. {
  109. if (uridUnmap != nullptr)
  110. {
  111. carla_debug("Host option %i:\"%s\"", i, uridUnmap->unmap(uridUnmap->handle, options[i].key));
  112. }
  113. if (options[i].key == uridMap->map(uridMap->handle, LV2_BUF_SIZE__nominalBlockLength))
  114. {
  115. if (options[i].type == uridMap->map(uridMap->handle, LV2_ATOM__Int))
  116. {
  117. const int value(*(const int*)options[i].value);
  118. CARLA_SAFE_ASSERT_CONTINUE(value > 0);
  119. fBufferSize = static_cast<uint32_t>(value);
  120. fUsingNominal = true;
  121. }
  122. else
  123. {
  124. carla_stderr("Host provides nominalBlockLength but has wrong value type");
  125. }
  126. break;
  127. }
  128. if (options[i].key == uridMap->map(uridMap->handle, LV2_BUF_SIZE__maxBlockLength))
  129. {
  130. if (options[i].type == uridMap->map(uridMap->handle, LV2_ATOM__Int))
  131. {
  132. const int value(*(const int*)options[i].value);
  133. CARLA_SAFE_ASSERT_CONTINUE(value > 0);
  134. fBufferSize = static_cast<uint32_t>(value);
  135. }
  136. else
  137. {
  138. carla_stderr("Host provides maxBlockLength but has wrong value type");
  139. }
  140. // no break, continue in case host supports nominalBlockLength
  141. }
  142. }
  143. fUridMap = uridMap;
  144. }
  145. ~NativePlugin()
  146. {
  147. CARLA_ASSERT(fHandle == nullptr);
  148. if (fHost.resourceDir != nullptr)
  149. {
  150. delete[] fHost.resourceDir;
  151. fHost.resourceDir = nullptr;
  152. }
  153. }
  154. bool init()
  155. {
  156. if (fUridMap == nullptr)
  157. {
  158. // host is missing features
  159. return false;
  160. }
  161. if (fDescriptor->instantiate == nullptr || fDescriptor->process == nullptr)
  162. {
  163. carla_stderr("Plugin is missing something...");
  164. return false;
  165. }
  166. if (fBufferSize == 0)
  167. {
  168. carla_stderr("Host is missing bufferSize feature");
  169. //return false;
  170. // as testing, continue for now
  171. fBufferSize = 1024;
  172. }
  173. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  174. carla_zeroStruct(fTimeInfo);
  175. fHandle = fDescriptor->instantiate(&fHost);
  176. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, false);
  177. if (fDescriptor->midiIns > 0)
  178. fUI.portOffset += fDescriptor->midiIns;
  179. else if (fDescriptor->hints & NATIVE_PLUGIN_USES_TIME)
  180. fUI.portOffset += 1;
  181. fUI.portOffset += fDescriptor->midiOuts;
  182. fUI.portOffset += 1; // freewheel
  183. fUI.portOffset += fDescriptor->audioIns;
  184. fUI.portOffset += fDescriptor->audioOuts;
  185. fPorts.init(fDescriptor, fHandle);
  186. fURIs.map(fUridMap);
  187. return true;
  188. }
  189. // -------------------------------------------------------------------
  190. // LV2 functions
  191. void lv2_connect_port(const uint32_t port, void* const dataLocation)
  192. {
  193. fPorts.connectPort(fDescriptor, port, dataLocation);
  194. }
  195. void lv2_activate()
  196. {
  197. if (fDescriptor->activate != nullptr)
  198. fDescriptor->activate(fHandle);
  199. carla_zeroStruct(fTimeInfo);
  200. // hosts may not send all values, resulting on some invalid data
  201. fTimeInfo.bbt.bar = 1;
  202. fTimeInfo.bbt.beat = 1;
  203. fTimeInfo.bbt.tick = 0;
  204. fTimeInfo.bbt.barStartTick = 0;
  205. fTimeInfo.bbt.beatsPerBar = 4;
  206. fTimeInfo.bbt.beatType = 4;
  207. fTimeInfo.bbt.ticksPerBeat = 960.0;
  208. fTimeInfo.bbt.beatsPerMinute = 120.0;
  209. }
  210. void lv2_deactivate()
  211. {
  212. if (fDescriptor->deactivate != nullptr)
  213. fDescriptor->deactivate(fHandle);
  214. }
  215. void lv2_cleanup()
  216. {
  217. if (fDescriptor->cleanup != nullptr)
  218. fDescriptor->cleanup(fHandle);
  219. fHandle = nullptr;
  220. }
  221. void lv2_run(const uint32_t frames)
  222. {
  223. fIsOffline = (fPorts.freewheel != nullptr && *fPorts.freewheel >= 0.5f);
  224. // cache midi events and time information first
  225. if (fDescriptor->midiIns > 0 || (fDescriptor->hints & NATIVE_PLUGIN_USES_TIME) != 0)
  226. {
  227. fMidiEventCount = 0;
  228. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  229. if (fDescriptor->hints & NATIVE_PLUGIN_USES_TIME)
  230. {
  231. LV2_ATOM_SEQUENCE_FOREACH(fPorts.eventsIn[0], event)
  232. {
  233. if (event == nullptr)
  234. continue;
  235. if (event->body.type != fURIs.atomBlank && event->body.type != fURIs.atomObject)
  236. continue;
  237. const LV2_Atom_Object* const obj((const LV2_Atom_Object*)&event->body);
  238. if (obj->body.otype != fURIs.timePos)
  239. continue;
  240. LV2_Atom* bar = nullptr;
  241. LV2_Atom* barBeat = nullptr;
  242. LV2_Atom* beatUnit = nullptr;
  243. LV2_Atom* beatsPerBar = nullptr;
  244. LV2_Atom* beatsPerMinute = nullptr;
  245. LV2_Atom* frame = nullptr;
  246. LV2_Atom* speed = nullptr;
  247. LV2_Atom* ticksPerBeat = nullptr;
  248. lv2_atom_object_get(obj,
  249. fURIs.timeBar, &bar,
  250. fURIs.timeBarBeat, &barBeat,
  251. fURIs.timeBeatUnit, &beatUnit,
  252. fURIs.timeBeatsPerBar, &beatsPerBar,
  253. fURIs.timeBeatsPerMinute, &beatsPerMinute,
  254. fURIs.timeFrame, &frame,
  255. fURIs.timeSpeed, &speed,
  256. fURIs.timeTicksPerBeat, &ticksPerBeat,
  257. 0);
  258. // need to handle this first as other values depend on it
  259. if (ticksPerBeat != nullptr)
  260. {
  261. double ticksPerBeatValue = -1.0;
  262. /**/ if (ticksPerBeat->type == fURIs.atomDouble)
  263. ticksPerBeatValue = ((LV2_Atom_Double*)ticksPerBeat)->body;
  264. else if (ticksPerBeat->type == fURIs.atomFloat)
  265. ticksPerBeatValue = ((LV2_Atom_Float*)ticksPerBeat)->body;
  266. else if (ticksPerBeat->type == fURIs.atomInt)
  267. ticksPerBeatValue = static_cast<double>(((LV2_Atom_Int*)ticksPerBeat)->body);
  268. else if (ticksPerBeat->type == fURIs.atomLong)
  269. ticksPerBeatValue = static_cast<double>(((LV2_Atom_Long*)ticksPerBeat)->body);
  270. else
  271. carla_stderr("Unknown lv2 ticksPerBeat value type");
  272. if (ticksPerBeatValue > 0.0)
  273. fTimeInfo.bbt.ticksPerBeat = fLastPositionData.ticksPerBeat = ticksPerBeatValue;
  274. else
  275. carla_stderr("Invalid lv2 ticksPerBeat value");
  276. }
  277. // same
  278. if (speed != nullptr)
  279. {
  280. /**/ if (speed->type == fURIs.atomDouble)
  281. fLastPositionData.speed = ((LV2_Atom_Double*)speed)->body;
  282. else if (speed->type == fURIs.atomFloat)
  283. fLastPositionData.speed = ((LV2_Atom_Float*)speed)->body;
  284. else if (speed->type == fURIs.atomInt)
  285. fLastPositionData.speed = static_cast<double>(((LV2_Atom_Int*)speed)->body);
  286. else if (speed->type == fURIs.atomLong)
  287. fLastPositionData.speed = static_cast<double>(((LV2_Atom_Long*)speed)->body);
  288. else
  289. carla_stderr("Unknown lv2 speed value type");
  290. fTimeInfo.playing = carla_isNotZero(fLastPositionData.speed);
  291. if (fTimeInfo.playing && fLastPositionData.beatsPerMinute > 0.0f)
  292. {
  293. fTimeInfo.bbt.beatsPerMinute = fLastPositionData.beatsPerMinute*
  294. std::abs(fLastPositionData.speed);
  295. }
  296. }
  297. if (bar != nullptr)
  298. {
  299. int64_t barValue = -1;
  300. /**/ if (bar->type == fURIs.atomDouble)
  301. barValue = static_cast<int64_t>(((LV2_Atom_Double*)bar)->body);
  302. else if (bar->type == fURIs.atomFloat)
  303. barValue = static_cast<int64_t>(((LV2_Atom_Float*)bar)->body);
  304. else if (bar->type == fURIs.atomInt)
  305. barValue = ((LV2_Atom_Int*)bar)->body;
  306. else if (bar->type == fURIs.atomLong)
  307. barValue = ((LV2_Atom_Long*)bar)->body;
  308. else
  309. carla_stderr("Unknown lv2 bar value type");
  310. if (barValue >= 0 && barValue < INT32_MAX)
  311. {
  312. fLastPositionData.bar = static_cast<int32_t>(barValue);
  313. fLastPositionData.bar_f = static_cast<float>(barValue);
  314. fTimeInfo.bbt.bar = fLastPositionData.bar + 1;
  315. }
  316. else
  317. {
  318. carla_stderr("Invalid lv2 bar value");
  319. }
  320. }
  321. if (barBeat != nullptr)
  322. {
  323. double barBeatValue = -1.0;
  324. /**/ if (barBeat->type == fURIs.atomDouble)
  325. barBeatValue = ((LV2_Atom_Double*)barBeat)->body;
  326. else if (barBeat->type == fURIs.atomFloat)
  327. barBeatValue = ((LV2_Atom_Float*)barBeat)->body;
  328. else if (barBeat->type == fURIs.atomInt)
  329. barBeatValue = static_cast<float>(((LV2_Atom_Int*)barBeat)->body);
  330. else if (barBeat->type == fURIs.atomLong)
  331. barBeatValue = static_cast<float>(((LV2_Atom_Long*)barBeat)->body);
  332. else
  333. carla_stderr("Unknown lv2 barBeat value type");
  334. if (barBeatValue >= 0.0)
  335. {
  336. fLastPositionData.barBeat = static_cast<float>(barBeatValue);
  337. const double rest = std::fmod(barBeatValue, 1.0);
  338. fTimeInfo.bbt.beat = static_cast<int32_t>(barBeatValue-rest+1.0);
  339. fTimeInfo.bbt.tick = static_cast<int32_t>(rest*fTimeInfo.bbt.ticksPerBeat+0.5);
  340. }
  341. else
  342. {
  343. carla_stderr("Invalid lv2 barBeat value");
  344. }
  345. }
  346. if (beatUnit != nullptr)
  347. {
  348. int64_t beatUnitValue = -1;
  349. /**/ if (beatUnit->type == fURIs.atomDouble)
  350. beatUnitValue = static_cast<int64_t>(((LV2_Atom_Double*)beatUnit)->body);
  351. else if (beatUnit->type == fURIs.atomFloat)
  352. beatUnitValue = static_cast<int64_t>(((LV2_Atom_Float*)beatUnit)->body);
  353. else if (beatUnit->type == fURIs.atomInt)
  354. beatUnitValue = ((LV2_Atom_Int*)beatUnit)->body;
  355. else if (beatUnit->type == fURIs.atomLong)
  356. beatUnitValue = ((LV2_Atom_Long*)beatUnit)->body;
  357. else
  358. carla_stderr("Unknown lv2 beatUnit value type");
  359. if (beatUnitValue > 0 && beatUnitValue < UINT32_MAX)
  360. {
  361. fLastPositionData.beatUnit = static_cast<uint32_t>(beatUnitValue);
  362. fTimeInfo.bbt.beatType = static_cast<float>(beatUnitValue);
  363. }
  364. else
  365. {
  366. carla_stderr("Invalid lv2 beatUnit value");
  367. }
  368. }
  369. if (beatsPerBar != nullptr)
  370. {
  371. float beatsPerBarValue = -1.0f;
  372. /**/ if (beatsPerBar->type == fURIs.atomDouble)
  373. beatsPerBarValue = static_cast<float>(((LV2_Atom_Double*)beatsPerBar)->body);
  374. else if (beatsPerBar->type == fURIs.atomFloat)
  375. beatsPerBarValue = ((LV2_Atom_Float*)beatsPerBar)->body;
  376. else if (beatsPerBar->type == fURIs.atomInt)
  377. beatsPerBarValue = static_cast<float>(((LV2_Atom_Int*)beatsPerBar)->body);
  378. else if (beatsPerBar->type == fURIs.atomLong)
  379. beatsPerBarValue = static_cast<float>(((LV2_Atom_Long*)beatsPerBar)->body);
  380. else
  381. carla_stderr("Unknown lv2 beatsPerBar value type");
  382. if (beatsPerBarValue > 0.0f)
  383. fTimeInfo.bbt.beatsPerBar = fLastPositionData.beatsPerBar = beatsPerBarValue;
  384. else
  385. carla_stderr("Invalid lv2 beatsPerBar value");
  386. }
  387. if (beatsPerMinute != nullptr)
  388. {
  389. double beatsPerMinuteValue = -1.0;
  390. /**/ if (beatsPerMinute->type == fURIs.atomDouble)
  391. beatsPerMinuteValue = ((LV2_Atom_Double*)beatsPerMinute)->body;
  392. else if (beatsPerMinute->type == fURIs.atomFloat)
  393. beatsPerMinuteValue = ((LV2_Atom_Float*)beatsPerMinute)->body;
  394. else if (beatsPerMinute->type == fURIs.atomInt)
  395. beatsPerMinuteValue = static_cast<double>(((LV2_Atom_Int*)beatsPerMinute)->body);
  396. else if (beatsPerMinute->type == fURIs.atomLong)
  397. beatsPerMinuteValue = static_cast<double>(((LV2_Atom_Long*)beatsPerMinute)->body);
  398. else
  399. carla_stderr("Unknown lv2 beatsPerMinute value type");
  400. if (beatsPerMinuteValue >= 12.0 && beatsPerMinuteValue <= 999.0)
  401. {
  402. fTimeInfo.bbt.beatsPerMinute = fLastPositionData.beatsPerMinute = beatsPerMinuteValue;
  403. if (carla_isNotZero(fLastPositionData.speed))
  404. fTimeInfo.bbt.beatsPerMinute *= std::abs(fLastPositionData.speed);
  405. }
  406. else
  407. {
  408. carla_stderr("Invalid lv2 beatsPerMinute value");
  409. }
  410. }
  411. if (frame != nullptr)
  412. {
  413. int64_t frameValue = -1;
  414. /**/ if (frame->type == fURIs.atomDouble)
  415. frameValue = static_cast<int64_t>(((LV2_Atom_Double*)frame)->body);
  416. else if (frame->type == fURIs.atomFloat)
  417. frameValue = static_cast<int64_t>(((LV2_Atom_Float*)frame)->body);
  418. else if (frame->type == fURIs.atomInt)
  419. frameValue = ((LV2_Atom_Int*)frame)->body;
  420. else if (frame->type == fURIs.atomLong)
  421. frameValue = ((LV2_Atom_Long*)frame)->body;
  422. else
  423. carla_stderr("Unknown lv2 frame value type");
  424. if (frameValue >= 0)
  425. fTimeInfo.frame = fLastPositionData.frame = static_cast<uint64_t>(frameValue);
  426. else
  427. carla_stderr("Invalid lv2 frame value");
  428. }
  429. fTimeInfo.bbt.barStartTick = fTimeInfo.bbt.ticksPerBeat*
  430. fTimeInfo.bbt.beatsPerBar*
  431. (fTimeInfo.bbt.bar-1);
  432. fTimeInfo.bbt.valid = (fLastPositionData.beatsPerMinute > 0.0 &&
  433. fLastPositionData.beatUnit > 0 &&
  434. fLastPositionData.beatsPerBar > 0.0f);
  435. }
  436. }
  437. for (uint32_t i=0; i < fDescriptor->midiIns; ++i)
  438. {
  439. LV2_ATOM_SEQUENCE_FOREACH(fPorts.eventsIn[i], event)
  440. {
  441. if (event == nullptr)
  442. continue;
  443. if (event->body.type != fURIs.midiEvent)
  444. continue;
  445. if (event->body.size > 4)
  446. continue;
  447. if (event->time.frames >= frames)
  448. break;
  449. if (fMidiEventCount >= kMaxMidiEvents)
  450. break;
  451. const uint8_t* const data((const uint8_t*)(event + 1));
  452. NativeMidiEvent& nativeEvent(fMidiEvents[fMidiEventCount++]);
  453. nativeEvent.port = (uint8_t)i;
  454. nativeEvent.size = (uint8_t)event->body.size;
  455. nativeEvent.time = (uint32_t)event->time.frames;
  456. uint32_t j=0;
  457. for (uint32_t size=event->body.size; j<size; ++j)
  458. nativeEvent.data[j] = data[j];
  459. for (; j<4; ++j)
  460. nativeEvent.data[j] = 0;
  461. }
  462. }
  463. }
  464. // init midi out data
  465. if (fDescriptor->midiOuts > 0)
  466. {
  467. for (uint32_t i=0, size=fDescriptor->midiOuts; i<size; ++i)
  468. {
  469. LV2_Atom_Sequence* const seq(fPorts.midiOuts[i]);
  470. CARLA_SAFE_ASSERT_CONTINUE(seq != nullptr);
  471. Ports::MidiOutData& mData(fPorts.midiOutData[i]);
  472. mData.capacity = seq->atom.size;
  473. mData.offset = 0;
  474. seq->atom.size = sizeof(LV2_Atom_Sequence_Body);
  475. seq->atom.type = fURIs.atomSequence;
  476. seq->body.unit = 0;
  477. seq->body.pad = 0;
  478. }
  479. }
  480. // Check for updated parameters
  481. float curValue;
  482. for (uint32_t i=0; i < fPorts.paramCount; ++i)
  483. {
  484. if (fPorts.paramsOut[i])
  485. continue;
  486. CARLA_SAFE_ASSERT_CONTINUE(fPorts.paramsPtr[i] != nullptr)
  487. curValue = *fPorts.paramsPtr[i];
  488. if (carla_isEqual(fPorts.paramsLast[i], curValue))
  489. continue;
  490. fPorts.paramsLast[i] = curValue;
  491. fDescriptor->set_parameter_value(fHandle, i, curValue);
  492. }
  493. if (frames == 0)
  494. return updateParameterOutputs();
  495. // FIXME
  496. fDescriptor->process(fHandle,
  497. const_cast<float**>(fPorts.audioIns), fPorts.audioOuts, frames,
  498. fMidiEvents, fMidiEventCount);
  499. // update timePos for next callback
  500. if (carla_isNotZero(fLastPositionData.speed))
  501. {
  502. if (fLastPositionData.speed > 0.0)
  503. {
  504. // playing forwards
  505. fLastPositionData.frame += frames;
  506. }
  507. else
  508. {
  509. // playing backwards
  510. if (frames >= fLastPositionData.frame)
  511. fLastPositionData.frame = 0;
  512. else
  513. fLastPositionData.frame -= frames;
  514. }
  515. fTimeInfo.frame = fLastPositionData.frame;
  516. if (fTimeInfo.bbt.valid)
  517. {
  518. const double beatsPerMinute = fLastPositionData.beatsPerMinute * fLastPositionData.speed;
  519. const double framesPerBeat = 60.0 * fSampleRate / beatsPerMinute;
  520. const double addedBarBeats = double(frames) / framesPerBeat;
  521. if (fLastPositionData.barBeat >= 0.0f)
  522. {
  523. fLastPositionData.barBeat = std::fmod(fLastPositionData.barBeat+static_cast<float>(addedBarBeats),
  524. fLastPositionData.beatsPerBar);
  525. const double rest = std::fmod(fLastPositionData.barBeat, 1.0f);
  526. fTimeInfo.bbt.beat = static_cast<int32_t>(fLastPositionData.barBeat-rest+1.0);
  527. fTimeInfo.bbt.tick = static_cast<int32_t>(rest*fTimeInfo.bbt.ticksPerBeat+0.5);
  528. if (fLastPositionData.bar_f >= 0.0f)
  529. {
  530. fLastPositionData.bar_f += std::floor((fLastPositionData.barBeat+static_cast<float>(addedBarBeats))/
  531. fLastPositionData.beatsPerBar);
  532. if (fLastPositionData.bar_f <= 0.0f)
  533. {
  534. fLastPositionData.bar = 0;
  535. fLastPositionData.bar_f = 0.0f;
  536. }
  537. else
  538. {
  539. fLastPositionData.bar = static_cast<int32_t>(fLastPositionData.bar_f+0.5f);
  540. }
  541. fTimeInfo.bbt.bar = fLastPositionData.bar + 1;
  542. fTimeInfo.bbt.barStartTick = fTimeInfo.bbt.ticksPerBeat*
  543. fTimeInfo.bbt.beatsPerBar*
  544. (fTimeInfo.bbt.bar-1);
  545. }
  546. }
  547. }
  548. }
  549. updateParameterOutputs();
  550. }
  551. // -------------------------------------------------------------------
  552. uint32_t lv2_get_options(LV2_Options_Option* const /*options*/) const
  553. {
  554. // currently unused
  555. return LV2_OPTIONS_SUCCESS;
  556. }
  557. uint32_t lv2_set_options(const LV2_Options_Option* const options)
  558. {
  559. for (int i=0; options[i].key != 0; ++i)
  560. {
  561. if (options[i].key == fUridMap->map(fUridMap->handle, LV2_BUF_SIZE__nominalBlockLength))
  562. {
  563. if (options[i].type == fURIs.atomInt)
  564. {
  565. const int value(*(const int*)options[i].value);
  566. CARLA_SAFE_ASSERT_CONTINUE(value > 0);
  567. fBufferSize = static_cast<uint32_t>(value);
  568. if (fDescriptor->dispatcher != nullptr)
  569. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, value, nullptr, 0.0f);
  570. }
  571. else
  572. carla_stderr("Host changed nominalBlockLength but with wrong value type");
  573. }
  574. else if (options[i].key == fUridMap->map(fUridMap->handle, LV2_BUF_SIZE__maxBlockLength) && ! fUsingNominal)
  575. {
  576. if (options[i].type == fURIs.atomInt)
  577. {
  578. const int value(*(const int*)options[i].value);
  579. CARLA_SAFE_ASSERT_CONTINUE(value > 0);
  580. fBufferSize = static_cast<uint32_t>(value);
  581. if (fDescriptor->dispatcher != nullptr)
  582. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, value, nullptr, 0.0f);
  583. }
  584. else
  585. carla_stderr("Host changed maxBlockLength but with wrong value type");
  586. }
  587. else if (options[i].key == fUridMap->map(fUridMap->handle, LV2_CORE__sampleRate))
  588. {
  589. if (options[i].type == fURIs.atomDouble)
  590. {
  591. const double value(*(const double*)options[i].value);
  592. CARLA_SAFE_ASSERT_CONTINUE(value > 0.0);
  593. fSampleRate = value;
  594. if (fDescriptor->dispatcher != nullptr)
  595. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)fSampleRate);
  596. }
  597. else
  598. carla_stderr("Host changed sampleRate but with wrong value type");
  599. }
  600. }
  601. return LV2_OPTIONS_SUCCESS;
  602. }
  603. const LV2_Program_Descriptor* lv2_get_program(const uint32_t index)
  604. {
  605. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  606. return nullptr;
  607. if (fDescriptor->get_midi_program_count == nullptr)
  608. return nullptr;
  609. if (fDescriptor->get_midi_program_info == nullptr)
  610. return nullptr;
  611. if (index >= fDescriptor->get_midi_program_count(fHandle))
  612. return nullptr;
  613. const NativeMidiProgram* const midiProg(fDescriptor->get_midi_program_info(fHandle, index));
  614. if (midiProg == nullptr)
  615. return nullptr;
  616. fProgramDesc.bank = midiProg->bank;
  617. fProgramDesc.program = midiProg->program;
  618. fProgramDesc.name = midiProg->name;
  619. return &fProgramDesc;
  620. }
  621. void lv2_select_program(uint32_t bank, uint32_t program)
  622. {
  623. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  624. return;
  625. if (fDescriptor->set_midi_program == nullptr)
  626. return;
  627. fDescriptor->set_midi_program(fHandle, 0, bank, program);
  628. for (uint32_t i=0; i < fPorts.paramCount; ++i)
  629. {
  630. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  631. if (fPorts.paramsPtr[i] != nullptr)
  632. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  633. }
  634. }
  635. LV2_State_Status lv2_save(const LV2_State_Store_Function store, const LV2_State_Handle handle, const uint32_t /*flags*/, const LV2_Feature* const* const /*features*/) const
  636. {
  637. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->get_state == nullptr)
  638. return LV2_STATE_ERR_NO_FEATURE;
  639. if (char* const state = fDescriptor->get_state(fHandle))
  640. {
  641. store(handle, fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"), state, std::strlen(state)+1, fURIs.atomString, LV2_STATE_IS_POD|LV2_STATE_IS_PORTABLE);
  642. std::free(state);
  643. return LV2_STATE_SUCCESS;
  644. }
  645. return LV2_STATE_ERR_UNKNOWN;
  646. }
  647. LV2_State_Status lv2_restore(const LV2_State_Retrieve_Function retrieve, const LV2_State_Handle handle, uint32_t flags, const LV2_Feature* const* const /*features*/) const
  648. {
  649. if ((fDescriptor->hints & NATIVE_PLUGIN_USES_STATE) == 0 || fDescriptor->set_state == nullptr)
  650. return LV2_STATE_ERR_NO_FEATURE;
  651. size_t size = 0;
  652. uint32_t type = 0;
  653. const void* const data = retrieve(handle, fUridMap->map(fUridMap->handle, "http://kxstudio.sf.net/ns/carla/chunk"), &size, &type, &flags);
  654. if (size == 0)
  655. return LV2_STATE_ERR_UNKNOWN;
  656. if (type == 0)
  657. return LV2_STATE_ERR_UNKNOWN;
  658. if (data == nullptr)
  659. return LV2_STATE_ERR_UNKNOWN;
  660. if (type != fURIs.atomString)
  661. return LV2_STATE_ERR_BAD_TYPE;
  662. fDescriptor->set_state(fHandle, (const char*)data);
  663. return LV2_STATE_SUCCESS;
  664. }
  665. // -------------------------------------------------------------------
  666. void lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  667. LV2UI_Widget* widget, const LV2_Feature* const* features, const bool isEmbed)
  668. {
  669. fUI.writeFunction = writeFunction;
  670. fUI.controller = controller;
  671. fUI.isEmbed = isEmbed;
  672. #ifdef CARLA_OS_LINUX
  673. // ---------------------------------------------------------------
  674. // show embed UI if needed
  675. if (isEmbed)
  676. {
  677. intptr_t parentId = 0;
  678. const LV2UI_Resize* uiResize = nullptr;
  679. for (int i=0; features[i] != nullptr; ++i)
  680. {
  681. if (std::strcmp(features[i]->URI, LV2_UI__parent) == 0)
  682. {
  683. parentId = (intptr_t)features[i]->data;
  684. }
  685. else if (std::strcmp(features[i]->URI, LV2_UI__resize) == 0)
  686. {
  687. uiResize = (const LV2UI_Resize*)features[i]->data;
  688. }
  689. }
  690. // -----------------------------------------------------------
  691. // see if the host can really embed the UI
  692. if (parentId != 0)
  693. {
  694. // wait for remote side to be ready
  695. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_NULL, (int32_t)0xDEADF00D, 0xC0C0B00B, nullptr, 0.0f);
  696. if (uiResize && uiResize->ui_resize != nullptr)
  697. uiResize->ui_resize(uiResize->handle, 740, 512);
  698. fHost.uiName = carla_strdup(fDescriptor->name);
  699. fUI.isVisible = true;
  700. char strBuf[0xff+1];
  701. strBuf[0xff] = '\0';
  702. std::snprintf(strBuf, 0xff, P_INTPTR, parentId);
  703. carla_setenv("CARLA_PLUGIN_EMBED_WINID", strBuf);
  704. fDescriptor->ui_show(fHandle, true);
  705. carla_setenv("CARLA_PLUGIN_EMBED_WINID", "0");
  706. const intptr_t winId(fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_NULL, (int32_t)0xDEADF00D, 0xC0C0B00B, nullptr, 0.0f));
  707. CARLA_SAFE_ASSERT_RETURN(winId != 0,);
  708. *widget = (LV2UI_Widget)winId;
  709. return;
  710. }
  711. }
  712. #endif
  713. // ---------------------------------------------------------------
  714. // see if the host supports external-ui
  715. for (int i=0; features[i] != nullptr; ++i)
  716. {
  717. if (std::strcmp(features[i]->URI, LV2_EXTERNAL_UI__Host) == 0 ||
  718. std::strcmp(features[i]->URI, LV2_EXTERNAL_UI_DEPRECATED_URI) == 0)
  719. {
  720. fUI.host = (const LV2_External_UI_Host*)features[i]->data;
  721. break;
  722. }
  723. }
  724. if (fUI.host != nullptr)
  725. {
  726. fHost.uiName = carla_strdup(fUI.host->plugin_human_id);
  727. *widget = (LV2_External_UI_Widget_Compat*)this;
  728. return;
  729. }
  730. // ---------------------------------------------------------------
  731. // no external-ui support, use showInterface
  732. for (int i=0; features[i] != nullptr; ++i)
  733. {
  734. if (std::strcmp(features[i]->URI, LV2_OPTIONS__options) == 0)
  735. {
  736. const LV2_Options_Option* const options((const LV2_Options_Option*)features[i]->data);
  737. for (int j=0; options[j].key != 0; ++j)
  738. {
  739. if (options[j].key == fUridMap->map(fUridMap->handle, LV2_UI__windowTitle))
  740. {
  741. fHost.uiName = carla_strdup((const char*)options[j].value);
  742. break;
  743. }
  744. }
  745. break;
  746. }
  747. }
  748. if (fHost.uiName == nullptr)
  749. fHost.uiName = carla_strdup(fDescriptor->name);
  750. *widget = nullptr;
  751. }
  752. void lv2ui_port_event(uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer) const
  753. {
  754. if (format != 0 || bufferSize != sizeof(float) || buffer == nullptr)
  755. return;
  756. if (portIndex >= fUI.portOffset || ! fUI.isVisible)
  757. return;
  758. if (fDescriptor->ui_set_parameter_value == nullptr)
  759. return;
  760. const float value(*(const float*)buffer);
  761. fDescriptor->ui_set_parameter_value(fHandle, portIndex-fUI.portOffset, value);
  762. }
  763. void lv2ui_cleanup()
  764. {
  765. if (fUI.isVisible)
  766. handleUiHide();
  767. fUI.host = nullptr;
  768. fUI.writeFunction = nullptr;
  769. fUI.controller = nullptr;
  770. if (fHost.uiName != nullptr)
  771. {
  772. delete[] fHost.uiName;
  773. fHost.uiName = nullptr;
  774. }
  775. }
  776. // -------------------------------------------------------------------
  777. void lv2ui_select_program(uint32_t bank, uint32_t program) const
  778. {
  779. if (fDescriptor->category == NATIVE_PLUGIN_CATEGORY_SYNTH)
  780. return;
  781. if (fDescriptor->ui_set_midi_program == nullptr)
  782. return;
  783. fDescriptor->ui_set_midi_program(fHandle, 0, bank, program);
  784. }
  785. // -------------------------------------------------------------------
  786. int lv2ui_idle() const
  787. {
  788. if (! fUI.isVisible)
  789. return 1;
  790. handleUiRun();
  791. return 0;
  792. }
  793. int lv2ui_show()
  794. {
  795. handleUiShow();
  796. return 0;
  797. }
  798. int lv2ui_hide()
  799. {
  800. handleUiHide();
  801. return 0;
  802. }
  803. // -------------------------------------------------------------------
  804. protected:
  805. void handleUiRun() const
  806. {
  807. if (fDescriptor->ui_idle != nullptr)
  808. fDescriptor->ui_idle(fHandle);
  809. }
  810. void handleUiShow()
  811. {
  812. if (fDescriptor->ui_show != nullptr)
  813. fDescriptor->ui_show(fHandle, true);
  814. fUI.isVisible = true;
  815. }
  816. void handleUiHide()
  817. {
  818. if (fDescriptor->ui_show != nullptr)
  819. fDescriptor->ui_show(fHandle, false);
  820. fUI.isVisible = false;
  821. }
  822. // -------------------------------------------------------------------
  823. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  824. {
  825. CARLA_SAFE_ASSERT_RETURN(fDescriptor->midiOuts > 0, false);
  826. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  827. CARLA_SAFE_ASSERT_RETURN(event->size > 0, false);
  828. const uint8_t port(event->port);
  829. CARLA_SAFE_ASSERT_RETURN(port < fDescriptor->midiOuts, false);
  830. LV2_Atom_Sequence* const seq(fPorts.midiOuts[port]);
  831. CARLA_SAFE_ASSERT_RETURN(seq != nullptr, false);
  832. Ports::MidiOutData& mData(fPorts.midiOutData[port]);
  833. if (sizeof(LV2_Atom_Event) + event->size > mData.capacity - mData.offset)
  834. return false;
  835. LV2_Atom_Event* const aev = (LV2_Atom_Event*)(LV2_ATOM_CONTENTS(LV2_Atom_Sequence, seq) + mData.offset);
  836. aev->time.frames = event->time;
  837. aev->body.size = event->size;
  838. aev->body.type = fURIs.midiEvent;
  839. std::memcpy(LV2_ATOM_BODY(&aev->body), event->data, event->size);
  840. const uint32_t size = lv2_atom_pad_size(static_cast<uint32_t>(sizeof(LV2_Atom_Event) + event->size));
  841. mData.offset += size;
  842. seq->atom.size += size;
  843. return true;
  844. }
  845. void handleUiParameterChanged(const uint32_t index, const float value) const
  846. {
  847. if (fUI.writeFunction != nullptr && fUI.controller != nullptr)
  848. fUI.writeFunction(fUI.controller, index+fUI.portOffset, sizeof(float), 0, &value);
  849. }
  850. void handleUiCustomDataChanged(const char* const /*key*/, const char* const /*value*/) const
  851. {
  852. //storeCustomData(key, value);
  853. }
  854. void handleUiClosed()
  855. {
  856. if (fUI.host != nullptr && fUI.host->ui_closed != nullptr && fUI.controller != nullptr)
  857. fUI.host->ui_closed(fUI.controller);
  858. fUI.host = nullptr;
  859. fUI.writeFunction = nullptr;
  860. fUI.controller = nullptr;
  861. fUI.isVisible = false;
  862. }
  863. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  864. {
  865. // TODO
  866. return nullptr;
  867. }
  868. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  869. {
  870. // TODO
  871. return nullptr;
  872. }
  873. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  874. {
  875. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)", opcode, index, value, ptr, opt);
  876. intptr_t ret = 0;
  877. switch (opcode)
  878. {
  879. case NATIVE_HOST_OPCODE_NULL:
  880. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  881. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  882. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  883. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  884. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  885. case NATIVE_HOST_OPCODE_HOST_IDLE:
  886. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  887. // nothing
  888. break;
  889. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  890. handleUiClosed();
  891. break;
  892. }
  893. return ret;
  894. // unused for now
  895. (void)index;
  896. (void)value;
  897. (void)ptr;
  898. (void)opt;
  899. }
  900. void updateParameterOutputs()
  901. {
  902. for (uint32_t i=0; i < fPorts.paramCount; ++i)
  903. {
  904. if (! fPorts.paramsOut[i])
  905. continue;
  906. fPorts.paramsLast[i] = fDescriptor->get_parameter_value(fHandle, i);
  907. if (fPorts.paramsPtr[i] != nullptr)
  908. *fPorts.paramsPtr[i] = fPorts.paramsLast[i];
  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. uint32_t fMidiEventCount;
  919. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  920. NativeTimeInfo fTimeInfo;
  921. // Lv2 host data
  922. bool fIsOffline;
  923. uint32_t fBufferSize;
  924. double fSampleRate;
  925. bool fUsingNominal;
  926. const LV2_URID_Map* fUridMap;
  927. struct Lv2PositionData {
  928. int32_t bar;
  929. float bar_f;
  930. float barBeat;
  931. uint32_t beatUnit;
  932. float beatsPerBar;
  933. double beatsPerMinute;
  934. uint64_t frame;
  935. double speed;
  936. double ticksPerBeat;
  937. Lv2PositionData()
  938. : bar(-1),
  939. bar_f(-1.0f),
  940. barBeat(-1.0f),
  941. beatUnit(0),
  942. beatsPerBar(0.0f),
  943. beatsPerMinute(-1.0),
  944. frame(0),
  945. speed(0.0),
  946. ticksPerBeat(-1.0) {}
  947. } fLastPositionData;
  948. struct URIDs {
  949. LV2_URID atomBlank;
  950. LV2_URID atomObject;
  951. LV2_URID atomDouble;
  952. LV2_URID atomFloat;
  953. LV2_URID atomInt;
  954. LV2_URID atomLong;
  955. LV2_URID atomSequence;
  956. LV2_URID atomString;
  957. LV2_URID midiEvent;
  958. LV2_URID timePos;
  959. LV2_URID timeBar;
  960. LV2_URID timeBarBeat;
  961. LV2_URID timeBeatsPerBar;
  962. LV2_URID timeBeatsPerMinute;
  963. LV2_URID timeBeatUnit;
  964. LV2_URID timeFrame;
  965. LV2_URID timeSpeed;
  966. LV2_URID timeTicksPerBeat;
  967. URIDs()
  968. : atomBlank(0),
  969. atomObject(0),
  970. atomDouble(0),
  971. atomFloat(0),
  972. atomInt(0),
  973. atomLong(0),
  974. atomSequence(0),
  975. atomString(0),
  976. midiEvent(0),
  977. timePos(0),
  978. timeBar(0),
  979. timeBarBeat(0),
  980. timeBeatsPerBar(0),
  981. timeBeatsPerMinute(0),
  982. timeBeatUnit(0),
  983. timeFrame(0),
  984. timeSpeed(0),
  985. timeTicksPerBeat(0) {}
  986. void map(const LV2_URID_Map* const uridMap)
  987. {
  988. atomBlank = uridMap->map(uridMap->handle, LV2_ATOM__Blank);
  989. atomObject = uridMap->map(uridMap->handle, LV2_ATOM__Object);
  990. atomDouble = uridMap->map(uridMap->handle, LV2_ATOM__Double);
  991. atomFloat = uridMap->map(uridMap->handle, LV2_ATOM__Float);
  992. atomInt = uridMap->map(uridMap->handle, LV2_ATOM__Int);
  993. atomLong = uridMap->map(uridMap->handle, LV2_ATOM__Long);
  994. atomSequence = uridMap->map(uridMap->handle, LV2_ATOM__Sequence);
  995. atomString = uridMap->map(uridMap->handle, LV2_ATOM__String);
  996. midiEvent = uridMap->map(uridMap->handle, LV2_MIDI__MidiEvent);
  997. timePos = uridMap->map(uridMap->handle, LV2_TIME__Position);
  998. timeBar = uridMap->map(uridMap->handle, LV2_TIME__bar);
  999. timeBarBeat = uridMap->map(uridMap->handle, LV2_TIME__barBeat);
  1000. timeBeatUnit = uridMap->map(uridMap->handle, LV2_TIME__beatUnit);
  1001. timeFrame = uridMap->map(uridMap->handle, LV2_TIME__frame);
  1002. timeSpeed = uridMap->map(uridMap->handle, LV2_TIME__speed);
  1003. timeBeatsPerBar = uridMap->map(uridMap->handle, LV2_TIME__beatsPerBar);
  1004. timeBeatsPerMinute = uridMap->map(uridMap->handle, LV2_TIME__beatsPerMinute);
  1005. timeTicksPerBeat = uridMap->map(uridMap->handle, LV2_KXSTUDIO_PROPERTIES__TimePositionTicksPerBeat);
  1006. }
  1007. } fURIs;
  1008. struct UI {
  1009. const LV2_External_UI_Host* host;
  1010. LV2UI_Write_Function writeFunction;
  1011. LV2UI_Controller controller;
  1012. uint32_t portOffset;
  1013. bool isEmbed;
  1014. bool isVisible;
  1015. UI()
  1016. : host(nullptr),
  1017. writeFunction(nullptr),
  1018. controller(nullptr),
  1019. portOffset(0),
  1020. isEmbed(false),
  1021. isVisible(false) {}
  1022. } fUI;
  1023. struct Ports {
  1024. // need to save current state
  1025. struct MidiOutData {
  1026. uint32_t capacity;
  1027. uint32_t offset;
  1028. MidiOutData()
  1029. : capacity(0),
  1030. offset(0) {}
  1031. };
  1032. const LV2_Atom_Sequence** eventsIn;
  1033. /* */ LV2_Atom_Sequence** midiOuts;
  1034. /* */ MidiOutData* midiOutData;
  1035. const float** audioIns;
  1036. /* */ float** audioOuts;
  1037. float* freewheel;
  1038. uint32_t paramCount;
  1039. float* paramsLast;
  1040. float** paramsPtr;
  1041. bool* paramsOut;
  1042. Ports()
  1043. : eventsIn(nullptr),
  1044. midiOuts(nullptr),
  1045. midiOutData(nullptr),
  1046. audioIns(nullptr),
  1047. audioOuts(nullptr),
  1048. freewheel(nullptr),
  1049. paramCount(0),
  1050. paramsLast(nullptr),
  1051. paramsPtr(nullptr),
  1052. paramsOut(nullptr) {}
  1053. ~Ports()
  1054. {
  1055. if (eventsIn != nullptr)
  1056. {
  1057. delete[] eventsIn;
  1058. eventsIn = nullptr;
  1059. }
  1060. if (midiOuts != nullptr)
  1061. {
  1062. delete[] midiOuts;
  1063. midiOuts = nullptr;
  1064. }
  1065. if (midiOutData != nullptr)
  1066. {
  1067. delete[] midiOutData;
  1068. midiOutData = nullptr;
  1069. }
  1070. if (audioIns != nullptr)
  1071. {
  1072. delete[] audioIns;
  1073. audioIns = nullptr;
  1074. }
  1075. if (audioOuts != nullptr)
  1076. {
  1077. delete[] audioOuts;
  1078. audioOuts = nullptr;
  1079. }
  1080. if (paramsLast != nullptr)
  1081. {
  1082. delete[] paramsLast;
  1083. paramsLast = nullptr;
  1084. }
  1085. if (paramsPtr != nullptr)
  1086. {
  1087. delete[] paramsPtr;
  1088. paramsPtr = nullptr;
  1089. }
  1090. if (paramsOut != nullptr)
  1091. {
  1092. delete[] paramsOut;
  1093. paramsOut = nullptr;
  1094. }
  1095. }
  1096. void init(const NativePluginDescriptor* const desc, NativePluginHandle handle)
  1097. {
  1098. CARLA_SAFE_ASSERT_RETURN(desc != nullptr && handle != nullptr,)
  1099. if (desc->midiIns > 0)
  1100. {
  1101. eventsIn = new const LV2_Atom_Sequence*[desc->midiIns];
  1102. for (uint32_t i=0; i < desc->midiIns; ++i)
  1103. eventsIn[i] = nullptr;
  1104. }
  1105. else if (desc->hints & NATIVE_PLUGIN_USES_TIME)
  1106. {
  1107. eventsIn = new const LV2_Atom_Sequence*[1];
  1108. eventsIn[0] = nullptr;
  1109. }
  1110. if (desc->midiOuts > 0)
  1111. {
  1112. midiOuts = new LV2_Atom_Sequence*[desc->midiOuts];
  1113. midiOutData = new MidiOutData[desc->midiOuts];
  1114. for (uint32_t i=0; i < desc->midiOuts; ++i)
  1115. midiOuts[i] = nullptr;
  1116. }
  1117. if (desc->audioIns > 0)
  1118. {
  1119. audioIns = new const float*[desc->audioIns];
  1120. for (uint32_t i=0; i < desc->audioIns; ++i)
  1121. audioIns[i] = nullptr;
  1122. }
  1123. if (desc->audioOuts > 0)
  1124. {
  1125. audioOuts = new float*[desc->audioOuts];
  1126. for (uint32_t i=0; i < desc->audioOuts; ++i)
  1127. audioOuts[i] = nullptr;
  1128. }
  1129. if (desc->get_parameter_count != nullptr && desc->get_parameter_info != nullptr && desc->get_parameter_value != nullptr && desc->set_parameter_value != nullptr)
  1130. {
  1131. paramCount = desc->get_parameter_count(handle);
  1132. if (paramCount > 0)
  1133. {
  1134. paramsLast = new float[paramCount];
  1135. paramsPtr = new float*[paramCount];
  1136. paramsOut = new bool[paramCount];
  1137. for (uint32_t i=0; i < paramCount; ++i)
  1138. {
  1139. paramsLast[i] = desc->get_parameter_value(handle, i);
  1140. paramsPtr [i] = nullptr;
  1141. paramsOut [i] = (desc->get_parameter_info(handle, i)->hints & NATIVE_PARAMETER_IS_OUTPUT);
  1142. }
  1143. }
  1144. }
  1145. }
  1146. void connectPort(const NativePluginDescriptor* const desc, const uint32_t port, void* const dataLocation)
  1147. {
  1148. uint32_t index = 0;
  1149. if (desc->midiIns > 0 || (desc->hints & NATIVE_PLUGIN_USES_TIME) != 0)
  1150. {
  1151. if (port == index++)
  1152. {
  1153. eventsIn[0] = (LV2_Atom_Sequence*)dataLocation;
  1154. return;
  1155. }
  1156. }
  1157. for (uint32_t i=1; i < desc->midiIns; ++i)
  1158. {
  1159. if (port == index++)
  1160. {
  1161. eventsIn[i] = (LV2_Atom_Sequence*)dataLocation;
  1162. return;
  1163. }
  1164. }
  1165. for (uint32_t i=0; i < desc->midiOuts; ++i)
  1166. {
  1167. if (port == index++)
  1168. {
  1169. midiOuts[i] = (LV2_Atom_Sequence*)dataLocation;
  1170. return;
  1171. }
  1172. }
  1173. if (port == index++)
  1174. {
  1175. freewheel = (float*)dataLocation;
  1176. return;
  1177. }
  1178. for (uint32_t i=0; i < desc->audioIns; ++i)
  1179. {
  1180. if (port == index++)
  1181. {
  1182. audioIns[i] = (float*)dataLocation;
  1183. return;
  1184. }
  1185. }
  1186. for (uint32_t i=0; i < desc->audioOuts; ++i)
  1187. {
  1188. if (port == index++)
  1189. {
  1190. audioOuts[i] = (float*)dataLocation;
  1191. return;
  1192. }
  1193. }
  1194. for (uint32_t i=0; i < paramCount; ++i)
  1195. {
  1196. if (port == index++)
  1197. {
  1198. paramsPtr[i] = (float*)dataLocation;
  1199. return;
  1200. }
  1201. }
  1202. }
  1203. CARLA_DECLARE_NON_COPY_STRUCT(Ports);
  1204. } fPorts;
  1205. // -------------------------------------------------------------------
  1206. #define handlePtr ((NativePlugin*)handle)
  1207. static void extui_run(LV2_External_UI_Widget_Compat* handle)
  1208. {
  1209. handlePtr->handleUiRun();
  1210. }
  1211. static void extui_show(LV2_External_UI_Widget_Compat* handle)
  1212. {
  1213. handlePtr->handleUiShow();
  1214. }
  1215. static void extui_hide(LV2_External_UI_Widget_Compat* handle)
  1216. {
  1217. handlePtr->handleUiHide();
  1218. }
  1219. // -------------------------------------------------------------------
  1220. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  1221. {
  1222. return handlePtr->fBufferSize;
  1223. }
  1224. static double host_get_sample_rate(NativeHostHandle handle)
  1225. {
  1226. return handlePtr->fSampleRate;
  1227. }
  1228. static bool host_is_offline(NativeHostHandle handle)
  1229. {
  1230. return handlePtr->fIsOffline;
  1231. }
  1232. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  1233. {
  1234. return &(handlePtr->fTimeInfo);
  1235. }
  1236. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  1237. {
  1238. return handlePtr->handleWriteMidiEvent(event);
  1239. }
  1240. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  1241. {
  1242. handlePtr->handleUiParameterChanged(index, value);
  1243. }
  1244. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  1245. {
  1246. handlePtr->handleUiCustomDataChanged(key, value);
  1247. }
  1248. static void host_ui_closed(NativeHostHandle handle)
  1249. {
  1250. handlePtr->handleUiClosed();
  1251. }
  1252. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  1253. {
  1254. return handlePtr->handleUiOpenFile(isDir, title, filter);
  1255. }
  1256. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  1257. {
  1258. return handlePtr->handleUiSaveFile(isDir, title, filter);
  1259. }
  1260. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  1261. {
  1262. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  1263. }
  1264. #undef handlePtr
  1265. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  1266. };
  1267. // -----------------------------------------------------------------------
  1268. // LV2 plugin descriptor functions
  1269. static LV2_Handle lv2_instantiate(const LV2_Descriptor* lv2Descriptor, double sampleRate, const char* bundlePath, const LV2_Feature* const* features)
  1270. {
  1271. carla_debug("lv2_instantiate(%p, %g, %s, %p)", lv2Descriptor, sampleRate, bundlePath, features);
  1272. const NativePluginDescriptor* pluginDesc = nullptr;
  1273. const char* pluginLabel = nullptr;
  1274. if (std::strncmp(lv2Descriptor->URI, "http://kxstudio.sf.net/carla/plugins/", 37) == 0)
  1275. pluginLabel = lv2Descriptor->URI+37;
  1276. if (pluginLabel == nullptr)
  1277. {
  1278. carla_stderr("Failed to find carla native plugin with URI \"%s\"", lv2Descriptor->URI);
  1279. return nullptr;
  1280. }
  1281. carla_debug("lv2_instantiate() - looking up label \"%s\"", pluginLabel);
  1282. PluginListManager& plm(PluginListManager::getInstance());
  1283. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  1284. {
  1285. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  1286. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  1287. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  1288. {
  1289. pluginDesc = tmpDesc;
  1290. break;
  1291. }
  1292. }
  1293. if (pluginDesc == nullptr)
  1294. {
  1295. carla_stderr("Failed to find carla native plugin with label \"%s\"", pluginLabel);
  1296. return nullptr;
  1297. }
  1298. NativePlugin* const plugin(new NativePlugin(pluginDesc, sampleRate, bundlePath, features));
  1299. if (! plugin->init())
  1300. {
  1301. carla_stderr("Failed to init plugin");
  1302. delete plugin;
  1303. return nullptr;
  1304. }
  1305. return (LV2_Handle)plugin;
  1306. }
  1307. #define instancePtr ((NativePlugin*)instance)
  1308. static void lv2_connect_port(LV2_Handle instance, uint32_t port, void* dataLocation)
  1309. {
  1310. instancePtr->lv2_connect_port(port, dataLocation);
  1311. }
  1312. static void lv2_activate(LV2_Handle instance)
  1313. {
  1314. carla_debug("lv2_activate(%p)", instance);
  1315. instancePtr->lv2_activate();
  1316. }
  1317. static void lv2_run(LV2_Handle instance, uint32_t sampleCount)
  1318. {
  1319. instancePtr->lv2_run(sampleCount);
  1320. }
  1321. static void lv2_deactivate(LV2_Handle instance)
  1322. {
  1323. carla_debug("lv2_deactivate(%p)", instance);
  1324. instancePtr->lv2_deactivate();
  1325. }
  1326. static void lv2_cleanup(LV2_Handle instance)
  1327. {
  1328. carla_debug("lv2_cleanup(%p)", instance);
  1329. instancePtr->lv2_cleanup();
  1330. delete instancePtr;
  1331. }
  1332. static uint32_t lv2_get_options(LV2_Handle instance, LV2_Options_Option* options)
  1333. {
  1334. carla_debug("lv2_get_options(%p, %p)", instance, options);
  1335. return instancePtr->lv2_get_options(options);
  1336. }
  1337. static uint32_t lv2_set_options(LV2_Handle instance, const LV2_Options_Option* options)
  1338. {
  1339. carla_debug("lv2_set_options(%p, %p)", instance, options);
  1340. return instancePtr->lv2_set_options(options);
  1341. }
  1342. static const LV2_Program_Descriptor* lv2_get_program(LV2_Handle instance, uint32_t index)
  1343. {
  1344. carla_debug("lv2_get_program(%p, %i)", instance, index);
  1345. return instancePtr->lv2_get_program(index);
  1346. }
  1347. static void lv2_select_program(LV2_Handle instance, uint32_t bank, uint32_t program)
  1348. {
  1349. carla_debug("lv2_select_program(%p, %i, %i)", instance, bank, program);
  1350. return instancePtr->lv2_select_program(bank, program);
  1351. }
  1352. 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)
  1353. {
  1354. carla_debug("lv2_save(%p, %p, %p, %i, %p)", instance, store, handle, flags, features);
  1355. return instancePtr->lv2_save(store, handle, flags, features);
  1356. }
  1357. 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)
  1358. {
  1359. carla_debug("lv2_restore(%p, %p, %p, %i, %p)", instance, retrieve, handle, flags, features);
  1360. return instancePtr->lv2_restore(retrieve, handle, flags, features);
  1361. }
  1362. static const void* lv2_extension_data(const char* uri)
  1363. {
  1364. carla_debug("lv2_extension_data(\"%s\")", uri);
  1365. static const LV2_Options_Interface options = { lv2_get_options, lv2_set_options };
  1366. static const LV2_Programs_Interface programs = { lv2_get_program, lv2_select_program };
  1367. static const LV2_State_Interface state = { lv2_save, lv2_restore };
  1368. if (std::strcmp(uri, LV2_OPTIONS__interface) == 0)
  1369. return &options;
  1370. if (std::strcmp(uri, LV2_PROGRAMS__Interface) == 0)
  1371. return &programs;
  1372. if (std::strcmp(uri, LV2_STATE__interface) == 0)
  1373. return &state;
  1374. return nullptr;
  1375. }
  1376. #undef instancePtr
  1377. // -----------------------------------------------------------------------
  1378. // LV2 UI descriptor functions
  1379. static LV2UI_Handle lv2ui_instantiate(LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  1380. LV2UI_Widget* widget, const LV2_Feature* const* features, const bool isEmbed)
  1381. {
  1382. carla_debug("lv2ui_instantiate(..., %p, %p, %p)", writeFunction, controller, widget, features);
  1383. #ifndef CARLA_OS_LINUX
  1384. CARLA_SAFE_ASSERT_RETURN(! isEmbed, nullptr);
  1385. #endif
  1386. NativePlugin* plugin = nullptr;
  1387. for (int i=0; features[i] != nullptr; ++i)
  1388. {
  1389. if (std::strcmp(features[i]->URI, LV2_INSTANCE_ACCESS_URI) == 0)
  1390. {
  1391. plugin = (NativePlugin*)features[i]->data;
  1392. break;
  1393. }
  1394. }
  1395. if (plugin == nullptr)
  1396. {
  1397. carla_stderr("Host doesn't support instance-access, cannot show UI");
  1398. return nullptr;
  1399. }
  1400. plugin->lv2ui_instantiate(writeFunction, controller, widget, features, isEmbed);
  1401. return (LV2UI_Handle)plugin;
  1402. }
  1403. #ifdef CARLA_OS_LINUX
  1404. static LV2UI_Handle lv2ui_instantiate_embed(const LV2UI_Descriptor*, const char*, const char*,
  1405. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  1406. LV2UI_Widget* widget, const LV2_Feature* const* features)
  1407. {
  1408. return lv2ui_instantiate(writeFunction, controller, widget, features, true);
  1409. }
  1410. #endif
  1411. static LV2UI_Handle lv2ui_instantiate_external(const LV2UI_Descriptor*, const char*, const char*,
  1412. LV2UI_Write_Function writeFunction, LV2UI_Controller controller,
  1413. LV2UI_Widget* widget, const LV2_Feature* const* features)
  1414. {
  1415. return lv2ui_instantiate(writeFunction, controller, widget, features, false);
  1416. }
  1417. #define uiPtr ((NativePlugin*)ui)
  1418. static void lv2ui_port_event(LV2UI_Handle ui, uint32_t portIndex, uint32_t bufferSize, uint32_t format, const void* buffer)
  1419. {
  1420. carla_debug("lv2ui_port_event(%p, %i, %i, %i, %p)", ui, portIndex, bufferSize, format, buffer);
  1421. uiPtr->lv2ui_port_event(portIndex, bufferSize, format, buffer);
  1422. }
  1423. static void lv2ui_cleanup(LV2UI_Handle ui)
  1424. {
  1425. carla_debug("lv2ui_cleanup(%p)", ui);
  1426. uiPtr->lv2ui_cleanup();
  1427. }
  1428. static void lv2ui_select_program(LV2UI_Handle ui, uint32_t bank, uint32_t program)
  1429. {
  1430. carla_debug("lv2ui_select_program(%p, %i, %i)", ui, bank, program);
  1431. uiPtr->lv2ui_select_program(bank, program);
  1432. }
  1433. static int lv2ui_idle(LV2UI_Handle ui)
  1434. {
  1435. return uiPtr->lv2ui_idle();
  1436. }
  1437. static int lv2ui_show(LV2UI_Handle ui)
  1438. {
  1439. carla_debug("lv2ui_show(%p)", ui);
  1440. return uiPtr->lv2ui_show();
  1441. }
  1442. static int lv2ui_hide(LV2UI_Handle ui)
  1443. {
  1444. carla_debug("lv2ui_hide(%p)", ui);
  1445. return uiPtr->lv2ui_hide();
  1446. }
  1447. static const void* lv2ui_extension_data(const char* uri)
  1448. {
  1449. carla_stdout("lv2ui_extension_data(\"%s\")", uri);
  1450. static const LV2UI_Idle_Interface uiidle = { lv2ui_idle };
  1451. static const LV2UI_Show_Interface uishow = { lv2ui_show, lv2ui_hide };
  1452. static const LV2_Programs_UI_Interface uiprograms = { lv2ui_select_program };
  1453. if (std::strcmp(uri, LV2_UI__idleInterface) == 0)
  1454. return &uiidle;
  1455. if (std::strcmp(uri, LV2_UI__showInterface) == 0)
  1456. return &uishow;
  1457. if (std::strcmp(uri, LV2_PROGRAMS__UIInterface) == 0)
  1458. return &uiprograms;
  1459. return nullptr;
  1460. }
  1461. #undef uiPtr
  1462. // -----------------------------------------------------------------------
  1463. // Startup code
  1464. CARLA_EXPORT
  1465. const LV2_Descriptor* lv2_descriptor(uint32_t index)
  1466. {
  1467. carla_debug("lv2_descriptor(%i)", index);
  1468. PluginListManager& plm(PluginListManager::getInstance());
  1469. if (index >= plm.descs.count())
  1470. {
  1471. carla_debug("lv2_descriptor(%i) - out of bounds", index);
  1472. return nullptr;
  1473. }
  1474. if (index < plm.lv2Descs.count())
  1475. {
  1476. carla_debug("lv2_descriptor(%i) - found previously allocated", index);
  1477. return plm.lv2Descs.getAt(index, nullptr);
  1478. }
  1479. const NativePluginDescriptor* const pluginDesc(plm.descs.getAt(index, nullptr));
  1480. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, nullptr);
  1481. CarlaString tmpURI;
  1482. tmpURI = "http://kxstudio.sf.net/carla/plugins/";
  1483. tmpURI += pluginDesc->label;
  1484. carla_debug("lv2_descriptor(%i) - not found, allocating new with uri \"%s\"", index, (const char*)tmpURI);
  1485. const LV2_Descriptor lv2DescTmp = {
  1486. /* URI */ carla_strdup(tmpURI),
  1487. /* instantiate */ lv2_instantiate,
  1488. /* connect_port */ lv2_connect_port,
  1489. /* activate */ lv2_activate,
  1490. /* run */ lv2_run,
  1491. /* deactivate */ lv2_deactivate,
  1492. /* cleanup */ lv2_cleanup,
  1493. /* extension_data */ lv2_extension_data
  1494. };
  1495. LV2_Descriptor* lv2Desc;
  1496. try {
  1497. lv2Desc = new LV2_Descriptor;
  1498. } CARLA_SAFE_EXCEPTION_RETURN("new LV2_Descriptor", nullptr);
  1499. std::memcpy(lv2Desc, &lv2DescTmp, sizeof(LV2_Descriptor));
  1500. plm.lv2Descs.append(lv2Desc);
  1501. return lv2Desc;
  1502. }
  1503. CARLA_EXPORT
  1504. const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
  1505. {
  1506. carla_debug("lv2ui_descriptor(%i)", index);
  1507. #ifdef CARLA_OS_LINUX
  1508. static const LV2UI_Descriptor lv2UiEmbedDesc = {
  1509. /* URI */ "http://kxstudio.sf.net/carla/ui-embed",
  1510. /* instantiate */ lv2ui_instantiate_embed,
  1511. /* cleanup */ lv2ui_cleanup,
  1512. /* port_event */ lv2ui_port_event,
  1513. /* extension_data */ lv2ui_extension_data
  1514. };
  1515. if (index == 0)
  1516. return &lv2UiEmbedDesc;
  1517. else
  1518. --index;
  1519. #endif
  1520. static const LV2UI_Descriptor lv2UiExtDesc = {
  1521. /* URI */ "http://kxstudio.sf.net/carla/ui-ext",
  1522. /* instantiate */ lv2ui_instantiate_external,
  1523. /* cleanup */ lv2ui_cleanup,
  1524. /* port_event */ lv2ui_port_event,
  1525. /* extension_data */ lv2ui_extension_data
  1526. };
  1527. return (index == 0) ? &lv2UiExtDesc : nullptr;
  1528. }
  1529. // -----------------------------------------------------------------------