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.

1104 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. PortNameToId portNameToId;
  366. portNameToId.setData(kExternalGraphGroupMidiIn, uint(i+1), midiIns[i].toRawUTF8(), "");
  367. extGraph.midiPorts.ins.append(portNameToId);
  368. }
  369. }
  370. // MIDI Out
  371. {
  372. juce::StringArray midiOuts(juce::MidiOutput::getDevices());
  373. for (int i=0, count=midiOuts.size(); i<count; ++i)
  374. {
  375. PortNameToId portNameToId;
  376. portNameToId.setData(kExternalGraphGroupMidiOut, uint(i+1), midiOuts[i].toRawUTF8(), "");
  377. extGraph.midiPorts.outs.append(portNameToId);
  378. }
  379. }
  380. // ---------------------------------------------------------------
  381. // now refresh
  382. if (sendHost || sendOSC)
  383. {
  384. juce::String deviceName(fDevice->getName());
  385. if (deviceName.isNotEmpty())
  386. deviceName = deviceName.dropLastCharacters(deviceName.fromFirstOccurrenceOf(", ", true, false).length());
  387. graph->refresh(sendHost, sendOSC, true, deviceName.toRawUTF8());
  388. }
  389. // ---------------------------------------------------------------
  390. // add midi connections
  391. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  392. {
  393. const MidiInPort& inPort(it.getValue(kMidiInPortFallback));
  394. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  395. const uint portId(extGraph.midiPorts.getPortId(true, inPort.name));
  396. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.ins.count());
  397. ConnectionToId connectionToId;
  398. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupMidiIn, portId, kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiIn);
  399. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  400. strBuf[STR_MAX-1] = '\0';
  401. callback(sendHost, sendOSC,
  402. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  403. connectionToId.id,
  404. 0, 0, 0, 0.0f,
  405. strBuf);
  406. extGraph.connections.list.append(connectionToId);
  407. }
  408. fMidiOutMutex.lock();
  409. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  410. {
  411. const MidiOutPort& outPort(it.getValue(kMidiOutPortFallback));
  412. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  413. const uint portId(extGraph.midiPorts.getPortId(false, outPort.name));
  414. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.outs.count());
  415. ConnectionToId connectionToId;
  416. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiOut, kExternalGraphGroupMidiOut, portId);
  417. std::snprintf(strBuf, STR_MAX-1, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  418. strBuf[STR_MAX-1] = '\0';
  419. callback(sendHost, sendOSC,
  420. ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED,
  421. connectionToId.id,
  422. 0, 0, 0, 0.0f,
  423. strBuf);
  424. extGraph.connections.list.append(connectionToId);
  425. }
  426. fMidiOutMutex.unlock();
  427. return true;
  428. }
  429. bool patchbayRefresh(const bool sendHost, const bool sendOSC, const bool external) override
  430. {
  431. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  432. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  433. return refreshExternalGraphPorts<RackGraph>(pData->graph.getRackGraph(), sendHost, sendOSC);
  434. if (sendHost)
  435. pData->graph.setUsingExternalHost(external);
  436. if (sendOSC)
  437. pData->graph.setUsingExternalOSC(external);
  438. if (external)
  439. return refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), sendHost, sendOSC);
  440. return CarlaEngine::patchbayRefresh(sendHost, sendOSC, false);
  441. }
  442. // -------------------------------------------------------------------
  443. protected:
  444. void audioDeviceIOCallback(const float** inputChannelData, int numInputChannels, float** outputChannelData,
  445. int numOutputChannels, int numSamples) override
  446. {
  447. CARLA_SAFE_ASSERT_RETURN(numSamples >= 0,);
  448. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  449. const PendingRtEventsRunner prt(this, nframes, true); // FIXME remove dspCalc after updating juce
  450. // assert juce buffers
  451. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0,);
  452. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0,);
  453. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr,);
  454. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize),);
  455. // initialize juce output
  456. for (int i=0; i < numOutputChannels; ++i)
  457. carla_zeroFloats(outputChannelData[i], nframes);
  458. // initialize events
  459. carla_zeroStructs(pData->events.in, kMaxEngineEventInternalCount);
  460. carla_zeroStructs(pData->events.out, kMaxEngineEventInternalCount);
  461. if (fMidiInEvents.mutex.tryLock())
  462. {
  463. uint32_t engineEventIndex = 0;
  464. fMidiInEvents.splice();
  465. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin2(); it.valid(); it.next())
  466. {
  467. const RtMidiEvent& midiEvent(it.getValue(kRtMidiEventFallback));
  468. CARLA_SAFE_ASSERT_CONTINUE(midiEvent.size > 0);
  469. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  470. if (midiEvent.time < pData->timeInfo.frame)
  471. {
  472. engineEvent.time = 0;
  473. }
  474. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  475. {
  476. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  477. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  478. }
  479. else
  480. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  481. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data, 0);
  482. if (engineEventIndex >= kMaxEngineEventInternalCount)
  483. break;
  484. }
  485. fMidiInEvents.data.clear();
  486. fMidiInEvents.mutex.unlock();
  487. }
  488. pData->graph.process(pData, inputChannelData, outputChannelData, nframes);
  489. fMidiOutMutex.lock();
  490. if (fMidiOuts.count() > 0)
  491. {
  492. uint8_t size = 0;
  493. uint8_t data[3] = { 0, 0, 0 };
  494. const uint8_t* dataPtr = data;
  495. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  496. {
  497. const EngineEvent& engineEvent(pData->events.out[i]);
  498. if (engineEvent.type == kEngineEventTypeNull)
  499. break;
  500. else if (engineEvent.type == kEngineEventTypeControl)
  501. {
  502. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  503. ctrlEvent.convertToMidiData(engineEvent.channel, data);
  504. dataPtr = data;
  505. }
  506. else if (engineEvent.type == kEngineEventTypeMidi)
  507. {
  508. const EngineMidiEvent& midiEvent(engineEvent.midi);
  509. size = midiEvent.size;
  510. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  511. dataPtr = midiEvent.dataExt;
  512. else
  513. dataPtr = midiEvent.data;
  514. }
  515. else
  516. {
  517. continue;
  518. }
  519. if (size > 0)
  520. {
  521. juce::MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  522. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  523. {
  524. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  525. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  526. outPort.port->sendMessageNow(message);
  527. }
  528. }
  529. }
  530. }
  531. fMidiOutMutex.unlock();
  532. }
  533. void audioDeviceAboutToStart(juce::AudioIODevice* /*device*/) override
  534. {
  535. }
  536. void audioDeviceStopped() override
  537. {
  538. }
  539. void audioDeviceError(const juce::String& errorMessage) override
  540. {
  541. callback(true, true, ENGINE_CALLBACK_ERROR, 0, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  542. }
  543. // -------------------------------------------------------------------
  544. void handleIncomingMidiMessage(juce::MidiInput* /*source*/, const juce::MidiMessage& message) override
  545. {
  546. const int messageSize(message.getRawDataSize());
  547. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  548. return;
  549. const uint8_t* const messageData(message.getRawData());
  550. RtMidiEvent midiEvent;
  551. midiEvent.time = 0; // TODO
  552. midiEvent.size = static_cast<uint8_t>(messageSize);
  553. int i=0;
  554. for (; i < messageSize; ++i)
  555. midiEvent.data[i] = messageData[i];
  556. for (; i < EngineMidiEvent::kDataSize; ++i)
  557. midiEvent.data[i] = 0;
  558. fMidiInEvents.append(midiEvent);
  559. }
  560. // -------------------------------------------------------------------
  561. bool connectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  562. {
  563. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  564. carla_stdout("CarlaEngineJuce::connectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  565. switch (connectionType)
  566. {
  567. case kExternalGraphConnectionAudioIn1:
  568. case kExternalGraphConnectionAudioIn2:
  569. case kExternalGraphConnectionAudioOut1:
  570. case kExternalGraphConnectionAudioOut2:
  571. return CarlaEngine::connectExternalGraphPort(connectionType, portId, portName);
  572. case kExternalGraphConnectionMidiInput: {
  573. juce::StringArray midiIns(juce::MidiInput::getDevices());
  574. if (! midiIns.contains(portName))
  575. return false;
  576. std::unique_ptr<juce::MidiInput> juceMidiIn(juce::MidiInput::openDevice(midiIns.indexOf(portName), this));
  577. juceMidiIn->start();
  578. MidiInPort midiPort;
  579. midiPort.port = juceMidiIn.release();
  580. std::strncpy(midiPort.name, portName, STR_MAX);
  581. midiPort.name[STR_MAX] = '\0';
  582. fMidiIns.append(midiPort);
  583. return true;
  584. } break;
  585. case kExternalGraphConnectionMidiOutput: {
  586. juce::StringArray midiOuts(juce::MidiOutput::getDevices());
  587. if (! midiOuts.contains(portName))
  588. return false;
  589. std::unique_ptr<juce::MidiOutput> juceMidiOut(juce::MidiOutput::openDevice(midiOuts.indexOf(portName)));
  590. juceMidiOut->startBackgroundThread();
  591. MidiOutPort midiPort;
  592. midiPort.port = juceMidiOut.release();
  593. std::strncpy(midiPort.name, portName, STR_MAX);
  594. midiPort.name[STR_MAX] = '\0';
  595. const CarlaMutexLocker cml(fMidiOutMutex);
  596. fMidiOuts.append(midiPort);
  597. return true;
  598. } break;
  599. }
  600. return false;
  601. }
  602. bool disconnectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  603. {
  604. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  605. carla_debug("CarlaEngineJuce::disconnectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  606. switch (connectionType)
  607. {
  608. case kExternalGraphConnectionAudioIn1:
  609. case kExternalGraphConnectionAudioIn2:
  610. case kExternalGraphConnectionAudioOut1:
  611. case kExternalGraphConnectionAudioOut2:
  612. return CarlaEngine::disconnectExternalGraphPort(connectionType, portId, portName);
  613. case kExternalGraphConnectionMidiInput:
  614. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin2(); it.valid(); it.next())
  615. {
  616. MidiInPort& inPort(it.getValue(kMidiInPortFallbackNC));
  617. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  618. if (std::strcmp(inPort.name, portName) != 0)
  619. continue;
  620. inPort.port->stop();
  621. delete inPort.port;
  622. fMidiIns.remove(it);
  623. return true;
  624. }
  625. break;
  626. case kExternalGraphConnectionMidiOutput: {
  627. const CarlaMutexLocker cml(fMidiOutMutex);
  628. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin2(); it.valid(); it.next())
  629. {
  630. MidiOutPort& outPort(it.getValue(kMidiOutPortFallbackNC));
  631. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  632. if (std::strcmp(outPort.name, portName) != 0)
  633. continue;
  634. outPort.port->stopBackgroundThread();
  635. delete outPort.port;
  636. fMidiOuts.remove(it);
  637. return true;
  638. }
  639. } break;
  640. }
  641. return false;
  642. }
  643. // -------------------------------------
  644. private:
  645. CarlaScopedPointer<juce::AudioIODevice> fDevice;
  646. juce::AudioIODeviceType* const fDeviceType;
  647. struct RtMidiEvents {
  648. CarlaMutex mutex;
  649. RtLinkedList<RtMidiEvent>::Pool dataPool;
  650. RtLinkedList<RtMidiEvent> data;
  651. RtLinkedList<RtMidiEvent> dataPending;
  652. RtMidiEvents()
  653. : mutex(),
  654. dataPool(512, 512),
  655. data(dataPool),
  656. dataPending(dataPool) {}
  657. ~RtMidiEvents()
  658. {
  659. clear();
  660. }
  661. void append(const RtMidiEvent& event)
  662. {
  663. mutex.lock();
  664. dataPending.append(event);
  665. mutex.unlock();
  666. }
  667. void clear()
  668. {
  669. mutex.lock();
  670. data.clear();
  671. dataPending.clear();
  672. mutex.unlock();
  673. }
  674. void splice()
  675. {
  676. if (dataPending.count() > 0)
  677. dataPending.moveTo(data, true /* append */);
  678. }
  679. };
  680. LinkedList<MidiInPort> fMidiIns;
  681. RtMidiEvents fMidiInEvents;
  682. LinkedList<MidiOutPort> fMidiOuts;
  683. CarlaMutex fMidiOutMutex;
  684. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  685. };
  686. // -----------------------------------------
  687. namespace EngineInit {
  688. CarlaEngine* newJuce(const AudioApi api)
  689. {
  690. initJuceDevicesIfNeeded();
  691. juce::String juceApi;
  692. switch (api)
  693. {
  694. case AUDIO_API_NULL:
  695. case AUDIO_API_OSS:
  696. case AUDIO_API_PULSEAUDIO:
  697. break;
  698. case AUDIO_API_JACK:
  699. juceApi = "JACK";
  700. break;
  701. case AUDIO_API_ALSA:
  702. juceApi = "ALSA";
  703. break;
  704. case AUDIO_API_COREAUDIO:
  705. juceApi = "CoreAudio";
  706. break;
  707. case AUDIO_API_ASIO:
  708. juceApi = "ASIO";
  709. break;
  710. case AUDIO_API_DIRECTSOUND:
  711. juceApi = "DirectSound";
  712. break;
  713. case AUDIO_API_WASAPI:
  714. juceApi = "Windows Audio";
  715. break;
  716. }
  717. if (juceApi.isEmpty())
  718. return nullptr;
  719. juce::AudioIODeviceType* deviceType = nullptr;
  720. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  721. {
  722. deviceType = gDeviceTypes[i];
  723. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  724. break;
  725. }
  726. if (deviceType == nullptr)
  727. return nullptr;
  728. deviceType->scanForDevices();
  729. return new CarlaEngineJuce(deviceType);
  730. }
  731. uint getJuceApiCount()
  732. {
  733. initJuceDevicesIfNeeded();
  734. return static_cast<uint>(gDeviceTypes.size());
  735. }
  736. const char* getJuceApiName(const uint uindex)
  737. {
  738. initJuceDevicesIfNeeded();
  739. const int index(static_cast<int>(uindex));
  740. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  741. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  742. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  743. return deviceType->getTypeName().toRawUTF8();
  744. }
  745. const char* const* getJuceApiDeviceNames(const uint uindex)
  746. {
  747. initJuceDevicesIfNeeded();
  748. const int index(static_cast<int>(uindex));
  749. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  750. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  751. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  752. deviceType->scanForDevices();
  753. juce::StringArray juceDeviceNames(deviceType->getDeviceNames());
  754. const int juceDeviceNameCount(juceDeviceNames.size());
  755. if (juceDeviceNameCount <= 0)
  756. return nullptr;
  757. CarlaStringList devNames;
  758. for (int i=0; i < juceDeviceNameCount; ++i)
  759. devNames.append(juceDeviceNames[i].toRawUTF8());
  760. gDeviceNames = devNames.toCharStringListPtr();
  761. return gDeviceNames;
  762. }
  763. const EngineDriverDeviceInfo* getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  764. {
  765. initJuceDevicesIfNeeded();
  766. const int index(static_cast<int>(uindex));
  767. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  768. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  769. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  770. deviceType->scanForDevices();
  771. CarlaScopedPointer<juce::AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  772. if (device == nullptr)
  773. return nullptr;
  774. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  775. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  776. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  777. // reset
  778. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  779. // cleanup
  780. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  781. {
  782. delete[] devInfo.bufferSizes;
  783. devInfo.bufferSizes = nullptr;
  784. }
  785. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  786. {
  787. delete[] devInfo.sampleRates;
  788. devInfo.sampleRates = nullptr;
  789. }
  790. if (device->hasControlPanel())
  791. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  792. juce::Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  793. if (int bufferSizesCount = juceBufferSizes.size())
  794. {
  795. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  796. for (int i=0; i < bufferSizesCount; ++i)
  797. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  798. bufferSizes[bufferSizesCount] = 0;
  799. devInfo.bufferSizes = bufferSizes;
  800. }
  801. else
  802. {
  803. devInfo.bufferSizes = dummyBufferSizes;
  804. }
  805. juce::Array<double> juceSampleRates = device->getAvailableSampleRates();
  806. if (int sampleRatesCount = juceSampleRates.size())
  807. {
  808. double* const sampleRates(new double[sampleRatesCount+1]);
  809. for (int i=0; i < sampleRatesCount; ++i)
  810. sampleRates[i] = juceSampleRates[i];
  811. sampleRates[sampleRatesCount] = 0.0;
  812. devInfo.sampleRates = sampleRates;
  813. }
  814. else
  815. {
  816. devInfo.sampleRates = dummySampleRates;
  817. }
  818. return &devInfo;
  819. }
  820. bool showJuceDeviceControlPanel(const uint uindex, const char* const deviceName)
  821. {
  822. const int index(static_cast<int>(uindex));
  823. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), false);
  824. juce::AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  825. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, false);
  826. deviceType->scanForDevices();
  827. CarlaScopedPointer<juce::AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  828. CARLA_SAFE_ASSERT_RETURN(device != nullptr, false);
  829. return device->showControlPanel();
  830. }
  831. }
  832. // -----------------------------------------
  833. CARLA_BACKEND_END_NAMESPACE