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