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.

1165 lines
36KB

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