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.

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