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.

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