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 37KB

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