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.

1334 lines
41KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2022 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. #include "CarlaEngineGraph.hpp"
  18. #include "CarlaEngineInit.hpp"
  19. #include "CarlaEngineInternal.hpp"
  20. #include "CarlaBackendUtils.hpp"
  21. #include "CarlaMathUtils.hpp"
  22. #include "CarlaStringList.hpp"
  23. #include "RtLinkedList.hpp"
  24. #include "jackbridge/JackBridge.hpp"
  25. #if defined(__clang__)
  26. # pragma clang diagnostic push
  27. # pragma clang diagnostic ignored "-Wconversion"
  28. # pragma clang diagnostic ignored "-Wdeprecated-copy"
  29. # pragma clang diagnostic ignored "-Weffc++"
  30. # pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  31. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  32. # pragma GCC diagnostic push
  33. # pragma GCC diagnostic ignored "-Wconversion"
  34. # pragma GCC diagnostic ignored "-Weffc++"
  35. # pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
  36. #endif
  37. #include "rtaudio/RtAudio.h"
  38. #include "rtmidi/RtMidi.h"
  39. #if defined(__clang__)
  40. # pragma clang diagnostic pop
  41. #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  42. # pragma GCC diagnostic pop
  43. #endif
  44. CARLA_BACKEND_START_NAMESPACE
  45. // -------------------------------------------------------------------------------------------------------------------
  46. // Global static data
  47. static CharStringListPtr gDeviceNames;
  48. static std::vector<RtAudio::Api> gRtAudioApis;
  49. // -------------------------------------------------------------------------------------------------------------------
  50. static void initRtAudioAPIsIfNeeded()
  51. {
  52. static bool needsInit = true;
  53. if (! needsInit)
  54. return;
  55. needsInit = false;
  56. // get APIs in a local var, and pass wanted ones into gRtAudioApis
  57. std::vector<RtAudio::Api> apis;
  58. RtAudio::getCompiledApi(apis);
  59. for (std::vector<RtAudio::Api>::const_iterator it = apis.begin(), end=apis.end(); it != end; ++it)
  60. {
  61. const RtAudio::Api& api(*it);
  62. if (api == RtAudio::UNIX_JACK)
  63. {
  64. #if defined(CARLA_OS_LINUX) || defined(CARLA_OS_MAC) || defined(CARLA_OS_WIN)
  65. if ( ! jackbridge_is_ok())
  66. continue;
  67. #else
  68. /* NOTE
  69. * RtMidi doesn't have a native MIDI backend for these OSes,
  70. * Using RtAudio JACK funcitonality is only useful when we need to access the native MIDI APIs.
  71. * (JACK audio + ALSA MIDI, or JACK audio + CoreMidi, or JACK audio + Windows MIDI)
  72. * Because RtMidi has no native MIDI support outside of win/mac/linux, we skip these RtAudio APIs.
  73. * Those OSes can use Carla's JACK support directly, which is much better than RtAudio classes.
  74. */
  75. continue;
  76. #endif
  77. }
  78. gRtAudioApis.push_back(api);
  79. }
  80. }
  81. static const char* getRtAudioApiName(const RtAudio::Api api) noexcept
  82. {
  83. switch (api)
  84. {
  85. case RtAudio::UNSPECIFIED:
  86. return "Unspecified";
  87. case RtAudio::LINUX_ALSA:
  88. return "ALSA";
  89. case RtAudio::LINUX_OSS:
  90. return "OSS";
  91. case RtAudio::UNIX_PULSE:
  92. return "PulseAudio";
  93. case RtAudio::UNIX_JACK:
  94. #if defined(CARLA_OS_LINUX) && defined(__LINUX_ALSA__)
  95. return "JACK with ALSA-MIDI";
  96. #elif defined(CARLA_OS_MAC)
  97. return "JACK with CoreMidi";
  98. #elif defined(CARLA_OS_WIN)
  99. return "JACK with WinMM";
  100. #else
  101. return "JACK (RtAudio)";
  102. #endif
  103. case RtAudio::MACOSX_CORE:
  104. return "CoreAudio";
  105. case RtAudio::WINDOWS_ASIO:
  106. return "ASIO";
  107. case RtAudio::WINDOWS_DS:
  108. return "DirectSound";
  109. case RtAudio::WINDOWS_WASAPI:
  110. return "WASAPI";
  111. case RtAudio::RTAUDIO_DUMMY:
  112. return "Dummy";
  113. }
  114. carla_stderr("CarlaBackend::getRtAudioApiName(%i) - invalid API", api);
  115. return nullptr;
  116. }
  117. static RtMidi::Api getMatchedAudioMidiAPI(const RtAudio::Api rtApi) noexcept
  118. {
  119. switch (rtApi)
  120. {
  121. case RtAudio::UNSPECIFIED:
  122. return RtMidi::UNSPECIFIED;
  123. case RtAudio::LINUX_ALSA:
  124. case RtAudio::LINUX_OSS:
  125. return RtMidi::LINUX_ALSA;
  126. case RtAudio::UNIX_PULSE:
  127. case RtAudio::UNIX_JACK:
  128. #if defined(CARLA_OS_LINUX) && defined(__LINUX_ALSA__)
  129. return RtMidi::LINUX_ALSA;
  130. #elif defined(CARLA_OS_MAC)
  131. return RtMidi::MACOSX_CORE;
  132. #elif defined(CARLA_OS_WIN)
  133. return RtMidi::WINDOWS_MM;
  134. #else
  135. return RtMidi::RTMIDI_DUMMY;
  136. #endif
  137. case RtAudio::MACOSX_CORE:
  138. return RtMidi::MACOSX_CORE;
  139. case RtAudio::WINDOWS_ASIO:
  140. case RtAudio::WINDOWS_DS:
  141. case RtAudio::WINDOWS_WASAPI:
  142. return RtMidi::WINDOWS_MM;
  143. case RtAudio::RTAUDIO_DUMMY:
  144. return RtMidi::RTMIDI_DUMMY;
  145. }
  146. return RtMidi::UNSPECIFIED;
  147. }
  148. // -------------------------------------------------------------------------------------------------------------------
  149. // RtAudio Engine
  150. class CarlaEngineRtAudio : public CarlaEngine
  151. {
  152. public:
  153. CarlaEngineRtAudio(const RtAudio::Api api)
  154. : CarlaEngine(),
  155. fAudio(api),
  156. fAudioInterleaved(false),
  157. fAudioInCount(0),
  158. fAudioOutCount(0),
  159. fLastEventTime(0),
  160. fDeviceName(),
  161. fAudioIntBufIn(nullptr),
  162. fAudioIntBufOut(nullptr),
  163. fMidiIns(),
  164. fMidiInEvents(),
  165. fMidiOuts(),
  166. fMidiOutMutex(),
  167. fMidiOutVector(EngineMidiEvent::kDataSize)
  168. {
  169. carla_debug("CarlaEngineRtAudio::CarlaEngineRtAudio(%i)", api);
  170. // just to make sure
  171. pData->options.transportMode = ENGINE_TRANSPORT_MODE_INTERNAL;
  172. }
  173. ~CarlaEngineRtAudio() override
  174. {
  175. CARLA_SAFE_ASSERT(fAudioInCount == 0);
  176. CARLA_SAFE_ASSERT(fAudioOutCount == 0);
  177. CARLA_SAFE_ASSERT(fLastEventTime == 0);
  178. carla_debug("CarlaEngineRtAudio::~CarlaEngineRtAudio()");
  179. }
  180. // -------------------------------------
  181. bool init(const char* const clientName) override
  182. {
  183. CARLA_SAFE_ASSERT_RETURN(fAudioInCount == 0, false);
  184. CARLA_SAFE_ASSERT_RETURN(fAudioOutCount == 0, false);
  185. CARLA_SAFE_ASSERT_RETURN(fLastEventTime == 0, false);
  186. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0', false);
  187. carla_debug("CarlaEngineRtAudio::init(\"%s\")", clientName);
  188. if (pData->options.processMode != ENGINE_PROCESS_MODE_CONTINUOUS_RACK && pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  189. {
  190. setLastError("Invalid process mode");
  191. return false;
  192. }
  193. const bool isDummy(fAudio.getCurrentApi() == RtAudio::RtAudio::RTAUDIO_DUMMY);
  194. bool deviceSet = false;
  195. RtAudio::StreamParameters iParams, oParams;
  196. if (isDummy)
  197. {
  198. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  199. {
  200. setLastError("Cannot use dummy driver in Rack mode");
  201. return false;
  202. }
  203. fDeviceName = "Dummy";
  204. }
  205. else
  206. {
  207. const uint devCount(fAudio.getDeviceCount());
  208. if (devCount == 0)
  209. {
  210. setLastError("No audio devices available for this driver");
  211. return false;
  212. }
  213. if (pData->options.audioDevice != nullptr && pData->options.audioDevice[0] != '\0')
  214. {
  215. for (uint i=0; i < devCount; ++i)
  216. {
  217. RtAudio::DeviceInfo devInfo(fAudio.getDeviceInfo(i));
  218. if (devInfo.probed && devInfo.outputChannels > 0 && devInfo.name == pData->options.audioDevice)
  219. {
  220. deviceSet = true;
  221. fDeviceName = devInfo.name.c_str();
  222. iParams.deviceId = i;
  223. oParams.deviceId = i;
  224. iParams.nChannels = devInfo.inputChannels;
  225. oParams.nChannels = devInfo.outputChannels;
  226. break;
  227. }
  228. }
  229. }
  230. if (! deviceSet)
  231. {
  232. iParams.deviceId = fAudio.getDefaultInputDevice();
  233. oParams.deviceId = fAudio.getDefaultOutputDevice();
  234. iParams.nChannels = fAudio.getDeviceInfo(iParams.deviceId).inputChannels;
  235. oParams.nChannels = fAudio.getDeviceInfo(oParams.deviceId).outputChannels;
  236. carla_stdout("No device set, using %i inputs and %i outputs", iParams.nChannels, oParams.nChannels);
  237. }
  238. if (oParams.nChannels == 0 && pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  239. {
  240. setLastError("Current audio setup has no outputs, cannot continue");
  241. return false;
  242. }
  243. iParams.nChannels = carla_fixedValue(0U, 128U, iParams.nChannels);
  244. oParams.nChannels = carla_fixedValue(0U, 128U, oParams.nChannels);
  245. fAudioInterleaved = fAudio.getCurrentApi() == RtAudio::UNIX_PULSE;
  246. }
  247. RtAudio::StreamOptions rtOptions;
  248. rtOptions.flags = RTAUDIO_MINIMIZE_LATENCY | RTAUDIO_SCHEDULE_REALTIME;
  249. rtOptions.numberOfBuffers = pData->options.audioTripleBuffer ? 3 : 2;
  250. rtOptions.streamName = clientName;
  251. rtOptions.priority = 85;
  252. if (fAudio.getCurrentApi() == RtAudio::LINUX_ALSA && ! deviceSet)
  253. rtOptions.flags |= RTAUDIO_ALSA_USE_DEFAULT;
  254. if (! fAudioInterleaved)
  255. rtOptions.flags |= RTAUDIO_NONINTERLEAVED;
  256. uint bufferFrames = pData->options.audioBufferSize;
  257. try {
  258. fAudio.openStream(oParams.nChannels > 0 ? &oParams : nullptr,
  259. iParams.nChannels > 0 ? &iParams : nullptr,
  260. RTAUDIO_FLOAT32, pData->options.audioSampleRate, &bufferFrames,
  261. carla_rtaudio_process_callback, this, &rtOptions,
  262. carla_rtaudio_buffer_size_callback);
  263. }
  264. catch (const RtAudioError& e) {
  265. setLastError(e.what());
  266. return false;
  267. }
  268. if (! pData->init(clientName))
  269. {
  270. close();
  271. setLastError("Failed to init internal data");
  272. return false;
  273. }
  274. pData->bufferSize = bufferFrames;
  275. pData->sampleRate = isDummy ? 44100.0 : fAudio.getStreamSampleRate();
  276. pData->initTime(pData->options.transportExtra);
  277. fAudioInCount = iParams.nChannels;
  278. fAudioOutCount = oParams.nChannels;
  279. fLastEventTime = 0;
  280. if (fAudioInCount > 0)
  281. fAudioIntBufIn = new float[fAudioInCount*bufferFrames];
  282. if (fAudioOutCount > 0)
  283. fAudioIntBufOut = new float[fAudioOutCount*bufferFrames];
  284. pData->graph.create(fAudioInCount, fAudioOutCount, 0, 0);
  285. try {
  286. fAudio.startStream();
  287. }
  288. catch (const RtAudioError& e)
  289. {
  290. close();
  291. setLastError(e.what());
  292. return false;
  293. }
  294. patchbayRefresh(true, false, false);
  295. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  296. refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), false, false);
  297. callback(true, true,
  298. ENGINE_CALLBACK_ENGINE_STARTED,
  299. 0,
  300. pData->options.processMode,
  301. pData->options.transportMode,
  302. static_cast<int>(pData->bufferSize),
  303. static_cast<float>(pData->sampleRate),
  304. getCurrentDriverName());
  305. return true;
  306. }
  307. bool close() override
  308. {
  309. carla_debug("CarlaEngineRtAudio::close()");
  310. bool hasError = false;
  311. // stop stream first
  312. if (fAudio.isStreamOpen() && fAudio.isStreamRunning())
  313. {
  314. try {
  315. fAudio.stopStream();
  316. }
  317. catch (const RtAudioError& e)
  318. {
  319. setLastError(e.what());
  320. hasError = true;
  321. }
  322. }
  323. // clear engine data
  324. CarlaEngine::close();
  325. pData->graph.destroy();
  326. for (LinkedList<MidiInPort>::Itenerator it = fMidiIns.begin2(); it.valid(); it.next())
  327. {
  328. static MidiInPort fallback = { nullptr, { '\0' } };
  329. MidiInPort& inPort(it.getValue(fallback));
  330. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  331. inPort.port->cancelCallback();
  332. inPort.port->closePort();
  333. delete inPort.port;
  334. }
  335. fMidiIns.clear();
  336. fMidiInEvents.clear();
  337. fMidiOutMutex.lock();
  338. for (LinkedList<MidiOutPort>::Itenerator it = fMidiOuts.begin2(); it.valid(); it.next())
  339. {
  340. static MidiOutPort fallback = { nullptr, { '\0' } };
  341. MidiOutPort& outPort(it.getValue(fallback));
  342. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  343. outPort.port->closePort();
  344. delete outPort.port;
  345. }
  346. fMidiOuts.clear();
  347. fMidiOutMutex.unlock();
  348. fAudioInCount = 0;
  349. fAudioOutCount = 0;
  350. fLastEventTime = 0;
  351. fDeviceName.clear();
  352. if (fAudioIntBufIn != nullptr)
  353. {
  354. delete[] fAudioIntBufIn;
  355. fAudioIntBufIn = nullptr;
  356. }
  357. if (fAudioIntBufOut != nullptr)
  358. {
  359. delete[] fAudioIntBufOut;
  360. fAudioIntBufOut = nullptr;
  361. }
  362. // close stream
  363. if (fAudio.isStreamOpen())
  364. fAudio.closeStream();
  365. return !hasError;
  366. }
  367. bool hasIdleOnMainThread() const noexcept override
  368. {
  369. return true;
  370. }
  371. bool isRunning() const noexcept override
  372. {
  373. return fAudio.isStreamOpen();
  374. }
  375. bool isOffline() const noexcept override
  376. {
  377. return false;
  378. }
  379. EngineType getType() const noexcept override
  380. {
  381. return kEngineTypeRtAudio;
  382. }
  383. const char* getCurrentDriverName() const noexcept override
  384. {
  385. return CARLA_BACKEND_NAMESPACE::getRtAudioApiName(fAudio.getCurrentApi());
  386. }
  387. // -------------------------------------------------------------------
  388. // Patchbay
  389. template<class Graph>
  390. bool refreshExternalGraphPorts(Graph* const graph, const bool sendHost, const bool sendOSC)
  391. {
  392. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  393. char strBuf[STR_MAX+1U];
  394. strBuf[STR_MAX] = '\0';
  395. ExternalGraph& extGraph(graph->extGraph);
  396. // ---------------------------------------------------------------
  397. // clear last ports
  398. extGraph.clear();
  399. // ---------------------------------------------------------------
  400. // fill in new ones
  401. // Audio In
  402. for (uint i=0; i < fAudioInCount; ++i)
  403. {
  404. std::snprintf(strBuf, STR_MAX, "capture_%i", i+1);
  405. PortNameToId portNameToId;
  406. portNameToId.setData(kExternalGraphGroupAudioIn, i+1, strBuf, "");
  407. extGraph.audioPorts.ins.append(portNameToId);
  408. }
  409. // Audio Out
  410. for (uint i=0; i < fAudioOutCount; ++i)
  411. {
  412. std::snprintf(strBuf, STR_MAX, "playback_%i", i+1);
  413. PortNameToId portNameToId;
  414. portNameToId.setData(kExternalGraphGroupAudioOut, i+1, strBuf, "");
  415. extGraph.audioPorts.outs.append(portNameToId);
  416. }
  417. // MIDI In
  418. try
  419. {
  420. RtMidiIn midiIn(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), "carla-discovery-in");
  421. for (uint i=0, count = midiIn.getPortCount(); i < count; ++i)
  422. {
  423. PortNameToId portNameToId;
  424. portNameToId.setData(kExternalGraphGroupMidiIn, i+1, midiIn.getPortName(i).c_str(), "");
  425. extGraph.midiPorts.ins.append(portNameToId);
  426. }
  427. } CARLA_SAFE_EXCEPTION("RtMidiIn discovery");
  428. // MIDI Out
  429. try
  430. {
  431. RtMidiOut midiOut(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), "carla-discovery-out");
  432. for (uint i=0, count = midiOut.getPortCount(); i < count; ++i)
  433. {
  434. PortNameToId portNameToId;
  435. portNameToId.setData(kExternalGraphGroupMidiOut, i+1, midiOut.getPortName(i).c_str(), "");
  436. extGraph.midiPorts.outs.append(portNameToId);
  437. }
  438. } CARLA_SAFE_EXCEPTION("RtMidiOut discovery");
  439. // ---------------------------------------------------------------
  440. // now refresh
  441. if (sendHost || sendOSC)
  442. graph->refresh(sendHost, sendOSC, true, fDeviceName.buffer());
  443. // ---------------------------------------------------------------
  444. // add midi connections
  445. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  446. {
  447. static const MidiInPort fallback = { nullptr, { '\0' } };
  448. const MidiInPort& inPort(it.getValue(fallback));
  449. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  450. const uint portId = extGraph.midiPorts.getPortIdFromName(true, inPort.name);
  451. CARLA_SAFE_ASSERT_UINT_CONTINUE(portId < extGraph.midiPorts.ins.count(), portId);
  452. ConnectionToId connectionToId;
  453. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupMidiIn, portId, kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiIn);
  454. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  455. extGraph.connections.list.append(connectionToId);
  456. callback(sendHost, sendOSC,
  457. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  458. connectionToId.id,
  459. 0, 0, 0, 0.0f,
  460. strBuf);
  461. }
  462. fMidiOutMutex.lock();
  463. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  464. {
  465. static const MidiOutPort fallback = { nullptr, { '\0' } };
  466. const MidiOutPort& outPort(it.getValue(fallback));
  467. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  468. const uint portId = extGraph.midiPorts.getPortIdFromName(false, outPort.name);
  469. CARLA_SAFE_ASSERT_UINT_CONTINUE(portId < extGraph.midiPorts.outs.count(), portId);
  470. ConnectionToId connectionToId;
  471. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiOut, kExternalGraphGroupMidiOut, portId);
  472. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  473. extGraph.connections.list.append(connectionToId);
  474. callback(sendHost, sendOSC,
  475. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  476. connectionToId.id,
  477. 0, 0, 0, 0.0f,
  478. strBuf);
  479. }
  480. fMidiOutMutex.unlock();
  481. return true;
  482. }
  483. bool patchbayRefresh(const bool sendHost, const bool sendOSC, const bool external) override
  484. {
  485. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  486. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  487. return refreshExternalGraphPorts<RackGraph>(pData->graph.getRackGraph(), sendHost, sendOSC);
  488. if (sendHost)
  489. pData->graph.setUsingExternalHost(external);
  490. if (sendOSC)
  491. pData->graph.setUsingExternalOSC(external);
  492. if (external)
  493. return refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), sendHost, sendOSC);
  494. return CarlaEngine::patchbayRefresh(sendHost, sendOSC, false);
  495. }
  496. // -------------------------------------------------------------------
  497. protected:
  498. void handleAudioProcessCallback(void* outputBuffer, void* inputBuffer,
  499. uint nframes, double streamTime, RtAudioStreamStatus status)
  500. {
  501. const PendingRtEventsRunner prt(this, nframes, true);
  502. if (status & RTAUDIO_INPUT_OVERFLOW)
  503. ++pData->xruns;
  504. if (status & RTAUDIO_OUTPUT_UNDERFLOW)
  505. ++pData->xruns;
  506. // get buffers from RtAudio
  507. const float* const insPtr = (const float*)inputBuffer;
  508. /* */ float* const outsPtr = (float*)outputBuffer;
  509. // assert rtaudio buffers
  510. CARLA_SAFE_ASSERT_RETURN(outputBuffer != nullptr,);
  511. // set rtaudio buffers as non-interleaved
  512. const float* inBuf[fAudioInCount];
  513. /* */ float* outBuf[fAudioOutCount];
  514. if (fAudioInterleaved)
  515. {
  516. // FIXME - this looks completely wrong!
  517. float* inBuf2[fAudioInCount];
  518. for (uint i=0, count=fAudioInCount; i<count; ++i)
  519. {
  520. inBuf [i] = fAudioIntBufIn + (nframes*i);
  521. inBuf2[i] = fAudioIntBufIn + (nframes*i);
  522. }
  523. for (uint i=0, count=fAudioOutCount; i<count; ++i)
  524. outBuf[i] = fAudioIntBufOut + (nframes*i);
  525. // init input
  526. for (uint i=0; i<nframes; ++i)
  527. for (uint j=0; j<fAudioInCount; ++j)
  528. inBuf2[j][i] = insPtr[i*fAudioInCount+j];
  529. // clear output
  530. carla_zeroFloats(fAudioIntBufOut, fAudioOutCount*nframes);
  531. }
  532. else
  533. {
  534. for (uint i=0; i < fAudioInCount; ++i)
  535. inBuf[i] = insPtr+(nframes*i);
  536. for (uint i=0; i < fAudioOutCount; ++i)
  537. outBuf[i] = outsPtr+(nframes*i);
  538. // clear output
  539. carla_zeroFloats(outsPtr, nframes*fAudioOutCount);
  540. }
  541. // initialize events
  542. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  543. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  544. if (fMidiInEvents.mutex.tryLock())
  545. {
  546. uint32_t engineEventIndex = 0;
  547. fMidiInEvents.splice();
  548. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin2(); it.valid(); it.next())
  549. {
  550. static const RtMidiEvent fallback = { 0, 0, { 0 } };
  551. const RtMidiEvent& midiEvent(it.getValue(fallback));
  552. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.size > 0);
  553. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  554. if (midiEvent.time < pData->timeInfo.frame)
  555. {
  556. engineEvent.time = 0;
  557. }
  558. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  559. {
  560. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  561. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  562. }
  563. else
  564. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  565. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data, 0);
  566. if (engineEventIndex >= kMaxEngineEventInternalCount)
  567. break;
  568. }
  569. fMidiInEvents.data.clear();
  570. fMidiInEvents.mutex.unlock();
  571. }
  572. pData->graph.process(pData, inBuf, outBuf, nframes);
  573. fMidiOutMutex.lock();
  574. if (fMidiOuts.count() > 0)
  575. {
  576. uint8_t size = 0;
  577. uint8_t mdata[3] = { 0, 0, 0 };
  578. uint8_t mdataTmp[EngineMidiEvent::kDataSize];
  579. const uint8_t* mdataPtr;
  580. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  581. {
  582. const EngineEvent& engineEvent(pData->events.out[i]);
  583. /**/ if (engineEvent.type == kEngineEventTypeNull)
  584. {
  585. break;
  586. }
  587. else if (engineEvent.type == kEngineEventTypeControl)
  588. {
  589. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  590. size = ctrlEvent.convertToMidiData(engineEvent.channel, mdata);
  591. mdataPtr = mdata;
  592. }
  593. else if (engineEvent.type == kEngineEventTypeMidi)
  594. {
  595. const EngineMidiEvent& midiEvent(engineEvent.midi);
  596. size = midiEvent.size;
  597. CARLA_SAFE_ASSERT_CONTINUE(size > 0);
  598. if (size > EngineMidiEvent::kDataSize)
  599. {
  600. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.dataExt != nullptr);
  601. mdataPtr = midiEvent.dataExt;
  602. }
  603. else
  604. {
  605. // set first byte
  606. mdataTmp[0] = static_cast<uint8_t>(midiEvent.data[0] | (engineEvent.channel & MIDI_CHANNEL_BIT));
  607. // copy rest
  608. carla_copy<uint8_t>(mdataTmp+1, midiEvent.data+1, size-1U);
  609. // done
  610. mdataPtr = mdataTmp;
  611. }
  612. }
  613. else
  614. {
  615. continue;
  616. }
  617. if (size > 0)
  618. {
  619. fMidiOutVector.assign(mdataPtr, mdataPtr + size);
  620. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  621. {
  622. static MidiOutPort fallback = { nullptr, { '\0' } };
  623. MidiOutPort& outPort(it.getValue(fallback));
  624. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  625. outPort.port->sendMessage(&fMidiOutVector);
  626. }
  627. }
  628. }
  629. }
  630. fMidiOutMutex.unlock();
  631. if (fAudioInterleaved)
  632. {
  633. for (uint i=0; i < nframes; ++i)
  634. for (uint j=0; j<fAudioOutCount; ++j)
  635. outsPtr[i*fAudioOutCount+j] = outBuf[j][i];
  636. }
  637. return; // unused
  638. (void)streamTime;
  639. }
  640. void handleBufferSizeCallback(const uint newBufferSize)
  641. {
  642. carla_stdout("bufferSize callback %u %u", pData->bufferSize, newBufferSize);
  643. if (pData->bufferSize == newBufferSize)
  644. return;
  645. if (fAudioInCount > 0)
  646. {
  647. delete[] fAudioIntBufIn;
  648. fAudioIntBufIn = new float[fAudioInCount*newBufferSize];
  649. }
  650. if (fAudioOutCount > 0)
  651. {
  652. delete[] fAudioIntBufOut;
  653. fAudioIntBufOut = new float[fAudioOutCount*newBufferSize];
  654. }
  655. pData->bufferSize = newBufferSize;
  656. bufferSizeChanged(newBufferSize);
  657. }
  658. void handleMidiCallback(double timeStamp, std::vector<uchar>* const message)
  659. {
  660. const size_t messageSize(message->size());
  661. if (messageSize == 0 || messageSize > EngineMidiEvent::kDataSize)
  662. return;
  663. timeStamp /= 2;
  664. if (timeStamp > 0.95)
  665. timeStamp = 0.95;
  666. else if (timeStamp < 0.0)
  667. timeStamp = 0.0;
  668. RtMidiEvent midiEvent;
  669. midiEvent.time = pData->timeInfo.frame + uint64_t(timeStamp * (double)pData->bufferSize);
  670. if (midiEvent.time < fLastEventTime)
  671. midiEvent.time = fLastEventTime;
  672. else
  673. fLastEventTime = midiEvent.time;
  674. midiEvent.size = static_cast<uint8_t>(messageSize);
  675. size_t i=0;
  676. for (; i < messageSize; ++i)
  677. midiEvent.data[i] = message->at(i);
  678. for (; i < EngineMidiEvent::kDataSize; ++i)
  679. midiEvent.data[i] = 0;
  680. fMidiInEvents.append(midiEvent);
  681. }
  682. // -------------------------------------------------------------------
  683. bool connectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  684. {
  685. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  686. carla_debug("CarlaEngineRtAudio::connectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  687. switch (connectionType)
  688. {
  689. case kExternalGraphConnectionAudioIn1:
  690. case kExternalGraphConnectionAudioIn2:
  691. case kExternalGraphConnectionAudioOut1:
  692. case kExternalGraphConnectionAudioOut2:
  693. return CarlaEngine::connectExternalGraphPort(connectionType, portId, portName);
  694. case kExternalGraphConnectionMidiInput: {
  695. CarlaString newRtMidiPortName;
  696. newRtMidiPortName += getName();
  697. newRtMidiPortName += ":";
  698. newRtMidiPortName += portName;
  699. RtMidiIn* rtMidiIn;
  700. try {
  701. rtMidiIn = new RtMidiIn(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), newRtMidiPortName.buffer(), 512);
  702. } CARLA_SAFE_EXCEPTION_RETURN("new RtMidiIn", false);
  703. rtMidiIn->ignoreTypes();
  704. rtMidiIn->setCallback(carla_rtmidi_callback, this);
  705. bool found = false;
  706. uint rtMidiPortIndex;
  707. for (uint i=0, count=rtMidiIn->getPortCount(); i < count; ++i)
  708. {
  709. if (rtMidiIn->getPortName(i) == portName)
  710. {
  711. found = true;
  712. rtMidiPortIndex = i;
  713. break;
  714. }
  715. }
  716. if (! found)
  717. {
  718. delete rtMidiIn;
  719. return false;
  720. }
  721. try {
  722. rtMidiIn->openPort(rtMidiPortIndex, portName);
  723. }
  724. catch(...) {
  725. delete rtMidiIn;
  726. return false;
  727. };
  728. MidiInPort midiPort;
  729. midiPort.port = rtMidiIn;
  730. std::strncpy(midiPort.name, portName, STR_MAX);
  731. midiPort.name[STR_MAX] = '\0';
  732. fMidiIns.append(midiPort);
  733. return true;
  734. } break;
  735. case kExternalGraphConnectionMidiOutput: {
  736. CarlaString newRtMidiPortName;
  737. newRtMidiPortName += getName();
  738. newRtMidiPortName += ":";
  739. newRtMidiPortName += portName;
  740. RtMidiOut* rtMidiOut;
  741. try {
  742. rtMidiOut = new RtMidiOut(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), newRtMidiPortName.buffer());
  743. } CARLA_SAFE_EXCEPTION_RETURN("new RtMidiOut", false);
  744. bool found = false;
  745. uint rtMidiPortIndex;
  746. for (uint i=0, count=rtMidiOut->getPortCount(); i < count; ++i)
  747. {
  748. if (rtMidiOut->getPortName(i) == portName)
  749. {
  750. found = true;
  751. rtMidiPortIndex = i;
  752. break;
  753. }
  754. }
  755. if (! found)
  756. {
  757. delete rtMidiOut;
  758. return false;
  759. }
  760. try {
  761. rtMidiOut->openPort(rtMidiPortIndex, portName);
  762. }
  763. catch(...) {
  764. delete rtMidiOut;
  765. return false;
  766. };
  767. MidiOutPort midiPort;
  768. midiPort.port = rtMidiOut;
  769. std::strncpy(midiPort.name, portName, STR_MAX);
  770. midiPort.name[STR_MAX] = '\0';
  771. const CarlaMutexLocker cml(fMidiOutMutex);
  772. fMidiOuts.append(midiPort);
  773. return true;
  774. } break;
  775. }
  776. return false;
  777. }
  778. bool disconnectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  779. {
  780. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  781. carla_debug("CarlaEngineRtAudio::disconnectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  782. switch (connectionType)
  783. {
  784. case kExternalGraphConnectionAudioIn1:
  785. case kExternalGraphConnectionAudioIn2:
  786. case kExternalGraphConnectionAudioOut1:
  787. case kExternalGraphConnectionAudioOut2:
  788. return CarlaEngine::disconnectExternalGraphPort(connectionType, portId, portName);
  789. case kExternalGraphConnectionMidiInput:
  790. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  791. {
  792. static MidiInPort fallback = { nullptr, { '\0' } };
  793. MidiInPort& inPort(it.getValue(fallback));
  794. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  795. if (std::strncmp(inPort.name, portName, STR_MAX) != 0)
  796. continue;
  797. inPort.port->cancelCallback();
  798. inPort.port->closePort();
  799. delete inPort.port;
  800. fMidiIns.remove(it);
  801. return true;
  802. }
  803. break;
  804. case kExternalGraphConnectionMidiOutput: {
  805. const CarlaMutexLocker cml(fMidiOutMutex);
  806. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  807. {
  808. static MidiOutPort fallback = { nullptr, { '\0' } };
  809. MidiOutPort& outPort(it.getValue(fallback));
  810. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  811. if (std::strncmp(outPort.name, portName, STR_MAX) != 0)
  812. continue;
  813. outPort.port->closePort();
  814. delete outPort.port;
  815. fMidiOuts.remove(it);
  816. return true;
  817. }
  818. } break;
  819. }
  820. return false;
  821. }
  822. // -------------------------------------------------------------------
  823. private:
  824. RtAudio fAudio;
  825. // useful info
  826. bool fAudioInterleaved;
  827. uint fAudioInCount;
  828. uint fAudioOutCount;
  829. uint64_t fLastEventTime;
  830. // current device name
  831. CarlaString fDeviceName;
  832. // temp buffer for interleaved audio
  833. float* fAudioIntBufIn;
  834. float* fAudioIntBufOut;
  835. struct MidiInPort {
  836. RtMidiIn* port;
  837. char name[STR_MAX+1];
  838. };
  839. struct MidiOutPort {
  840. RtMidiOut* port;
  841. char name[STR_MAX+1];
  842. };
  843. struct RtMidiEvent {
  844. uint64_t time; // needs to compare to internal time
  845. uint8_t size;
  846. uint8_t data[EngineMidiEvent::kDataSize];
  847. };
  848. struct RtMidiEvents {
  849. CarlaMutex mutex;
  850. RtLinkedList<RtMidiEvent>::Pool dataPool;
  851. RtLinkedList<RtMidiEvent> data;
  852. RtLinkedList<RtMidiEvent> dataPending;
  853. RtMidiEvents()
  854. : mutex(),
  855. dataPool("RtMidiEvents", 512, 512),
  856. data(dataPool),
  857. dataPending(dataPool) {}
  858. ~RtMidiEvents()
  859. {
  860. clear();
  861. }
  862. void append(const RtMidiEvent& event)
  863. {
  864. mutex.lock();
  865. dataPending.append(event);
  866. mutex.unlock();
  867. }
  868. void clear()
  869. {
  870. mutex.lock();
  871. data.clear();
  872. dataPending.clear();
  873. mutex.unlock();
  874. }
  875. void splice()
  876. {
  877. if (dataPending.count() > 0)
  878. dataPending.moveTo(data, true /* append */);
  879. }
  880. };
  881. LinkedList<MidiInPort> fMidiIns;
  882. RtMidiEvents fMidiInEvents;
  883. LinkedList<MidiOutPort> fMidiOuts;
  884. CarlaMutex fMidiOutMutex;
  885. std::vector<uint8_t> fMidiOutVector;
  886. #define handlePtr ((CarlaEngineRtAudio*)userData)
  887. static int carla_rtaudio_process_callback(void* outputBuffer, void* inputBuffer, uint nframes, double streamTime, RtAudioStreamStatus status, void* userData)
  888. {
  889. handlePtr->handleAudioProcessCallback(outputBuffer, inputBuffer, nframes, streamTime, status);
  890. return 0;
  891. }
  892. static bool carla_rtaudio_buffer_size_callback(unsigned int bufferSize, void* userData)
  893. {
  894. handlePtr->handleBufferSizeCallback(bufferSize);
  895. return true;
  896. }
  897. static void carla_rtmidi_callback(double timeStamp, std::vector<uchar>* message, void* userData)
  898. {
  899. handlePtr->handleMidiCallback(timeStamp, message);
  900. }
  901. #undef handlePtr
  902. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineRtAudio)
  903. };
  904. // -----------------------------------------
  905. namespace EngineInit {
  906. CarlaEngine* newRtAudio(const AudioApi api)
  907. {
  908. initRtAudioAPIsIfNeeded();
  909. RtAudio::Api rtApi = RtAudio::UNSPECIFIED;
  910. switch (api)
  911. {
  912. case AUDIO_API_NULL:
  913. rtApi = RtAudio::RTAUDIO_DUMMY;
  914. break;
  915. case AUDIO_API_JACK:
  916. rtApi = RtAudio::UNIX_JACK;
  917. break;
  918. case AUDIO_API_OSS:
  919. rtApi = RtAudio::LINUX_OSS;
  920. break;
  921. case AUDIO_API_ALSA:
  922. rtApi = RtAudio::LINUX_ALSA;
  923. break;
  924. case AUDIO_API_PULSEAUDIO:
  925. rtApi = RtAudio::UNIX_PULSE;
  926. break;
  927. case AUDIO_API_COREAUDIO:
  928. rtApi = RtAudio::MACOSX_CORE;
  929. break;
  930. case AUDIO_API_ASIO:
  931. rtApi = RtAudio::WINDOWS_ASIO;
  932. break;
  933. case AUDIO_API_DIRECTSOUND:
  934. rtApi = RtAudio::WINDOWS_DS;
  935. break;
  936. case AUDIO_API_WASAPI:
  937. rtApi = RtAudio::WINDOWS_WASAPI;
  938. break;
  939. }
  940. return new CarlaEngineRtAudio(rtApi);
  941. }
  942. uint getRtAudioApiCount()
  943. {
  944. initRtAudioAPIsIfNeeded();
  945. return static_cast<uint>(gRtAudioApis.size());
  946. }
  947. const char* getRtAudioApiName(const uint index)
  948. {
  949. initRtAudioAPIsIfNeeded();
  950. CARLA_SAFE_ASSERT_RETURN(index < gRtAudioApis.size(), nullptr);
  951. return CARLA_BACKEND_NAMESPACE::getRtAudioApiName(gRtAudioApis[index]);
  952. }
  953. const char* const* getRtAudioApiDeviceNames(const uint index)
  954. {
  955. initRtAudioAPIsIfNeeded();
  956. if (index >= gRtAudioApis.size())
  957. return nullptr;
  958. const RtAudio::Api& api(gRtAudioApis[index]);
  959. CarlaStringList devNames;
  960. try {
  961. RtAudio rtAudio(api);
  962. const uint devCount(rtAudio.getDeviceCount());
  963. if (devCount == 0)
  964. return nullptr;
  965. for (uint i=0; i < devCount; ++i)
  966. {
  967. RtAudio::DeviceInfo devInfo(rtAudio.getDeviceInfo(i));
  968. if (devInfo.probed && devInfo.outputChannels > 0 /*&& (devInfo.nativeFormats & RTAUDIO_FLOAT32) != 0*/)
  969. devNames.append(devInfo.name.c_str());
  970. }
  971. } CARLA_SAFE_EXCEPTION_RETURN("RtAudio device names", nullptr);
  972. gDeviceNames = devNames.toCharStringListPtr();
  973. return gDeviceNames;
  974. }
  975. const EngineDriverDeviceInfo* getRtAudioDeviceInfo(const uint index, const char* const deviceName)
  976. {
  977. initRtAudioAPIsIfNeeded();
  978. if (index >= gRtAudioApis.size())
  979. return nullptr;
  980. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  981. static uint32_t dummyBufferSizes[] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  982. static double dummySampleRates[] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  983. // reset
  984. devInfo.hints = 0x0;
  985. // cleanup
  986. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  987. {
  988. delete[] devInfo.bufferSizes;
  989. devInfo.bufferSizes = nullptr;
  990. }
  991. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  992. {
  993. delete[] devInfo.sampleRates;
  994. devInfo.sampleRates = nullptr;
  995. }
  996. const RtAudio::Api& api(gRtAudioApis[index]);
  997. if (api == RtAudio::UNIX_JACK)
  998. {
  999. devInfo.bufferSizes = nullptr;
  1000. devInfo.sampleRates = nullptr;
  1001. return &devInfo;
  1002. }
  1003. RtAudio::DeviceInfo rtAudioDevInfo;
  1004. try {
  1005. RtAudio rtAudio(api);
  1006. const uint devCount(rtAudio.getDeviceCount());
  1007. if (devCount == 0)
  1008. return nullptr;
  1009. uint i;
  1010. for (i=0; i < devCount; ++i)
  1011. {
  1012. rtAudioDevInfo = rtAudio.getDeviceInfo(i);
  1013. if (rtAudioDevInfo.name == deviceName)
  1014. break;
  1015. }
  1016. if (i == devCount)
  1017. rtAudioDevInfo = rtAudio.getDeviceInfo(rtAudio.getDefaultOutputDevice());
  1018. } CARLA_SAFE_EXCEPTION_RETURN("RtAudio device discovery", nullptr);
  1019. // a few APIs can do triple buffer
  1020. switch (api)
  1021. {
  1022. case RtAudio::LINUX_ALSA:
  1023. case RtAudio::LINUX_OSS:
  1024. case RtAudio::WINDOWS_DS:
  1025. devInfo.hints |= ENGINE_DRIVER_DEVICE_CAN_TRIPLE_BUFFER;
  1026. break;
  1027. default:
  1028. break;
  1029. }
  1030. // always use default buffer sizes
  1031. devInfo.bufferSizes = dummyBufferSizes;
  1032. // valid sample rates
  1033. if (const size_t sampleRatesCount = rtAudioDevInfo.sampleRates.size())
  1034. {
  1035. double* const sampleRates(new double[sampleRatesCount+1]);
  1036. for (size_t i=0; i < sampleRatesCount; ++i)
  1037. sampleRates[i] = rtAudioDevInfo.sampleRates[i];
  1038. sampleRates[sampleRatesCount] = 0.0;
  1039. devInfo.sampleRates = sampleRates;
  1040. }
  1041. else
  1042. {
  1043. devInfo.sampleRates = dummySampleRates;
  1044. }
  1045. return &devInfo;
  1046. }
  1047. }
  1048. // -----------------------------------------
  1049. CARLA_BACKEND_END_NAMESPACE