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

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