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.

985 lines
30KB

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