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.

942 lines
29KB

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