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.

1286 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)",
  604. opcode, index, value, ptr, static_cast<double>(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. case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
  615. // nothing
  616. break;
  617. case NATIVE_HOST_OPCODE_RELOAD_ALL:
  618. hostCallback(audioMasterUpdateDisplay);
  619. break;
  620. case NATIVE_HOST_OPCODE_HOST_IDLE:
  621. hostCallback(audioMasterIdle);
  622. break;
  623. case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
  624. CARLA_SAFE_ASSERT_RETURN(index >= 0, 0);
  625. handleUiParameterTouch(static_cast<uint32_t>(index), value != 0);
  626. break;
  627. }
  628. // unused for now
  629. return 0;
  630. (void)ptr; (void)opt;
  631. }
  632. private:
  633. // VST stuff
  634. AEffect* const fEffect;
  635. // Native data
  636. NativePluginHandle fHandle;
  637. NativeHostDescriptor fHost;
  638. const NativePluginDescriptor* const fDescriptor;
  639. // VST host data
  640. uint32_t fBufferSize;
  641. double fSampleRate;
  642. // Temporary data
  643. bool fIsActive;
  644. uint32_t fMidiEventCount;
  645. NativeMidiEvent fMidiEvents[kMaxMidiEvents];
  646. char fProgramName[32+1];
  647. NativeTimeInfo fTimeInfo;
  648. ERect fVstRect;
  649. // UI button
  650. CarlaUILauncher* fUiLauncher;
  651. // Host data
  652. enum HostType {
  653. kHostTypeNull = 0,
  654. kHostTypeArdour,
  655. kHostTypeBitwig
  656. };
  657. HostType fHostType;
  658. // host callback
  659. intptr_t hostCallback(const int32_t opcode,
  660. const int32_t index = 0,
  661. const intptr_t value = 0,
  662. void* const ptr = nullptr,
  663. const float opt = 0.0f) const
  664. {
  665. return VSTAudioMaster(fEffect, opcode, index, value, ptr, opt);
  666. }
  667. struct FixedVstEvents {
  668. int32_t numEvents;
  669. intptr_t reserved;
  670. VstEvent* data[kMaxMidiEvents];
  671. VstMidiEvent mdata[kMaxMidiEvents];
  672. FixedVstEvents()
  673. : numEvents(0),
  674. reserved(0)
  675. {
  676. for (uint32_t i=0; i<kMaxMidiEvents; ++i)
  677. data[i] = (VstEvent*)&mdata[i];
  678. carla_zeroStructs(mdata, kMaxMidiEvents);
  679. }
  680. CARLA_DECLARE_NON_COPY_STRUCT(FixedVstEvents);
  681. } fMidiOutEvents;
  682. #ifdef USING_JUCE
  683. juce::SharedResourcePointer<juce::ScopedJuceInitialiser_GUI> fJuceInitialiser;
  684. #endif
  685. char* fStateChunk;
  686. // -------------------------------------------------------------------
  687. #define handlePtr ((NativePlugin*)handle)
  688. static uint32_t host_get_buffer_size(NativeHostHandle handle)
  689. {
  690. return handlePtr->fBufferSize;
  691. }
  692. static double host_get_sample_rate(NativeHostHandle handle)
  693. {
  694. return handlePtr->fSampleRate;
  695. }
  696. static bool host_is_offline(NativeHostHandle /*handle*/)
  697. {
  698. // TODO
  699. return false;
  700. }
  701. static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
  702. {
  703. return &(handlePtr->fTimeInfo);
  704. }
  705. static bool host_write_midi_event(NativeHostHandle handle, const NativeMidiEvent* event)
  706. {
  707. return handlePtr->handleWriteMidiEvent(event);
  708. }
  709. static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
  710. {
  711. handlePtr->handleUiParameterChanged(index, value);
  712. }
  713. static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
  714. {
  715. handlePtr->handleUiCustomDataChanged(key, value);
  716. }
  717. static void host_ui_closed(NativeHostHandle handle)
  718. {
  719. handlePtr->handleUiClosed();
  720. }
  721. static const char* host_ui_open_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  722. {
  723. return handlePtr->handleUiOpenFile(isDir, title, filter);
  724. }
  725. static const char* host_ui_save_file(NativeHostHandle handle, bool isDir, const char* title, const char* filter)
  726. {
  727. return handlePtr->handleUiSaveFile(isDir, title, filter);
  728. }
  729. static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
  730. {
  731. return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
  732. }
  733. #undef handlePtr
  734. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(NativePlugin)
  735. };
  736. // -----------------------------------------------------------------------
  737. #define validObject effect != nullptr && effect->object != nullptr
  738. #define validPlugin effect != nullptr && effect->object != nullptr && ((VstObject*)effect->object)->plugin != nullptr
  739. #define vstObjectPtr (VstObject*)effect->object
  740. #define pluginPtr (vstObjectPtr)->plugin
  741. intptr_t vst_dispatcherCallback(AEffect* effect, int32_t opcode, int32_t index, intptr_t value, void* ptr, float opt)
  742. {
  743. // handle base opcodes
  744. switch (opcode)
  745. {
  746. case effOpen:
  747. if (VstObject* const obj = vstObjectPtr)
  748. {
  749. // this must always be valid
  750. CARLA_SAFE_ASSERT_RETURN(obj->audioMaster != nullptr, 0);
  751. // some hosts call effOpen twice
  752. CARLA_SAFE_ASSERT_RETURN(obj->plugin == nullptr, 1);
  753. d_lastBufferSize = static_cast<uint32_t>(VSTAudioMaster(effect, audioMasterGetBlockSize, 0, 0, nullptr, 0.0f));
  754. d_lastSampleRate = static_cast<double>(VSTAudioMaster(effect, audioMasterGetSampleRate, 0, 0, nullptr, 0.0f));
  755. // some hosts are not ready at this point or return 0 buffersize/samplerate
  756. if (d_lastBufferSize == 0)
  757. d_lastBufferSize = 2048;
  758. if (d_lastSampleRate <= 0.0)
  759. d_lastSampleRate = 44100.0;
  760. const NativePluginDescriptor* pluginDesc = nullptr;
  761. PluginListManager& plm(PluginListManager::getInstance());
  762. #ifdef CARLA_VST_SHELL
  763. if (effect->uniqueID == 0)
  764. effect->uniqueID = kShellUniqueID;
  765. if (effect->uniqueID == kShellUniqueID)
  766. {
  767. // first open for discovery, nothing to do
  768. effect->numParams = 0;
  769. effect->numPrograms = 0;
  770. effect->numInputs = 0;
  771. effect->numOutputs = 0;
  772. return 1;
  773. }
  774. const int32_t plugIndex = effect->uniqueID - kShellUniqueID - 1;
  775. CARLA_SAFE_ASSERT_RETURN(plugIndex >= 0, 0);
  776. pluginDesc = plm.descs.getAt(static_cast<size_t>(plugIndex), nullptr);
  777. #else // CARLA_VST_SHELL
  778. # if defined(CARLA_PLUGIN_32CH)
  779. const char* const pluginLabel = "carlapatchbay32";
  780. # elif defined(CARLA_PLUGIN_16CH)
  781. const char* const pluginLabel = "carlapatchbay16";
  782. # elif CARLA_PLUGIN_PATCHBAY
  783. const char* const pluginLabel = "carlapatchbay";
  784. # else
  785. const char* const pluginLabel = "carlarack";
  786. # endif
  787. for (LinkedList<const NativePluginDescriptor*>::Itenerator it = plm.descs.begin2(); it.valid(); it.next())
  788. {
  789. const NativePluginDescriptor* const& tmpDesc(it.getValue(nullptr));
  790. CARLA_SAFE_ASSERT_CONTINUE(tmpDesc != nullptr);
  791. if (std::strcmp(tmpDesc->label, pluginLabel) == 0)
  792. {
  793. pluginDesc = tmpDesc;
  794. break;
  795. }
  796. }
  797. #endif // CARLA_VST_SHELL
  798. CARLA_SAFE_ASSERT_RETURN(pluginDesc != nullptr, 0);
  799. #ifdef CARLA_VST_SHELL
  800. effect->numPrograms = 1;
  801. effect->numParams = static_cast<int>(pluginDesc->paramIns);
  802. effect->numInputs = static_cast<int>(pluginDesc->audioIns);
  803. effect->numOutputs = static_cast<int>(pluginDesc->audioOuts);
  804. if (pluginDesc->hints & NATIVE_PLUGIN_HAS_UI)
  805. effect->flags |= effFlagsHasEditor;
  806. else
  807. effect->flags &= ~effFlagsHasEditor;
  808. if (pluginDesc->hints & NATIVE_PLUGIN_IS_SYNTH)
  809. effect->flags |= effFlagsIsSynth;
  810. else
  811. effect->flags &= ~effFlagsIsSynth;
  812. #endif // CARLA_VST_SHELL
  813. #if CARLA_PLUGIN_SYNTH
  814. // override if requested
  815. effect->flags |= effFlagsIsSynth;
  816. #endif
  817. obj->plugin = new NativePlugin(effect, pluginDesc);
  818. return 1;
  819. }
  820. return 0;
  821. case effClose:
  822. if (VstObject* const obj = vstObjectPtr)
  823. {
  824. NativePlugin* const plugin(obj->plugin);
  825. if (plugin != nullptr)
  826. {
  827. obj->plugin = nullptr;
  828. delete plugin;
  829. }
  830. #if 0
  831. /* This code invalidates the object created in VSTPluginMain
  832. * Probably not safe against all hosts */
  833. obj->audioMaster = nullptr;
  834. effect->object = nullptr;
  835. delete obj;
  836. #endif
  837. return 1;
  838. }
  839. //delete effect;
  840. return 0;
  841. case effGetPlugCategory:
  842. #ifdef CARLA_VST_SHELL
  843. if (validPlugin)
  844. {
  845. #if CARLA_PLUGIN_SYNTH
  846. return kPlugCategSynth;
  847. #else
  848. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  849. return desc->category == NATIVE_PLUGIN_CATEGORY_SYNTH ? kPlugCategSynth : kPlugCategEffect;
  850. #endif
  851. }
  852. return kPlugCategShell;
  853. #elif CARLA_PLUGIN_SYNTH
  854. return kPlugCategSynth;
  855. #else
  856. return kPlugCategEffect;
  857. #endif
  858. case effGetEffectName:
  859. if (char* const cptr = (char*)ptr)
  860. {
  861. #if defined(CARLA_VST_SHELL)
  862. if (validPlugin)
  863. {
  864. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  865. std::strncpy(cptr, desc->name, 32);
  866. }
  867. else
  868. {
  869. std::strncpy(cptr, "Carla-VstShell", 32);
  870. }
  871. #elif defined(CARLA_PLUGIN_32CH)
  872. std::strncpy(cptr, "Carla-Patchbay32", 32);
  873. #elif defined(CARLA_PLUGIN_16CH)
  874. std::strncpy(cptr, "Carla-Patchbay16", 32);
  875. #elif CARLA_PLUGIN_PATCHBAY
  876. # if CARLA_PLUGIN_SYNTH
  877. std::strncpy(cptr, "Carla-Patchbay", 32);
  878. # else
  879. std::strncpy(cptr, "Carla-PatchbayFX", 32);
  880. # endif
  881. #else // Rack mode
  882. # if CARLA_PLUGIN_SYNTH
  883. std::strncpy(cptr, "Carla-Rack", 32);
  884. # else
  885. std::strncpy(cptr, "Carla-RackFX", 32);
  886. # endif
  887. #endif
  888. return 1;
  889. }
  890. return 0;
  891. case effGetVendorString:
  892. if (char* const cptr = (char*)ptr)
  893. {
  894. #ifdef CARLA_VST_SHELL
  895. if (validPlugin)
  896. {
  897. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  898. std::strncpy(cptr, desc->maker, 32);
  899. }
  900. else
  901. #endif
  902. std::strncpy(cptr, "falkTX", 32);
  903. return 1;
  904. }
  905. return 0;
  906. case effGetProductString:
  907. if (char* const cptr = (char*)ptr)
  908. {
  909. #if defined(CARLA_VST_SHELL)
  910. if (validPlugin)
  911. {
  912. const NativePluginDescriptor* const desc = pluginPtr->getDescriptor();
  913. std::strncpy(cptr, desc->label, 32);
  914. }
  915. else
  916. {
  917. std::strncpy(cptr, "CarlaVstShell", 32);
  918. }
  919. #elif defined(CARLA_PLUGIN_32CH)
  920. std::strncpy(cptr, "CarlaPatchbay32", 32);
  921. #elif defined(CARLA_PLUGIN_16CH)
  922. std::strncpy(cptr, "CarlaPatchbay16", 32);
  923. #elif CARLA_PLUGIN_PATCHBAY
  924. # if CARLA_PLUGIN_SYNTH
  925. std::strncpy(cptr, "CarlaPatchbay", 32);
  926. # else
  927. std::strncpy(cptr, "CarlaPatchbayFX", 32);
  928. # endif
  929. #else
  930. # if CARLA_PLUGIN_SYNTH
  931. std::strncpy(cptr, "CarlaRack", 32);
  932. # else
  933. std::strncpy(cptr, "CarlaRackFX", 32);
  934. # endif
  935. #endif
  936. return 1;
  937. }
  938. return 0;
  939. case effGetVendorVersion:
  940. return CARLA_VERSION_HEX;
  941. case effGetVstVersion:
  942. return kVstVersion;
  943. #ifdef CARLA_VST_SHELL
  944. case effShellGetNextPlugin:
  945. if (char* const cptr = (char*)ptr)
  946. {
  947. CARLA_SAFE_ASSERT_RETURN(effect != nullptr, 0);
  948. CARLA_SAFE_ASSERT_RETURN(effect->uniqueID >= kShellUniqueID, 0);
  949. PluginListManager& plm(PluginListManager::getInstance());
  950. for (;;)
  951. {
  952. const uint index2 = static_cast<uint>(effect->uniqueID - kShellUniqueID);
  953. if (index2 >= plm.descs.count())
  954. {
  955. effect->uniqueID = kShellUniqueID;
  956. return 0;
  957. }
  958. const NativePluginDescriptor* const desc = plm.descs.getAt(index2, nullptr);
  959. CARLA_SAFE_ASSERT_RETURN(desc != nullptr, 0);
  960. ++effect->uniqueID;
  961. if (desc->midiIns > 1 || desc->midiOuts > 1)
  962. continue;
  963. std::strncpy(cptr, desc->label, 32);
  964. return effect->uniqueID;
  965. }
  966. }
  967. #endif
  968. };
  969. // handle advanced opcodes
  970. if (validPlugin)
  971. return pluginPtr->vst_dispatcher(opcode, index, value, ptr, opt);
  972. return 0;
  973. }
  974. float vst_getParameterCallback(AEffect* effect, int32_t index)
  975. {
  976. if (validPlugin)
  977. return pluginPtr->vst_getParameter(index);
  978. return 0.0f;
  979. }
  980. void vst_setParameterCallback(AEffect* effect, int32_t index, float value)
  981. {
  982. if (validPlugin)
  983. pluginPtr->vst_setParameter(index, value);
  984. }
  985. void vst_processCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames)
  986. {
  987. if (validPlugin)
  988. pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames);
  989. }
  990. void vst_processReplacingCallback(AEffect* effect, float** inputs, float** outputs, int32_t sampleFrames)
  991. {
  992. if (validPlugin)
  993. pluginPtr->vst_processReplacing(const_cast<const float**>(inputs), outputs, sampleFrames);
  994. }
  995. #undef pluginPtr
  996. #undef validObject
  997. #undef validPlugin
  998. #undef vstObjectPtr
  999. // -----------------------------------------------------------------------
  1000. const AEffect* VSTPluginMainInit(AEffect* const effect)
  1001. {
  1002. #if defined(CARLA_VST_SHELL)
  1003. if (const intptr_t uniqueID = VSTAudioMaster(effect, audioMasterCurrentId, 0, 0, nullptr, 0.0f))
  1004. effect->uniqueID = static_cast<int>(uniqueID);
  1005. else
  1006. effect->uniqueID = kShellUniqueID;
  1007. #elif defined(CARLA_PLUGIN_32CH)
  1008. effect->uniqueID = kBaseUniqueID+6;
  1009. #elif defined(CARLA_PLUGIN_16CH)
  1010. effect->uniqueID = kBaseUniqueID+5;
  1011. #elif CARLA_PLUGIN_PATCHBAY
  1012. # if CARLA_PLUGIN_SYNTH
  1013. effect->uniqueID = kBaseUniqueID+4;
  1014. # else
  1015. effect->uniqueID = kBaseUniqueID+3;
  1016. # endif
  1017. #else
  1018. # if CARLA_PLUGIN_SYNTH
  1019. effect->uniqueID = kBaseUniqueID+2;
  1020. # else
  1021. effect->uniqueID = kBaseUniqueID+1;
  1022. # endif
  1023. #endif
  1024. // plugin fields
  1025. #ifndef CARLA_VST_SHELL
  1026. effect->numParams = kNumParameters;
  1027. effect->numPrograms = 1;
  1028. # if defined(CARLA_PLUGIN_32CH)
  1029. effect->numInputs = 32;
  1030. effect->numOutputs = 32;
  1031. # elif defined(CARLA_PLUGIN_16CH)
  1032. effect->numInputs = 16;
  1033. effect->numOutputs = 16;
  1034. # else
  1035. effect->numInputs = 2;
  1036. effect->numOutputs = 2;
  1037. # endif
  1038. #endif
  1039. // plugin flags
  1040. effect->flags |= effFlagsCanReplacing;
  1041. effect->flags |= effFlagsProgramChunks;
  1042. #ifndef CARLA_VST_SHELL
  1043. effect->flags |= effFlagsHasEditor;
  1044. #endif
  1045. #if CARLA_PLUGIN_SYNTH
  1046. effect->flags |= effFlagsIsSynth;
  1047. #endif
  1048. return effect;
  1049. }
  1050. // -----------------------------------------------------------------------