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.

CarlaEngineJuce.cpp 30KB

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