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 28KB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*
  2. * Carla Plugin Host
  3. * Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of
  8. * the License, or any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * For a full copy of the GNU General Public License see the GPL.txt file
  16. */
  17. #include "CarlaEngineGraph.hpp"
  18. #include "CarlaEngineInternal.hpp"
  19. #include "CarlaBackendUtils.hpp"
  20. #include "CarlaStringList.hpp"
  21. #include "RtLinkedList.hpp"
  22. #include "juce_audio_devices.h"
  23. using namespace juce;
  24. CARLA_BACKEND_START_NAMESPACE
  25. // -------------------------------------------------------------------------------------------------------------------
  26. // Global static data
  27. static CharStringListPtr gDeviceNames;
  28. static OwnedArray<AudioIODeviceType> gDeviceTypes;
  29. struct JuceCleanup : public DeletedAtShutdown {
  30. JuceCleanup() noexcept {}
  31. ~JuceCleanup()
  32. {
  33. gDeviceTypes.clear(true);
  34. }
  35. };
  36. // -------------------------------------------------------------------------------------------------------------------
  37. // Cleanup
  38. static void initJuceDevicesIfNeeded()
  39. {
  40. static AudioDeviceManager sDeviceManager;
  41. if (gDeviceTypes.size() != 0)
  42. return;
  43. sDeviceManager.createAudioDeviceTypes(gDeviceTypes);
  44. CARLA_SAFE_ASSERT_RETURN(gDeviceTypes.size() != 0,);
  45. new JuceCleanup();
  46. // remove JACK from device list
  47. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  48. {
  49. if (gDeviceTypes[i]->getTypeName() == "JACK")
  50. {
  51. gDeviceTypes.remove(i, true);
  52. break;
  53. }
  54. }
  55. }
  56. // -------------------------------------------------------------------------------------------------------------------
  57. // Juce Engine
  58. class CarlaEngineJuce : public CarlaEngine,
  59. public AudioIODeviceCallback,
  60. public MidiInputCallback
  61. {
  62. public:
  63. CarlaEngineJuce(AudioIODeviceType* const devType)
  64. : CarlaEngine(),
  65. AudioIODeviceCallback(),
  66. fDevice(),
  67. fDeviceType(devType),
  68. fMidiIns(),
  69. fMidiInEvents(),
  70. fMidiOuts(),
  71. fMidiOutMutex(),
  72. leakDetector_CarlaEngineJuce()
  73. {
  74. carla_debug("CarlaEngineJuce::CarlaEngineJuce(%p)", devType);
  75. // just to make sure
  76. pData->options.transportMode = ENGINE_TRANSPORT_MODE_INTERNAL;
  77. }
  78. ~CarlaEngineJuce() override
  79. {
  80. carla_debug("CarlaEngineJuce::~CarlaEngineJuce()");
  81. }
  82. // -------------------------------------
  83. bool init(const char* const clientName) override
  84. {
  85. CARLA_SAFE_ASSERT_RETURN(clientName != nullptr && clientName[0] != '\0', false);
  86. carla_debug("CarlaEngineJuce::init(\"%s\")", clientName);
  87. if (pData->options.processMode != ENGINE_PROCESS_MODE_CONTINUOUS_RACK && pData->options.processMode != ENGINE_PROCESS_MODE_PATCHBAY)
  88. {
  89. setLastError("Invalid process mode");
  90. return false;
  91. }
  92. String deviceName;
  93. if (pData->options.audioDevice != nullptr && pData->options.audioDevice[0] != '\0')
  94. {
  95. deviceName = pData->options.audioDevice;
  96. }
  97. else
  98. {
  99. const int defaultIndex(fDeviceType->getDefaultDeviceIndex(false));
  100. StringArray deviceNames(fDeviceType->getDeviceNames());
  101. if (defaultIndex >= 0 && defaultIndex < deviceNames.size())
  102. deviceName = deviceNames[defaultIndex];
  103. }
  104. if (deviceName.isEmpty())
  105. {
  106. setLastError("Audio device has not been selected yet and a default one is not available");
  107. return false;
  108. }
  109. fDevice = fDeviceType->createDevice(deviceName, deviceName);
  110. if (fDevice == nullptr)
  111. {
  112. setLastError("Failed to create device");
  113. return false;
  114. }
  115. StringArray inputNames(fDevice->getInputChannelNames());
  116. StringArray outputNames(fDevice->getOutputChannelNames());
  117. if (inputNames.size() < 0 || outputNames.size() <= 0)
  118. {
  119. setLastError("Selected device does not have any outputs");
  120. return false;
  121. }
  122. BigInteger inputChannels;
  123. inputChannels.setRange(0, inputNames.size(), true);
  124. BigInteger outputChannels;
  125. outputChannels.setRange(0, outputNames.size(), true);
  126. String error = fDevice->open(inputChannels, outputChannels, pData->options.audioSampleRate, static_cast<int>(pData->options.audioBufferSize));
  127. if (error.isNotEmpty())
  128. {
  129. setLastError(error.toUTF8());
  130. fDevice = nullptr;
  131. return false;
  132. }
  133. if (! pData->init(clientName))
  134. {
  135. close();
  136. setLastError("Failed to init internal data");
  137. return false;
  138. }
  139. pData->bufferSize = static_cast<uint32_t>(fDevice->getCurrentBufferSizeSamples());
  140. pData->sampleRate = fDevice->getCurrentSampleRate();
  141. pData->graph.create(static_cast<uint32_t>(inputNames.size()), static_cast<uint32_t>(outputNames.size()));
  142. fDevice->start(this);
  143. patchbayRefresh(false);
  144. if (pData->options.processMode == ENGINE_PROCESS_MODE_PATCHBAY)
  145. refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), false);
  146. callback(ENGINE_CALLBACK_ENGINE_STARTED, 0, pData->options.processMode, pData->options.transportMode, 0.0f, getCurrentDriverName());
  147. return true;
  148. }
  149. bool close() override
  150. {
  151. carla_debug("CarlaEngineJuce::close()");
  152. bool hasError = false;
  153. // stop stream first
  154. if (fDevice != nullptr && fDevice->isPlaying())
  155. fDevice->stop();
  156. // clear engine data
  157. CarlaEngine::close();
  158. pData->graph.destroy();
  159. for (LinkedList<MidiInPort>::Itenerator it = fMidiIns.begin(); it.valid(); it.next())
  160. {
  161. MidiInPort& inPort(it.getValue());
  162. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  163. inPort.port->stop();
  164. delete inPort.port;
  165. }
  166. fMidiIns.clear();
  167. fMidiInEvents.clear();
  168. fMidiOutMutex.lock();
  169. for (LinkedList<MidiOutPort>::Itenerator it = fMidiOuts.begin(); it.valid(); it.next())
  170. {
  171. MidiOutPort& outPort(it.getValue());
  172. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  173. outPort.port->stopBackgroundThread();
  174. delete outPort.port;
  175. }
  176. fMidiOuts.clear();
  177. fMidiOutMutex.unlock();
  178. // close stream
  179. if (fDevice != nullptr)
  180. {
  181. if (fDevice->isOpen())
  182. fDevice->close();
  183. fDevice = nullptr;
  184. }
  185. return !hasError;
  186. }
  187. bool isRunning() const noexcept override
  188. {
  189. return fDevice != nullptr && fDevice->isOpen();
  190. }
  191. bool isOffline() const noexcept override
  192. {
  193. return false;
  194. }
  195. EngineType getType() const noexcept override
  196. {
  197. return kEngineTypeJuce;
  198. }
  199. const char* getCurrentDriverName() const noexcept override
  200. {
  201. return fDeviceType->getTypeName().toRawUTF8();
  202. }
  203. // -------------------------------------------------------------------
  204. // Patchbay
  205. template<class Graph>
  206. bool refreshExternalGraphPorts(Graph* const graph, const bool sendCallback)
  207. {
  208. CARLA_SAFE_ASSERT_RETURN(graph != nullptr, false);
  209. char strBuf[STR_MAX+1];
  210. strBuf[STR_MAX] = '\0';
  211. ExternalGraph& extGraph(graph->extGraph);
  212. // ---------------------------------------------------------------
  213. // clear last ports
  214. extGraph.clear();
  215. // ---------------------------------------------------------------
  216. // fill in new ones
  217. // Audio In
  218. {
  219. StringArray inputNames(fDevice->getInputChannelNames());
  220. for (int i=0, count=inputNames.size(); i<count; ++i)
  221. {
  222. PortNameToId portNameToId;
  223. portNameToId.setData(kExternalGraphGroupAudioIn, uint(i+1), inputNames[i].toRawUTF8(), "");
  224. extGraph.audioPorts.ins.append(portNameToId);
  225. }
  226. }
  227. // Audio Out
  228. {
  229. StringArray outputNames(fDevice->getOutputChannelNames());
  230. for (int i=0, count=outputNames.size(); i<count; ++i)
  231. {
  232. PortNameToId portNameToId;
  233. portNameToId.setData(kExternalGraphGroupAudioOut, uint(i+1), outputNames[i].toRawUTF8(), "");
  234. }
  235. }
  236. // MIDI In
  237. {
  238. StringArray midiIns(MidiInput::getDevices());
  239. for (int i=0, count=midiIns.size(); i<count; ++i)
  240. {
  241. PortNameToId portNameToId;
  242. portNameToId.setData(kExternalGraphGroupMidiIn, uint(i+1), midiIns[i].toRawUTF8(), "");
  243. extGraph.midiPorts.ins.append(portNameToId);
  244. }
  245. }
  246. // MIDI Out
  247. {
  248. StringArray midiOuts(MidiOutput::getDevices());
  249. for (int i=0, count=midiOuts.size(); i<count; ++i)
  250. {
  251. PortNameToId portNameToId;
  252. portNameToId.setData(kExternalGraphGroupMidiOut, uint(i+1), midiOuts[i].toRawUTF8(), "");
  253. extGraph.midiPorts.outs.append(portNameToId);
  254. }
  255. }
  256. // ---------------------------------------------------------------
  257. // now refresh
  258. if (sendCallback)
  259. {
  260. String deviceName(fDevice->getName());
  261. if (deviceName.isNotEmpty())
  262. deviceName = deviceName.dropLastCharacters(deviceName.fromFirstOccurrenceOf(", ", true, false).length());
  263. graph->refresh(deviceName.toRawUTF8());
  264. }
  265. // ---------------------------------------------------------------
  266. // add midi connections
  267. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  268. {
  269. const MidiInPort& inPort(it.getValue());
  270. const uint portId(extGraph.midiPorts.getPortId(true, inPort.name));
  271. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.ins.count());
  272. ConnectionToId connectionToId;
  273. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupMidiIn, portId, kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiIn);
  274. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  275. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  276. extGraph.connections.list.append(connectionToId);
  277. }
  278. fMidiOutMutex.lock();
  279. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  280. {
  281. const MidiOutPort& outPort(it.getValue());
  282. const uint portId(extGraph.midiPorts.getPortId(false, outPort.name));
  283. CARLA_SAFE_ASSERT_CONTINUE(portId < extGraph.midiPorts.outs.count());
  284. ConnectionToId connectionToId;
  285. connectionToId.setData(++(extGraph.connections.lastId), kExternalGraphGroupCarla, kExternalGraphCarlaPortMidiOut, kExternalGraphGroupMidiOut, portId);
  286. std::snprintf(strBuf, STR_MAX, "%i:%i:%i:%i", connectionToId.groupA, connectionToId.portA, connectionToId.groupB, connectionToId.portB);
  287. callback(ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED, connectionToId.id, 0, 0, 0.0f, strBuf);
  288. extGraph.connections.list.append(connectionToId);
  289. }
  290. fMidiOutMutex.unlock();
  291. return true;
  292. }
  293. bool patchbayRefresh(const bool external) override
  294. {
  295. CARLA_SAFE_ASSERT_RETURN(pData->graph.isReady(), false);
  296. if (pData->options.processMode == ENGINE_PROCESS_MODE_CONTINUOUS_RACK)
  297. {
  298. return refreshExternalGraphPorts<RackGraph>(pData->graph.getRackGraph(), true);
  299. }
  300. else
  301. {
  302. pData->graph.setUsingExternal(external);
  303. if (external)
  304. return refreshExternalGraphPorts<PatchbayGraph>(pData->graph.getPatchbayGraph(), true);
  305. else
  306. return CarlaEngine::patchbayRefresh(false);
  307. }
  308. return false;
  309. }
  310. // -------------------------------------------------------------------
  311. protected:
  312. void audioDeviceIOCallback(const float** inputChannelData, int numInputChannels, float** outputChannelData, int numOutputChannels, int numSamples) override
  313. {
  314. const PendingRtEventsRunner prt(this);
  315. // assert juce buffers
  316. CARLA_SAFE_ASSERT_RETURN(numInputChannels >= 0,);
  317. CARLA_SAFE_ASSERT_RETURN(numOutputChannels > 0,);
  318. CARLA_SAFE_ASSERT_RETURN(outputChannelData != nullptr,);
  319. CARLA_SAFE_ASSERT_RETURN(numSamples == static_cast<int>(pData->bufferSize),);
  320. const uint32_t nframes(static_cast<uint32_t>(numSamples));
  321. // initialize juce output
  322. for (int i=0; i < numOutputChannels; ++i)
  323. FloatVectorOperations::clear(outputChannelData[i], numSamples);
  324. // initialize events
  325. carla_zeroStruct<EngineEvent>(pData->events.in, kMaxEngineEventInternalCount);
  326. carla_zeroStruct<EngineEvent>(pData->events.out, kMaxEngineEventInternalCount);
  327. if (fMidiInEvents.mutex.tryLock())
  328. {
  329. uint32_t engineEventIndex = 0;
  330. fMidiInEvents.splice();
  331. for (LinkedList<RtMidiEvent>::Itenerator it = fMidiInEvents.data.begin(); it.valid(); it.next())
  332. {
  333. const RtMidiEvent& midiEvent(it.getValue());
  334. EngineEvent& engineEvent(pData->events.in[engineEventIndex++]);
  335. if (midiEvent.time < pData->timeInfo.frame)
  336. {
  337. engineEvent.time = 0;
  338. }
  339. else if (midiEvent.time >= pData->timeInfo.frame + nframes)
  340. {
  341. carla_stderr("MIDI Event in the future!, %i vs %i", engineEvent.time, pData->timeInfo.frame);
  342. engineEvent.time = static_cast<uint32_t>(pData->timeInfo.frame) + nframes - 1;
  343. }
  344. else
  345. engineEvent.time = static_cast<uint32_t>(midiEvent.time - pData->timeInfo.frame);
  346. engineEvent.fillFromMidiData(midiEvent.size, midiEvent.data);
  347. if (engineEventIndex >= kMaxEngineEventInternalCount)
  348. break;
  349. }
  350. fMidiInEvents.data.clear();
  351. fMidiInEvents.mutex.unlock();
  352. }
  353. pData->graph.process(pData, inputChannelData, outputChannelData, static_cast<uint32_t>(numSamples));
  354. fMidiOutMutex.lock();
  355. if (fMidiOuts.count() > 0)
  356. {
  357. uint8_t size = 0;
  358. uint8_t data[3] = { 0, 0, 0 };
  359. const uint8_t* dataPtr = data;
  360. for (ushort i=0; i < kMaxEngineEventInternalCount; ++i)
  361. {
  362. const EngineEvent& engineEvent(pData->events.out[i]);
  363. if (engineEvent.type == kEngineEventTypeNull)
  364. break;
  365. else if (engineEvent.type == kEngineEventTypeControl)
  366. {
  367. const EngineControlEvent& ctrlEvent(engineEvent.ctrl);
  368. ctrlEvent.convertToMidiData(engineEvent.channel, size, data);
  369. dataPtr = data;
  370. }
  371. else if (engineEvent.type == kEngineEventTypeMidi)
  372. {
  373. const EngineMidiEvent& midiEvent(engineEvent.midi);
  374. size = midiEvent.size;
  375. if (size > EngineMidiEvent::kDataSize && midiEvent.dataExt != nullptr)
  376. dataPtr = midiEvent.dataExt;
  377. else
  378. dataPtr = midiEvent.data;
  379. }
  380. else
  381. {
  382. continue;
  383. }
  384. if (size > 0)
  385. {
  386. MidiMessage message(static_cast<const void*>(dataPtr), static_cast<int>(size), static_cast<double>(engineEvent.time)/nframes);
  387. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  388. {
  389. MidiOutPort& outPort(it.getValue());
  390. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  391. outPort.port->sendMessageNow(message);
  392. }
  393. }
  394. }
  395. }
  396. fMidiOutMutex.unlock();
  397. }
  398. void audioDeviceAboutToStart(AudioIODevice* /*device*/) override
  399. {
  400. }
  401. void audioDeviceStopped() override
  402. {
  403. }
  404. void audioDeviceError(const String& errorMessage) override
  405. {
  406. callback(ENGINE_CALLBACK_ERROR, 0, 0, 0, 0.0f, errorMessage.toRawUTF8());
  407. }
  408. // -------------------------------------------------------------------
  409. void handleIncomingMidiMessage(MidiInput* /*source*/, const MidiMessage& message) override
  410. {
  411. const int messageSize(message.getRawDataSize());
  412. if (messageSize <= 0 || messageSize > EngineMidiEvent::kDataSize)
  413. return;
  414. const uint8_t* const messageData(message.getRawData());
  415. RtMidiEvent midiEvent;
  416. midiEvent.time = 0; // TODO
  417. midiEvent.size = static_cast<uint8_t>(messageSize);
  418. int i=0;
  419. for (; i < messageSize; ++i)
  420. midiEvent.data[i] = messageData[i];
  421. for (; i < EngineMidiEvent::kDataSize; ++i)
  422. midiEvent.data[i] = 0;
  423. fMidiInEvents.append(midiEvent);
  424. }
  425. // -------------------------------------------------------------------
  426. bool connectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  427. {
  428. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  429. carla_stdout("CarlaEngineJuce::connectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  430. switch (connectionType)
  431. {
  432. case kExternalGraphConnectionAudioIn1:
  433. case kExternalGraphConnectionAudioIn2:
  434. case kExternalGraphConnectionAudioOut1:
  435. case kExternalGraphConnectionAudioOut2:
  436. return CarlaEngine::connectExternalGraphPort(connectionType, portId, portName);
  437. case kExternalGraphConnectionMidiInput: {
  438. StringArray midiIns(MidiInput::getDevices());
  439. if (! midiIns.contains(portName))
  440. return false;
  441. MidiInput* const juceMidiIn(MidiInput::openDevice(midiIns.indexOf(portName), this));
  442. juceMidiIn->start();
  443. MidiInPort midiPort;
  444. midiPort.port = juceMidiIn;
  445. std::strncpy(midiPort.name, portName, STR_MAX);
  446. midiPort.name[STR_MAX] = '\0';
  447. fMidiIns.append(midiPort);
  448. return true;
  449. } break;
  450. case kExternalGraphConnectionMidiOutput: {
  451. StringArray midiOuts(MidiOutput::getDevices());
  452. if (! midiOuts.contains(portName))
  453. return false;
  454. MidiOutput* const juceMidiOut(MidiOutput::openDevice(midiOuts.indexOf(portName)));
  455. juceMidiOut->startBackgroundThread();
  456. MidiOutPort midiPort;
  457. midiPort.port = juceMidiOut;
  458. std::strncpy(midiPort.name, portName, STR_MAX);
  459. midiPort.name[STR_MAX] = '\0';
  460. const CarlaMutexLocker cml(fMidiOutMutex);
  461. fMidiOuts.append(midiPort);
  462. return true;
  463. } break;
  464. }
  465. return false;
  466. }
  467. bool disconnectExternalGraphPort(const uint connectionType, const uint portId, const char* const portName) override
  468. {
  469. CARLA_SAFE_ASSERT_RETURN(connectionType != 0 || (portName != nullptr && portName[0] != '\0'), false);
  470. carla_debug("CarlaEngineJuce::disconnectExternalGraphPort(%u, %u, \"%s\")", connectionType, portId, portName);
  471. switch (connectionType)
  472. {
  473. case kExternalGraphConnectionAudioIn1:
  474. case kExternalGraphConnectionAudioIn2:
  475. case kExternalGraphConnectionAudioOut1:
  476. case kExternalGraphConnectionAudioOut2:
  477. return CarlaEngine::disconnectExternalGraphPort(connectionType, portId, portName);
  478. case kExternalGraphConnectionMidiInput:
  479. for (LinkedList<MidiInPort>::Itenerator it=fMidiIns.begin(); it.valid(); it.next())
  480. {
  481. MidiInPort& inPort(it.getValue());
  482. CARLA_SAFE_ASSERT_CONTINUE(inPort.port != nullptr);
  483. if (std::strcmp(inPort.name, portName) != 0)
  484. continue;
  485. inPort.port->stop();
  486. delete inPort.port;
  487. fMidiIns.remove(it);
  488. return true;
  489. }
  490. break;
  491. case kExternalGraphConnectionMidiOutput: {
  492. const CarlaMutexLocker cml(fMidiOutMutex);
  493. for (LinkedList<MidiOutPort>::Itenerator it=fMidiOuts.begin(); it.valid(); it.next())
  494. {
  495. MidiOutPort& outPort(it.getValue());
  496. CARLA_SAFE_ASSERT_CONTINUE(outPort.port != nullptr);
  497. if (std::strcmp(outPort.name, portName) != 0)
  498. continue;
  499. outPort.port->stopBackgroundThread();
  500. delete outPort.port;
  501. fMidiOuts.remove(it);
  502. return true;
  503. }
  504. } break;
  505. }
  506. return false;
  507. }
  508. // -------------------------------------
  509. private:
  510. ScopedPointer<AudioIODevice> fDevice;
  511. AudioIODeviceType* const fDeviceType;
  512. struct MidiInPort {
  513. MidiInput* port;
  514. char name[STR_MAX+1];
  515. };
  516. struct MidiOutPort {
  517. MidiOutput* port;
  518. char name[STR_MAX+1];
  519. };
  520. struct RtMidiEvent {
  521. uint64_t time; // needs to compare to internal time
  522. uint8_t size;
  523. uint8_t data[EngineMidiEvent::kDataSize];
  524. };
  525. struct RtMidiEvents {
  526. CarlaMutex mutex;
  527. RtLinkedList<RtMidiEvent>::Pool dataPool;
  528. RtLinkedList<RtMidiEvent> data;
  529. RtLinkedList<RtMidiEvent> dataPending;
  530. RtMidiEvents()
  531. : mutex(),
  532. dataPool(512, 512),
  533. data(dataPool),
  534. dataPending(dataPool) {}
  535. ~RtMidiEvents()
  536. {
  537. clear();
  538. }
  539. void append(const RtMidiEvent& event)
  540. {
  541. mutex.lock();
  542. dataPending.append(event);
  543. mutex.unlock();
  544. }
  545. void clear()
  546. {
  547. mutex.lock();
  548. data.clear();
  549. dataPending.clear();
  550. mutex.unlock();
  551. }
  552. void splice()
  553. {
  554. if (dataPending.count() > 0)
  555. dataPending.moveTo(data, true /* append */);
  556. }
  557. };
  558. LinkedList<MidiInPort> fMidiIns;
  559. RtMidiEvents fMidiInEvents;
  560. LinkedList<MidiOutPort> fMidiOuts;
  561. CarlaMutex fMidiOutMutex;
  562. CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CarlaEngineJuce)
  563. };
  564. // -----------------------------------------
  565. CarlaEngine* CarlaEngine::newJuce(const AudioApi api)
  566. {
  567. initJuceDevicesIfNeeded();
  568. String juceApi;
  569. switch (api)
  570. {
  571. case AUDIO_API_NULL:
  572. case AUDIO_API_OSS:
  573. case AUDIO_API_PULSE:
  574. break;
  575. case AUDIO_API_JACK:
  576. juceApi = "JACK";
  577. break;
  578. case AUDIO_API_ALSA:
  579. juceApi = "ALSA";
  580. break;
  581. case AUDIO_API_CORE:
  582. juceApi = "CoreAudio";
  583. break;
  584. case AUDIO_API_ASIO:
  585. juceApi = "ASIO";
  586. break;
  587. case AUDIO_API_DS:
  588. juceApi = "DirectSound";
  589. break;
  590. }
  591. if (juceApi.isEmpty())
  592. return nullptr;
  593. AudioIODeviceType* deviceType = nullptr;
  594. for (int i=0, count=gDeviceTypes.size(); i < count; ++i)
  595. {
  596. deviceType = gDeviceTypes[i];
  597. if (deviceType == nullptr || deviceType->getTypeName() == juceApi)
  598. break;
  599. }
  600. if (deviceType == nullptr)
  601. return nullptr;
  602. deviceType->scanForDevices();
  603. return new CarlaEngineJuce(deviceType);
  604. }
  605. uint CarlaEngine::getJuceApiCount()
  606. {
  607. initJuceDevicesIfNeeded();
  608. return static_cast<uint>(gDeviceTypes.size());
  609. }
  610. const char* CarlaEngine::getJuceApiName(const uint uindex)
  611. {
  612. initJuceDevicesIfNeeded();
  613. const int index(static_cast<int>(uindex));
  614. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  615. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  616. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  617. return deviceType->getTypeName().toRawUTF8();
  618. }
  619. const char* const* CarlaEngine::getJuceApiDeviceNames(const uint uindex)
  620. {
  621. initJuceDevicesIfNeeded();
  622. const int index(static_cast<int>(uindex));
  623. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  624. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  625. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  626. deviceType->scanForDevices();
  627. StringArray juceDeviceNames(deviceType->getDeviceNames());
  628. const int juceDeviceNameCount(juceDeviceNames.size());
  629. if (juceDeviceNameCount <= 0)
  630. return nullptr;
  631. CarlaStringList devNames;
  632. for (int i=0; i < juceDeviceNameCount; ++i)
  633. devNames.append(juceDeviceNames[i].toRawUTF8());
  634. gDeviceNames = devNames.toCharStringListPtr();
  635. return gDeviceNames;
  636. }
  637. const EngineDriverDeviceInfo* CarlaEngine::getJuceDeviceInfo(const uint uindex, const char* const deviceName)
  638. {
  639. initJuceDevicesIfNeeded();
  640. const int index(static_cast<int>(uindex));
  641. CARLA_SAFE_ASSERT_RETURN(index < gDeviceTypes.size(), nullptr);
  642. AudioIODeviceType* const deviceType(gDeviceTypes[index]);
  643. CARLA_SAFE_ASSERT_RETURN(deviceType != nullptr, nullptr);
  644. deviceType->scanForDevices();
  645. ScopedPointer<AudioIODevice> device(deviceType->createDevice(deviceName, deviceName));
  646. if (device == nullptr)
  647. return nullptr;
  648. static EngineDriverDeviceInfo devInfo = { 0x0, nullptr, nullptr };
  649. static uint32_t dummyBufferSizes[11] = { 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 0 };
  650. static double dummySampleRates[14] = { 22050.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0, 0.0 };
  651. // reset
  652. devInfo.hints = ENGINE_DRIVER_DEVICE_VARIABLE_BUFFER_SIZE | ENGINE_DRIVER_DEVICE_VARIABLE_SAMPLE_RATE;
  653. // cleanup
  654. if (devInfo.bufferSizes != nullptr && devInfo.bufferSizes != dummyBufferSizes)
  655. {
  656. delete[] devInfo.bufferSizes;
  657. devInfo.bufferSizes = nullptr;
  658. }
  659. if (devInfo.sampleRates != nullptr && devInfo.sampleRates != dummySampleRates)
  660. {
  661. delete[] devInfo.sampleRates;
  662. devInfo.sampleRates = nullptr;
  663. }
  664. if (device->hasControlPanel())
  665. devInfo.hints |= ENGINE_DRIVER_DEVICE_HAS_CONTROL_PANEL;
  666. Array<int> juceBufferSizes = device->getAvailableBufferSizes();
  667. if (int bufferSizesCount = juceBufferSizes.size())
  668. {
  669. uint32_t* const bufferSizes(new uint32_t[bufferSizesCount+1]);
  670. for (int i=0; i < bufferSizesCount; ++i)
  671. bufferSizes[i] = static_cast<uint32_t>(juceBufferSizes[i]);
  672. bufferSizes[bufferSizesCount] = 0;
  673. devInfo.bufferSizes = bufferSizes;
  674. }
  675. else
  676. {
  677. devInfo.bufferSizes = dummyBufferSizes;
  678. }
  679. Array<double> juceSampleRates = device->getAvailableSampleRates();
  680. if (int sampleRatesCount = juceSampleRates.size())
  681. {
  682. double* const sampleRates(new double[sampleRatesCount+1]);
  683. for (int i=0; i < sampleRatesCount; ++i)
  684. sampleRates[i] = juceSampleRates[i];
  685. sampleRates[sampleRatesCount] = 0.0;
  686. devInfo.sampleRates = sampleRates;
  687. }
  688. else
  689. {
  690. devInfo.sampleRates = dummySampleRates;
  691. }
  692. return &devInfo;
  693. }
  694. // -----------------------------------------
  695. CARLA_BACKEND_END_NAMESPACE