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

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