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.

CarlaEngineRtAudio.cpp 35KB

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