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.

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