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.

941 lines
29KB

  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2014 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 "juce_audio_devices/juce_audio_devices.h"
  23. using namespace juce;
  24. CARLA_BACKEND_START_NAMESPACE
  25. // -------------------------------------------------------------------------------------------------------------------
  26. struct MidiInPort {
  27. MidiInput* port;
  28. char name[STR_MAX+1];
  29. };
  30. struct MidiOutPort {
  31. 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 OwnedArray<AudioIODeviceType> gDeviceTypes;
  50. struct JuceCleanup : public DeletedAtShutdown {
  51. JuceCleanup() noexcept {}
  52. ~JuceCleanup()
  53. {
  54. gDeviceTypes.clear(true);
  55. }
  56. };
  57. // -------------------------------------------------------------------------------------------------------------------
  58. // Cleanup
  59. static void initJuceDevicesIfNeeded()
  60. {
  61. static 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 AudioIODeviceCallback,
  81. public MidiInputCallback
  82. {
  83. public:
  84. CarlaEngineJuce(AudioIODeviceType* const devType)
  85. : CarlaEngine(),
  86. 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. 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. 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. StringArray inputNames(fDevice->getInputChannelNames());
  136. 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. BigInteger inputChannels;
  143. inputChannels.setRange(0, inputNames.size(), true);
  144. BigInteger outputChannels;
  145. outputChannels.setRange(0, outputNames.size(), true);
  146. 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();
  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. 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. 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. StringArray midiIns(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. StringArray midiOuts(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. 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, int numOutputChannels, int numSamples) override
  336. {
  337. const PendingRtEventsRunner prt(this);
  338. // assert juce buffers
  339. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0,);
  340. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0,);
  341. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr,);
  342. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize),);
  343. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  344. // initialize juce output
  345. for (int i=0; i < numOutputChannels; ++i)
  346. FloatVectorOperations::clear(outputChannelData[i], numSamples);
  347. // initialize events
  348. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  349. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  350. if (fMidiInEvents.mutex.tryLock())
  351. {
  352. uint32_t engineEventIndex = 0;
  353. fMidiInEvents.splice();
  354. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin2(); it.valid(); it.next())
  355. {
  356. const RtMidiEvent& midiEvent(it.getValue(kRtMidiEventFallback));
  357. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.size > 0);
  358. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  359. if (midiEvent.time < pData->timeInfo.frame)
  360. {
  361. engineEvent.time = 0;
  362. }
  363. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  364. {
  365. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  366. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  367. }
  368. else
  369. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  370. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data, 0);
  371. if (engineEventIndex >= kMaxEngineEventInternalCount)
  372. break;
  373. }
  374. fMidiInEvents.data.clear();
  375. fMidiInEvents.mutex.unlock();
  376. }
  377. pData->graph.process(pData, inputChannelData, outputChannelData, nframes);
  378. fMidiOutMutex.lock();
  379. if (fMidiOuts.count() > 0)
  380. {
  381. uint8_t size = 0;
  382. uint8_t data[3] = { 0, 0, 0 };
  383. const uint8_t* dataPtr = data;
  384. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  385. {
  386. const EngineEvent& engineEvent(pData->events.out[i]);
  387. if (engineEvent.type == kEngineEventTypeNull)
  388. break;
  389. else if (engineEvent.type == kEngineEventTypeControl)
  390. {
  391. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  392. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  393. dataPtr = data;
  394. }
  395. else if (engineEvent.type == kEngineEventTypeMidi)
  396. {
  397. const EngineMidiEvent& midiEvent(engineEvent.midi);
  398. size = midiEvent.size;
  399. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  400. dataPtr = midiEvent.dataExt;
  401. else
  402. dataPtr = midiEvent.data;
  403. }
  404. else
  405. {
  406. continue;
  407. }
  408. if (size > 0)
  409. {
  410. MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  411. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  412. {
  413. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  414. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  415. outPort.port->sendMessageNow(message);
  416. }
  417. }
  418. }
  419. }
  420. fMidiOutMutex.unlock();
  421. }
  422. void audioDeviceAboutToStart(AudioIODevice* /*device*/) override
  423. {
  424. }
  425. void audioDeviceStopped() override
  426. {
  427. }
  428. void audioDeviceError(const String& errorMessage) override
  429. {
  430. callback(ENGINE_CALLBACK_ERROR, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  431. }
  432. // -------------------------------------------------------------------
  433. void handleIncomingMidiMessage(MidiInput* /*source*/, const MidiMessage& message) override
  434. {
  435. const int messageSize(message.getRawDataSize());
  436. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  437. return;
  438. const uint8_t* const messageData(message.getRawData());
  439. RtMidiEvent midiEvent;
  440. midiEvent.time = 0; // TODO
  441. midiEvent.size = static_cast<uint8_t>(messageSize);
  442. int i=0;
  443. for (; i < messageSize; ++i)
  444. midiEvent.data[i] = messageData[i];
  445. for (; i < EngineMidiEvent::kDataSize; ++i)
  446. midiEvent.data[i] = 0;
  447. fMidiInEvents.append(midiEvent);
  448. }
  449. // -------------------------------------------------------------------
  450. bool connectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  451. {
  452. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  453. carla_stdout("CarlaEngineJuce::connectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  454. switch (connectionType)
  455. {
  456. case kExternalGraphConnectionAudioIn1:
  457. case kExternalGraphConnectionAudioIn2:
  458. case kExternalGraphConnectionAudioOut1:
  459. case kExternalGraphConnectionAudioOut2:
  460. return CarlaEngine::connectExternalGraphPort(connectionType, portId, portName);
  461. case kExternalGraphConnectionMidiInput: {
  462. StringArray midiIns(MidiInput::getDevices());
  463. if (! midiIns.contains(portName))
  464. return false;
  465. MidiInput* const juceMidiIn(MidiInput::openDevice(midiIns.indexOf(portName), this));
  466. juceMidiIn->start();
  467. MidiInPort midiPort;
  468. midiPort.port = juceMidiIn;
  469. std::strncpy(midiPort.name, portName, STR_MAX);
  470. midiPort.name[STR_MAX] = '\0';
  471. fMidiIns.append(midiPort);
  472. return true;
  473. } break;
  474. case kExternalGraphConnectionMidiOutput: {
  475. StringArray midiOuts(MidiOutput::getDevices());
  476. if (! midiOuts.contains(portName))
  477. return false;
  478. MidiOutput* const juceMidiOut(MidiOutput::openDevice(midiOuts.indexOf(portName)));
  479. juceMidiOut->startBackgroundThread();
  480. MidiOutPort midiPort;
  481. midiPort.port = juceMidiOut;
  482. std::strncpy(midiPort.name, portName, STR_MAX);
  483. midiPort.name[STR_MAX] = '\0';
  484. const CarlaMutexLocker cml(fMidiOutMutex);
  485. fMidiOuts.append(midiPort);
  486. return true;
  487. } break;
  488. }
  489. return false;
  490. }
  491. bool disconnectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  492. {
  493. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  494. carla_debug("CarlaEngineJuce::disconnectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  495. switch (connectionType)
  496. {
  497. case kExternalGraphConnectionAudioIn1:
  498. case kExternalGraphConnectionAudioIn2:
  499. case kExternalGraphConnectionAudioOut1:
  500. case kExternalGraphConnectionAudioOut2:
  501. return CarlaEngine::disconnectExternalGraphPort(connectionType, portId, portName);
  502. case kExternalGraphConnectionMidiInput:
  503. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  504. {
  505. MidiInPort& inPort(it.getValue(kMidiInPortFallbackNC));
  506. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  507. if (std::strcmp(inPort.name, portName) != 0)
  508. continue;
  509. inPort.port->stop();
  510. delete inPort.port;
  511. fMidiIns.remove(it);
  512. return true;
  513. }
  514. break;
  515. case kExternalGraphConnectionMidiOutput: {
  516. const CarlaMutexLocker cml(fMidiOutMutex);
  517. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  518. {
  519. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  520. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  521. if (std::strcmp(outPort.name, portName) != 0)
  522. continue;
  523. outPort.port->stopBackgroundThread();
  524. delete outPort.port;
  525. fMidiOuts.remove(it);
  526. return true;
  527. }
  528. } break;
  529. }
  530. return false;
  531. }
  532. // -------------------------------------
  533. private:
  534. ScopedPointer<AudioIODevice> fDevice;
  535. AudioIODeviceType* const fDeviceType;
  536. struct RtMidiEvents {
  537. CarlaMutex mutex;
  538. RtLinkedList<RtMidiEvent>::Pool dataPool;
  539. RtLinkedList<RtMidiEvent> data;
  540. RtLinkedList<RtMidiEvent> dataPending;
  541. RtMidiEvents()
  542. : mutex(),
  543. dataPool(512, 512),
  544. data(dataPool),
  545. dataPending(dataPool) {}
  546. ~RtMidiEvents()
  547. {
  548. clear();
  549. }
  550. void append(const RtMidiEvent& event)
  551. {
  552. mutex.lock();
  553. dataPending.append(event);
  554. mutex.unlock();
  555. }
  556. void clear()
  557. {
  558. mutex.lock();
  559. data.clear();
  560. dataPending.clear();
  561. mutex.unlock();
  562. }
  563. void splice()
  564. {
  565. if (dataPending.count() > 0)
  566. dataPending.moveTo(data, true /* append */);
  567. }
  568. };
  569. LinkedList<MidiInPort> fMidiIns;
  570. RtMidiEvents fMidiInEvents;
  571. LinkedList<MidiOutPort> fMidiOuts;
  572. CarlaMutex fMidiOutMutex;
  573. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  574. };
  575. // -----------------------------------------
  576. CarlaEngine* CarlaEngine::newJuce(const AudioApi api)
  577. {
  578. initJuceDevicesIfNeeded();
  579. String juceApi;
  580. switch (api)
  581. {
  582. case AUDIO_API_NULL:
  583. case AUDIO_API_OSS:
  584. case AUDIO_API_PULSE:
  585. break;
  586. case AUDIO_API_JACK:
  587. juceApi = "JACK";
  588. break;
  589. case AUDIO_API_ALSA:
  590. juceApi = "ALSA";
  591. break;
  592. case AUDIO_API_CORE:
  593. juceApi = "CoreAudio";
  594. break;
  595. case AUDIO_API_ASIO:
  596. juceApi = "ASIO";
  597. break;
  598. case AUDIO_API_DS:
  599. juceApi = "DirectSound";
  600. break;
  601. }
  602. if (juceApi.isEmpty())
  603. return nullptr;
  604. AudioIODeviceType* deviceType = nullptr;
  605. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  606. {
  607. deviceType = gDeviceTypes[i];
  608. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  609. break;
  610. }
  611. if (deviceType == nullptr)
  612. return nullptr;
  613. deviceType->scanForDevices();
  614. return new CarlaEngineJuce(deviceType);
  615. }
  616. uint CarlaEngine::getJuceApiCount()
  617. {
  618. initJuceDevicesIfNeeded();
  619. return static_cast<uint>(gDeviceTypes.size());
  620. }
  621. const char* CarlaEngine::getJuceApiName(const uint uindex)
  622. {
  623. initJuceDevicesIfNeeded();
  624. const int index(static_cast<int>(uindex));
  625. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  626. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  627. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  628. return deviceType->getTypeName().toRawUTF8();
  629. }
  630. const char* const* CarlaEngine::getJuceApiDeviceNames(const uint uindex)
  631. {
  632. initJuceDevicesIfNeeded();
  633. const int index(static_cast<int>(uindex));
  634. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  635. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  636. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  637. deviceType->scanForDevices();
  638. StringArray juceDeviceNames(deviceType->getDeviceNames());
  639. const int juceDeviceNameCount(juceDeviceNames.size());
  640. if (juceDeviceNameCount <= 0)
  641. return nullptr;
  642. CarlaStringList devNames;
  643. for (int i=0; i < juceDeviceNameCount; ++i)
  644. devNames.append(juceDeviceNames[i].toRawUTF8());
  645. gDeviceNames = devNames.toCharStringListPtr();
  646. return gDeviceNames;
  647. }
  648. const EngineDriverDeviceInfo* CarlaEngine::getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  649. {
  650. initJuceDevicesIfNeeded();
  651. const int index(static_cast<int>(uindex));
  652. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  653. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  654. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  655. deviceType->scanForDevices();
  656. ScopedPointer<AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  657. if (device == nullptr)
  658. return nullptr;
  659. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  660. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  661. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  662. // reset
  663. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  664. // cleanup
  665. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  666. {
  667. delete[] devInfo.bufferSizes;
  668. devInfo.bufferSizes = nullptr;
  669. }
  670. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  671. {
  672. delete[] devInfo.sampleRates;
  673. devInfo.sampleRates = nullptr;
  674. }
  675. if (device->hasControlPanel())
  676. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  677. Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  678. if (int bufferSizesCount = juceBufferSizes.size())
  679. {
  680. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  681. for (int i=0; i < bufferSizesCount; ++i)
  682. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  683. bufferSizes[bufferSizesCount] = 0;
  684. devInfo.bufferSizes = bufferSizes;
  685. }
  686. else
  687. {
  688. devInfo.bufferSizes = dummyBufferSizes;
  689. }
  690. Array<double> juceSampleRates = device->getAvailableSampleRates();
  691. if (int sampleRatesCount = juceSampleRates.size())
  692. {
  693. double* const sampleRates(new double[sampleRatesCount+1]);
  694. for (int i=0; i < sampleRatesCount; ++i)
  695. sampleRates[i] = juceSampleRates[i];
  696. sampleRates[sampleRatesCount] = 0.0;
  697. devInfo.sampleRates = sampleRates;
  698. }
  699. else
  700. {
  701. devInfo.sampleRates = dummySampleRates;
  702. }
  703. return &devInfo;
  704. }
  705. // -----------------------------------------
  706. CARLA_BACKEND_END_NAMESPACE