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.

1016 lines
31KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2019 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 GPL.txt file
  16. */
  17. #include "CarlaEngineGraph.hpp"
  18. #include "CarlaEngineInternal.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaStringList.hpp"
  21. #include "RtLinkedList.hpp"
  22. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  23. # pragma GCC diagnostic push
  24. # pragma GCC diagnostic ignored "-Wcast-qual"
  25. # pragma GCC diagnostic ignored "-Wclass-memaccess"
  26. # pragma GCC diagnostic ignored "-Wconversion"
  27. # pragma GCC diagnostic ignored "-Wdouble-promotion"
  28. # pragma GCC diagnostic ignored "-Weffc++"
  29. # pragma GCC diagnostic ignored "-Wfloat-equal"
  30. # pragma GCC diagnostic ignored "-Wsign-conversion"
  31. # pragma GCC diagnostic ignored "-Wundef"
  32. # pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
  33. #endif
  34. #include "AppConfig.h"
  35. #include "juce_audio_devices/juce_audio_devices.h"
  36. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
  37. # pragma GCC diagnostic pop
  38. #endif
  39. CARLA_BACKEND_START_NAMESPACE
  40. // -------------------------------------------------------------------------------------------------------------------
  41. struct MidiInPort {
  42. juce::MidiInput* port;
  43. char name[STR_MAX+1];
  44. };
  45. struct MidiOutPort {
  46. juce::MidiOutput* port;
  47. char name[STR_MAX+1];
  48. };
  49. struct RtMidiEvent {
  50. uint64_t time; // needs to compare to internal time
  51. uint8_t size;
  52. uint8_t data[EngineMidiEvent::kDataSize];
  53. };
  54. // -------------------------------------------------------------------------------------------------------------------
  55. // Fallback data
  56. static const MidiInPort kMidiInPortFallback = { nullptr, { '\0' } };
  57. static /* */ MidiInPort kMidiInPortFallbackNC = { nullptr, { '\0' } };
  58. static const MidiOutPort kMidiOutPortFallback = { nullptr, { '\0' } };
  59. static /* */ MidiOutPort kMidiOutPortFallbackNC = { nullptr, { '\0' } };
  60. static const RtMidiEvent kRtMidiEventFallback = { 0, 0, { 0 } };
  61. // -------------------------------------------------------------------------------------------------------------------
  62. // Global static data
  63. static CharStringListPtr gDeviceNames;
  64. static juce::OwnedArray<juce::AudioIODeviceType> gDeviceTypes;
  65. struct JuceCleanup : public juce::DeletedAtShutdown {
  66. JuceCleanup() noexcept {}
  67. ~JuceCleanup()
  68. {
  69. gDeviceTypes.clear(true);
  70. }
  71. };
  72. // -------------------------------------------------------------------------------------------------------------------
  73. // Cleanup
  74. struct AudioIODeviceTypeComparator
  75. {
  76. static int compareElements (const juce::AudioIODeviceType* d1, const juce::AudioIODeviceType* d2) noexcept
  77. {
  78. return d1->getTypeName().compareNatural (d2->getTypeName());
  79. }
  80. };
  81. static void initJuceDevicesIfNeeded()
  82. {
  83. static juce::AudioDeviceManager sDeviceManager;
  84. if (gDeviceTypes.size() != 0)
  85. return;
  86. sDeviceManager.createAudioDeviceTypes(gDeviceTypes);
  87. CARLA_SAFE_ASSERT_RETURN(gDeviceTypes.size() != 0,);
  88. new JuceCleanup();
  89. // remove JACK from device list
  90. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  91. {
  92. if (gDeviceTypes[i]->getTypeName() == "JACK")
  93. {
  94. gDeviceTypes.remove(i, true);
  95. break;
  96. }
  97. }
  98. AudioIODeviceTypeComparator comp;
  99. gDeviceTypes.sort(comp);
  100. }
  101. // -------------------------------------------------------------------------------------------------------------------
  102. // Juce Engine
  103. class CarlaEngineJuce : public CarlaEngine,
  104. public juce::AudioIODeviceCallback,
  105. public juce::MidiInputCallback
  106. {
  107. public:
  108. CarlaEngineJuce(juce::AudioIODeviceType* const devType)
  109. : CarlaEngine(),
  110. juce::AudioIODeviceCallback(),
  111. fDevice(),
  112. fDeviceType(devType),
  113. fMidiIns(),
  114. fMidiInEvents(),
  115. fMidiOuts(),
  116. fMidiOutMutex()
  117. {
  118. carla_debug("CarlaEngineJuce::CarlaEngineJuce(%p)", devType);
  119. // just to make sure
  120. pData->options.transportMode = ENGINE_TRANSPORT_MODE_INTERNAL;
  121. }
  122. ~CarlaEngineJuce() override
  123. {
  124. carla_debug("CarlaEngineJuce::~CarlaEngineJuce()");
  125. }
  126. // -------------------------------------
  127. bool init(const char* const clientName) override
  128. {
  129. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0', false);
  130. carla_debug("CarlaEngineJuce::init(\"%s\")", clientName);
  131. if (pData->options.processMode != ENGINE_PROCESS_MODE_CONTINUOUS_RACK && pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  132. {
  133. setLastError("Invalid process mode");
  134. return false;
  135. }
  136. juce::String deviceName;
  137. if (pData->options.audioDevice != nullptr && pData->options.audioDevice[0] != '\0')
  138. {
  139. deviceName = pData->options.audioDevice;
  140. }
  141. else
  142. {
  143. const int defaultIndex = fDeviceType->getDefaultDeviceIndex(false);
  144. juce::StringArray deviceNames(fDeviceType->getDeviceNames());
  145. if (defaultIndex >= 0 && defaultIndex < deviceNames.size())
  146. deviceName = deviceNames[defaultIndex];
  147. }
  148. if (deviceName.isEmpty())
  149. {
  150. setLastError("Audio device has not been selected yet and a default one is not available");
  151. return false;
  152. }
  153. fDevice = fDeviceType->createDevice(deviceName, deviceName);
  154. if (fDevice == nullptr)
  155. {
  156. setLastError("Failed to create device");
  157. return false;
  158. }
  159. juce::StringArray inputNames(fDevice->getInputChannelNames());
  160. juce::StringArray outputNames(fDevice->getOutputChannelNames());
  161. if (inputNames.size() < 0 || outputNames.size() <= 0)
  162. {
  163. setLastError("Selected device does not have any outputs");
  164. return false;
  165. }
  166. juce::BigInteger inputChannels;
  167. inputChannels.setRange(0, inputNames.size(), true);
  168. juce::BigInteger outputChannels;
  169. outputChannels.setRange(0, outputNames.size(), true);
  170. juce::String error = fDevice->open(inputChannels, outputChannels, pData->options.audioSampleRate, static_cast<int>(pData->options.audioBufferSize));
  171. if (error.isNotEmpty())
  172. {
  173. setLastError(error.toUTF8());
  174. fDevice = nullptr;
  175. return false;
  176. }
  177. if (! pData->init(clientName))
  178. {
  179. close();
  180. setLastError("Failed to init internal data");
  181. return false;
  182. }
  183. pData->bufferSize = static_cast<uint32_t>(fDevice->getCurrentBufferSizeSamples());
  184. pData->sampleRate = fDevice->getCurrentSampleRate();
  185. pData->initTime(pData->options.transportExtra);
  186. pData->graph.create(static_cast<uint32_t>(inputNames.size()),
  187. static_cast<uint32_t>(outputNames.size()),
  188. 0, 0);
  189. fDevice->start(this);
  190. patchbayRefresh(true, false, false);
  191. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  192. refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), false, false);
  193. callback(true, true,
  194. ENGINE_CALLBACK_ENGINE_STARTED,
  195. 0,
  196. pData->options.processMode,
  197. pData->options.transportMode,
  198. static_cast<int>(pData->bufferSize),
  199. static_cast<float>(pData->sampleRate),
  200. getCurrentDriverName());
  201. return true;
  202. }
  203. bool close() override
  204. {
  205. carla_debug("CarlaEngineJuce::close()");
  206. bool hasError = false;
  207. // stop stream first
  208. if (fDevice != nullptr && fDevice->isPlaying())
  209. fDevice->stop();
  210. // clear engine data
  211. CarlaEngine::close();
  212. pData->graph.destroy();
  213. for (LinkedList<MidiInPort>::Itenerator it = fMidiIns.begin2(); it.valid(); it.next())
  214. {
  215. MidiInPort& inPort(it.getValue(kMidiInPortFallbackNC));
  216. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  217. inPort.port->stop();
  218. delete inPort.port;
  219. }
  220. fMidiIns.clear();
  221. fMidiInEvents.clear();
  222. fMidiOutMutex.lock();
  223. for (LinkedList<MidiOutPort>::Itenerator it = fMidiOuts.begin2(); it.valid(); it.next())
  224. {
  225. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  226. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  227. outPort.port->stopBackgroundThread();
  228. delete outPort.port;
  229. }
  230. fMidiOuts.clear();
  231. fMidiOutMutex.unlock();
  232. // close stream
  233. if (fDevice != nullptr)
  234. {
  235. if (fDevice->isOpen())
  236. fDevice->close();
  237. fDevice = nullptr;
  238. }
  239. return !hasError;
  240. }
  241. bool isRunning() const noexcept override
  242. {
  243. return fDevice != nullptr && fDevice->isOpen();
  244. }
  245. bool isOffline() const noexcept override
  246. {
  247. return false;
  248. }
  249. EngineType getType() const noexcept override
  250. {
  251. return kEngineTypeJuce;
  252. }
  253. const char* getCurrentDriverName() const noexcept override
  254. {
  255. return fDeviceType->getTypeName().toRawUTF8();
  256. }
  257. /*
  258. float getDSPLoad() const noexcept override
  259. {
  260. return 0.0f;
  261. }
  262. */
  263. uint32_t getTotalXruns() const noexcept override
  264. {
  265. const int xruns = fDevice->getXRunCount();
  266. if (xruns <= 0)
  267. return 0;
  268. const uint uxruns = static_cast<uint>(xruns);
  269. if (uxruns <= pData->xruns)
  270. return 0;
  271. return uxruns - pData->xruns;
  272. }
  273. void clearXruns() const noexcept override
  274. {
  275. const int xruns = fDevice->getXRunCount();
  276. pData->xruns = xruns > 0 ? static_cast<uint32_t>(xruns) : 0;
  277. }
  278. // -------------------------------------------------------------------
  279. // Patchbay
  280. template<class Graph>
  281. bool refreshExternalGraphPorts(Graph* const graph, const bool sendHost, const bool sendOSC)
  282. {
  283. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  284. char strBuf[STR_MAX];
  285. ExternalGraph& extGraph(graph->extGraph);
  286. // ---------------------------------------------------------------
  287. // clear last ports
  288. extGraph.clear();
  289. // ---------------------------------------------------------------
  290. // fill in new ones
  291. // Audio In
  292. {
  293. juce::StringArray inputNames(fDevice->getInputChannelNames());
  294. for (int i=0, count=inputNames.size(); i<count; ++i)
  295. {
  296. PortNameToId portNameToId;
  297. portNameToId.setData(kExternalGraphGroupAudioIn, uint(i+1), inputNames[i].toRawUTF8(), "");
  298. extGraph.audioPorts.ins.append(portNameToId);
  299. }
  300. }
  301. // Audio Out
  302. {
  303. juce::StringArray outputNames(fDevice->getOutputChannelNames());
  304. for (int i=0, count=outputNames.size(); i<count; ++i)
  305. {
  306. PortNameToId portNameToId;
  307. portNameToId.setData(kExternalGraphGroupAudioOut, uint(i+1), outputNames[i].toRawUTF8(), "");
  308. }
  309. }
  310. // MIDI In
  311. {
  312. juce::StringArray midiIns(juce::MidiInput::getDevices());
  313. for (int i=0, count=midiIns.size(); i<count; ++i)
  314. {
  315. PortNameToId portNameToId;
  316. portNameToId.setData(kExternalGraphGroupMidiIn, uint(i+1), midiIns[i].toRawUTF8(), "");
  317. extGraph.midiPorts.ins.append(portNameToId);
  318. }
  319. }
  320. // MIDI Out
  321. {
  322. juce::StringArray midiOuts(juce::MidiOutput::getDevices());
  323. for (int i=0, count=midiOuts.size(); i<count; ++i)
  324. {
  325. PortNameToId portNameToId;
  326. portNameToId.setData(kExternalGraphGroupMidiOut, uint(i+1), midiOuts[i].toRawUTF8(), "");
  327. extGraph.midiPorts.outs.append(portNameToId);
  328. }
  329. }
  330. // ---------------------------------------------------------------
  331. // now refresh
  332. if (sendHost || sendOSC)
  333. {
  334. juce::String deviceName(fDevice->getName());
  335. if (deviceName.isNotEmpty())
  336. deviceName = deviceName.dropLastCharacters(deviceName.fromFirstOccurrenceOf(", ", true, false).length());
  337. graph->refresh(sendHost, sendOSC, true, deviceName.toRawUTF8());
  338. }
  339. // ---------------------------------------------------------------
  340. // add midi connections
  341. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  342. {
  343. const MidiInPort& inPort(it.getValue(kMidiInPortFallback));
  344. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  345. const uint portId(extGraph.midiPorts.getPortId(true, inPort.name));
  346. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.ins.count());
  347. ConnectionToId connectionToId;
  348. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupMidiIn, portId, kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiIn);
  349. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  350. strBuf[STR_MAX-1] = '\0';
  351. callback(sendHost, sendOSC,
  352. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  353. connectionToId.id,
  354. 0, 0, 0, 0.0f,
  355. strBuf);
  356. extGraph.connections.list.append(connectionToId);
  357. }
  358. fMidiOutMutex.lock();
  359. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  360. {
  361. const MidiOutPort& outPort(it.getValue(kMidiOutPortFallback));
  362. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  363. const uint portId(extGraph.midiPorts.getPortId(false, outPort.name));
  364. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.outs.count());
  365. ConnectionToId connectionToId;
  366. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiOut, kExternalGraphGroupMidiOut, portId);
  367. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  368. strBuf[STR_MAX-1] = '\0';
  369. callback(sendHost, sendOSC,
  370. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  371. connectionToId.id,
  372. 0, 0, 0, 0.0f,
  373. strBuf);
  374. extGraph.connections.list.append(connectionToId);
  375. }
  376. fMidiOutMutex.unlock();
  377. return true;
  378. }
  379. bool patchbayRefresh(const bool sendHost, const bool sendOSC, const bool external) override
  380. {
  381. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  382. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  383. return refreshExternalGraphPorts<RackGraph>(pData->graph.getRackGraph(), sendHost, sendOSC);
  384. if (sendHost)
  385. pData->graph.setUsingExternalHost(external);
  386. if (sendOSC)
  387. pData->graph.setUsingExternalOSC(external);
  388. if (external)
  389. return refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), sendHost, sendOSC);
  390. return CarlaEngine::patchbayRefresh(sendHost, sendOSC, false);
  391. }
  392. // -------------------------------------------------------------------
  393. protected:
  394. void audioDeviceIOCallback(const float** inputChannelData, int numInputChannels, float** outputChannelData,
  395. int numOutputChannels, int numSamples) override
  396. {
  397. CARLA_SAFE_ASSERT_RETURN(numSamples >= 0,);
  398. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  399. const PendingRtEventsRunner prt(this, nframes, true); // FIXME remove dspCalc after updating juce
  400. // assert juce buffers
  401. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0,);
  402. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0,);
  403. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr,);
  404. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize),);
  405. // initialize juce output
  406. for (int i=0; i < numOutputChannels; ++i)
  407. carla_zeroFloats(outputChannelData[i], nframes);
  408. // initialize events
  409. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  410. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  411. if (fMidiInEvents.mutex.tryLock())
  412. {
  413. uint32_t engineEventIndex = 0;
  414. fMidiInEvents.splice();
  415. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin2(); it.valid(); it.next())
  416. {
  417. const RtMidiEvent& midiEvent(it.getValue(kRtMidiEventFallback));
  418. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.size > 0);
  419. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  420. if (midiEvent.time < pData->timeInfo.frame)
  421. {
  422. engineEvent.time = 0;
  423. }
  424. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  425. {
  426. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  427. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  428. }
  429. else
  430. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  431. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data, 0);
  432. if (engineEventIndex >= kMaxEngineEventInternalCount)
  433. break;
  434. }
  435. fMidiInEvents.data.clear();
  436. fMidiInEvents.mutex.unlock();
  437. }
  438. pData->graph.process(pData, inputChannelData, outputChannelData, nframes);
  439. fMidiOutMutex.lock();
  440. if (fMidiOuts.count() > 0)
  441. {
  442. uint8_t size = 0;
  443. uint8_t data[3] = { 0, 0, 0 };
  444. const uint8_t* dataPtr = data;
  445. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  446. {
  447. const EngineEvent& engineEvent(pData->events.out[i]);
  448. if (engineEvent.type == kEngineEventTypeNull)
  449. break;
  450. else if (engineEvent.type == kEngineEventTypeControl)
  451. {
  452. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  453. ctrlEvent.convertToMidiData(engineEvent.channel, data);
  454. dataPtr = data;
  455. }
  456. else if (engineEvent.type == kEngineEventTypeMidi)
  457. {
  458. const EngineMidiEvent& midiEvent(engineEvent.midi);
  459. size = midiEvent.size;
  460. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  461. dataPtr = midiEvent.dataExt;
  462. else
  463. dataPtr = midiEvent.data;
  464. }
  465. else
  466. {
  467. continue;
  468. }
  469. if (size > 0)
  470. {
  471. juce::MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  472. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  473. {
  474. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  475. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  476. outPort.port->sendMessageNow(message);
  477. }
  478. }
  479. }
  480. }
  481. fMidiOutMutex.unlock();
  482. }
  483. void audioDeviceAboutToStart(juce::AudioIODevice* /*device*/) override
  484. {
  485. }
  486. void audioDeviceStopped() override
  487. {
  488. }
  489. void audioDeviceError(const juce::String& errorMessage) override
  490. {
  491. callback(true, true, ENGINE_CALLBACK_ERROR, 0, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  492. }
  493. // -------------------------------------------------------------------
  494. void handleIncomingMidiMessage(juce::MidiInput* /*source*/, const juce::MidiMessage& message) override
  495. {
  496. const int messageSize(message.getRawDataSize());
  497. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  498. return;
  499. const uint8_t* const messageData(message.getRawData());
  500. RtMidiEvent midiEvent;
  501. midiEvent.time = 0; // TODO
  502. midiEvent.size = static_cast<uint8_t>(messageSize);
  503. int i=0;
  504. for (; i < messageSize; ++i)
  505. midiEvent.data[i] = messageData[i];
  506. for (; i < EngineMidiEvent::kDataSize; ++i)
  507. midiEvent.data[i] = 0;
  508. fMidiInEvents.append(midiEvent);
  509. }
  510. // -------------------------------------------------------------------
  511. bool connectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  512. {
  513. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  514. carla_stdout("CarlaEngineJuce::connectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  515. switch (connectionType)
  516. {
  517. case kExternalGraphConnectionAudioIn1:
  518. case kExternalGraphConnectionAudioIn2:
  519. case kExternalGraphConnectionAudioOut1:
  520. case kExternalGraphConnectionAudioOut2:
  521. return CarlaEngine::connectExternalGraphPort(connectionType, portId, portName);
  522. case kExternalGraphConnectionMidiInput: {
  523. juce::StringArray midiIns(juce::MidiInput::getDevices());
  524. if (! midiIns.contains(portName))
  525. return false;
  526. juce::MidiInput* const juceMidiIn(juce::MidiInput::openDevice(midiIns.indexOf(portName), this));
  527. juceMidiIn->start();
  528. MidiInPort midiPort;
  529. midiPort.port = juceMidiIn;
  530. std::strncpy(midiPort.name, portName, STR_MAX);
  531. midiPort.name[STR_MAX] = '\0';
  532. fMidiIns.append(midiPort);
  533. return true;
  534. } break;
  535. case kExternalGraphConnectionMidiOutput: {
  536. juce::StringArray midiOuts(juce::MidiOutput::getDevices());
  537. if (! midiOuts.contains(portName))
  538. return false;
  539. juce::MidiOutput* const juceMidiOut(juce::MidiOutput::openDevice(midiOuts.indexOf(portName)));
  540. juceMidiOut->startBackgroundThread();
  541. MidiOutPort midiPort;
  542. midiPort.port = juceMidiOut;
  543. std::strncpy(midiPort.name, portName, STR_MAX);
  544. midiPort.name[STR_MAX] = '\0';
  545. const CarlaMutexLocker cml(fMidiOutMutex);
  546. fMidiOuts.append(midiPort);
  547. return true;
  548. } break;
  549. }
  550. return false;
  551. }
  552. bool disconnectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  553. {
  554. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  555. carla_debug("CarlaEngineJuce::disconnectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  556. switch (connectionType)
  557. {
  558. case kExternalGraphConnectionAudioIn1:
  559. case kExternalGraphConnectionAudioIn2:
  560. case kExternalGraphConnectionAudioOut1:
  561. case kExternalGraphConnectionAudioOut2:
  562. return CarlaEngine::disconnectExternalGraphPort(connectionType, portId, portName);
  563. case kExternalGraphConnectionMidiInput:
  564. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  565. {
  566. MidiInPort& inPort(it.getValue(kMidiInPortFallbackNC));
  567. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  568. if (std::strcmp(inPort.name, portName) != 0)
  569. continue;
  570. inPort.port->stop();
  571. delete inPort.port;
  572. fMidiIns.remove(it);
  573. return true;
  574. }
  575. break;
  576. case kExternalGraphConnectionMidiOutput: {
  577. const CarlaMutexLocker cml(fMidiOutMutex);
  578. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  579. {
  580. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  581. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  582. if (std::strcmp(outPort.name, portName) != 0)
  583. continue;
  584. outPort.port->stopBackgroundThread();
  585. delete outPort.port;
  586. fMidiOuts.remove(it);
  587. return true;
  588. }
  589. } break;
  590. }
  591. return false;
  592. }
  593. // -------------------------------------
  594. private:
  595. ScopedPointer<juce::AudioIODevice> fDevice;
  596. juce::AudioIODeviceType* const fDeviceType;
  597. struct RtMidiEvents {
  598. CarlaMutex mutex;
  599. RtLinkedList<RtMidiEvent>::Pool dataPool;
  600. RtLinkedList<RtMidiEvent> data;
  601. RtLinkedList<RtMidiEvent> dataPending;
  602. RtMidiEvents()
  603. : mutex(),
  604. dataPool(512, 512),
  605. data(dataPool),
  606. dataPending(dataPool) {}
  607. ~RtMidiEvents()
  608. {
  609. clear();
  610. }
  611. void append(const RtMidiEvent& event)
  612. {
  613. mutex.lock();
  614. dataPending.append(event);
  615. mutex.unlock();
  616. }
  617. void clear()
  618. {
  619. mutex.lock();
  620. data.clear();
  621. dataPending.clear();
  622. mutex.unlock();
  623. }
  624. void splice()
  625. {
  626. if (dataPending.count() > 0)
  627. dataPending.moveTo(data, true /* append */);
  628. }
  629. };
  630. LinkedList<MidiInPort> fMidiIns;
  631. RtMidiEvents fMidiInEvents;
  632. LinkedList<MidiOutPort> fMidiOuts;
  633. CarlaMutex fMidiOutMutex;
  634. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  635. };
  636. // -----------------------------------------
  637. CarlaEngine* CarlaEngine::newJuce(const AudioApi api)
  638. {
  639. initJuceDevicesIfNeeded();
  640. juce::String juceApi;
  641. switch (api)
  642. {
  643. case AUDIO_API_NULL:
  644. case AUDIO_API_OSS:
  645. case AUDIO_API_PULSEAUDIO:
  646. break;
  647. case AUDIO_API_JACK:
  648. juceApi = "JACK";
  649. break;
  650. case AUDIO_API_ALSA:
  651. juceApi = "ALSA";
  652. break;
  653. case AUDIO_API_COREAUDIO:
  654. juceApi = "CoreAudio";
  655. break;
  656. case AUDIO_API_ASIO:
  657. juceApi = "ASIO";
  658. break;
  659. case AUDIO_API_DIRECTSOUND:
  660. juceApi = "DirectSound";
  661. break;
  662. case AUDIO_API_WASAPI:
  663. juceApi = "Windows Audio";
  664. break;
  665. }
  666. if (juceApi.isEmpty())
  667. return nullptr;
  668. juce::AudioIODeviceType* deviceType = nullptr;
  669. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  670. {
  671. deviceType = gDeviceTypes[i];
  672. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  673. break;
  674. }
  675. if (deviceType == nullptr)
  676. return nullptr;
  677. deviceType->scanForDevices();
  678. return new CarlaEngineJuce(deviceType);
  679. }
  680. uint CarlaEngine::getJuceApiCount()
  681. {
  682. initJuceDevicesIfNeeded();
  683. return static_cast<uint>(gDeviceTypes.size());
  684. }
  685. const char* CarlaEngine::getJuceApiName(const uint uindex)
  686. {
  687. initJuceDevicesIfNeeded();
  688. const int index(static_cast<int>(uindex));
  689. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  690. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  691. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  692. return deviceType->getTypeName().toRawUTF8();
  693. }
  694. const char* const* CarlaEngine::getJuceApiDeviceNames(const uint uindex)
  695. {
  696. initJuceDevicesIfNeeded();
  697. const int index(static_cast<int>(uindex));
  698. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  699. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  700. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  701. deviceType->scanForDevices();
  702. juce::StringArray juceDeviceNames(deviceType->getDeviceNames());
  703. const int juceDeviceNameCount(juceDeviceNames.size());
  704. if (juceDeviceNameCount <= 0)
  705. return nullptr;
  706. CarlaStringList devNames;
  707. for (int i=0; i < juceDeviceNameCount; ++i)
  708. devNames.append(juceDeviceNames[i].toRawUTF8());
  709. gDeviceNames = devNames.toCharStringListPtr();
  710. return gDeviceNames;
  711. }
  712. const EngineDriverDeviceInfo* CarlaEngine::getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  713. {
  714. initJuceDevicesIfNeeded();
  715. const int index(static_cast<int>(uindex));
  716. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  717. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  718. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  719. deviceType->scanForDevices();
  720. ScopedPointer<juce::AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  721. if (device == nullptr)
  722. return nullptr;
  723. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  724. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  725. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  726. // reset
  727. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  728. // cleanup
  729. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  730. {
  731. delete[] devInfo.bufferSizes;
  732. devInfo.bufferSizes = nullptr;
  733. }
  734. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  735. {
  736. delete[] devInfo.sampleRates;
  737. devInfo.sampleRates = nullptr;
  738. }
  739. if (device->hasControlPanel())
  740. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  741. juce::Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  742. if (int bufferSizesCount = juceBufferSizes.size())
  743. {
  744. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  745. for (int i=0; i < bufferSizesCount; ++i)
  746. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  747. bufferSizes[bufferSizesCount] = 0;
  748. devInfo.bufferSizes = bufferSizes;
  749. }
  750. else
  751. {
  752. devInfo.bufferSizes = dummyBufferSizes;
  753. }
  754. juce::Array<double> juceSampleRates = device->getAvailableSampleRates();
  755. if (int sampleRatesCount = juceSampleRates.size())
  756. {
  757. double* const sampleRates(new double[sampleRatesCount+1]);
  758. for (int i=0; i < sampleRatesCount; ++i)
  759. sampleRates[i] = juceSampleRates[i];
  760. sampleRates[sampleRatesCount] = 0.0;
  761. devInfo.sampleRates = sampleRates;
  762. }
  763. else
  764. {
  765. devInfo.sampleRates = dummySampleRates;
  766. }
  767. return &devInfo;
  768. }
  769. // -----------------------------------------
  770. CARLA_BACKEND_END_NAMESPACE