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.

1040 lines
32KB

  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. bool showDeviceControlPanel() const noexcept override
  279. {
  280. try {
  281. return fDevice->showControlPanel();
  282. } CARLA_SAFE_EXCEPTION_RETURN("showDeviceControlPanel", false);
  283. }
  284. // -------------------------------------------------------------------
  285. // Patchbay
  286. template<class Graph>
  287. bool refreshExternalGraphPorts(Graph* const graph, const bool sendHost, const bool sendOSC)
  288. {
  289. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  290. char strBuf[STR_MAX];
  291. ExternalGraph& extGraph(graph->extGraph);
  292. // ---------------------------------------------------------------
  293. // clear last ports
  294. extGraph.clear();
  295. // ---------------------------------------------------------------
  296. // fill in new ones
  297. // Audio In
  298. {
  299. juce::StringArray inputNames(fDevice->getInputChannelNames());
  300. for (int i=0, count=inputNames.size(); i<count; ++i)
  301. {
  302. PortNameToId portNameToId;
  303. portNameToId.setData(kExternalGraphGroupAudioIn, uint(i+1), inputNames[i].toRawUTF8(), "");
  304. extGraph.audioPorts.ins.append(portNameToId);
  305. }
  306. }
  307. // Audio Out
  308. {
  309. juce::StringArray outputNames(fDevice->getOutputChannelNames());
  310. for (int i=0, count=outputNames.size(); i<count; ++i)
  311. {
  312. PortNameToId portNameToId;
  313. portNameToId.setData(kExternalGraphGroupAudioOut, uint(i+1), outputNames[i].toRawUTF8(), "");
  314. }
  315. }
  316. // MIDI In
  317. {
  318. juce::StringArray midiIns(juce::MidiInput::getDevices());
  319. for (int i=0, count=midiIns.size(); i<count; ++i)
  320. {
  321. PortNameToId portNameToId;
  322. portNameToId.setData(kExternalGraphGroupMidiIn, uint(i+1), midiIns[i].toRawUTF8(), "");
  323. extGraph.midiPorts.ins.append(portNameToId);
  324. }
  325. }
  326. // MIDI Out
  327. {
  328. juce::StringArray midiOuts(juce::MidiOutput::getDevices());
  329. for (int i=0, count=midiOuts.size(); i<count; ++i)
  330. {
  331. PortNameToId portNameToId;
  332. portNameToId.setData(kExternalGraphGroupMidiOut, uint(i+1), midiOuts[i].toRawUTF8(), "");
  333. extGraph.midiPorts.outs.append(portNameToId);
  334. }
  335. }
  336. // ---------------------------------------------------------------
  337. // now refresh
  338. if (sendHost || sendOSC)
  339. {
  340. juce::String deviceName(fDevice->getName());
  341. if (deviceName.isNotEmpty())
  342. deviceName = deviceName.dropLastCharacters(deviceName.fromFirstOccurrenceOf(", ", true, false).length());
  343. graph->refresh(sendHost, sendOSC, true, deviceName.toRawUTF8());
  344. }
  345. // ---------------------------------------------------------------
  346. // add midi connections
  347. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  348. {
  349. const MidiInPort& inPort(it.getValue(kMidiInPortFallback));
  350. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  351. const uint portId(extGraph.midiPorts.getPortId(true, inPort.name));
  352. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.ins.count());
  353. ConnectionToId connectionToId;
  354. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupMidiIn, portId, kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiIn);
  355. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  356. strBuf[STR_MAX-1] = '\0';
  357. callback(sendHost, sendOSC,
  358. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  359. connectionToId.id,
  360. 0, 0, 0, 0.0f,
  361. strBuf);
  362. extGraph.connections.list.append(connectionToId);
  363. }
  364. fMidiOutMutex.lock();
  365. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  366. {
  367. const MidiOutPort& outPort(it.getValue(kMidiOutPortFallback));
  368. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  369. const uint portId(extGraph.midiPorts.getPortId(false, outPort.name));
  370. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.outs.count());
  371. ConnectionToId connectionToId;
  372. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiOut, kExternalGraphGroupMidiOut, portId);
  373. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  374. strBuf[STR_MAX-1] = '\0';
  375. callback(sendHost, sendOSC,
  376. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  377. connectionToId.id,
  378. 0, 0, 0, 0.0f,
  379. strBuf);
  380. extGraph.connections.list.append(connectionToId);
  381. }
  382. fMidiOutMutex.unlock();
  383. return true;
  384. }
  385. bool patchbayRefresh(const bool sendHost, const bool sendOSC, const bool external) override
  386. {
  387. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  388. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  389. return refreshExternalGraphPorts<RackGraph>(pData->graph.getRackGraph(), sendHost, sendOSC);
  390. if (sendHost)
  391. pData->graph.setUsingExternalHost(external);
  392. if (sendOSC)
  393. pData->graph.setUsingExternalOSC(external);
  394. if (external)
  395. return refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), sendHost, sendOSC);
  396. return CarlaEngine::patchbayRefresh(sendHost, sendOSC, false);
  397. }
  398. // -------------------------------------------------------------------
  399. protected:
  400. void audioDeviceIOCallback(const float** inputChannelData, int numInputChannels, float** outputChannelData,
  401. int numOutputChannels, int numSamples) override
  402. {
  403. CARLA_SAFE_ASSERT_RETURN(numSamples >= 0,);
  404. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  405. const PendingRtEventsRunner prt(this, nframes, true); // FIXME remove dspCalc after updating juce
  406. // assert juce buffers
  407. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0,);
  408. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0,);
  409. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr,);
  410. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize),);
  411. // initialize juce output
  412. for (int i=0; i < numOutputChannels; ++i)
  413. carla_zeroFloats(outputChannelData[i], nframes);
  414. // initialize events
  415. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  416. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  417. if (fMidiInEvents.mutex.tryLock())
  418. {
  419. uint32_t engineEventIndex = 0;
  420. fMidiInEvents.splice();
  421. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin2(); it.valid(); it.next())
  422. {
  423. const RtMidiEvent& midiEvent(it.getValue(kRtMidiEventFallback));
  424. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.size > 0);
  425. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  426. if (midiEvent.time < pData->timeInfo.frame)
  427. {
  428. engineEvent.time = 0;
  429. }
  430. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  431. {
  432. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  433. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  434. }
  435. else
  436. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  437. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data, 0);
  438. if (engineEventIndex >= kMaxEngineEventInternalCount)
  439. break;
  440. }
  441. fMidiInEvents.data.clear();
  442. fMidiInEvents.mutex.unlock();
  443. }
  444. pData->graph.process(pData, inputChannelData, outputChannelData, nframes);
  445. fMidiOutMutex.lock();
  446. if (fMidiOuts.count() > 0)
  447. {
  448. uint8_t size = 0;
  449. uint8_t data[3] = { 0, 0, 0 };
  450. const uint8_t* dataPtr = data;
  451. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  452. {
  453. const EngineEvent& engineEvent(pData->events.out[i]);
  454. if (engineEvent.type == kEngineEventTypeNull)
  455. break;
  456. else if (engineEvent.type == kEngineEventTypeControl)
  457. {
  458. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  459. ctrlEvent.convertToMidiData(engineEvent.channel, data);
  460. dataPtr = data;
  461. }
  462. else if (engineEvent.type == kEngineEventTypeMidi)
  463. {
  464. const EngineMidiEvent& midiEvent(engineEvent.midi);
  465. size = midiEvent.size;
  466. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  467. dataPtr = midiEvent.dataExt;
  468. else
  469. dataPtr = midiEvent.data;
  470. }
  471. else
  472. {
  473. continue;
  474. }
  475. if (size > 0)
  476. {
  477. juce::MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  478. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  479. {
  480. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  481. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  482. outPort.port->sendMessageNow(message);
  483. }
  484. }
  485. }
  486. }
  487. fMidiOutMutex.unlock();
  488. }
  489. void audioDeviceAboutToStart(juce::AudioIODevice* /*device*/) override
  490. {
  491. }
  492. void audioDeviceStopped() override
  493. {
  494. }
  495. void audioDeviceError(const juce::String& errorMessage) override
  496. {
  497. callback(true, true, ENGINE_CALLBACK_ERROR, 0, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  498. }
  499. // -------------------------------------------------------------------
  500. void handleIncomingMidiMessage(juce::MidiInput* /*source*/, const juce::MidiMessage& message) override
  501. {
  502. const int messageSize(message.getRawDataSize());
  503. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  504. return;
  505. const uint8_t* const messageData(message.getRawData());
  506. RtMidiEvent midiEvent;
  507. midiEvent.time = 0; // TODO
  508. midiEvent.size = static_cast<uint8_t>(messageSize);
  509. int i=0;
  510. for (; i < messageSize; ++i)
  511. midiEvent.data[i] = messageData[i];
  512. for (; i < EngineMidiEvent::kDataSize; ++i)
  513. midiEvent.data[i] = 0;
  514. fMidiInEvents.append(midiEvent);
  515. }
  516. // -------------------------------------------------------------------
  517. bool connectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  518. {
  519. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  520. carla_stdout("CarlaEngineJuce::connectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  521. switch (connectionType)
  522. {
  523. case kExternalGraphConnectionAudioIn1:
  524. case kExternalGraphConnectionAudioIn2:
  525. case kExternalGraphConnectionAudioOut1:
  526. case kExternalGraphConnectionAudioOut2:
  527. return CarlaEngine::connectExternalGraphPort(connectionType, portId, portName);
  528. case kExternalGraphConnectionMidiInput: {
  529. juce::StringArray midiIns(juce::MidiInput::getDevices());
  530. if (! midiIns.contains(portName))
  531. return false;
  532. juce::MidiInput* const juceMidiIn(juce::MidiInput::openDevice(midiIns.indexOf(portName), this));
  533. juceMidiIn->start();
  534. MidiInPort midiPort;
  535. midiPort.port = juceMidiIn;
  536. std::strncpy(midiPort.name, portName, STR_MAX);
  537. midiPort.name[STR_MAX] = '\0';
  538. fMidiIns.append(midiPort);
  539. return true;
  540. } break;
  541. case kExternalGraphConnectionMidiOutput: {
  542. juce::StringArray midiOuts(juce::MidiOutput::getDevices());
  543. if (! midiOuts.contains(portName))
  544. return false;
  545. juce::MidiOutput* const juceMidiOut(juce::MidiOutput::openDevice(midiOuts.indexOf(portName)));
  546. juceMidiOut->startBackgroundThread();
  547. MidiOutPort midiPort;
  548. midiPort.port = juceMidiOut;
  549. std::strncpy(midiPort.name, portName, STR_MAX);
  550. midiPort.name[STR_MAX] = '\0';
  551. const CarlaMutexLocker cml(fMidiOutMutex);
  552. fMidiOuts.append(midiPort);
  553. return true;
  554. } break;
  555. }
  556. return false;
  557. }
  558. bool disconnectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  559. {
  560. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  561. carla_debug("CarlaEngineJuce::disconnectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  562. switch (connectionType)
  563. {
  564. case kExternalGraphConnectionAudioIn1:
  565. case kExternalGraphConnectionAudioIn2:
  566. case kExternalGraphConnectionAudioOut1:
  567. case kExternalGraphConnectionAudioOut2:
  568. return CarlaEngine::disconnectExternalGraphPort(connectionType, portId, portName);
  569. case kExternalGraphConnectionMidiInput:
  570. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  571. {
  572. MidiInPort& inPort(it.getValue(kMidiInPortFallbackNC));
  573. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  574. if (std::strcmp(inPort.name, portName) != 0)
  575. continue;
  576. inPort.port->stop();
  577. delete inPort.port;
  578. fMidiIns.remove(it);
  579. return true;
  580. }
  581. break;
  582. case kExternalGraphConnectionMidiOutput: {
  583. const CarlaMutexLocker cml(fMidiOutMutex);
  584. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  585. {
  586. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  587. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  588. if (std::strcmp(outPort.name, portName) != 0)
  589. continue;
  590. outPort.port->stopBackgroundThread();
  591. delete outPort.port;
  592. fMidiOuts.remove(it);
  593. return true;
  594. }
  595. } break;
  596. }
  597. return false;
  598. }
  599. // -------------------------------------
  600. private:
  601. ScopedPointer<juce::AudioIODevice> fDevice;
  602. juce::AudioIODeviceType* const fDeviceType;
  603. struct RtMidiEvents {
  604. CarlaMutex mutex;
  605. RtLinkedList<RtMidiEvent>::Pool dataPool;
  606. RtLinkedList<RtMidiEvent> data;
  607. RtLinkedList<RtMidiEvent> dataPending;
  608. RtMidiEvents()
  609. : mutex(),
  610. dataPool(512, 512),
  611. data(dataPool),
  612. dataPending(dataPool) {}
  613. ~RtMidiEvents()
  614. {
  615. clear();
  616. }
  617. void append(const RtMidiEvent& event)
  618. {
  619. mutex.lock();
  620. dataPending.append(event);
  621. mutex.unlock();
  622. }
  623. void clear()
  624. {
  625. mutex.lock();
  626. data.clear();
  627. dataPending.clear();
  628. mutex.unlock();
  629. }
  630. void splice()
  631. {
  632. if (dataPending.count() > 0)
  633. dataPending.moveTo(data, true /* append */);
  634. }
  635. };
  636. LinkedList<MidiInPort> fMidiIns;
  637. RtMidiEvents fMidiInEvents;
  638. LinkedList<MidiOutPort> fMidiOuts;
  639. CarlaMutex fMidiOutMutex;
  640. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  641. };
  642. // -----------------------------------------
  643. CarlaEngine* CarlaEngine::newJuce(const AudioApi api)
  644. {
  645. initJuceDevicesIfNeeded();
  646. juce::String juceApi;
  647. switch (api)
  648. {
  649. case AUDIO_API_NULL:
  650. case AUDIO_API_OSS:
  651. case AUDIO_API_PULSEAUDIO:
  652. break;
  653. case AUDIO_API_JACK:
  654. juceApi = "JACK";
  655. break;
  656. case AUDIO_API_ALSA:
  657. juceApi = "ALSA";
  658. break;
  659. case AUDIO_API_COREAUDIO:
  660. juceApi = "CoreAudio";
  661. break;
  662. case AUDIO_API_ASIO:
  663. juceApi = "ASIO";
  664. break;
  665. case AUDIO_API_DIRECTSOUND:
  666. juceApi = "DirectSound";
  667. break;
  668. case AUDIO_API_WASAPI:
  669. juceApi = "Windows Audio";
  670. break;
  671. }
  672. if (juceApi.isEmpty())
  673. return nullptr;
  674. juce::AudioIODeviceType* deviceType = nullptr;
  675. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  676. {
  677. deviceType = gDeviceTypes[i];
  678. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  679. break;
  680. }
  681. if (deviceType == nullptr)
  682. return nullptr;
  683. deviceType->scanForDevices();
  684. return new CarlaEngineJuce(deviceType);
  685. }
  686. uint CarlaEngine::getJuceApiCount()
  687. {
  688. initJuceDevicesIfNeeded();
  689. return static_cast<uint>(gDeviceTypes.size());
  690. }
  691. const char* CarlaEngine::getJuceApiName(const uint uindex)
  692. {
  693. initJuceDevicesIfNeeded();
  694. const int index(static_cast<int>(uindex));
  695. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  696. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  697. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  698. return deviceType->getTypeName().toRawUTF8();
  699. }
  700. const char* const* CarlaEngine::getJuceApiDeviceNames(const uint uindex)
  701. {
  702. initJuceDevicesIfNeeded();
  703. const int index(static_cast<int>(uindex));
  704. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  705. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  706. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  707. deviceType->scanForDevices();
  708. juce::StringArray juceDeviceNames(deviceType->getDeviceNames());
  709. const int juceDeviceNameCount(juceDeviceNames.size());
  710. if (juceDeviceNameCount <= 0)
  711. return nullptr;
  712. CarlaStringList devNames;
  713. for (int i=0; i < juceDeviceNameCount; ++i)
  714. devNames.append(juceDeviceNames[i].toRawUTF8());
  715. gDeviceNames = devNames.toCharStringListPtr();
  716. return gDeviceNames;
  717. }
  718. const EngineDriverDeviceInfo* CarlaEngine::getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  719. {
  720. initJuceDevicesIfNeeded();
  721. const int index(static_cast<int>(uindex));
  722. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  723. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  724. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  725. deviceType->scanForDevices();
  726. ScopedPointer<juce::AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  727. if (device == nullptr)
  728. return nullptr;
  729. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  730. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  731. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  732. // reset
  733. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  734. // cleanup
  735. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  736. {
  737. delete[] devInfo.bufferSizes;
  738. devInfo.bufferSizes = nullptr;
  739. }
  740. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  741. {
  742. delete[] devInfo.sampleRates;
  743. devInfo.sampleRates = nullptr;
  744. }
  745. if (device->hasControlPanel())
  746. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  747. juce::Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  748. if (int bufferSizesCount = juceBufferSizes.size())
  749. {
  750. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  751. for (int i=0; i < bufferSizesCount; ++i)
  752. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  753. bufferSizes[bufferSizesCount] = 0;
  754. devInfo.bufferSizes = bufferSizes;
  755. }
  756. else
  757. {
  758. devInfo.bufferSizes = dummyBufferSizes;
  759. }
  760. juce::Array<double> juceSampleRates = device->getAvailableSampleRates();
  761. if (int sampleRatesCount = juceSampleRates.size())
  762. {
  763. double* const sampleRates(new double[sampleRatesCount+1]);
  764. for (int i=0; i < sampleRatesCount; ++i)
  765. sampleRates[i] = juceSampleRates[i];
  766. sampleRates[sampleRatesCount] = 0.0;
  767. devInfo.sampleRates = sampleRates;
  768. }
  769. else
  770. {
  771. devInfo.sampleRates = dummySampleRates;
  772. }
  773. return &devInfo;
  774. }
  775. bool CarlaEngine::showJuceDeviceControlPanel(const uint uindex, const char* const deviceName)
  776. {
  777. const int index(static_cast<int>(uindex));
  778. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), false);
  779. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  780. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, false);
  781. deviceType->scanForDevices();
  782. ScopedPointer<juce::AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  783. CARLA_SAFE_ASSERT_RETURN(device != nullptr, false);
  784. return device->showControlPanel();
  785. }
  786. // -----------------------------------------
  787. CARLA_BACKEND_END_NAMESPACE