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.

1277 lines
41KB

  1. /*
  2. * Carla Native Plugins
  3. * Copyright (C) 2013-2019 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the doc/GPL.txt file.
  16. */
  17. #ifdef __WINE__
  18. #error This file is not supposed to be built with wine!
  19. #endif
  20. #ifndef CARLA_PLUGIN_SYNTH
  21. #error CARLA_PLUGIN_SYNTH undefined
  22. #endif
  23. #ifndef CARLA_VST_SHELL
  24. #ifndef CARLA_PLUGIN_PATCHBAY
  25. #error CARLA_PLUGIN_PATCHBAY undefined
  26. #endif
  27. #if defined(CARLA_PLUGIN_32CH) || defined(CARLA_PLUGIN_16CH)
  28. #if ! CARLA_PLUGIN_SYNTH
  29. #error CARLA_PLUGIN_16/32CH requires CARLA_PLUGIN_SYNTH
  30. #endif
  31. #endif
  32. #endif
  33. #define CARLA_NATIVE_PLUGIN_VST
  34. #include "carla-base.cpp"
  35. #include "carla-vst.hpp"
  36. #include "water/files/File.h"
  37. #include "CarlaMathUtils.hpp"
  38. #include "CarlaVstUtils.hpp"
  39. #ifdef USING_JUCE
  40. # if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  41. # pragma GCC diagnostic push
  42. # pragma GCC diagnostic ignored "-Wconversion"
  43. # pragma GCC diagnostic ignored "-Weffc++"
  44. # pragma GCC diagnostic ignored "-Wsign-conversion"
  45. # pragma GCC diagnostic ignored "-Wundef"
  46. # pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
  47. # endif
  48. # include "AppConfig.h"
  49. # include "juce_events/juce_events.h"
  50. # if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  51. # pragma GCC diagnostic pop
  52. # endif
  53. #endif
  54. static uint32_t d_lastBufferSize = 0;
  55. static double d_lastSampleRate = 0.0;
  56. static const int32_t kBaseUniqueID = CCONST('C', 'r', 'l', 'a');
  57. static const int32_t kShellUniqueID = CCONST('C', 'r', 'l', 's');
  58. static const int32_t kNumParameters = 100;
  59. static const int32_t kVstMidiEventSize = static_cast<int32_t>(sizeof(VstMidiEvent));
  60. static const bool kIsUsingUILauncher = isUsingUILauncher();
  61. // --------------------------------------------------------------------------------------------------------------------
  62. // Carla Internal Plugin API exposed as VST plugin
  63. class NativePlugin
  64. {
  65. public:
  66. static const uint32_t kMaxMidiEvents = 512;
  67. NativePlugin(AEffect* const effect, const NativePluginDescriptor* desc)
  68. : fEffect(effect),
  69. fHandle(nullptr),
  70. fHost(),
  71. fDescriptor(desc),
  72. fBufferSize(d_lastBufferSize),
  73. fSampleRate(d_lastSampleRate),
  74. fIsActive(false),
  75. fMidiEventCount(0),
  76. fTimeInfo(),
  77. fVstRect(),
  78. fUiLauncher(nullptr),
  79. fHostType(kHostTypeNull),
  80. fMidiOutEvents(),
  81. #ifdef USING_JUCE
  82. fJuceInitialiser(),
  83. #endif
  84. fStateChunk(nullptr)
  85. {
  86. fHost.handle = this;
  87. fHost.uiName = carla_strdup("CarlaVST");
  88. fHost.uiParentId = 0;
  89. std::memset(fProgramName, 0, sizeof(fProgramName));
  90. std::strcpy(fProgramName, "Default");
  91. // find resource dir
  92. using water::File;
  93. using water::String;
  94. File curExe = File::getSpecialLocation(File::currentExecutableFile).getLinkedTarget();
  95. File resDir = curExe.getSiblingFile("resources");
  96. // FIXME: proper fallback path for other OSes
  97. if (! resDir.exists())
  98. resDir = File("/usr/local/share/carla/resources");
  99. if (! resDir.exists())
  100. resDir = File("/usr/share/carla/resources");
  101. // find host type
  102. const String hostFilename(File::getSpecialLocation(File::hostApplicationPath).getFileName());
  103. /**/ if (hostFilename.startsWith("ardour"))
  104. fHostType = kHostTypeArdour;
  105. else if (hostFilename.startsWith("Bitwig"))
  106. fHostType = kHostTypeBitwig;
  107. fHost.resourceDir = carla_strdup(resDir.getFullPathName().toRawUTF8());
  108. fHost.get_buffer_size = host_get_buffer_size;
  109. fHost.get_sample_rate = host_get_sample_rate;
  110. fHost.is_offline = host_is_offline;
  111. fHost.get_time_info = host_get_time_info;
  112. fHost.write_midi_event = host_write_midi_event;
  113. fHost.ui_parameter_changed = host_ui_parameter_changed;
  114. fHost.ui_custom_data_changed = host_ui_custom_data_changed;
  115. fHost.ui_closed = host_ui_closed;
  116. fHost.ui_open_file = host_ui_open_file;
  117. fHost.ui_save_file = host_ui_save_file;
  118. fHost.dispatcher = host_dispatcher;
  119. fVstRect.top = 0;
  120. fVstRect.left = 0;
  121. if (kIsUsingUILauncher)
  122. {
  123. fVstRect.bottom = ui_launcher_res::carla_uiHeight;
  124. fVstRect.right = ui_launcher_res::carla_uiWidth;
  125. }
  126. else
  127. {
  128. fVstRect.bottom = 712;
  129. fVstRect.right = 1024;
  130. }
  131. init();
  132. }
  133. ~NativePlugin()
  134. {
  135. if (fIsActive)
  136. {
  137. // host has not de-activated the plugin yet, nasty!
  138. fIsActive = false;
  139. if (fDescriptor->deactivate != nullptr)
  140. fDescriptor->deactivate(fHandle);
  141. }
  142. if (fDescriptor->cleanup != nullptr && fHandle != nullptr)
  143. fDescriptor->cleanup(fHandle);
  144. fHandle = nullptr;
  145. if (fStateChunk != nullptr)
  146. {
  147. std::free(fStateChunk);
  148. fStateChunk = nullptr;
  149. }
  150. if (fHost.uiName != nullptr)
  151. {
  152. delete[] fHost.uiName;
  153. fHost.uiName = nullptr;
  154. }
  155. if (fHost.resourceDir != nullptr)
  156. {
  157. delete[] fHost.resourceDir;
  158. fHost.resourceDir = nullptr;
  159. }
  160. }
  161. bool init()
  162. {
  163. if (fDescriptor->instantiate == nullptr || fDescriptor->process == nullptr)
  164. {
  165. carla_stderr("Plugin is missing something...");
  166. return false;
  167. }
  168. fHandle = fDescriptor->instantiate(&fHost);
  169. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, false);
  170. carla_zeroStructs(fMidiEvents, kMaxMidiEvents);
  171. carla_zeroStruct(fTimeInfo);
  172. return true;
  173. }
  174. const NativePluginDescriptor* getDescriptor() const noexcept
  175. {
  176. return fDescriptor;
  177. }
  178. // -------------------------------------------------------------------
  179. intptr_t vst_dispatcher(const int32_t opcode,
  180. const int32_t index, const intptr_t value, void* const ptr, const float opt)
  181. {
  182. CARLA_SAFE_ASSERT_RETURN(fHandle != nullptr, 0);
  183. intptr_t ret = 0;
  184. switch (opcode)
  185. {
  186. case effGetProgram:
  187. return 0;
  188. case effSetProgramName:
  189. if (char* const programName = (char*)ptr)
  190. {
  191. std::strncpy(fProgramName, programName, 32);
  192. return 1;
  193. }
  194. break;
  195. case effGetProgramName:
  196. if (char* const programName = (char*)ptr)
  197. {
  198. std::strncpy(programName, fProgramName, 24);
  199. return 1;
  200. }
  201. break;
  202. case effGetProgramNameIndexed:
  203. if (char* const programName = (char*)ptr)
  204. {
  205. std::strncpy(programName, fProgramName, 24);
  206. return 1;
  207. }
  208. break;
  209. case effGetParamDisplay:
  210. CARLA_SAFE_ASSERT_RETURN(index >= 0 && index < kNumParameters, 0);
  211. if (char* const cptr = (char*)ptr)
  212. {
  213. const uint32_t uindex = static_cast<uint32_t>(index);
  214. CARLA_SAFE_ASSERT_RETURN(uindex < fDescriptor->paramIns, 0);
  215. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, uindex);
  216. CARLA_SAFE_ASSERT_RETURN(param != nullptr, 0);
  217. float paramValue = fDescriptor->get_parameter_value(fHandle, uindex);
  218. if (param->hints & NATIVE_PARAMETER_IS_BOOLEAN)
  219. {
  220. const NativeParameterRanges& ranges(param->ranges);
  221. const float midRange = ranges.min + (ranges.max - ranges.min) / 2.0f;
  222. paramValue = paramValue > midRange ? ranges.max : ranges.min;
  223. }
  224. else if (param->hints & NATIVE_PARAMETER_IS_INTEGER)
  225. {
  226. paramValue = std::round(paramValue);
  227. }
  228. for (uint32_t i = 0; i < param->scalePointCount; ++i)
  229. {
  230. const NativeParameterScalePoint& scalePoint(param->scalePoints[uindex]);
  231. if (carla_isNotEqual(paramValue, scalePoint.value))
  232. continue;
  233. std::strncpy(cptr, scalePoint.label, 23);
  234. cptr[23] = '\0';
  235. return 1;
  236. }
  237. if (param->hints & NATIVE_PARAMETER_IS_INTEGER)
  238. {
  239. std::snprintf(cptr, 23, "%d%s%s",
  240. static_cast<int>(paramValue),
  241. param->unit != nullptr && param->unit[0] != '\0' ? " " : "",
  242. param->unit != nullptr ? param->unit : "");
  243. cptr[23] = '\0';
  244. }
  245. else
  246. {
  247. std::snprintf(cptr, 23, "%f%s%s",
  248. static_cast<double>(paramValue),
  249. param->unit != nullptr && param->unit[0] != '\0' ? " " : "",
  250. param->unit != nullptr ? param->unit : "");
  251. cptr[23] = '\0';
  252. }
  253. return 1;
  254. }
  255. break;
  256. case effGetParamName:
  257. CARLA_SAFE_ASSERT_RETURN(index >= 0 && index < kNumParameters, 0);
  258. if (char* const cptr = (char*)ptr)
  259. {
  260. const uint32_t uindex = static_cast<uint32_t>(index);
  261. CARLA_SAFE_ASSERT_RETURN(uindex < fDescriptor->paramIns, 0);
  262. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, uindex);
  263. CARLA_SAFE_ASSERT_RETURN(param != nullptr, 0);
  264. std::strncpy(cptr, param->name, 15);
  265. cptr[15] = '\0';
  266. return 1;
  267. }
  268. return 0;
  269. case effSetSampleRate:
  270. CARLA_SAFE_ASSERT_RETURN(opt > 0.0f, 0);
  271. if (carla_isEqual(fSampleRate, static_cast<double>(opt)))
  272. return 0;
  273. fSampleRate = opt;
  274. if (fDescriptor->dispatcher != nullptr)
  275. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, opt);
  276. break;
  277. case effSetBlockSize:
  278. CARLA_SAFE_ASSERT_RETURN(value > 0, 0);
  279. if (fBufferSize == static_cast<uint32_t>(value))
  280. return 0;
  281. fBufferSize = static_cast<uint32_t>(value);
  282. if (fDescriptor->dispatcher != nullptr)
  283. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, value, nullptr, 0.0f);
  284. break;
  285. case effMainsChanged:
  286. if (value != 0)
  287. {
  288. fMidiEventCount = 0;
  289. carla_zeroStruct(fTimeInfo);
  290. // tell host we want MIDI events
  291. if (fDescriptor->midiIns > 0)
  292. hostCallback(audioMasterWantMidi);
  293. // deactivate for possible changes
  294. if (fDescriptor->deactivate != nullptr && fIsActive)
  295. fDescriptor->deactivate(fHandle);
  296. // check if something changed
  297. const uint32_t bufferSize = static_cast<uint32_t>(hostCallback(audioMasterGetBlockSize));
  298. const double sampleRate = static_cast<double>(hostCallback(audioMasterGetSampleRate));
  299. if (bufferSize != 0 && fBufferSize != bufferSize && (fHostType != kHostTypeArdour || fBufferSize == 0))
  300. {
  301. fBufferSize = bufferSize;
  302. if (fDescriptor->dispatcher != nullptr)
  303. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, bufferSize, nullptr, 0.0f);
  304. }
  305. if (carla_isNotZero(sampleRate) && carla_isNotEqual(fSampleRate, sampleRate))
  306. {
  307. fSampleRate = sampleRate;
  308. if (fDescriptor->dispatcher != nullptr)
  309. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, (float)sampleRate);
  310. }
  311. if (fDescriptor->activate != nullptr)
  312. fDescriptor->activate(fHandle);
  313. fIsActive = true;
  314. }
  315. else
  316. {
  317. CARLA_SAFE_ASSERT_BREAK(fIsActive);
  318. if (fDescriptor->deactivate != nullptr)
  319. fDescriptor->deactivate(fHandle);
  320. fIsActive = false;
  321. }
  322. break;
  323. case effEditGetRect:
  324. *(ERect**)ptr = &fVstRect;
  325. ret = 1;
  326. break;
  327. case effEditOpen:
  328. if (fDescriptor->ui_show != nullptr)
  329. {
  330. #ifdef HAVE_X11
  331. if (! kIsUsingUILauncher)
  332. {
  333. char strBuf[0xff+1];
  334. std::snprintf(strBuf, 0xff, P_INTPTR, (intptr_t)ptr);
  335. strBuf[0xff] = '\0';
  336. // set CARLA_PLUGIN_EMBED_WINID for external process
  337. carla_setenv("CARLA_PLUGIN_EMBED_WINID", strBuf);
  338. // show UI now
  339. fDescriptor->ui_show(fHandle, true);
  340. // reset CARLA_PLUGIN_EMBED_WINID just in case
  341. carla_setenv("CARLA_PLUGIN_EMBED_WINID", "0");
  342. }
  343. else
  344. #endif
  345. {
  346. destoryUILauncher(fUiLauncher);
  347. fUiLauncher = createUILauncher((intptr_t)ptr, fDescriptor, fHandle);
  348. }
  349. ret = 1;
  350. }
  351. break;
  352. case effEditClose:
  353. if (fDescriptor->ui_show != nullptr)
  354. {
  355. #ifdef HAVE_X11
  356. if (! kIsUsingUILauncher)
  357. {
  358. fDescriptor->ui_show(fHandle, false);
  359. }
  360. else
  361. #endif
  362. {
  363. destoryUILauncher(fUiLauncher);
  364. fUiLauncher = nullptr;
  365. }
  366. ret = 1;
  367. }
  368. break;
  369. case effEditIdle:
  370. if (fUiLauncher != nullptr)
  371. idleUILauncher(fUiLauncher);
  372. if (fDescriptor->ui_idle != nullptr)
  373. fDescriptor->ui_idle(fHandle);
  374. break;
  375. case effGetChunk:
  376. if (ptr == nullptr || fDescriptor->get_state == nullptr)
  377. return 0;
  378. if (fStateChunk != nullptr)
  379. std::free(fStateChunk);
  380. fStateChunk = fDescriptor->get_state(fHandle);
  381. if (fStateChunk == nullptr)
  382. return 0;
  383. ret = static_cast<intptr_t>(std::strlen(fStateChunk)+1);
  384. *(void**)ptr = fStateChunk;
  385. break;
  386. case effSetChunk:
  387. if (value <= 0 || fDescriptor->set_state == nullptr)
  388. return 0;
  389. if (value == 1)
  390. return 1;
  391. if (const char* const state = (const char*)ptr)
  392. {
  393. fDescriptor->set_state(fHandle, state);
  394. ret = 1;
  395. }
  396. break;
  397. case effProcessEvents:
  398. if (! fIsActive)
  399. {
  400. // host has not activated the plugin yet, nasty!
  401. vst_dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  402. }
  403. if (const VstEvents* const events = (const VstEvents*)ptr)
  404. {
  405. if (events->numEvents == 0)
  406. break;
  407. for (int i=0, count=events->numEvents; i < count; ++i)
  408. {
  409. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)events->events[i]);
  410. if (vstMidiEvent == nullptr)
  411. break;
  412. if (vstMidiEvent->type != kVstMidiType || vstMidiEvent->deltaFrames < 0)
  413. continue;
  414. if (fMidiEventCount >= kMaxMidiEvents)
  415. break;
  416. const uint32_t j(fMidiEventCount++);
  417. fMidiEvents[j].port = 0;
  418. fMidiEvents[j].time = static_cast<uint32_t>(vstMidiEvent->deltaFrames);
  419. fMidiEvents[j].size = 3;
  420. for (uint32_t k=0; k<3; ++k)
  421. fMidiEvents[j].data[k] = static_cast<uint8_t>(vstMidiEvent->midiData[k]);
  422. }
  423. }
  424. break;
  425. case effCanBeAutomated:
  426. ret = 1;
  427. break;
  428. case effCanDo:
  429. if (const char* const canDo = (const char*)ptr)
  430. {
  431. if (std::strcmp(canDo, "receiveVstEvents") == 0 || std::strcmp(canDo, "receiveVstMidiEvent") == 0)
  432. {
  433. if (fDescriptor->midiIns == 0)
  434. return -1;
  435. return 1;
  436. }
  437. if (std::strcmp(canDo, "sendVstEvents") == 0 || std::strcmp(canDo, "sendVstMidiEvent") == 0)
  438. {
  439. if (fDescriptor->midiOuts == 0)
  440. return -1;
  441. return 1;
  442. }
  443. if (std::strcmp(canDo, "receiveVstTimeInfo") == 0)
  444. return 1;
  445. }
  446. break;
  447. }
  448. return ret;
  449. }
  450. float vst_getParameter(const int32_t index)
  451. {
  452. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0.0f);
  453. const uint32_t uindex = static_cast<uint32_t>(index);
  454. CARLA_SAFE_ASSERT_RETURN(uindex < fDescriptor->paramIns, 0.0f);
  455. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, uindex);
  456. CARLA_SAFE_ASSERT_RETURN(param != nullptr, 0);
  457. const float realValue = fDescriptor->get_parameter_value(fHandle, uindex);
  458. return (realValue - param->ranges.min) / (param->ranges.max - param->ranges.min);
  459. }
  460. void vst_setParameter(const int32_t index, const float value)
  461. {
  462. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  463. const uint32_t uindex = static_cast<uint32_t>(index);
  464. CARLA_SAFE_ASSERT_RETURN(uindex < fDescriptor->paramIns,);
  465. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, uindex);
  466. CARLA_SAFE_ASSERT_RETURN(param != nullptr,);
  467. float realValue;
  468. if (param->hints & NATIVE_PARAMETER_IS_BOOLEAN)
  469. {
  470. realValue = value > 0.5f ? param->ranges.max : param->ranges.min;
  471. }
  472. else
  473. {
  474. realValue = param->ranges.min + ((param->ranges.max - param->ranges.min) * value);
  475. if (param->hints & NATIVE_PARAMETER_IS_INTEGER)
  476. realValue = std::round(realValue);
  477. }
  478. fDescriptor->set_parameter_value(fHandle, uindex, realValue);
  479. }
  480. void vst_processReplacing(const float** const inputs, float** const outputs, const int32_t sampleFrames)
  481. {
  482. if (sampleFrames <= 0)
  483. return;
  484. if (fHostType == kHostTypeBitwig && static_cast<int32_t>(fBufferSize) != sampleFrames)
  485. {
  486. // deactivate first if needed
  487. if (fIsActive && fDescriptor->deactivate != nullptr)
  488. fDescriptor->deactivate(fHandle);
  489. fBufferSize = static_cast<uint32_t>(sampleFrames);
  490. if (fDescriptor->dispatcher != nullptr)
  491. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, sampleFrames, nullptr, 0.0f);
  492. // activate again
  493. if (fDescriptor->activate != nullptr)
  494. fDescriptor->activate(fHandle);
  495. fIsActive = true;
  496. }
  497. if (! fIsActive)
  498. {
  499. // host has not activated the plugin yet, nasty!
  500. vst_dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  501. }
  502. static const int kWantVstTimeFlags = kVstTransportPlaying|kVstPpqPosValid|kVstTempoValid|kVstTimeSigValid;
  503. if (const VstTimeInfo* const vstTimeInfo = (const VstTimeInfo*)hostCallback(audioMasterGetTime, 0, kWantVstTimeFlags))
  504. {
  505. fTimeInfo.frame = static_cast<uint64_t>(vstTimeInfo->samplePos);
  506. fTimeInfo.playing = (vstTimeInfo->flags & kVstTransportPlaying);
  507. fTimeInfo.bbt.valid = ((vstTimeInfo->flags & kVstTempoValid) != 0 || (vstTimeInfo->flags & kVstTimeSigValid) != 0);
  508. // ticksPerBeat is not possible with VST
  509. fTimeInfo.bbt.ticksPerBeat = 960.0;
  510. if (vstTimeInfo->flags & kVstTempoValid)
  511. fTimeInfo.bbt.beatsPerMinute = vstTimeInfo->tempo;
  512. else
  513. fTimeInfo.bbt.beatsPerMinute = 120.0;
  514. if (vstTimeInfo->flags & (kVstPpqPosValid|kVstTimeSigValid))
  515. {
  516. const double ppqPos = std::abs(vstTimeInfo->ppqPos);
  517. const int ppqPerBar = vstTimeInfo->timeSigNumerator * 4 / vstTimeInfo->timeSigDenominator;
  518. const double barBeats = (std::fmod(ppqPos, ppqPerBar) / ppqPerBar) * vstTimeInfo->timeSigNumerator;
  519. const double rest = std::fmod(barBeats, 1.0);
  520. fTimeInfo.bbt.bar = static_cast<int32_t>(ppqPos) / ppqPerBar + 1;
  521. fTimeInfo.bbt.beat = static_cast<int32_t>(barBeats - rest + 0.5) + 1;
  522. fTimeInfo.bbt.tick = static_cast<int32_t>(rest * fTimeInfo.bbt.ticksPerBeat + 0.5);
  523. fTimeInfo.bbt.beatsPerBar = static_cast<float>(vstTimeInfo->timeSigNumerator);
  524. fTimeInfo.bbt.beatType = static_cast<float>(vstTimeInfo->timeSigDenominator);
  525. if (vstTimeInfo->ppqPos < 0.0)
  526. {
  527. --fTimeInfo.bbt.bar;
  528. fTimeInfo.bbt.beat = vstTimeInfo->timeSigNumerator - fTimeInfo.bbt.beat + 1;
  529. fTimeInfo.bbt.tick = fTimeInfo.bbt.ticksPerBeat - fTimeInfo.bbt.tick - 1;
  530. }
  531. }
  532. else
  533. {
  534. fTimeInfo.bbt.bar = 1;
  535. fTimeInfo.bbt.beat = 1;
  536. fTimeInfo.bbt.tick = 0;
  537. fTimeInfo.bbt.beatsPerBar = 4.0f;
  538. fTimeInfo.bbt.beatType = 4.0f;
  539. }
  540. fTimeInfo.bbt.barStartTick = fTimeInfo.bbt.ticksPerBeat *
  541. static_cast<double>(fTimeInfo.bbt.beatsPerBar) *
  542. (fTimeInfo.bbt.bar - 1);
  543. }
  544. fMidiOutEvents.numEvents = 0;
  545. if (fHandle != nullptr)
  546. // FIXME
  547. fDescriptor->process(fHandle,
  548. inputs, outputs, static_cast<uint32_t>(sampleFrames),
  549. fMidiEvents, fMidiEventCount);
  550. fMidiEventCount = 0;
  551. if (fMidiOutEvents.numEvents > 0)
  552. hostCallback(audioMasterProcessEvents, 0, 0, &fMidiOutEvents, 0.0f);
  553. }
  554. protected:
  555. // -------------------------------------------------------------------
  556. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  557. {
  558. CARLA_SAFE_ASSERT_RETURN(fDescriptor->midiOuts > 0, false);
  559. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  560. CARLA_SAFE_ASSERT_RETURN(event->data[0] != 0, false);
  561. if (fMidiOutEvents.numEvents >= static_cast<int32_t>(kMaxMidiEvents))
  562. {
  563. // send current events
  564. hostCallback(audioMasterProcessEvents, 0, 0, &fMidiOutEvents, 0.0f);
  565. // clear
  566. fMidiOutEvents.numEvents = 0;
  567. }
  568. VstMidiEvent& vstMidiEvent(fMidiOutEvents.mdata[fMidiOutEvents.numEvents++]);
  569. vstMidiEvent.type = kVstMidiType;
  570. vstMidiEvent.byteSize = kVstMidiEventSize;
  571. uint8_t i=0;
  572. for (; i<event->size; ++i)
  573. vstMidiEvent.midiData[i] = static_cast<char>(event->data[i]);
  574. for (; i<4; ++i)
  575. vstMidiEvent.midiData[i] = 0;
  576. return true;
  577. }
  578. void handleUiParameterChanged(const uint32_t index, const float value) const
  579. {
  580. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, index);
  581. CARLA_SAFE_ASSERT_RETURN(param != nullptr,);
  582. const float normalizedValue = (value - param->ranges.min) / (param->ranges.max - param->ranges.min);
  583. hostCallback(audioMasterAutomate, static_cast<int32_t>(index), 0, nullptr, normalizedValue);
  584. }
  585. void handleUiCustomDataChanged(const char* const /*key*/, const char* const /*value*/) const
  586. {
  587. }
  588. void handleUiClosed()
  589. {
  590. }
  591. const char* handleUiOpenFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  592. {
  593. // TODO
  594. return nullptr;
  595. }
  596. const char* handleUiSaveFile(const bool /*isDir*/, const char* const /*title*/, const char* const /*filter*/) const
  597. {
  598. // TODO
  599. return nullptr;
  600. }
  601. intptr_t handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index, const intptr_t value, void* const ptr, const float opt)
  602. {
  603. carla_debug("NativePlugin::handleDispatcher(%i, %i, " P_INTPTR ", %p, %f)", opcode, index, value, ptr, opt);
  604. switch (opcode)
  605. {
  606. case NATIVE_HOST_OPCODE_NULL:
  607. case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
  608. case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
  609. case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
  610. case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
  611. case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
  612. case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
  613. break;
  614. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  615. hostCallback(audioMasterUpdateDisplay);
  616. break;
  617. case NATIVE_HOST_OPCODE_HOST_IDLE:
  618. hostCallback(audioMasterIdle);
  619. break;
  620. }
  621. // unused for now
  622. return 0;
  623. (void)index; (void)value; (void)ptr; (void)opt;
  624. }
  625. private:
  626. // VST stuff
  627. AEffect* const fEffect;
  628. // Native data
  629. NativePluginHandle fHandle;
  630. NativeHostDescriptor fHost;
  631. const NativePluginDescriptor* const fDescriptor;
  632. // VST host data
  633. uint32_t fBufferSize;
  634. double fSampleRate;
  635. // Temporary data
  636. bool fIsActive;
  637. uint32_t fMidiEventCount;
  638. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  639. char fProgramName[32+1];
  640. NativeTimeInfo fTimeInfo;
  641. ERect fVstRect;
  642. // UI button
  643. CarlaUILauncher* fUiLauncher;
  644. // Host data
  645. enum HostType {
  646. kHostTypeNull = 0,
  647. kHostTypeArdour,
  648. kHostTypeBitwig
  649. };
  650. HostType fHostType;
  651. // host callback
  652. intptr_t hostCallback(const int32_t opcode,
  653. const int32_t index = 0,
  654. const intptr_t value = 0,
  655. void* const ptr = nullptr,
  656. const float opt = 0.0f) const
  657. {
  658. return VSTAudioMaster(fEffect, opcode, index, value, ptr, opt);
  659. }
  660. struct FixedVstEvents {
  661. int32_t numEvents;
  662. intptr_t reserved;
  663. VstEvent* data[kMaxMidiEvents];
  664. VstMidiEvent mdata[kMaxMidiEvents];
  665. FixedVstEvents()
  666. : numEvents(0),
  667. reserved(0)
  668. {
  669. for (uint32_t i=0; i<kMaxMidiEvents; ++i)
  670. data[i] = (VstEvent*)&mdata[i];
  671. carla_zeroStructs(mdata, kMaxMidiEvents);
  672. }
  673. CARLA_DECLARE_NON_COPY_STRUCT(FixedVstEvents);
  674. } fMidiOutEvents;
  675. #ifdef USING_JUCE
  676. juce::SharedResourcePointer<juce::ScopedJuceInitialiser_GUI> fJuceInitialiser;
  677. #endif
  678. char* fStateChunk;
  679. // -------------------------------------------------------------------
  680. #define handlePtr ((NativePlugin*)handle)
  681. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  682. {
  683. return handlePtr->fBufferSize;
  684. }
  685. static double host_get_sample_rate(NativeHostHandle handle)
  686. {
  687. return handlePtr->fSampleRate;
  688. }
  689. static bool host_is_offline(NativeHostHandle /*handle*/)
  690. {
  691. // TODO
  692. return false;
  693. }
  694. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  695. {
  696. return &(handlePtr->fTimeInfo);
  697. }
  698. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  699. {
  700. return handlePtr->handleWriteMidiEvent(event);
  701. }
  702. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  703. {
  704. handlePtr->handleUiParameterChanged(index, value);
  705. }
  706. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  707. {
  708. handlePtr->handleUiCustomDataChanged(key, value);
  709. }
  710. static void host_ui_closed(NativeHostHandle handle)
  711. {
  712. handlePtr->handleUiClosed();
  713. }
  714. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  715. {
  716. return handlePtr->handleUiOpenFile(isDir, title, filter);
  717. }
  718. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  719. {
  720. return handlePtr->handleUiSaveFile(isDir, title, filter);
  721. }
  722. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  723. {
  724. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  725. }
  726. #undef handlePtr
  727. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  728. };
  729. // -----------------------------------------------------------------------
  730. #define validObject effect != nullptr && effect->object != nullptr
  731. #define validPlugin effect != nullptr && effect->object != nullptr && ((VstObject*)effect->object)->plugin != nullptr
  732. #define vstObjectPtr (VstObject*)effect->object
  733. #define pluginPtr (vstObjectPtr)->plugin
  734. intptr_t vst_dispatcherCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  735. {
  736. // handle base opcodes
  737. switch (opcode)
  738. {
  739. case effOpen:
  740. if (VstObject* const obj = vstObjectPtr)
  741. {
  742. // this must always be valid
  743. CARLA_SAFE_ASSERT_RETURN(obj->audioMaster != nullptr, 0);
  744. // some hosts call effOpen twice
  745. CARLA_SAFE_ASSERT_RETURN(obj->plugin == nullptr, 1);
  746. d_lastBufferSize = static_cast<uint32_t>(VSTAudioMaster(effect, audioMasterGetBlockSize, 0, 0, nullptr, 0.0f));
  747. d_lastSampleRate = static_cast<double>(VSTAudioMaster(effect, audioMasterGetSampleRate, 0, 0, nullptr, 0.0f));
  748. // some hosts are not ready at this point or return 0 buffersize/samplerate
  749. if (d_lastBufferSize == 0)
  750. d_lastBufferSize = 2048;
  751. if (d_lastSampleRate <= 0.0)
  752. d_lastSampleRate = 44100.0;
  753. const NativePluginDescriptor* pluginDesc = nullptr;
  754. PluginListManager& plm(PluginListManager::getInstance());
  755. #ifdef CARLA_VST_SHELL
  756. if (effect->uniqueID == 0)
  757. effect->uniqueID = kShellUniqueID;
  758. if (effect->uniqueID == kShellUniqueID)
  759. {
  760. // first open for discovery, nothing to do
  761. effect->numParams = 0;
  762. effect->numPrograms = 0;
  763. effect->numInputs = 0;
  764. effect->numOutputs = 0;
  765. return 1;
  766. }
  767. const int32_t plugIndex = effect->uniqueID - kShellUniqueID - 1;
  768. CARLA_SAFE_ASSERT_RETURN(plugIndex >= 0, 0);
  769. pluginDesc = plm.descs.getAt(static_cast<size_t>(plugIndex), nullptr);
  770. #else // CARLA_VST_SHELL
  771. # if defined(CARLA_PLUGIN_32CH)
  772. const char* const pluginLabel = "carlapatchbay32";
  773. # elif defined(CARLA_PLUGIN_16CH)
  774. const char* const pluginLabel = "carlapatchbay16";
  775. # elif CARLA_PLUGIN_PATCHBAY
  776. const char* const pluginLabel = "carlapatchbay";
  777. # else
  778. const char* const pluginLabel = "carlarack";
  779. # endif
  780. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  781. {
  782. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  783. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  784. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  785. {
  786. pluginDesc = tmpDesc;
  787. break;
  788. }
  789. }
  790. #endif // CARLA_VST_SHELL
  791. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, 0);
  792. #ifdef CARLA_VST_SHELL
  793. effect->numPrograms = 1;
  794. effect->numParams = static_cast<int>(pluginDesc->paramIns);
  795. effect->numInputs = static_cast<int>(pluginDesc->audioIns);
  796. effect->numOutputs = static_cast<int>(pluginDesc->audioOuts);
  797. if (pluginDesc->hints & NATIVE_PLUGIN_HAS_UI)
  798. effect->flags |= effFlagsHasEditor;
  799. else
  800. effect->flags &= ~effFlagsHasEditor;
  801. if (pluginDesc->hints & NATIVE_PLUGIN_IS_SYNTH)
  802. effect->flags |= effFlagsIsSynth;
  803. else
  804. effect->flags &= ~effFlagsIsSynth;
  805. #endif // CARLA_VST_SHELL
  806. #if CARLA_PLUGIN_SYNTH
  807. // override if requested
  808. effect->flags |= effFlagsIsSynth;
  809. #endif
  810. obj->plugin = new NativePlugin(effect, pluginDesc);
  811. return 1;
  812. }
  813. return 0;
  814. case effClose:
  815. if (VstObject* const obj = vstObjectPtr)
  816. {
  817. NativePlugin* const plugin(obj->plugin);
  818. if (plugin != nullptr)
  819. {
  820. obj->plugin = nullptr;
  821. delete plugin;
  822. }
  823. #if 0
  824. /* This code invalidates the object created in VSTPluginMain
  825. * Probably not safe against all hosts */
  826. obj->audioMaster = nullptr;
  827. effect->object = nullptr;
  828. delete obj;
  829. #endif
  830. return 1;
  831. }
  832. //delete effect;
  833. return 0;
  834. case effGetPlugCategory:
  835. #ifdef CARLA_VST_SHELL
  836. if (validPlugin)
  837. {
  838. #if CARLA_PLUGIN_SYNTH
  839. return kPlugCategSynth;
  840. #else
  841. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  842. return desc->category == NATIVE_PLUGIN_CATEGORY_SYNTH ? kPlugCategSynth : kPlugCategEffect;
  843. #endif
  844. }
  845. return kPlugCategShell;
  846. #elif CARLA_PLUGIN_SYNTH
  847. return kPlugCategSynth;
  848. #else
  849. return kPlugCategEffect;
  850. #endif
  851. case effGetEffectName:
  852. if (char* const cptr = (char*)ptr)
  853. {
  854. #if defined(CARLA_VST_SHELL)
  855. if (validPlugin)
  856. {
  857. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  858. std::strncpy(cptr, desc->name, 32);
  859. }
  860. else
  861. {
  862. std::strncpy(cptr, "Carla-VstShell", 32);
  863. }
  864. #elif defined(CARLA_PLUGIN_32CH)
  865. std::strncpy(cptr, "Carla-Patchbay32", 32);
  866. #elif defined(CARLA_PLUGIN_16CH)
  867. std::strncpy(cptr, "Carla-Patchbay16", 32);
  868. #elif CARLA_PLUGIN_PATCHBAY
  869. # if CARLA_PLUGIN_SYNTH
  870. std::strncpy(cptr, "Carla-Patchbay", 32);
  871. # else
  872. std::strncpy(cptr, "Carla-PatchbayFX", 32);
  873. # endif
  874. #else // Rack mode
  875. # if CARLA_PLUGIN_SYNTH
  876. std::strncpy(cptr, "Carla-Rack", 32);
  877. # else
  878. std::strncpy(cptr, "Carla-RackFX", 32);
  879. # endif
  880. #endif
  881. return 1;
  882. }
  883. return 0;
  884. case effGetVendorString:
  885. if (char* const cptr = (char*)ptr)
  886. {
  887. #ifdef CARLA_VST_SHELL
  888. if (validPlugin)
  889. {
  890. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  891. std::strncpy(cptr, desc->maker, 32);
  892. }
  893. else
  894. #endif
  895. std::strncpy(cptr, "falkTX", 32);
  896. return 1;
  897. }
  898. return 0;
  899. case effGetProductString:
  900. if (char* const cptr = (char*)ptr)
  901. {
  902. #if defined(CARLA_VST_SHELL)
  903. if (validPlugin)
  904. {
  905. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  906. std::strncpy(cptr, desc->label, 32);
  907. }
  908. else
  909. {
  910. std::strncpy(cptr, "CarlaVstShell", 32);
  911. }
  912. #elif defined(CARLA_PLUGIN_32CH)
  913. std::strncpy(cptr, "CarlaPatchbay32", 32);
  914. #elif defined(CARLA_PLUGIN_16CH)
  915. std::strncpy(cptr, "CarlaPatchbay16", 32);
  916. #elif CARLA_PLUGIN_PATCHBAY
  917. # if CARLA_PLUGIN_SYNTH
  918. std::strncpy(cptr, "CarlaPatchbay", 32);
  919. # else
  920. std::strncpy(cptr, "CarlaPatchbayFX", 32);
  921. # endif
  922. #else
  923. # if CARLA_PLUGIN_SYNTH
  924. std::strncpy(cptr, "CarlaRack", 32);
  925. # else
  926. std::strncpy(cptr, "CarlaRackFX", 32);
  927. # endif
  928. #endif
  929. return 1;
  930. }
  931. return 0;
  932. case effGetVendorVersion:
  933. return CARLA_VERSION_HEX;
  934. case effGetVstVersion:
  935. return kVstVersion;
  936. #ifdef CARLA_VST_SHELL
  937. case effShellGetNextPlugin:
  938. if (char* const cptr = (char*)ptr)
  939. {
  940. CARLA_SAFE_ASSERT_RETURN(effect != nullptr, 0);
  941. CARLA_SAFE_ASSERT_RETURN(effect->uniqueID >= kShellUniqueID, 0);
  942. PluginListManager& plm(PluginListManager::getInstance());
  943. for (;;)
  944. {
  945. const uint index2 = static_cast<uint>(effect->uniqueID - kShellUniqueID);
  946. if (index2 >= plm.descs.count())
  947. {
  948. effect->uniqueID = kShellUniqueID;
  949. return 0;
  950. }
  951. const NativePluginDescriptor* const desc = plm.descs.getAt(index2, nullptr);
  952. CARLA_SAFE_ASSERT_RETURN(desc != nullptr, 0);
  953. ++effect->uniqueID;
  954. if (desc->midiIns > 1 || desc->midiOuts > 1)
  955. continue;
  956. std::strncpy(cptr, desc->label, 32);
  957. return effect->uniqueID;
  958. }
  959. }
  960. #endif
  961. };
  962. // handle advanced opcodes
  963. if (validPlugin)
  964. return pluginPtr->vst_dispatcher(opcode, index, value, ptr, opt);
  965. return 0;
  966. }
  967. float vst_getParameterCallback(AEffect* effect, int32_t index)
  968. {
  969. if (validPlugin)
  970. return pluginPtr->vst_getParameter(index);
  971. return 0.0f;
  972. }
  973. void vst_setParameterCallback(AEffect* effect, int32_t index, float value)
  974. {
  975. if (validPlugin)
  976. pluginPtr->vst_setParameter(index, value);
  977. }
  978. void vst_processCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames)
  979. {
  980. if (validPlugin)
  981. pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames);
  982. }
  983. void vst_processReplacingCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames)
  984. {
  985. if (validPlugin)
  986. pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames);
  987. }
  988. #undef pluginPtr
  989. #undef validObject
  990. #undef validPlugin
  991. #undef vstObjectPtr
  992. // -----------------------------------------------------------------------
  993. const AEffect* VSTPluginMainInit(AEffect* const effect)
  994. {
  995. #if defined(CARLA_VST_SHELL)
  996. if (const intptr_t uniqueID = VSTAudioMaster(effect, audioMasterCurrentId, 0, 0, nullptr, 0.0f))
  997. effect->uniqueID = static_cast<int>(uniqueID);
  998. else
  999. effect->uniqueID = kShellUniqueID;
  1000. #elif defined(CARLA_PLUGIN_32CH)
  1001. effect->uniqueID = kBaseUniqueID+6;
  1002. #elif defined(CARLA_PLUGIN_16CH)
  1003. effect->uniqueID = kBaseUniqueID+5;
  1004. #elif CARLA_PLUGIN_PATCHBAY
  1005. # if CARLA_PLUGIN_SYNTH
  1006. effect->uniqueID = kBaseUniqueID+4;
  1007. # else
  1008. effect->uniqueID = kBaseUniqueID+3;
  1009. # endif
  1010. #else
  1011. # if CARLA_PLUGIN_SYNTH
  1012. effect->uniqueID = kBaseUniqueID+2;
  1013. # else
  1014. effect->uniqueID = kBaseUniqueID+1;
  1015. # endif
  1016. #endif
  1017. // plugin fields
  1018. #ifndef CARLA_VST_SHELL
  1019. effect->numParams = kNumParameters;
  1020. effect->numPrograms = 1;
  1021. # if defined(CARLA_PLUGIN_32CH)
  1022. effect->numInputs = 32;
  1023. effect->numOutputs = 32;
  1024. # elif defined(CARLA_PLUGIN_16CH)
  1025. effect->numInputs = 16;
  1026. effect->numOutputs = 16;
  1027. # else
  1028. effect->numInputs = 2;
  1029. effect->numOutputs = 2;
  1030. # endif
  1031. #endif
  1032. // plugin flags
  1033. effect->flags |= effFlagsCanReplacing;
  1034. effect->flags |= effFlagsProgramChunks;
  1035. #ifndef CARLA_VST_SHELL
  1036. effect->flags |= effFlagsHasEditor;
  1037. #endif
  1038. #if CARLA_PLUGIN_SYNTH
  1039. effect->flags |= effFlagsIsSynth;
  1040. #endif
  1041. return effect;
  1042. }
  1043. // -----------------------------------------------------------------------