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.

1285 lines
39KB

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