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.

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