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.

1302 lines
40KB

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