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.

1180 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. if (! pData->init(clientName))
  224. {
  225. close();
  226. setLastError("Failed to init internal data");
  227. return false;
  228. }
  229. pData->bufferSize = bufferFrames;
  230. pData->sampleRate = fAudio.getStreamSampleRate();
  231. fAudioInCount = iParams.nChannels;
  232. fAudioOutCount = oParams.nChannels;
  233. fLastEventTime = 0;
  234. pData->graph.create(pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK, pData->sampleRate, pData->bufferSize, fAudioInCount, fAudioOutCount);
  235. try {
  236. fAudio.startStream();
  237. }
  238. catch (const RtAudioError& e)
  239. {
  240. close();
  241. setLastError(e.what());
  242. return false;
  243. }
  244. patchbayRefresh(false);
  245. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0, pData->options.processMode, pData->options.transportMode, 0.0f, getCurrentDriverName());
  246. return true;
  247. }
  248. bool close() override
  249. {
  250. CARLA_SAFE_ASSERT(fAudioOutCount != 0);
  251. carla_debug("CarlaEngineRtAudio::close()");
  252. bool hasError = false;
  253. // stop stream first
  254. if (fAudio.isStreamOpen() && fAudio.isStreamRunning())
  255. {
  256. try {
  257. fAudio.stopStream();
  258. }
  259. catch (const RtAudioError& e)
  260. {
  261. setLastError(e.what());
  262. hasError = true;
  263. }
  264. }
  265. // clear engine data
  266. CarlaEngine::close();
  267. pData->graph.destroy();
  268. for (LinkedList<MidiInPort>::Itenerator it = fMidiIns.begin(); it.valid(); it.next())
  269. {
  270. MidiInPort& inPort(it.getValue());
  271. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  272. inPort.port->cancelCallback();
  273. inPort.port->closePort();
  274. delete inPort.port;
  275. }
  276. fMidiIns.clear();
  277. fMidiInEvents.clear();
  278. fMidiOutMutex.lock();
  279. for (LinkedList<MidiOutPort>::Itenerator it = fMidiOuts.begin(); it.valid(); it.next())
  280. {
  281. MidiOutPort& outPort(it.getValue());
  282. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  283. outPort.port->closePort();
  284. delete outPort.port;
  285. }
  286. fMidiOuts.clear();
  287. fMidiOutMutex.unlock();
  288. fAudioInCount = 0;
  289. fAudioOutCount = 0;
  290. fLastEventTime = 0;
  291. fDeviceName.clear();
  292. // close stream
  293. if (fAudio.isStreamOpen())
  294. fAudio.closeStream();
  295. return !hasError;
  296. }
  297. bool isRunning() const noexcept override
  298. {
  299. return fAudio.isStreamRunning();
  300. }
  301. bool isOffline() const noexcept override
  302. {
  303. return false;
  304. }
  305. EngineType getType() const noexcept override
  306. {
  307. return kEngineTypeRtAudio;
  308. }
  309. const char* getCurrentDriverName() const noexcept override
  310. {
  311. return CarlaBackend::getRtAudioApiName(fAudio.getCurrentApi());
  312. }
  313. // -------------------------------------------------------------------
  314. // Patchbay
  315. bool patchbayRefresh(const bool /*external*/) override
  316. {
  317. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  318. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  319. patchbayRefreshRack();
  320. else
  321. patchbayRefreshPatchbay();
  322. return true;
  323. }
  324. void patchbayRefreshRack()
  325. {
  326. RackGraph* const graph(pData->graph.getRackGraph());
  327. CARLA_SAFE_ASSERT_RETURN(graph != nullptr,);
  328. graph->connections.clear();
  329. char strBuf[STR_MAX+1];
  330. strBuf[STR_MAX] = '\0';
  331. // Main
  332. {
  333. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_CARLA, PATCHBAY_ICON_CARLA, -1, 0.0f, getName());
  334. 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");
  335. 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");
  336. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_OUT1, PATCHBAY_PORT_TYPE_AUDIO, 0.0f, "audio-out1");
  337. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_OUT2, PATCHBAY_PORT_TYPE_AUDIO, 0.0f, "audio-out2");
  338. 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");
  339. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_MIDI_OUT, PATCHBAY_PORT_TYPE_MIDI, 0.0f, "midi-out");
  340. }
  341. // Audio In
  342. {
  343. if (fDeviceName.isNotEmpty())
  344. std::snprintf(strBuf, STR_MAX, "Capture (%s)", fDeviceName.buffer());
  345. else
  346. std::strncpy(strBuf, "Capture", STR_MAX);
  347. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_AUDIO_IN, PATCHBAY_ICON_HARDWARE, -1, 0.0f, strBuf);
  348. for (uint i=0; i < fAudioInCount; ++i)
  349. {
  350. std::snprintf(strBuf, STR_MAX, "capture_%i", i+1);
  351. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, RACK_GRAPH_GROUP_AUDIO_IN, static_cast<int>(i), PATCHBAY_PORT_TYPE_AUDIO, 0.0f, strBuf);
  352. }
  353. }
  354. // Audio Out
  355. {
  356. if (fDeviceName.isNotEmpty())
  357. std::snprintf(strBuf, STR_MAX, "Playback (%s)", fDeviceName.buffer());
  358. else
  359. std::strncpy(strBuf, "Playback", STR_MAX);
  360. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_AUDIO_OUT, PATCHBAY_ICON_HARDWARE, -1, 0.0f, strBuf);
  361. for (uint i=0; i < fAudioOutCount; ++i)
  362. {
  363. std::snprintf(strBuf, STR_MAX, "playback_%i", i+1);
  364. 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);
  365. }
  366. }
  367. // MIDI In
  368. {
  369. RtMidiIn midiIn(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), "carla-discovery");
  370. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_MIDI_IN, PATCHBAY_ICON_HARDWARE, -1, 0.0f, "Readable MIDI ports");
  371. for (uint i=0, count = midiIn.getPortCount(); i < count; ++i)
  372. {
  373. std::string portName(midiIn.getPortName(i));
  374. std::snprintf(strBuf, STR_MAX, "Readable MIDI ports:%s", portName.c_str());
  375. PortNameToId portNameToId;
  376. portNameToId.setData(RACK_GRAPH_GROUP_MIDI_IN, i, portName.c_str(), strBuf);
  377. callback(ENGINE_CALLBACK_PATCHBAY_PORT_ADDED, portNameToId.group, static_cast<int>(portNameToId.port), PATCHBAY_PORT_TYPE_MIDI, 0.0f, portNameToId.name);
  378. graph->midi.ins.append(portNameToId);
  379. }
  380. }
  381. // MIDI Out
  382. {
  383. RtMidiOut midiOut(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), "carla-discovery");
  384. callback(ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED, RACK_GRAPH_GROUP_MIDI_OUT, PATCHBAY_ICON_HARDWARE, -1, 0.0f, "Writable MIDI ports");
  385. for (uint i=0, count = midiOut.getPortCount(); i < count; ++i)
  386. {
  387. std::string portName(midiOut.getPortName(i));
  388. std::snprintf(strBuf, STR_MAX, "Writable MIDI ports:%s", portName.c_str());
  389. PortNameToId portNameToId;
  390. portNameToId.setData(RACK_GRAPH_GROUP_MIDI_OUT, i, portName.c_str(), strBuf);
  391. 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);
  392. graph->midi.outs.append(portNameToId);
  393. }
  394. }
  395. // Connections
  396. graph->audio.mutex.lock();
  397. for (LinkedList<uint>::Itenerator it = graph->audio.connectedIn1.begin(); it.valid(); it.next())
  398. {
  399. const uint& portId(it.getValue());
  400. CARLA_SAFE_ASSERT_CONTINUE(portId < fAudioInCount);
  401. ConnectionToId connectionToId;
  402. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_AUDIO_IN, portId, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_IN1);
  403. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  404. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  405. graph->connections.list.append(connectionToId);
  406. }
  407. for (LinkedList<uint>::Itenerator it = graph->audio.connectedIn2.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_IN2);
  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.connectedOut1.begin(); it.valid(); it.next())
  418. {
  419. const uint& portId(it.getValue());
  420. CARLA_SAFE_ASSERT_CONTINUE(portId < fAudioOutCount);
  421. ConnectionToId connectionToId;
  422. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_AUDIO_OUT1, RACK_GRAPH_GROUP_AUDIO_OUT, portId);
  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.connectedOut2.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_OUT2, 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. graph->audio.mutex.unlock();
  438. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  439. {
  440. const MidiInPort& inPort(it.getValue());
  441. const uint portId(graph->midi.getPortId(true, inPort.name));
  442. CARLA_SAFE_ASSERT_CONTINUE(portId < graph->midi.ins.count());
  443. ConnectionToId connectionToId;
  444. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_MIDI_IN, portId, RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_MIDI_IN);
  445. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  446. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  447. graph->connections.list.append(connectionToId);
  448. }
  449. fMidiOutMutex.lock();
  450. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  451. {
  452. const MidiOutPort& outPort(it.getValue());
  453. const uint portId(graph->midi.getPortId(false, outPort.name));
  454. CARLA_SAFE_ASSERT_CONTINUE(portId < graph->midi.outs.count());
  455. ConnectionToId connectionToId;
  456. connectionToId.setData(++(graph->connections.lastId), RACK_GRAPH_GROUP_CARLA, RACK_GRAPH_CARLA_PORT_MIDI_OUT, RACK_GRAPH_GROUP_MIDI_OUT, portId);
  457. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  458. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  459. graph->connections.list.append(connectionToId);
  460. }
  461. fMidiOutMutex.unlock();
  462. }
  463. void patchbayRefreshPatchbay() noexcept
  464. {
  465. PatchbayGraph* const graph(pData->graph.getPatchbayGraph());
  466. CARLA_SAFE_ASSERT_RETURN(graph != nullptr,);
  467. graph->refreshConnections(this);
  468. }
  469. // -------------------------------------------------------------------
  470. protected:
  471. void handleAudioProcessCallback(void* outputBuffer, void* inputBuffer, uint nframes, double streamTime, RtAudioStreamStatus status)
  472. {
  473. const PendingRtEventsRunner prt(this);
  474. // get buffers from RtAudio
  475. const float* const insPtr = (const float*)inputBuffer;
  476. float* const outsPtr = (float*)outputBuffer;
  477. // assert rtaudio buffers
  478. CARLA_SAFE_ASSERT_RETURN(outputBuffer != nullptr,);
  479. CARLA_SAFE_ASSERT_RETURN(pData->bufferSize == nframes,);
  480. // initialize rtaudio input
  481. const float* inBuf[fAudioInCount];
  482. for (uint i=0; i < fAudioInCount; ++i)
  483. inBuf[i] = insPtr+(nframes*i);
  484. // initialize rtaudio output
  485. float* outBuf[fAudioOutCount];
  486. for (uint i=0; i < fAudioOutCount; ++i)
  487. outBuf[i] = outsPtr+(nframes*i);
  488. FloatVectorOperations::clear(outsPtr, static_cast<int>(nframes*fAudioOutCount));
  489. // initialize events
  490. carla_zeroStruct<EngineEvent>(pData->events.in, kMaxEngineEventInternalCount);
  491. carla_zeroStruct<EngineEvent>(pData->events.out, kMaxEngineEventInternalCount);
  492. if (fMidiInEvents.mutex.tryLock())
  493. {
  494. uint32_t engineEventIndex = 0;
  495. fMidiInEvents.splice();
  496. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin(); it.valid(); it.next())
  497. {
  498. const RtMidiEvent& midiEvent(it.getValue());
  499. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  500. if (midiEvent.time < pData->timeInfo.frame)
  501. {
  502. engineEvent.time = 0;
  503. }
  504. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  505. {
  506. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  507. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  508. }
  509. else
  510. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  511. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data);
  512. if (engineEventIndex >= kMaxEngineEventInternalCount)
  513. break;
  514. }
  515. fMidiInEvents.data.clear();
  516. fMidiInEvents.mutex.unlock();
  517. }
  518. pData->graph.process(pData, inBuf, outBuf, nframes);
  519. fMidiOutMutex.lock();
  520. if (fMidiOuts.count() > 0)
  521. {
  522. uint8_t size = 0;
  523. uint8_t data[3] = { 0, 0, 0 };
  524. const uint8_t* dataPtr = data;
  525. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  526. {
  527. const EngineEvent& engineEvent(pData->events.out[i]);
  528. if (engineEvent.type == kEngineEventTypeNull)
  529. break;
  530. else if (engineEvent.type == kEngineEventTypeControl)
  531. {
  532. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  533. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  534. dataPtr = data;
  535. }
  536. else if (engineEvent.type == kEngineEventTypeMidi)
  537. {
  538. const EngineMidiEvent& midiEvent(engineEvent.midi);
  539. size = midiEvent.size;
  540. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  541. dataPtr = midiEvent.dataExt;
  542. else
  543. dataPtr = midiEvent.data;
  544. }
  545. else
  546. {
  547. continue;
  548. }
  549. if (size > 0)
  550. {
  551. fMidiOutVector.assign(dataPtr, dataPtr + size);
  552. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  553. {
  554. MidiOutPort& outPort(it.getValue());
  555. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  556. outPort.port->sendMessage(&fMidiOutVector);
  557. }
  558. }
  559. }
  560. }
  561. fMidiOutMutex.unlock();
  562. return; // unused
  563. (void)streamTime; (void)status;
  564. }
  565. void handleMidiCallback(double timeStamp, std::vector<uchar>* const message)
  566. {
  567. const size_t messageSize(message->size());
  568. if (messageSize == 0 || messageSize > EngineMidiEvent::kDataSize)
  569. return;
  570. timeStamp /= 2;
  571. if (timeStamp > 0.95)
  572. timeStamp = 0.95;
  573. else if (timeStamp < 0.0)
  574. timeStamp = 0.0;
  575. RtMidiEvent midiEvent;
  576. midiEvent.time = pData->timeInfo.frame + uint64_t(timeStamp * (double)pData->bufferSize);
  577. if (midiEvent.time < fLastEventTime)
  578. midiEvent.time = fLastEventTime;
  579. else
  580. fLastEventTime = midiEvent.time;
  581. midiEvent.size = static_cast<uint8_t>(messageSize);
  582. size_t i=0;
  583. for (; i < messageSize; ++i)
  584. midiEvent.data[i] = message->at(i);
  585. for (; i < EngineMidiEvent::kDataSize; ++i)
  586. midiEvent.data[i] = 0;
  587. fMidiInEvents.append(midiEvent);
  588. }
  589. // -------------------------------------------------------------------
  590. bool connectRackMidiInPort(const char* const portName) override
  591. {
  592. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  593. carla_debug("CarlaEngineRtAudio::connectRackMidiInPort(\"%s\")", portName);
  594. RackGraph* const graph(pData->graph.getRackGraph());
  595. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  596. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  597. CarlaString newRtMidiPortName;
  598. newRtMidiPortName += getName();
  599. newRtMidiPortName += ":";
  600. newRtMidiPortName += portName;
  601. RtMidiIn* const rtMidiIn(new RtMidiIn(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), newRtMidiPortName.buffer(), 512));
  602. rtMidiIn->ignoreTypes();
  603. rtMidiIn->setCallback(carla_rtmidi_callback, this);
  604. bool found = false;
  605. uint rtMidiPortIndex;
  606. for (uint i=0, count=rtMidiIn->getPortCount(); i < count; ++i)
  607. {
  608. if (rtMidiIn->getPortName(i) == portName)
  609. {
  610. found = true;
  611. rtMidiPortIndex = i;
  612. break;
  613. }
  614. }
  615. if (! found)
  616. {
  617. delete rtMidiIn;
  618. return false;
  619. }
  620. try {
  621. rtMidiIn->openPort(rtMidiPortIndex, portName);
  622. }
  623. catch(...) {
  624. delete rtMidiIn;
  625. return false;
  626. };
  627. MidiInPort midiPort;
  628. midiPort.port = rtMidiIn;
  629. std::strncpy(midiPort.name, portName, STR_MAX);
  630. midiPort.name[STR_MAX] = '\0';
  631. fMidiIns.append(midiPort);
  632. return true;
  633. }
  634. bool connectRackMidiOutPort(const char* const portName) override
  635. {
  636. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  637. carla_debug("CarlaEngineRtAudio::connectRackMidiOutPort(\"%s\")", portName);
  638. RackGraph* const graph(pData->graph.getRackGraph());
  639. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  640. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  641. CarlaString newRtMidiPortName;
  642. newRtMidiPortName += getName();
  643. newRtMidiPortName += ":";
  644. newRtMidiPortName += portName;
  645. RtMidiOut* const rtMidiOut(new RtMidiOut(getMatchedAudioMidiAPI(fAudio.getCurrentApi()), newRtMidiPortName.buffer()));
  646. bool found = false;
  647. uint rtMidiPortIndex;
  648. for (uint i=0, count=rtMidiOut->getPortCount(); i < count; ++i)
  649. {
  650. if (rtMidiOut->getPortName(i) == portName)
  651. {
  652. found = true;
  653. rtMidiPortIndex = i;
  654. break;
  655. }
  656. }
  657. if (! found)
  658. {
  659. delete rtMidiOut;
  660. return false;
  661. }
  662. try {
  663. rtMidiOut->openPort(rtMidiPortIndex, portName);
  664. }
  665. catch(...) {
  666. delete rtMidiOut;
  667. return false;
  668. };
  669. MidiOutPort midiPort;
  670. midiPort.port = rtMidiOut;
  671. std::strncpy(midiPort.name, portName, STR_MAX);
  672. midiPort.name[STR_MAX] = '\0';
  673. const CarlaMutexLocker cml(fMidiOutMutex);
  674. fMidiOuts.append(midiPort);
  675. return true;
  676. }
  677. bool disconnectRackMidiInPort(const char* const portName) override
  678. {
  679. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  680. carla_debug("CarlaEngineRtAudio::disconnectRackMidiInPort(\"%s\")", portName);
  681. RackGraph* const graph(pData->graph.getRackGraph());
  682. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  683. CARLA_SAFE_ASSERT_RETURN(graph->midi.ins.count() > 0, false);
  684. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  685. {
  686. MidiInPort& inPort(it.getValue());
  687. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  688. if (std::strcmp(inPort.name, portName) != 0)
  689. continue;
  690. inPort.port->cancelCallback();
  691. inPort.port->closePort();
  692. delete inPort.port;
  693. fMidiIns.remove(it);
  694. return true;
  695. }
  696. return false;
  697. }
  698. bool disconnectRackMidiOutPort(const char* const portName) override
  699. {
  700. CARLA_SAFE_ASSERT_RETURN(portName != nullptr && portName[0] != '\0', false);
  701. carla_debug("CarlaEngineRtAudio::disconnectRackMidiOutPort(\"%s\")", portName);
  702. RackGraph* const graph(pData->graph.getRackGraph());
  703. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  704. CARLA_SAFE_ASSERT_RETURN(graph->midi.outs.count() > 0, false);
  705. const CarlaMutexLocker cml(fMidiOutMutex);
  706. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  707. {
  708. MidiOutPort& outPort(it.getValue());
  709. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  710. if (std::strcmp(outPort.name, portName) != 0)
  711. continue;
  712. outPort.port->closePort();
  713. delete outPort.port;
  714. fMidiOuts.remove(it);
  715. return true;
  716. }
  717. return false;
  718. }
  719. // -------------------------------------------------------------------
  720. private:
  721. RtAudio fAudio;
  722. // useful info
  723. uint fAudioInCount;
  724. uint fAudioOutCount;
  725. uint64_t fLastEventTime;
  726. // current device name
  727. CarlaString fDeviceName;
  728. struct MidiInPort {
  729. RtMidiIn* port;
  730. char name[STR_MAX+1];
  731. };
  732. struct MidiOutPort {
  733. RtMidiOut* port;
  734. char name[STR_MAX+1];
  735. };
  736. struct RtMidiEvent {
  737. uint64_t time; // needs to compare to internal time
  738. uint8_t size;
  739. uint8_t data[EngineMidiEvent::kDataSize];
  740. };
  741. struct RtMidiEvents {
  742. CarlaMutex mutex;
  743. RtLinkedList<RtMidiEvent>::Pool dataPool;
  744. RtLinkedList<RtMidiEvent> data;
  745. RtLinkedList<RtMidiEvent> dataPending;
  746. RtMidiEvents()
  747. : mutex(),
  748. dataPool(512, 512),
  749. data(dataPool),
  750. dataPending(dataPool) {}
  751. ~RtMidiEvents()
  752. {
  753. clear();
  754. }
  755. void append(const RtMidiEvent& event)
  756. {
  757. mutex.lock();
  758. dataPending.append(event);
  759. mutex.unlock();
  760. }
  761. void clear()
  762. {
  763. mutex.lock();
  764. data.clear();
  765. dataPending.clear();
  766. mutex.unlock();
  767. }
  768. void splice()
  769. {
  770. dataPending.spliceAppendTo(data);
  771. }
  772. };
  773. LinkedList<MidiInPort> fMidiIns;
  774. RtMidiEvents fMidiInEvents;
  775. LinkedList<MidiOutPort> fMidiOuts;
  776. CarlaMutex fMidiOutMutex;
  777. std::vector<uint8_t> fMidiOutVector;
  778. #define handlePtr ((CarlaEngineRtAudio*)userData)
  779. static int carla_rtaudio_process_callback(void* outputBuffer, void* inputBuffer, uint nframes, double streamTime, RtAudioStreamStatus status, void* userData)
  780. {
  781. handlePtr->handleAudioProcessCallback(outputBuffer, inputBuffer, nframes, streamTime, status);
  782. return 0;
  783. }
  784. static void carla_rtmidi_callback(double timeStamp, std::vector<uchar>* message, void* userData)
  785. {
  786. handlePtr->handleMidiCallback(timeStamp, message);
  787. }
  788. #undef handlePtr
  789. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineRtAudio)
  790. };
  791. // -----------------------------------------
  792. CarlaEngine* CarlaEngine::newRtAudio(const AudioApi api)
  793. {
  794. initRtAudioAPIsIfNeeded();
  795. RtAudio::Api rtApi(RtAudio::UNSPECIFIED);
  796. switch (api)
  797. {
  798. case AUDIO_API_NULL:
  799. rtApi = RtAudio::RTAUDIO_DUMMY;
  800. break;
  801. case AUDIO_API_JACK:
  802. rtApi = RtAudio::UNIX_JACK;
  803. break;
  804. case AUDIO_API_ALSA:
  805. rtApi = RtAudio::LINUX_ALSA;
  806. break;
  807. case AUDIO_API_OSS:
  808. rtApi = RtAudio::LINUX_OSS;
  809. break;
  810. case AUDIO_API_PULSE:
  811. rtApi = RtAudio::LINUX_PULSE;
  812. break;
  813. case AUDIO_API_CORE:
  814. rtApi = RtAudio::MACOSX_CORE;
  815. break;
  816. case AUDIO_API_ASIO:
  817. rtApi = RtAudio::WINDOWS_ASIO;
  818. break;
  819. case AUDIO_API_DS:
  820. rtApi = RtAudio::WINDOWS_DS;
  821. break;
  822. }
  823. return new CarlaEngineRtAudio(rtApi);
  824. }
  825. uint CarlaEngine::getRtAudioApiCount()
  826. {
  827. initRtAudioAPIsIfNeeded();
  828. return static_cast<uint>(gRtAudioApis.size());
  829. }
  830. const char* CarlaEngine::getRtAudioApiName(const uint index)
  831. {
  832. initRtAudioAPIsIfNeeded();
  833. CARLA_SAFE_ASSERT_RETURN(index < gRtAudioApis.size(), nullptr);
  834. return CarlaBackend::getRtAudioApiName(gRtAudioApis[index]);
  835. }
  836. const char* const* CarlaEngine::getRtAudioApiDeviceNames(const uint index)
  837. {
  838. initRtAudioAPIsIfNeeded();
  839. if (index >= gRtAudioApis.size())
  840. return nullptr;
  841. const RtAudio::Api& api(gRtAudioApis[index]);
  842. RtAudio rtAudio(api);
  843. const uint devCount(rtAudio.getDeviceCount());
  844. if (devCount == 0)
  845. return nullptr;
  846. CarlaStringList devNames;
  847. for (uint i=0; i < devCount; ++i)
  848. {
  849. RtAudio::DeviceInfo devInfo(rtAudio.getDeviceInfo(i));
  850. if (devInfo.probed && devInfo.outputChannels > 0 /*&& (devInfo.nativeFormats & RTAUDIO_FLOAT32) != 0*/)
  851. devNames.append(devInfo.name.c_str());
  852. }
  853. gDeviceNames = devNames.toCharStringListPtr();
  854. return gDeviceNames;
  855. }
  856. const EngineDriverDeviceInfo* CarlaEngine::getRtAudioDeviceInfo(const uint index, const char* const deviceName)
  857. {
  858. initRtAudioAPIsIfNeeded();
  859. if (index >= gRtAudioApis.size())
  860. return nullptr;
  861. const RtAudio::Api& api(gRtAudioApis[index]);
  862. RtAudio rtAudio(api);
  863. const uint devCount(rtAudio.getDeviceCount());
  864. if (devCount == 0)
  865. return nullptr;
  866. uint i;
  867. RtAudio::DeviceInfo rtAudioDevInfo;
  868. for (i=0; i < devCount; ++i)
  869. {
  870. rtAudioDevInfo = rtAudio.getDeviceInfo(i);
  871. if (rtAudioDevInfo.name == deviceName)
  872. break;
  873. }
  874. if (i == devCount)
  875. return nullptr;
  876. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  877. static uint32_t dummyBufferSizes[] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  878. static double dummySampleRates[] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  879. // reset
  880. devInfo.hints = 0x0;
  881. devInfo.bufferSizes = dummyBufferSizes;
  882. // cleanup
  883. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  884. {
  885. delete[] devInfo.sampleRates;
  886. devInfo.sampleRates = nullptr;
  887. }
  888. if (size_t sampleRatesCount = rtAudioDevInfo.sampleRates.size())
  889. {
  890. double* const sampleRates(new double[sampleRatesCount+1]);
  891. for (size_t j=0; j < sampleRatesCount; ++j)
  892. sampleRates[j] = rtAudioDevInfo.sampleRates[j];
  893. sampleRates[sampleRatesCount] = 0.0;
  894. devInfo.sampleRates = sampleRates;
  895. }
  896. else
  897. {
  898. devInfo.sampleRates = dummySampleRates;
  899. }
  900. return &devInfo;
  901. }
  902. // -----------------------------------------
  903. CARLA_BACKEND_END_NAMESPACE