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.

1168 lines
36KB

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