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.

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