The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

235 lines
6.7KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. class MidiDeviceListConnectionBroadcaster final : private AsyncUpdater
  20. {
  21. public:
  22. ~MidiDeviceListConnectionBroadcaster() override
  23. {
  24. cancelPendingUpdate();
  25. }
  26. MidiDeviceListConnection::Key add (std::function<void()> callback)
  27. {
  28. JUCE_ASSERT_MESSAGE_THREAD
  29. return callbacks.emplace (key++, std::move (callback)).first->first;
  30. }
  31. void remove (const MidiDeviceListConnection::Key k)
  32. {
  33. JUCE_ASSERT_MESSAGE_THREAD
  34. callbacks.erase (k);
  35. }
  36. void notify()
  37. {
  38. if (MessageManager::getInstance()->isThisTheMessageThread())
  39. {
  40. cancelPendingUpdate();
  41. const State newState;
  42. if (std::exchange (lastNotifiedState, newState) != newState)
  43. for (auto it = callbacks.begin(); it != callbacks.end();)
  44. NullCheckedInvocation::invoke ((it++)->second);
  45. }
  46. else
  47. {
  48. triggerAsyncUpdate();
  49. }
  50. }
  51. static auto& get()
  52. {
  53. static MidiDeviceListConnectionBroadcaster result;
  54. return result;
  55. }
  56. private:
  57. MidiDeviceListConnectionBroadcaster() = default;
  58. class State
  59. {
  60. Array<MidiDeviceInfo> ins = MidiInput::getAvailableDevices(), outs = MidiOutput::getAvailableDevices();
  61. auto tie() const { return std::tie (ins, outs); }
  62. public:
  63. bool operator== (const State& other) const { return tie() == other.tie(); }
  64. bool operator!= (const State& other) const { return tie() != other.tie(); }
  65. };
  66. void handleAsyncUpdate() override
  67. {
  68. notify();
  69. }
  70. std::map<MidiDeviceListConnection::Key, std::function<void()>> callbacks;
  71. State lastNotifiedState;
  72. MidiDeviceListConnection::Key key = 0;
  73. };
  74. //==============================================================================
  75. MidiDeviceListConnection::~MidiDeviceListConnection() noexcept
  76. {
  77. if (broadcaster != nullptr)
  78. broadcaster->remove (key);
  79. }
  80. //==============================================================================
  81. void MidiInputCallback::handlePartialSysexMessage ([[maybe_unused]] MidiInput* source,
  82. [[maybe_unused]] const uint8* messageData,
  83. [[maybe_unused]] int numBytesSoFar,
  84. [[maybe_unused]] double timestamp) {}
  85. //==============================================================================
  86. MidiOutput::MidiOutput (const String& deviceName, const String& deviceIdentifier)
  87. : Thread ("midi out"), deviceInfo (deviceName, deviceIdentifier)
  88. {
  89. }
  90. void MidiOutput::sendBlockOfMessagesNow (const MidiBuffer& buffer)
  91. {
  92. for (const auto metadata : buffer)
  93. sendMessageNow (metadata.getMessage());
  94. }
  95. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  96. double millisecondCounterToStartAt,
  97. double samplesPerSecondForBuffer)
  98. {
  99. // You've got to call startBackgroundThread() for this to actually work..
  100. jassert (isThreadRunning());
  101. // this needs to be a value in the future - RTFM for this method!
  102. jassert (millisecondCounterToStartAt > 0);
  103. auto timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  104. for (const auto metadata : buffer)
  105. {
  106. auto eventTime = millisecondCounterToStartAt + timeScaleFactor * metadata.samplePosition;
  107. auto* m = new PendingMessage (metadata.data, metadata.numBytes, eventTime);
  108. const ScopedLock sl (lock);
  109. if (firstMessage == nullptr || firstMessage->message.getTimeStamp() > eventTime)
  110. {
  111. m->next = firstMessage;
  112. firstMessage = m;
  113. }
  114. else
  115. {
  116. auto* mm = firstMessage;
  117. while (mm->next != nullptr && mm->next->message.getTimeStamp() <= eventTime)
  118. mm = mm->next;
  119. m->next = mm->next;
  120. mm->next = m;
  121. }
  122. }
  123. notify();
  124. }
  125. void MidiOutput::clearAllPendingMessages()
  126. {
  127. const ScopedLock sl (lock);
  128. while (firstMessage != nullptr)
  129. {
  130. auto* m = firstMessage;
  131. firstMessage = firstMessage->next;
  132. delete m;
  133. }
  134. }
  135. void MidiOutput::startBackgroundThread()
  136. {
  137. startThread (Priority::high);
  138. }
  139. void MidiOutput::stopBackgroundThread()
  140. {
  141. stopThread (5000);
  142. }
  143. void MidiOutput::run()
  144. {
  145. while (! threadShouldExit())
  146. {
  147. auto now = Time::getMillisecondCounter();
  148. uint32 eventTime = 0;
  149. uint32 timeToWait = 500;
  150. PendingMessage* message;
  151. {
  152. const ScopedLock sl (lock);
  153. message = firstMessage;
  154. if (message != nullptr)
  155. {
  156. eventTime = (uint32) roundToInt (message->message.getTimeStamp());
  157. if (eventTime > now + 20)
  158. {
  159. timeToWait = eventTime - (now + 20);
  160. message = nullptr;
  161. }
  162. else
  163. {
  164. firstMessage = message->next;
  165. }
  166. }
  167. }
  168. if (message != nullptr)
  169. {
  170. std::unique_ptr<PendingMessage> messageDeleter (message);
  171. if (eventTime > now)
  172. {
  173. Time::waitForMillisecondCounter (eventTime);
  174. if (threadShouldExit())
  175. break;
  176. }
  177. if (eventTime > now - 200)
  178. sendMessageNow (message->message);
  179. }
  180. else
  181. {
  182. jassert (timeToWait < 1000 * 30);
  183. wait ((int) timeToWait);
  184. }
  185. }
  186. clearAllPendingMessages();
  187. }
  188. } // namespace juce