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.

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