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.

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