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.

1166 lines
35KB

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