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.

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