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.

1224 lines
39KB

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