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.

1174 lines
37KB

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