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.

1112 lines
34KB

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