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

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