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.

980 lines
32KB

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