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

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