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.

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