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.

1323 lines
40KB

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