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.

1164 lines
35KB

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