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

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