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.

1173 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(false);
  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(const bool /*external*/) 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. graph->refreshConnections(this);
  463. }
  464. // -------------------------------------------------------------------
  465. protected:
  466. void handleAudioProcessCallback(void* outputBuffer, void* inputBuffer, uint nframes, double streamTime, RtAudioStreamStatus status)
  467. {
  468. const PendingRtEventsRunner prt(this);
  469. // get buffers from RtAudio
  470. const float* const insPtr = (const float*)inputBuffer;
  471. float* const outsPtr = (float*)outputBuffer;
  472. // assert rtaudio buffers
  473. CARLA_SAFE_ASSERT_RETURN(outputBuffer != nullptr,);
  474. CARLA_SAFE_ASSERT_RETURN(pData->bufferSize == nframes,);
  475. // initialize rtaudio input
  476. const float* inBuf[fAudioInCount];
  477. for (uint i=0; i < fAudioInCount; ++i)
  478. inBuf[i] = insPtr+(nframes*i);
  479. // initialize rtaudio output
  480. float* outBuf[fAudioOutCount];
  481. for (uint i=0; i < fAudioOutCount; ++i)
  482. outBuf[i] = outsPtr+(nframes*i);
  483. FloatVectorOperations::clear(outsPtr, static_cast<int>(nframes*fAudioOutCount));
  484. // initialize events
  485. carla_zeroStruct<EngineEvent>(pData->events.in, kMaxEngineEventInternalCount);
  486. carla_zeroStruct<EngineEvent>(pData->events.out, kMaxEngineEventInternalCount);
  487. if (fMidiInEvents.mutex.tryLock())
  488. {
  489. uint32_t engineEventIndex = 0;
  490. fMidiInEvents.splice();
  491. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin(); it.valid(); it.next())
  492. {
  493. const RtMidiEvent& midiEvent(it.getValue());
  494. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  495. if (midiEvent.time < pData->timeInfo.frame)
  496. {
  497. engineEvent.time = 0;
  498. }
  499. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  500. {
  501. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  502. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  503. }
  504. else
  505. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  506. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data);
  507. if (engineEventIndex >= kMaxEngineEventInternalCount)
  508. break;
  509. }
  510. fMidiInEvents.data.clear();
  511. fMidiInEvents.mutex.unlock();
  512. }
  513. pData->graph.process(pData, inBuf, outBuf, nframes);
  514. fMidiOutMutex.lock();
  515. if (fMidiOuts.count() > 0)
  516. {
  517. uint8_t size = 0;
  518. uint8_t data[3] = { 0, 0, 0 };
  519. const uint8_t* dataPtr = data;
  520. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  521. {
  522. const EngineEvent& engineEvent(pData->events.out[i]);
  523. if (engineEvent.type == kEngineEventTypeNull)
  524. break;
  525. else if (engineEvent.type == kEngineEventTypeControl)
  526. {
  527. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  528. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  529. dataPtr = data;
  530. }
  531. else if (engineEvent.type == kEngineEventTypeMidi)
  532. {
  533. const EngineMidiEvent& midiEvent(engineEvent.midi);
  534. size = midiEvent.size;
  535. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  536. dataPtr = midiEvent.dataExt;
  537. else
  538. dataPtr = midiEvent.data;
  539. }
  540. else
  541. {
  542. continue;
  543. }
  544. if (size > 0)
  545. {
  546. fMidiOutVector.assign(dataPtr, dataPtr + size);
  547. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  548. {
  549. MidiOutPort& outPort(it.getValue());
  550. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  551. outPort.port->sendMessage(&fMidiOutVector);
  552. }
  553. }
  554. }
  555. }
  556. fMidiOutMutex.unlock();
  557. return; // unused
  558. (void)streamTime; (void)status;
  559. }
  560. void handleMidiCallback(double timeStamp, std::vector<uchar>* const message)
  561. {
  562. const size_t messageSize(message->size());
  563. if (messageSize == 0 || messageSize > EngineMidiEvent::kDataSize)
  564. return;
  565. timeStamp /= 2;
  566. if (timeStamp > 0.95)
  567. timeStamp = 0.95;
  568. else if (timeStamp < 0.0)
  569. timeStamp = 0.0;
  570. RtMidiEvent midiEvent;
  571. midiEvent.time = pData->timeInfo.frame + uint64_t(timeStamp * (double)pData->bufferSize);
  572. if (midiEvent.time < fLastEventTime)
  573. midiEvent.time = fLastEventTime;
  574. else
  575. fLastEventTime = midiEvent.time;
  576. midiEvent.size = static_cast<uint8_t>(messageSize);
  577. size_t i=0;
  578. for (; i < messageSize; ++i)
  579. midiEvent.data[i] = message->at(i);
  580. for (; i < EngineMidiEvent::kDataSize; ++i)
  581. midiEvent.data[i] = 0;
  582. fMidiInEvents.append(midiEvent);
  583. }
  584. // -------------------------------------------------------------------
  585. bool connectRackMidiInPort(const char* const portName) override
  586. {
  587. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  588. carla_debug("CarlaEngineRtAudio::connectRackMidiInPort(\"%s\")", portName);
  589. RackGraph* const graph(pData->graph.getRackGraph());
  590. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  591. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  592. CarlaString newRtMidiPortName;
  593. newRtMidiPortName += getName();
  594. newRtMidiPortName += ":";
  595. newRtMidiPortName += portName;
  596. RtMidiIn* const rtMidiIn(new RtMidiIn(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), newRtMidiPortName.buffer(), 512));
  597. rtMidiIn->ignoreTypes();
  598. rtMidiIn->setCallback(carla_rtmidi_callback, this);
  599. bool found = false;
  600. uint rtMidiPortIndex;
  601. for (uint i=0, count=rtMidiIn->getPortCount(); i < count; ++i)
  602. {
  603. if (rtMidiIn->getPortName(i) == portName)
  604. {
  605. found = true;
  606. rtMidiPortIndex = i;
  607. break;
  608. }
  609. }
  610. if (! found)
  611. {
  612. delete rtMidiIn;
  613. return false;
  614. }
  615. try {
  616. rtMidiIn->openPort(rtMidiPortIndex, portName);
  617. }
  618. catch(...) {
  619. delete rtMidiIn;
  620. return false;
  621. };
  622. MidiInPort midiPort;
  623. midiPort.port = rtMidiIn;
  624. std::strncpy(midiPort.name, portName, STR_MAX);
  625. midiPort.name[STR_MAX] = '\0';
  626. fMidiIns.append(midiPort);
  627. return true;
  628. }
  629. bool connectRackMidiOutPort(const char* const portName) override
  630. {
  631. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  632. carla_debug("CarlaEngineRtAudio::connectRackMidiOutPort(\"%s\")", portName);
  633. RackGraph* const graph(pData->graph.getRackGraph());
  634. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  635. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  636. CarlaString newRtMidiPortName;
  637. newRtMidiPortName += getName();
  638. newRtMidiPortName += ":";
  639. newRtMidiPortName += portName;
  640. RtMidiOut* const rtMidiOut(new RtMidiOut(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), newRtMidiPortName.buffer()));
  641. bool found = false;
  642. uint rtMidiPortIndex;
  643. for (uint i=0, count=rtMidiOut->getPortCount(); i < count; ++i)
  644. {
  645. if (rtMidiOut->getPortName(i) == portName)
  646. {
  647. found = true;
  648. rtMidiPortIndex = i;
  649. break;
  650. }
  651. }
  652. if (! found)
  653. {
  654. delete rtMidiOut;
  655. return false;
  656. }
  657. try {
  658. rtMidiOut->openPort(rtMidiPortIndex, portName);
  659. }
  660. catch(...) {
  661. delete rtMidiOut;
  662. return false;
  663. };
  664. MidiOutPort midiPort;
  665. midiPort.port = rtMidiOut;
  666. std::strncpy(midiPort.name, portName, STR_MAX);
  667. midiPort.name[STR_MAX] = '\0';
  668. const CarlaMutexLocker cml(fMidiOutMutex);
  669. fMidiOuts.append(midiPort);
  670. return true;
  671. }
  672. bool disconnectRackMidiInPort(const char* const portName) override
  673. {
  674. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  675. carla_debug("CarlaEngineRtAudio::disconnectRackMidiInPort(\"%s\")", portName);
  676. RackGraph* const graph(pData->graph.getRackGraph());
  677. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  678. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  679. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  680. {
  681. MidiInPort& inPort(it.getValue());
  682. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  683. if (std::strcmp(inPort.name, portName) != 0)
  684. continue;
  685. inPort.port->cancelCallback();
  686. inPort.port->closePort();
  687. delete inPort.port;
  688. fMidiIns.remove(it);
  689. return true;
  690. }
  691. return false;
  692. }
  693. bool disconnectRackMidiOutPort(const char* const portName) override
  694. {
  695. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  696. carla_debug("CarlaEngineRtAudio::disconnectRackMidiOutPort(\"%s\")", portName);
  697. RackGraph* const graph(pData->graph.getRackGraph());
  698. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  699. CARLA_SAFE_ASSERT_RETURN(graph->midi.outs.count() > 0, false);
  700. const CarlaMutexLocker cml(fMidiOutMutex);
  701. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  702. {
  703. MidiOutPort& outPort(it.getValue());
  704. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  705. if (std::strcmp(outPort.name, portName) != 0)
  706. continue;
  707. outPort.port->closePort();
  708. delete outPort.port;
  709. fMidiOuts.remove(it);
  710. return true;
  711. }
  712. return false;
  713. }
  714. // -------------------------------------------------------------------
  715. private:
  716. RtAudio fAudio;
  717. // useful info
  718. uint fAudioInCount;
  719. uint fAudioOutCount;
  720. uint64_t fLastEventTime;
  721. // current device name
  722. CarlaString fDeviceName;
  723. struct MidiInPort {
  724. RtMidiIn* port;
  725. char name[STR_MAX+1];
  726. };
  727. struct MidiOutPort {
  728. RtMidiOut* port;
  729. char name[STR_MAX+1];
  730. };
  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. : mutex(),
  743. dataPool(512, 512),
  744. data(dataPool),
  745. dataPending(dataPool) {}
  746. ~RtMidiEvents()
  747. {
  748. clear();
  749. }
  750. void append(const RtMidiEvent& event)
  751. {
  752. mutex.lock();
  753. dataPending.append(event);
  754. mutex.unlock();
  755. }
  756. void clear()
  757. {
  758. mutex.lock();
  759. data.clear();
  760. dataPending.clear();
  761. mutex.unlock();
  762. }
  763. void splice()
  764. {
  765. dataPending.spliceAppendTo(data);
  766. }
  767. };
  768. LinkedList<MidiInPort> fMidiIns;
  769. RtMidiEvents fMidiInEvents;
  770. LinkedList<MidiOutPort> fMidiOuts;
  771. CarlaMutex fMidiOutMutex;
  772. std::vector<uint8_t> fMidiOutVector;
  773. #define handlePtr ((CarlaEngineRtAudio*)userData)
  774. static int carla_rtaudio_process_callback(void* outputBuffer, void* inputBuffer, uint nframes, double streamTime, RtAudioStreamStatus status, void* userData)
  775. {
  776. handlePtr->handleAudioProcessCallback(outputBuffer, inputBuffer, nframes, streamTime, status);
  777. return 0;
  778. }
  779. static void carla_rtmidi_callback(double timeStamp, std::vector<uchar>* message, void* userData)
  780. {
  781. handlePtr->handleMidiCallback(timeStamp, message);
  782. }
  783. #undef handlePtr
  784. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineRtAudio)
  785. };
  786. // -----------------------------------------
  787. CarlaEngine* CarlaEngine::newRtAudio(const AudioApi api)
  788. {
  789. initRtAudioAPIsIfNeeded();
  790. RtAudio::Api rtApi(RtAudio::UNSPECIFIED);
  791. switch (api)
  792. {
  793. case AUDIO_API_NULL:
  794. rtApi = RtAudio::RTAUDIO_DUMMY;
  795. break;
  796. case AUDIO_API_JACK:
  797. rtApi = RtAudio::UNIX_JACK;
  798. break;
  799. case AUDIO_API_ALSA:
  800. rtApi = RtAudio::LINUX_ALSA;
  801. break;
  802. case AUDIO_API_OSS:
  803. rtApi = RtAudio::LINUX_OSS;
  804. break;
  805. case AUDIO_API_PULSE:
  806. rtApi = RtAudio::LINUX_PULSE;
  807. break;
  808. case AUDIO_API_CORE:
  809. rtApi = RtAudio::MACOSX_CORE;
  810. break;
  811. case AUDIO_API_ASIO:
  812. rtApi = RtAudio::WINDOWS_ASIO;
  813. break;
  814. case AUDIO_API_DS:
  815. rtApi = RtAudio::WINDOWS_DS;
  816. break;
  817. }
  818. return new CarlaEngineRtAudio(rtApi);
  819. }
  820. uint CarlaEngine::getRtAudioApiCount()
  821. {
  822. initRtAudioAPIsIfNeeded();
  823. return static_cast<uint>(gRtAudioApis.size());
  824. }
  825. const char* CarlaEngine::getRtAudioApiName(const uint index)
  826. {
  827. initRtAudioAPIsIfNeeded();
  828. CARLA_SAFE_ASSERT_RETURN(index < gRtAudioApis.size(), nullptr);
  829. return CarlaBackend::getRtAudioApiName(gRtAudioApis[index]);
  830. }
  831. const char* const* CarlaEngine::getRtAudioApiDeviceNames(const uint index)
  832. {
  833. initRtAudioAPIsIfNeeded();
  834. if (index >= gRtAudioApis.size())
  835. return nullptr;
  836. const RtAudio::Api& api(gRtAudioApis[index]);
  837. RtAudio rtAudio(api);
  838. const uint devCount(rtAudio.getDeviceCount());
  839. if (devCount == 0)
  840. return nullptr;
  841. CarlaStringList devNames;
  842. for (uint i=0; i < devCount; ++i)
  843. {
  844. RtAudio::DeviceInfo devInfo(rtAudio.getDeviceInfo(i));
  845. if (devInfo.probed && devInfo.outputChannels > 0 /*&& (devInfo.nativeFormats & RTAUDIO_FLOAT32) != 0*/)
  846. devNames.append(devInfo.name.c_str());
  847. }
  848. gDeviceNames = devNames.toCharStringListPtr();
  849. return gDeviceNames;
  850. }
  851. const EngineDriverDeviceInfo* CarlaEngine::getRtAudioDeviceInfo(const uint index, const char* const deviceName)
  852. {
  853. initRtAudioAPIsIfNeeded();
  854. if (index >= gRtAudioApis.size())
  855. return nullptr;
  856. const RtAudio::Api& api(gRtAudioApis[index]);
  857. RtAudio rtAudio(api);
  858. const uint devCount(rtAudio.getDeviceCount());
  859. if (devCount == 0)
  860. return nullptr;
  861. uint i;
  862. RtAudio::DeviceInfo rtAudioDevInfo;
  863. for (i=0; i < devCount; ++i)
  864. {
  865. rtAudioDevInfo = rtAudio.getDeviceInfo(i);
  866. if (rtAudioDevInfo.name == deviceName)
  867. break;
  868. }
  869. if (i == devCount)
  870. return nullptr;
  871. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  872. static uint32_t dummyBufferSizes[] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  873. static double dummySampleRates[] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  874. // reset
  875. devInfo.hints = 0x0;
  876. devInfo.bufferSizes = dummyBufferSizes;
  877. // cleanup
  878. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  879. {
  880. delete[] devInfo.sampleRates;
  881. devInfo.sampleRates = nullptr;
  882. }
  883. if (size_t sampleRatesCount = rtAudioDevInfo.sampleRates.size())
  884. {
  885. double* const sampleRates(new double[sampleRatesCount+1]);
  886. for (size_t j=0; j < sampleRatesCount; ++j)
  887. sampleRates[j] = rtAudioDevInfo.sampleRates[j];
  888. sampleRates[sampleRatesCount] = 0.0;
  889. devInfo.sampleRates = sampleRates;
  890. }
  891. else
  892. {
  893. devInfo.sampleRates = dummySampleRates;
  894. }
  895. return &devInfo;
  896. }
  897. // -----------------------------------------
  898. CARLA_BACKEND_END_NAMESPACE