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.

1285 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. if (kIsUsingUILauncher)
  331. {
  332. destoryUILauncher(fUiLauncher);
  333. fUiLauncher = createUILauncher((intptr_t)ptr, fDescriptor, fHandle);
  334. }
  335. else
  336. {
  337. char strBuf[0xff+1];
  338. std::snprintf(strBuf, 0xff, P_INTPTR, (intptr_t)ptr);
  339. strBuf[0xff] = '\0';
  340. // set CARLA_PLUGIN_EMBED_WINID for external process
  341. carla_setenv("CARLA_PLUGIN_EMBED_WINID", strBuf);
  342. // show UI now
  343. fDescriptor->ui_show(fHandle, true);
  344. // reset CARLA_PLUGIN_EMBED_WINID just in case
  345. carla_setenv("CARLA_PLUGIN_EMBED_WINID", "0");
  346. }
  347. ret = 1;
  348. }
  349. break;
  350. case effEditClose:
  351. if (fDescriptor->ui_show != nullptr)
  352. {
  353. if (kIsUsingUILauncher)
  354. {
  355. destoryUILauncher(fUiLauncher);
  356. fUiLauncher = nullptr;
  357. }
  358. else
  359. {
  360. fDescriptor->ui_show(fHandle, false);
  361. }
  362. ret = 1;
  363. }
  364. break;
  365. case effEditIdle:
  366. if (fUiLauncher != nullptr)
  367. idleUILauncher(fUiLauncher);
  368. if (fDescriptor->ui_idle != nullptr)
  369. fDescriptor->ui_idle(fHandle);
  370. break;
  371. case effGetChunk:
  372. if (ptr == nullptr || fDescriptor->get_state == nullptr)
  373. return 0;
  374. if (fStateChunk != nullptr)
  375. std::free(fStateChunk);
  376. fStateChunk = fDescriptor->get_state(fHandle);
  377. if (fStateChunk == nullptr)
  378. return 0;
  379. ret = static_cast<intptr_t>(std::strlen(fStateChunk)+1);
  380. *(void**)ptr = fStateChunk;
  381. break;
  382. case effSetChunk:
  383. if (value <= 0 || fDescriptor->set_state == nullptr)
  384. return 0;
  385. if (value == 1)
  386. return 1;
  387. if (const char* const state = (const char*)ptr)
  388. {
  389. fDescriptor->set_state(fHandle, state);
  390. ret = 1;
  391. }
  392. break;
  393. case effProcessEvents:
  394. if (! fIsActive)
  395. {
  396. // host has not activated the plugin yet, nasty!
  397. vst_dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  398. }
  399. if (const VstEvents* const events = (const VstEvents*)ptr)
  400. {
  401. if (events->numEvents == 0)
  402. break;
  403. for (int i=0, count=events->numEvents; i < count; ++i)
  404. {
  405. const VstMidiEvent* const vstMidiEvent((const VstMidiEvent*)events->events[i]);
  406. if (vstMidiEvent == nullptr)
  407. break;
  408. if (vstMidiEvent->type != kVstMidiType || vstMidiEvent->deltaFrames < 0)
  409. continue;
  410. if (fMidiEventCount >= kMaxMidiEvents)
  411. break;
  412. const uint32_t j(fMidiEventCount++);
  413. fMidiEvents[j].port = 0;
  414. fMidiEvents[j].time = static_cast<uint32_t>(vstMidiEvent->deltaFrames);
  415. fMidiEvents[j].size = 3;
  416. for (uint32_t k=0; k<3; ++k)
  417. fMidiEvents[j].data[k] = static_cast<uint8_t>(vstMidiEvent->midiData[k]);
  418. }
  419. }
  420. break;
  421. case effCanBeAutomated:
  422. ret = 1;
  423. break;
  424. case effCanDo:
  425. if (const char* const canDo = (const char*)ptr)
  426. {
  427. if (std::strcmp(canDo, "receiveVstEvents") == 0 || std::strcmp(canDo, "receiveVstMidiEvent") == 0)
  428. {
  429. if (fDescriptor->midiIns == 0)
  430. return -1;
  431. return 1;
  432. }
  433. if (std::strcmp(canDo, "sendVstEvents") == 0 || std::strcmp(canDo, "sendVstMidiEvent") == 0)
  434. {
  435. if (fDescriptor->midiOuts == 0)
  436. return -1;
  437. return 1;
  438. }
  439. if (std::strcmp(canDo, "receiveVstTimeInfo") == 0)
  440. return 1;
  441. }
  442. break;
  443. }
  444. return ret;
  445. }
  446. float vst_getParameter(const int32_t index)
  447. {
  448. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0.0f);
  449. const uint32_t uindex = static_cast<uint32_t>(index);
  450. CARLA_SAFE_ASSERT_RETURN(uindex < fDescriptor->paramIns, 0.0f);
  451. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, uindex);
  452. CARLA_SAFE_ASSERT_RETURN(param != nullptr, 0);
  453. const float realValue = fDescriptor->get_parameter_value(fHandle, uindex);
  454. return (realValue - param->ranges.min) / (param->ranges.max - param->ranges.min);
  455. }
  456. void vst_setParameter(const int32_t index, const float value)
  457. {
  458. CARLA_SAFE_ASSERT_RETURN(index >= 0,);
  459. const uint32_t uindex = static_cast<uint32_t>(index);
  460. CARLA_SAFE_ASSERT_RETURN(uindex < fDescriptor->paramIns,);
  461. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, uindex);
  462. CARLA_SAFE_ASSERT_RETURN(param != nullptr,);
  463. float realValue;
  464. if (param->hints & NATIVE_PARAMETER_IS_BOOLEAN)
  465. {
  466. realValue = value > 0.5f ? param->ranges.max : param->ranges.min;
  467. }
  468. else
  469. {
  470. realValue = param->ranges.min + ((param->ranges.max - param->ranges.min) * value);
  471. if (param->hints & NATIVE_PARAMETER_IS_INTEGER)
  472. realValue = std::round(realValue);
  473. }
  474. fDescriptor->set_parameter_value(fHandle, uindex, realValue);
  475. }
  476. void vst_processReplacing(const float** const inputs, float** const outputs, const int32_t sampleFrames)
  477. {
  478. if (sampleFrames <= 0)
  479. return;
  480. if (fHostType == kHostTypeBitwig && static_cast<int32_t>(fBufferSize) != sampleFrames)
  481. {
  482. // deactivate first if needed
  483. if (fIsActive && fDescriptor->deactivate != nullptr)
  484. fDescriptor->deactivate(fHandle);
  485. fBufferSize = static_cast<uint32_t>(sampleFrames);
  486. if (fDescriptor->dispatcher != nullptr)
  487. fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_BUFFER_SIZE_CHANGED, 0, sampleFrames, nullptr, 0.0f);
  488. // activate again
  489. if (fDescriptor->activate != nullptr)
  490. fDescriptor->activate(fHandle);
  491. fIsActive = true;
  492. }
  493. if (! fIsActive)
  494. {
  495. // host has not activated the plugin yet, nasty!
  496. vst_dispatcher(effMainsChanged, 0, 1, nullptr, 0.0f);
  497. }
  498. static const int kWantVstTimeFlags = kVstTransportPlaying|kVstPpqPosValid|kVstTempoValid|kVstTimeSigValid;
  499. if (const VstTimeInfo* const vstTimeInfo = (const VstTimeInfo*)hostCallback(audioMasterGetTime, 0, kWantVstTimeFlags))
  500. {
  501. fTimeInfo.frame = static_cast<uint64_t>(vstTimeInfo->samplePos);
  502. fTimeInfo.playing = (vstTimeInfo->flags & kVstTransportPlaying);
  503. fTimeInfo.bbt.valid = ((vstTimeInfo->flags & kVstTempoValid) != 0 || (vstTimeInfo->flags & kVstTimeSigValid) != 0);
  504. // ticksPerBeat is not possible with VST
  505. fTimeInfo.bbt.ticksPerBeat = 960.0;
  506. if (vstTimeInfo->flags & kVstTempoValid)
  507. fTimeInfo.bbt.beatsPerMinute = vstTimeInfo->tempo;
  508. else
  509. fTimeInfo.bbt.beatsPerMinute = 120.0;
  510. if (vstTimeInfo->flags & (kVstPpqPosValid|kVstTimeSigValid))
  511. {
  512. const double ppqPos = std::abs(vstTimeInfo->ppqPos);
  513. const int ppqPerBar = vstTimeInfo->timeSigNumerator * 4 / vstTimeInfo->timeSigDenominator;
  514. const double barBeats = (std::fmod(ppqPos, ppqPerBar) / ppqPerBar) * vstTimeInfo->timeSigNumerator;
  515. const double rest = std::fmod(barBeats, 1.0);
  516. fTimeInfo.bbt.bar = static_cast<int32_t>(ppqPos) / ppqPerBar + 1;
  517. fTimeInfo.bbt.beat = static_cast<int32_t>(barBeats - rest + 0.5) + 1;
  518. fTimeInfo.bbt.tick = static_cast<int32_t>(rest * fTimeInfo.bbt.ticksPerBeat + 0.5);
  519. fTimeInfo.bbt.beatsPerBar = static_cast<float>(vstTimeInfo->timeSigNumerator);
  520. fTimeInfo.bbt.beatType = static_cast<float>(vstTimeInfo->timeSigDenominator);
  521. if (vstTimeInfo->ppqPos < 0.0)
  522. {
  523. --fTimeInfo.bbt.bar;
  524. fTimeInfo.bbt.beat = vstTimeInfo->timeSigNumerator - fTimeInfo.bbt.beat + 1;
  525. fTimeInfo.bbt.tick = fTimeInfo.bbt.ticksPerBeat - fTimeInfo.bbt.tick - 1;
  526. }
  527. }
  528. else
  529. {
  530. fTimeInfo.bbt.bar = 1;
  531. fTimeInfo.bbt.beat = 1;
  532. fTimeInfo.bbt.tick = 0;
  533. fTimeInfo.bbt.beatsPerBar = 4.0f;
  534. fTimeInfo.bbt.beatType = 4.0f;
  535. }
  536. fTimeInfo.bbt.barStartTick = fTimeInfo.bbt.ticksPerBeat *
  537. static_cast<double>(fTimeInfo.bbt.beatsPerBar) *
  538. (fTimeInfo.bbt.bar - 1);
  539. }
  540. fMidiOutEvents.numEvents = 0;
  541. if (fHandle != nullptr)
  542. // FIXME
  543. fDescriptor->process(fHandle,
  544. inputs, outputs, static_cast<uint32_t>(sampleFrames),
  545. fMidiEvents, fMidiEventCount);
  546. fMidiEventCount = 0;
  547. if (fMidiOutEvents.numEvents > 0)
  548. hostCallback(audioMasterProcessEvents, 0, 0, &fMidiOutEvents, 0.0f);
  549. }
  550. protected:
  551. // -------------------------------------------------------------------
  552. bool handleWriteMidiEvent(const NativeMidiEvent* const event)
  553. {
  554. CARLA_SAFE_ASSERT_RETURN(fDescriptor->midiOuts > 0, false);
  555. CARLA_SAFE_ASSERT_RETURN(event != nullptr, false);
  556. CARLA_SAFE_ASSERT_RETURN(event->data[0] != 0, false);
  557. if (fMidiOutEvents.numEvents >= static_cast<int32_t>(kMaxMidiEvents))
  558. {
  559. // send current events
  560. hostCallback(audioMasterProcessEvents, 0, 0, &fMidiOutEvents, 0.0f);
  561. // clear
  562. fMidiOutEvents.numEvents = 0;
  563. }
  564. VstMidiEvent& vstMidiEvent(fMidiOutEvents.mdata[fMidiOutEvents.numEvents++]);
  565. vstMidiEvent.type = kVstMidiType;
  566. vstMidiEvent.byteSize = kVstMidiEventSize;
  567. uint8_t i=0;
  568. for (; i<event->size; ++i)
  569. vstMidiEvent.midiData[i] = static_cast<char>(event->data[i]);
  570. for (; i<4; ++i)
  571. vstMidiEvent.midiData[i] = 0;
  572. return true;
  573. }
  574. void handleUiParameterChanged(const uint32_t index, const float value) const
  575. {
  576. const NativeParameter* const param = fDescriptor->get_parameter_info(fHandle, index);
  577. CARLA_SAFE_ASSERT_RETURN(param != nullptr,);
  578. const float normalizedValue = (value - param->ranges.min) / (param->ranges.max - param->ranges.min);
  579. hostCallback(audioMasterAutomate, static_cast<int32_t>(index), 0, nullptr, normalizedValue);
  580. }
  581. void handleUiParameterTouch(const uint32_t index, const bool touch) const
  582. {
  583. hostCallback(touch ? audioMasterBeginEdit : audioMasterEndEdit, static_cast<int32_t>(index));
  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. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  614. // nothing
  615. break;
  616. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  617. hostCallback(audioMasterUpdateDisplay);
  618. break;
  619. case NATIVE_HOST_OPCODE_HOST_IDLE:
  620. hostCallback(audioMasterIdle);
  621. break;
  622. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  623. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  624. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  625. break;
  626. }
  627. // unused for now
  628. return 0;
  629. (void)ptr; (void)opt;
  630. }
  631. private:
  632. // VST stuff
  633. AEffect* const fEffect;
  634. // Native data
  635. NativePluginHandle fHandle;
  636. NativeHostDescriptor fHost;
  637. const NativePluginDescriptor* const fDescriptor;
  638. // VST host data
  639. uint32_t fBufferSize;
  640. double fSampleRate;
  641. // Temporary data
  642. bool fIsActive;
  643. uint32_t fMidiEventCount;
  644. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  645. char fProgramName[32+1];
  646. NativeTimeInfo fTimeInfo;
  647. ERect fVstRect;
  648. // UI button
  649. CarlaUILauncher* fUiLauncher;
  650. // Host data
  651. enum HostType {
  652. kHostTypeNull = 0,
  653. kHostTypeArdour,
  654. kHostTypeBitwig
  655. };
  656. HostType fHostType;
  657. // host callback
  658. intptr_t hostCallback(const int32_t opcode,
  659. const int32_t index = 0,
  660. const intptr_t value = 0,
  661. void* const ptr = nullptr,
  662. const float opt = 0.0f) const
  663. {
  664. return VSTAudioMaster(fEffect, opcode, index, value, ptr, opt);
  665. }
  666. struct FixedVstEvents {
  667. int32_t numEvents;
  668. intptr_t reserved;
  669. VstEvent* data[kMaxMidiEvents];
  670. VstMidiEvent mdata[kMaxMidiEvents];
  671. FixedVstEvents()
  672. : numEvents(0),
  673. reserved(0)
  674. {
  675. for (uint32_t i=0; i<kMaxMidiEvents; ++i)
  676. data[i] = (VstEvent*)&mdata[i];
  677. carla_zeroStructs(mdata, kMaxMidiEvents);
  678. }
  679. CARLA_DECLARE_NON_COPY_STRUCT(FixedVstEvents);
  680. } fMidiOutEvents;
  681. #ifdef USING_JUCE
  682. juce::SharedResourcePointer<juce::ScopedJuceInitialiser_GUI> fJuceInitialiser;
  683. #endif
  684. char* fStateChunk;
  685. // -------------------------------------------------------------------
  686. #define handlePtr ((NativePlugin*)handle)
  687. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  688. {
  689. return handlePtr->fBufferSize;
  690. }
  691. static double host_get_sample_rate(NativeHostHandle handle)
  692. {
  693. return handlePtr->fSampleRate;
  694. }
  695. static bool host_is_offline(NativeHostHandle /*handle*/)
  696. {
  697. // TODO
  698. return false;
  699. }
  700. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  701. {
  702. return &(handlePtr->fTimeInfo);
  703. }
  704. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  705. {
  706. return handlePtr->handleWriteMidiEvent(event);
  707. }
  708. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  709. {
  710. handlePtr->handleUiParameterChanged(index, value);
  711. }
  712. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  713. {
  714. handlePtr->handleUiCustomDataChanged(key, value);
  715. }
  716. static void host_ui_closed(NativeHostHandle handle)
  717. {
  718. handlePtr->handleUiClosed();
  719. }
  720. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  721. {
  722. return handlePtr->handleUiOpenFile(isDir, title, filter);
  723. }
  724. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  725. {
  726. return handlePtr->handleUiSaveFile(isDir, title, filter);
  727. }
  728. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  729. {
  730. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  731. }
  732. #undef handlePtr
  733. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  734. };
  735. // -----------------------------------------------------------------------
  736. #define validObject effect != nullptr && effect->object != nullptr
  737. #define validPlugin effect != nullptr && effect->object != nullptr && ((VstObject*)effect->object)->plugin != nullptr
  738. #define vstObjectPtr (VstObject*)effect->object
  739. #define pluginPtr (vstObjectPtr)->plugin
  740. intptr_t vst_dispatcherCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  741. {
  742. // handle base opcodes
  743. switch (opcode)
  744. {
  745. case effOpen:
  746. if (VstObject* const obj = vstObjectPtr)
  747. {
  748. // this must always be valid
  749. CARLA_SAFE_ASSERT_RETURN(obj->audioMaster != nullptr, 0);
  750. // some hosts call effOpen twice
  751. CARLA_SAFE_ASSERT_RETURN(obj->plugin == nullptr, 1);
  752. d_lastBufferSize = static_cast<uint32_t>(VSTAudioMaster(effect, audioMasterGetBlockSize, 0, 0, nullptr, 0.0f));
  753. d_lastSampleRate = static_cast<double>(VSTAudioMaster(effect, audioMasterGetSampleRate, 0, 0, nullptr, 0.0f));
  754. // some hosts are not ready at this point or return 0 buffersize/samplerate
  755. if (d_lastBufferSize == 0)
  756. d_lastBufferSize = 2048;
  757. if (d_lastSampleRate <= 0.0)
  758. d_lastSampleRate = 44100.0;
  759. const NativePluginDescriptor* pluginDesc = nullptr;
  760. PluginListManager& plm(PluginListManager::getInstance());
  761. #ifdef CARLA_VST_SHELL
  762. if (effect->uniqueID == 0)
  763. effect->uniqueID = kShellUniqueID;
  764. if (effect->uniqueID == kShellUniqueID)
  765. {
  766. // first open for discovery, nothing to do
  767. effect->numParams = 0;
  768. effect->numPrograms = 0;
  769. effect->numInputs = 0;
  770. effect->numOutputs = 0;
  771. return 1;
  772. }
  773. const int32_t plugIndex = effect->uniqueID - kShellUniqueID - 1;
  774. CARLA_SAFE_ASSERT_RETURN(plugIndex >= 0, 0);
  775. pluginDesc = plm.descs.getAt(static_cast<size_t>(plugIndex), nullptr);
  776. #else // CARLA_VST_SHELL
  777. # if defined(CARLA_PLUGIN_32CH)
  778. const char* const pluginLabel = "carlapatchbay32";
  779. # elif defined(CARLA_PLUGIN_16CH)
  780. const char* const pluginLabel = "carlapatchbay16";
  781. # elif CARLA_PLUGIN_PATCHBAY
  782. const char* const pluginLabel = "carlapatchbay";
  783. # else
  784. const char* const pluginLabel = "carlarack";
  785. # endif
  786. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  787. {
  788. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  789. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  790. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  791. {
  792. pluginDesc = tmpDesc;
  793. break;
  794. }
  795. }
  796. #endif // CARLA_VST_SHELL
  797. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, 0);
  798. #ifdef CARLA_VST_SHELL
  799. effect->numPrograms = 1;
  800. effect->numParams = static_cast<int>(pluginDesc->paramIns);
  801. effect->numInputs = static_cast<int>(pluginDesc->audioIns);
  802. effect->numOutputs = static_cast<int>(pluginDesc->audioOuts);
  803. if (pluginDesc->hints & NATIVE_PLUGIN_HAS_UI)
  804. effect->flags |= effFlagsHasEditor;
  805. else
  806. effect->flags &= ~effFlagsHasEditor;
  807. if (pluginDesc->hints & NATIVE_PLUGIN_IS_SYNTH)
  808. effect->flags |= effFlagsIsSynth;
  809. else
  810. effect->flags &= ~effFlagsIsSynth;
  811. #endif // CARLA_VST_SHELL
  812. #if CARLA_PLUGIN_SYNTH
  813. // override if requested
  814. effect->flags |= effFlagsIsSynth;
  815. #endif
  816. obj->plugin = new NativePlugin(effect, pluginDesc);
  817. return 1;
  818. }
  819. return 0;
  820. case effClose:
  821. if (VstObject* const obj = vstObjectPtr)
  822. {
  823. NativePlugin* const plugin(obj->plugin);
  824. if (plugin != nullptr)
  825. {
  826. obj->plugin = nullptr;
  827. delete plugin;
  828. }
  829. #if 0
  830. /* This code invalidates the object created in VSTPluginMain
  831. * Probably not safe against all hosts */
  832. obj->audioMaster = nullptr;
  833. effect->object = nullptr;
  834. delete obj;
  835. #endif
  836. return 1;
  837. }
  838. //delete effect;
  839. return 0;
  840. case effGetPlugCategory:
  841. #ifdef CARLA_VST_SHELL
  842. if (validPlugin)
  843. {
  844. #if CARLA_PLUGIN_SYNTH
  845. return kPlugCategSynth;
  846. #else
  847. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  848. return desc->category == NATIVE_PLUGIN_CATEGORY_SYNTH ? kPlugCategSynth : kPlugCategEffect;
  849. #endif
  850. }
  851. return kPlugCategShell;
  852. #elif CARLA_PLUGIN_SYNTH
  853. return kPlugCategSynth;
  854. #else
  855. return kPlugCategEffect;
  856. #endif
  857. case effGetEffectName:
  858. if (char* const cptr = (char*)ptr)
  859. {
  860. #if defined(CARLA_VST_SHELL)
  861. if (validPlugin)
  862. {
  863. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  864. std::strncpy(cptr, desc->name, 32);
  865. }
  866. else
  867. {
  868. std::strncpy(cptr, "Carla-VstShell", 32);
  869. }
  870. #elif defined(CARLA_PLUGIN_32CH)
  871. std::strncpy(cptr, "Carla-Patchbay32", 32);
  872. #elif defined(CARLA_PLUGIN_16CH)
  873. std::strncpy(cptr, "Carla-Patchbay16", 32);
  874. #elif CARLA_PLUGIN_PATCHBAY
  875. # if CARLA_PLUGIN_SYNTH
  876. std::strncpy(cptr, "Carla-Patchbay", 32);
  877. # else
  878. std::strncpy(cptr, "Carla-PatchbayFX", 32);
  879. # endif
  880. #else // Rack mode
  881. # if CARLA_PLUGIN_SYNTH
  882. std::strncpy(cptr, "Carla-Rack", 32);
  883. # else
  884. std::strncpy(cptr, "Carla-RackFX", 32);
  885. # endif
  886. #endif
  887. return 1;
  888. }
  889. return 0;
  890. case effGetVendorString:
  891. if (char* const cptr = (char*)ptr)
  892. {
  893. #ifdef CARLA_VST_SHELL
  894. if (validPlugin)
  895. {
  896. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  897. std::strncpy(cptr, desc->maker, 32);
  898. }
  899. else
  900. #endif
  901. std::strncpy(cptr, "falkTX", 32);
  902. return 1;
  903. }
  904. return 0;
  905. case effGetProductString:
  906. if (char* const cptr = (char*)ptr)
  907. {
  908. #if defined(CARLA_VST_SHELL)
  909. if (validPlugin)
  910. {
  911. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  912. std::strncpy(cptr, desc->label, 32);
  913. }
  914. else
  915. {
  916. std::strncpy(cptr, "CarlaVstShell", 32);
  917. }
  918. #elif defined(CARLA_PLUGIN_32CH)
  919. std::strncpy(cptr, "CarlaPatchbay32", 32);
  920. #elif defined(CARLA_PLUGIN_16CH)
  921. std::strncpy(cptr, "CarlaPatchbay16", 32);
  922. #elif CARLA_PLUGIN_PATCHBAY
  923. # if CARLA_PLUGIN_SYNTH
  924. std::strncpy(cptr, "CarlaPatchbay", 32);
  925. # else
  926. std::strncpy(cptr, "CarlaPatchbayFX", 32);
  927. # endif
  928. #else
  929. # if CARLA_PLUGIN_SYNTH
  930. std::strncpy(cptr, "CarlaRack", 32);
  931. # else
  932. std::strncpy(cptr, "CarlaRackFX", 32);
  933. # endif
  934. #endif
  935. return 1;
  936. }
  937. return 0;
  938. case effGetVendorVersion:
  939. return CARLA_VERSION_HEX;
  940. case effGetVstVersion:
  941. return kVstVersion;
  942. #ifdef CARLA_VST_SHELL
  943. case effShellGetNextPlugin:
  944. if (char* const cptr = (char*)ptr)
  945. {
  946. CARLA_SAFE_ASSERT_RETURN(effect != nullptr, 0);
  947. CARLA_SAFE_ASSERT_RETURN(effect->uniqueID >= kShellUniqueID, 0);
  948. PluginListManager& plm(PluginListManager::getInstance());
  949. for (;;)
  950. {
  951. const uint index2 = static_cast<uint>(effect->uniqueID - kShellUniqueID);
  952. if (index2 >= plm.descs.count())
  953. {
  954. effect->uniqueID = kShellUniqueID;
  955. return 0;
  956. }
  957. const NativePluginDescriptor* const desc = plm.descs.getAt(index2, nullptr);
  958. CARLA_SAFE_ASSERT_RETURN(desc != nullptr, 0);
  959. ++effect->uniqueID;
  960. if (desc->midiIns > 1 || desc->midiOuts > 1)
  961. continue;
  962. std::strncpy(cptr, desc->label, 32);
  963. return effect->uniqueID;
  964. }
  965. }
  966. #endif
  967. };
  968. // handle advanced opcodes
  969. if (validPlugin)
  970. return pluginPtr->vst_dispatcher(opcode, index, value, ptr, opt);
  971. return 0;
  972. }
  973. float vst_getParameterCallback(AEffect* effect, int32_t index)
  974. {
  975. if (validPlugin)
  976. return pluginPtr->vst_getParameter(index);
  977. return 0.0f;
  978. }
  979. void vst_setParameterCallback(AEffect* effect, int32_t index, float value)
  980. {
  981. if (validPlugin)
  982. pluginPtr->vst_setParameter(index, value);
  983. }
  984. void vst_processCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames)
  985. {
  986. if (validPlugin)
  987. pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames);
  988. }
  989. void vst_processReplacingCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames)
  990. {
  991. if (validPlugin)
  992. pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames);
  993. }
  994. #undef pluginPtr
  995. #undef validObject
  996. #undef validPlugin
  997. #undef vstObjectPtr
  998. // -----------------------------------------------------------------------
  999. const AEffect* VSTPluginMainInit(AEffect* const effect)
  1000. {
  1001. #if defined(CARLA_VST_SHELL)
  1002. if (const intptr_t uniqueID = VSTAudioMaster(effect, audioMasterCurrentId, 0, 0, nullptr, 0.0f))
  1003. effect->uniqueID = static_cast<int>(uniqueID);
  1004. else
  1005. effect->uniqueID = kShellUniqueID;
  1006. #elif defined(CARLA_PLUGIN_32CH)
  1007. effect->uniqueID = kBaseUniqueID+6;
  1008. #elif defined(CARLA_PLUGIN_16CH)
  1009. effect->uniqueID = kBaseUniqueID+5;
  1010. #elif CARLA_PLUGIN_PATCHBAY
  1011. # if CARLA_PLUGIN_SYNTH
  1012. effect->uniqueID = kBaseUniqueID+4;
  1013. # else
  1014. effect->uniqueID = kBaseUniqueID+3;
  1015. # endif
  1016. #else
  1017. # if CARLA_PLUGIN_SYNTH
  1018. effect->uniqueID = kBaseUniqueID+2;
  1019. # else
  1020. effect->uniqueID = kBaseUniqueID+1;
  1021. # endif
  1022. #endif
  1023. // plugin fields
  1024. #ifndef CARLA_VST_SHELL
  1025. effect->numParams = kNumParameters;
  1026. effect->numPrograms = 1;
  1027. # if defined(CARLA_PLUGIN_32CH)
  1028. effect->numInputs = 32;
  1029. effect->numOutputs = 32;
  1030. # elif defined(CARLA_PLUGIN_16CH)
  1031. effect->numInputs = 16;
  1032. effect->numOutputs = 16;
  1033. # else
  1034. effect->numInputs = 2;
  1035. effect->numOutputs = 2;
  1036. # endif
  1037. #endif
  1038. // plugin flags
  1039. effect->flags |= effFlagsCanReplacing;
  1040. effect->flags |= effFlagsProgramChunks;
  1041. #ifndef CARLA_VST_SHELL
  1042. effect->flags |= effFlagsHasEditor;
  1043. #endif
  1044. #if CARLA_PLUGIN_SYNTH
  1045. effect->flags |= effFlagsIsSynth;
  1046. #endif
  1047. return effect;
  1048. }
  1049. // -----------------------------------------------------------------------