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.

2017 lines
67KB

  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. #ifndef DRV_QUERYDEVICEINTERFACE
  18. #define DRV_RESERVED 0x0800
  19. #define DRV_QUERYDEVICEINTERFACE (DRV_RESERVED + 12)
  20. #define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
  21. #endif
  22. namespace juce
  23. {
  24. template <typename T>
  25. class CheckedReference
  26. {
  27. public:
  28. template <typename Ptr>
  29. friend auto createCheckedReference (Ptr*);
  30. void clear()
  31. {
  32. std::lock_guard lock { mutex };
  33. ptr = nullptr;
  34. }
  35. template <typename Callback>
  36. void access (Callback&& callback)
  37. {
  38. std::lock_guard lock { mutex };
  39. callback (ptr);
  40. }
  41. private:
  42. explicit CheckedReference (T* ptrIn) : ptr (ptrIn) {}
  43. T* ptr;
  44. std::mutex mutex;
  45. };
  46. template <typename Ptr>
  47. auto createCheckedReference (Ptr* ptrIn)
  48. {
  49. return std::shared_ptr<CheckedReference<Ptr>> { new CheckedReference<Ptr> (ptrIn) };
  50. }
  51. class MidiInput::Pimpl
  52. {
  53. public:
  54. virtual ~Pimpl() noexcept = default;
  55. virtual String getDeviceIdentifier() = 0;
  56. virtual String getDeviceName() = 0;
  57. virtual void start() = 0;
  58. virtual void stop() = 0;
  59. };
  60. class MidiOutput::Pimpl
  61. {
  62. public:
  63. virtual ~Pimpl() noexcept = default;
  64. virtual String getDeviceIdentifier() = 0;
  65. virtual String getDeviceName() = 0;
  66. virtual void sendMessageNow (const MidiMessage&) = 0;
  67. };
  68. struct MidiServiceType
  69. {
  70. MidiServiceType() = default;
  71. virtual ~MidiServiceType() noexcept = default;
  72. virtual Array<MidiDeviceInfo> getAvailableDevices (bool) = 0;
  73. virtual MidiDeviceInfo getDefaultDevice (bool) = 0;
  74. virtual MidiInput::Pimpl* createInputWrapper (MidiInput&, const String&, MidiInputCallback&) = 0;
  75. virtual MidiOutput::Pimpl* createOutputWrapper (const String&) = 0;
  76. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiServiceType)
  77. };
  78. //==============================================================================
  79. struct Win32MidiService : public MidiServiceType,
  80. private Timer
  81. {
  82. Win32MidiService() {}
  83. Array<MidiDeviceInfo> getAvailableDevices (bool isInput) override
  84. {
  85. return isInput ? Win32InputWrapper::getAvailableDevices()
  86. : Win32OutputWrapper::getAvailableDevices();
  87. }
  88. MidiDeviceInfo getDefaultDevice (bool isInput) override
  89. {
  90. return isInput ? Win32InputWrapper::getDefaultDevice()
  91. : Win32OutputWrapper::getDefaultDevice();
  92. }
  93. MidiInput::Pimpl* createInputWrapper (MidiInput& input, const String& deviceIdentifier, MidiInputCallback& callback) override
  94. {
  95. return new Win32InputWrapper (*this, input, deviceIdentifier, callback);
  96. }
  97. MidiOutput::Pimpl* createOutputWrapper (const String& deviceIdentifier) override
  98. {
  99. return new Win32OutputWrapper (*this, deviceIdentifier);
  100. }
  101. private:
  102. struct Win32InputWrapper;
  103. //==============================================================================
  104. struct MidiInCollector : public ReferenceCountedObject
  105. {
  106. MidiInCollector (Win32MidiService& s, MidiDeviceInfo d)
  107. : deviceInfo (d), midiService (s)
  108. {
  109. }
  110. ~MidiInCollector()
  111. {
  112. stop();
  113. if (deviceHandle != nullptr)
  114. {
  115. for (int count = 5; --count >= 0;)
  116. {
  117. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  118. break;
  119. Sleep (20);
  120. }
  121. }
  122. }
  123. using Ptr = ReferenceCountedObjectPtr<MidiInCollector>;
  124. void addClient (Win32InputWrapper* c)
  125. {
  126. const ScopedLock sl (clientLock);
  127. jassert (! clients.contains (c));
  128. clients.add (c);
  129. }
  130. void removeClient (Win32InputWrapper* c)
  131. {
  132. const ScopedLock sl (clientLock);
  133. clients.removeFirstMatchingValue (c);
  134. startOrStop();
  135. midiService.asyncCheckForUnusedCollectors();
  136. }
  137. void handleMessage (const uint8* bytes, uint32 timeStamp)
  138. {
  139. if (bytes[0] >= 0x80 && isStarted.load())
  140. {
  141. {
  142. auto len = MidiMessage::getMessageLengthFromFirstByte (bytes[0]);
  143. auto time = convertTimeStamp (timeStamp);
  144. const ScopedLock sl (clientLock);
  145. for (auto* c : clients)
  146. c->pushMidiData (bytes, len, time);
  147. }
  148. writeFinishedBlocks();
  149. }
  150. }
  151. void handleSysEx (MIDIHDR* hdr, uint32 timeStamp)
  152. {
  153. if (isStarted.load() && hdr->dwBytesRecorded > 0)
  154. {
  155. {
  156. auto time = convertTimeStamp (timeStamp);
  157. const ScopedLock sl (clientLock);
  158. for (auto* c : clients)
  159. c->pushMidiData (hdr->lpData, (int) hdr->dwBytesRecorded, time);
  160. }
  161. writeFinishedBlocks();
  162. }
  163. }
  164. void startOrStop()
  165. {
  166. const ScopedLock sl (clientLock);
  167. if (countRunningClients() == 0)
  168. stop();
  169. else
  170. start();
  171. }
  172. void start()
  173. {
  174. if (deviceHandle != nullptr && ! isStarted.load())
  175. {
  176. activeMidiCollectors.addIfNotAlreadyThere (this);
  177. for (int i = 0; i < (int) numHeaders; ++i)
  178. {
  179. headers[i].prepare (deviceHandle);
  180. headers[i].write (deviceHandle);
  181. }
  182. startTime = Time::getMillisecondCounterHiRes();
  183. auto res = midiInStart (deviceHandle);
  184. if (res == MMSYSERR_NOERROR)
  185. isStarted = true;
  186. else
  187. unprepareAllHeaders();
  188. }
  189. }
  190. void stop()
  191. {
  192. if (isStarted.load())
  193. {
  194. isStarted = false;
  195. midiInReset (deviceHandle);
  196. midiInStop (deviceHandle);
  197. activeMidiCollectors.removeFirstMatchingValue (this);
  198. unprepareAllHeaders();
  199. }
  200. }
  201. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance,
  202. DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  203. {
  204. auto* collector = reinterpret_cast<MidiInCollector*> (dwInstance);
  205. // This is primarily a check for the collector being a dangling
  206. // pointer, as the callback can sometimes be delayed
  207. if (activeMidiCollectors.contains (collector))
  208. {
  209. if (uMsg == MIM_DATA)
  210. collector->handleMessage ((const uint8*) &midiMessage, (uint32) timeStamp);
  211. else if (uMsg == MIM_LONGDATA)
  212. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  213. }
  214. }
  215. MidiDeviceInfo deviceInfo;
  216. HMIDIIN deviceHandle = nullptr;
  217. private:
  218. Win32MidiService& midiService;
  219. CriticalSection clientLock;
  220. Array<Win32InputWrapper*> clients;
  221. std::atomic<bool> isStarted { false };
  222. double startTime = 0;
  223. // This static array is used to prevent occasional callbacks to objects that are
  224. // in the process of being deleted
  225. static Array<MidiInCollector*, CriticalSection> activeMidiCollectors;
  226. int countRunningClients() const
  227. {
  228. int num = 0;
  229. for (auto* c : clients)
  230. if (c->started)
  231. ++num;
  232. return num;
  233. }
  234. struct MidiHeader
  235. {
  236. MidiHeader() = default;
  237. void prepare (HMIDIIN device)
  238. {
  239. zerostruct (hdr);
  240. hdr.lpData = data;
  241. hdr.dwBufferLength = (DWORD) numElementsInArray (data);
  242. midiInPrepareHeader (device, &hdr, sizeof (hdr));
  243. }
  244. void unprepare (HMIDIIN device)
  245. {
  246. if ((hdr.dwFlags & WHDR_DONE) != 0)
  247. {
  248. int c = 10;
  249. while (--c >= 0 && midiInUnprepareHeader (device, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  250. Thread::sleep (20);
  251. jassert (c >= 0);
  252. }
  253. }
  254. void write (HMIDIIN device)
  255. {
  256. hdr.dwBytesRecorded = 0;
  257. midiInAddBuffer (device, &hdr, sizeof (hdr));
  258. }
  259. void writeIfFinished (HMIDIIN device)
  260. {
  261. if ((hdr.dwFlags & WHDR_DONE) != 0)
  262. write (device);
  263. }
  264. MIDIHDR hdr;
  265. char data[256];
  266. JUCE_DECLARE_NON_COPYABLE (MidiHeader)
  267. };
  268. enum { numHeaders = 32 };
  269. MidiHeader headers[numHeaders];
  270. void writeFinishedBlocks()
  271. {
  272. for (int i = 0; i < (int) numHeaders; ++i)
  273. headers[i].writeIfFinished (deviceHandle);
  274. }
  275. void unprepareAllHeaders()
  276. {
  277. for (int i = 0; i < (int) numHeaders; ++i)
  278. headers[i].unprepare (deviceHandle);
  279. }
  280. double convertTimeStamp (uint32 timeStamp)
  281. {
  282. auto t = startTime + timeStamp;
  283. auto now = Time::getMillisecondCounterHiRes();
  284. if (t > now)
  285. {
  286. if (t > now + 2.0)
  287. startTime -= 1.0;
  288. t = now;
  289. }
  290. return t * 0.001;
  291. }
  292. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector)
  293. };
  294. //==============================================================================
  295. template <class WrapperType>
  296. struct Win32MidiDeviceQuery
  297. {
  298. static Array<MidiDeviceInfo> getAvailableDevices()
  299. {
  300. StringArray deviceNames, deviceIDs;
  301. auto deviceCaps = WrapperType::getDeviceCaps();
  302. for (int i = 0; i < deviceCaps.size(); ++i)
  303. {
  304. deviceNames.add (deviceCaps[i].szPname);
  305. auto identifier = getInterfaceIDForDevice ((UINT) i);
  306. if (identifier.isNotEmpty())
  307. deviceIDs.add (identifier);
  308. else
  309. deviceIDs.add (deviceNames[i]);
  310. }
  311. deviceNames.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
  312. deviceIDs .appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
  313. Array<MidiDeviceInfo> devices;
  314. for (int i = 0; i < deviceNames.size(); ++i)
  315. devices.add ({ deviceNames[i], deviceIDs[i] });
  316. return devices;
  317. }
  318. private:
  319. static String getInterfaceIDForDevice (UINT id)
  320. {
  321. ULONG size = 0;
  322. if (WrapperType::sendMidiMessage ((UINT_PTR) id, DRV_QUERYDEVICEINTERFACESIZE, (DWORD_PTR) &size, 0) == MMSYSERR_NOERROR)
  323. {
  324. WCHAR interfaceName[512] = {};
  325. if (isPositiveAndBelow (size, sizeof (interfaceName))
  326. && WrapperType::sendMidiMessage ((UINT_PTR) id, DRV_QUERYDEVICEINTERFACE,
  327. (DWORD_PTR) interfaceName, sizeof (interfaceName)) == MMSYSERR_NOERROR)
  328. {
  329. return interfaceName;
  330. }
  331. }
  332. return {};
  333. }
  334. };
  335. struct Win32InputWrapper : public MidiInput::Pimpl,
  336. public Win32MidiDeviceQuery<Win32InputWrapper>
  337. {
  338. Win32InputWrapper (Win32MidiService& parentService, MidiInput& midiInput, const String& deviceIdentifier, MidiInputCallback& c)
  339. : input (midiInput), callback (c)
  340. {
  341. collector = getOrCreateCollector (parentService, deviceIdentifier);
  342. collector->addClient (this);
  343. }
  344. ~Win32InputWrapper() override
  345. {
  346. collector->removeClient (this);
  347. }
  348. static MidiInCollector::Ptr getOrCreateCollector (Win32MidiService& parentService, const String& deviceIdentifier)
  349. {
  350. UINT deviceID = MIDI_MAPPER;
  351. String deviceName;
  352. auto devices = getAvailableDevices();
  353. for (int i = 0; i < devices.size(); ++i)
  354. {
  355. auto d = devices.getUnchecked (i);
  356. if (d.identifier == deviceIdentifier)
  357. {
  358. deviceID = (UINT) i;
  359. deviceName = d.name;
  360. break;
  361. }
  362. }
  363. const ScopedLock sl (parentService.activeCollectorLock);
  364. for (auto& c : parentService.activeCollectors)
  365. if (c->deviceInfo.identifier == deviceIdentifier)
  366. return c;
  367. MidiInCollector::Ptr c (new MidiInCollector (parentService, { deviceName, deviceIdentifier }));
  368. HMIDIIN h;
  369. auto err = midiInOpen (&h, deviceID,
  370. (DWORD_PTR) &MidiInCollector::midiInCallback,
  371. (DWORD_PTR) (MidiInCollector*) c.get(),
  372. CALLBACK_FUNCTION);
  373. if (err != MMSYSERR_NOERROR)
  374. throw std::runtime_error ("Failed to create Windows input device wrapper");
  375. c->deviceHandle = h;
  376. parentService.activeCollectors.add (c);
  377. return c;
  378. }
  379. static DWORD sendMidiMessage (UINT_PTR deviceID, UINT msg, DWORD_PTR arg1, DWORD_PTR arg2)
  380. {
  381. return midiInMessage ((HMIDIIN) deviceID, msg, arg1, arg2);
  382. }
  383. static Array<MIDIINCAPS> getDeviceCaps()
  384. {
  385. Array<MIDIINCAPS> devices;
  386. for (UINT i = 0; i < midiInGetNumDevs(); ++i)
  387. {
  388. MIDIINCAPS mc = {};
  389. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  390. devices.add (mc);
  391. }
  392. return devices;
  393. }
  394. static MidiDeviceInfo getDefaultDevice() { return getAvailableDevices().getFirst(); }
  395. void start() override { started = true; concatenator.reset(); collector->startOrStop(); }
  396. void stop() override { started = false; collector->startOrStop(); concatenator.reset(); }
  397. String getDeviceIdentifier() override { return collector->deviceInfo.identifier; }
  398. String getDeviceName() override { return collector->deviceInfo.name; }
  399. void pushMidiData (const void* inputData, int numBytes, double time)
  400. {
  401. concatenator.pushMidiData (inputData, numBytes, time, &input, callback);
  402. }
  403. MidiInput& input;
  404. MidiInputCallback& callback;
  405. MidiDataConcatenator concatenator { 4096 };
  406. MidiInCollector::Ptr collector;
  407. bool started = false;
  408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32InputWrapper)
  409. };
  410. //==============================================================================
  411. struct MidiOutHandle : public ReferenceCountedObject
  412. {
  413. using Ptr = ReferenceCountedObjectPtr<MidiOutHandle>;
  414. MidiOutHandle (Win32MidiService& parent, MidiDeviceInfo d, HMIDIOUT h)
  415. : owner (parent), deviceInfo (d), handle (h)
  416. {
  417. owner.activeOutputHandles.add (this);
  418. }
  419. ~MidiOutHandle()
  420. {
  421. if (handle != nullptr)
  422. midiOutClose (handle);
  423. owner.activeOutputHandles.removeFirstMatchingValue (this);
  424. }
  425. Win32MidiService& owner;
  426. MidiDeviceInfo deviceInfo;
  427. HMIDIOUT handle;
  428. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiOutHandle)
  429. };
  430. //==============================================================================
  431. struct Win32OutputWrapper : public MidiOutput::Pimpl,
  432. public Win32MidiDeviceQuery<Win32OutputWrapper>
  433. {
  434. Win32OutputWrapper (Win32MidiService& p, const String& deviceIdentifier)
  435. : parent (p)
  436. {
  437. auto devices = getAvailableDevices();
  438. UINT deviceID = MIDI_MAPPER;
  439. String deviceName;
  440. for (int i = 0; i < devices.size(); ++i)
  441. {
  442. auto d = devices.getUnchecked (i);
  443. if (d.identifier == deviceIdentifier)
  444. {
  445. deviceID = (UINT) i;
  446. deviceName = d.name;
  447. break;
  448. }
  449. }
  450. if (deviceID == MIDI_MAPPER)
  451. {
  452. // use the microsoft sw synth as a default - best not to allow deviceID
  453. // to be MIDI_MAPPER, or else device sharing breaks
  454. for (int i = 0; i < devices.size(); ++i)
  455. if (devices[i].name.containsIgnoreCase ("microsoft"))
  456. deviceID = (UINT) i;
  457. }
  458. for (int i = parent.activeOutputHandles.size(); --i >= 0;)
  459. {
  460. auto* activeHandle = parent.activeOutputHandles.getUnchecked (i);
  461. if (activeHandle->deviceInfo.identifier == deviceIdentifier)
  462. {
  463. han = activeHandle;
  464. return;
  465. }
  466. }
  467. for (int i = 4; --i >= 0;)
  468. {
  469. HMIDIOUT h = nullptr;
  470. auto res = midiOutOpen (&h, deviceID, 0, 0, CALLBACK_NULL);
  471. if (res == MMSYSERR_NOERROR)
  472. {
  473. han = new MidiOutHandle (parent, { deviceName, deviceIdentifier }, h);
  474. return;
  475. }
  476. if (res == MMSYSERR_ALLOCATED)
  477. Sleep (100);
  478. else
  479. break;
  480. }
  481. throw std::runtime_error ("Failed to create Windows output device wrapper");
  482. }
  483. void sendMessageNow (const MidiMessage& message) override
  484. {
  485. if (message.getRawDataSize() > 3 || message.isSysEx())
  486. {
  487. MIDIHDR h = {};
  488. h.lpData = (char*) message.getRawData();
  489. h.dwBytesRecorded = h.dwBufferLength = (DWORD) message.getRawDataSize();
  490. if (midiOutPrepareHeader (han->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  491. {
  492. auto res = midiOutLongMsg (han->handle, &h, sizeof (MIDIHDR));
  493. if (res == MMSYSERR_NOERROR)
  494. {
  495. while ((h.dwFlags & MHDR_DONE) == 0)
  496. Sleep (1);
  497. int count = 500; // 1 sec timeout
  498. while (--count >= 0)
  499. {
  500. res = midiOutUnprepareHeader (han->handle, &h, sizeof (MIDIHDR));
  501. if (res == MIDIERR_STILLPLAYING)
  502. Sleep (2);
  503. else
  504. break;
  505. }
  506. }
  507. }
  508. }
  509. else
  510. {
  511. for (int i = 0; i < 50; ++i)
  512. {
  513. if (midiOutShortMsg (han->handle, *unalignedPointerCast<const unsigned int*> (message.getRawData())) != MIDIERR_NOTREADY)
  514. break;
  515. Sleep (1);
  516. }
  517. }
  518. }
  519. static DWORD sendMidiMessage (UINT_PTR deviceID, UINT msg, DWORD_PTR arg1, DWORD_PTR arg2)
  520. {
  521. return midiOutMessage ((HMIDIOUT) deviceID, msg, arg1, arg2);
  522. }
  523. static Array<MIDIOUTCAPS> getDeviceCaps()
  524. {
  525. Array<MIDIOUTCAPS> devices;
  526. for (UINT i = 0; i < midiOutGetNumDevs(); ++i)
  527. {
  528. MIDIOUTCAPS mc = {};
  529. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  530. devices.add (mc);
  531. }
  532. return devices;
  533. }
  534. static MidiDeviceInfo getDefaultDevice()
  535. {
  536. auto defaultIndex = []()
  537. {
  538. auto deviceCaps = getDeviceCaps();
  539. for (int i = 0; i < deviceCaps.size(); ++i)
  540. if ((deviceCaps[i].wTechnology & MOD_MAPPER) != 0)
  541. return i;
  542. return 0;
  543. }();
  544. return getAvailableDevices()[defaultIndex];
  545. }
  546. String getDeviceIdentifier() override { return han->deviceInfo.identifier; }
  547. String getDeviceName() override { return han->deviceInfo.name; }
  548. Win32MidiService& parent;
  549. MidiOutHandle::Ptr han;
  550. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Win32OutputWrapper)
  551. };
  552. //==============================================================================
  553. void asyncCheckForUnusedCollectors()
  554. {
  555. startTimer (10);
  556. }
  557. void timerCallback() override
  558. {
  559. stopTimer();
  560. const ScopedLock sl (activeCollectorLock);
  561. for (int i = activeCollectors.size(); --i >= 0;)
  562. if (activeCollectors.getObjectPointer(i)->getReferenceCount() == 1)
  563. activeCollectors.remove (i);
  564. }
  565. CriticalSection activeCollectorLock;
  566. ReferenceCountedArray<MidiInCollector> activeCollectors;
  567. Array<MidiOutHandle*> activeOutputHandles;
  568. };
  569. Array<Win32MidiService::MidiInCollector*, CriticalSection> Win32MidiService::MidiInCollector::activeMidiCollectors;
  570. //==============================================================================
  571. //==============================================================================
  572. #if JUCE_USE_WINRT_MIDI
  573. #ifndef JUCE_FORCE_WINRT_MIDI
  574. #define JUCE_FORCE_WINRT_MIDI 0
  575. #endif
  576. #ifndef JUCE_WINRT_MIDI_LOGGING
  577. #define JUCE_WINRT_MIDI_LOGGING 0
  578. #endif
  579. #if JUCE_WINRT_MIDI_LOGGING
  580. #define JUCE_WINRT_MIDI_LOG(x) DBG(x)
  581. #else
  582. #define JUCE_WINRT_MIDI_LOG(x)
  583. #endif
  584. using namespace Microsoft::WRL;
  585. using namespace ABI::Windows::Foundation;
  586. using namespace ABI::Windows::Foundation::Collections;
  587. using namespace ABI::Windows::Devices::Midi;
  588. using namespace ABI::Windows::Devices::Enumeration;
  589. using namespace ABI::Windows::Storage::Streams;
  590. //==============================================================================
  591. struct WinRTMidiService : public MidiServiceType
  592. {
  593. public:
  594. //==============================================================================
  595. WinRTMidiService()
  596. {
  597. auto* wrtWrapper = WinRTWrapper::getInstance();
  598. if (! wrtWrapper->isInitialised())
  599. throw std::runtime_error ("Failed to initialise the WinRT wrapper");
  600. midiInFactory = wrtWrapper->getWRLFactory<IMidiInPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiInPort[0]);
  601. if (midiInFactory == nullptr)
  602. throw std::runtime_error ("Failed to create midi in factory");
  603. midiOutFactory = wrtWrapper->getWRLFactory<IMidiOutPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiOutPort[0]);
  604. if (midiOutFactory == nullptr)
  605. throw std::runtime_error ("Failed to create midi out factory");
  606. // The WinRT BLE MIDI API doesn't provide callbacks when devices become disconnected,
  607. // but it does require a disconnection via the API before a device will reconnect again.
  608. // We can monitor the BLE connection state of paired devices to get callbacks when
  609. // connections are broken.
  610. bleDeviceWatcher.reset (new BLEDeviceWatcher());
  611. if (! bleDeviceWatcher->start())
  612. throw std::runtime_error ("Failed to start the BLE device watcher");
  613. inputDeviceWatcher.reset (new MidiIODeviceWatcher<IMidiInPortStatics> (midiInFactory));
  614. if (! inputDeviceWatcher->start())
  615. throw std::runtime_error ("Failed to start the midi input device watcher");
  616. outputDeviceWatcher.reset (new MidiIODeviceWatcher<IMidiOutPortStatics> (midiOutFactory));
  617. if (! outputDeviceWatcher->start())
  618. throw std::runtime_error ("Failed to start the midi output device watcher");
  619. }
  620. Array<MidiDeviceInfo> getAvailableDevices (bool isInput) override
  621. {
  622. return isInput ? inputDeviceWatcher ->getAvailableDevices()
  623. : outputDeviceWatcher->getAvailableDevices();
  624. }
  625. MidiDeviceInfo getDefaultDevice (bool isInput) override
  626. {
  627. return isInput ? inputDeviceWatcher ->getDefaultDevice()
  628. : outputDeviceWatcher->getDefaultDevice();
  629. }
  630. MidiInput::Pimpl* createInputWrapper (MidiInput& input, const String& deviceIdentifier, MidiInputCallback& callback) override
  631. {
  632. return new WinRTInputWrapper (*this, input, deviceIdentifier, callback);
  633. }
  634. MidiOutput::Pimpl* createOutputWrapper (const String& deviceIdentifier) override
  635. {
  636. return new WinRTOutputWrapper (*this, deviceIdentifier);
  637. }
  638. private:
  639. //==============================================================================
  640. class DeviceCallbackHandler
  641. {
  642. public:
  643. virtual ~DeviceCallbackHandler() {};
  644. JUCE_COMCALL addDevice (IDeviceInformation*) = 0;
  645. JUCE_COMCALL removeDevice (IDeviceInformationUpdate*) = 0;
  646. JUCE_COMCALL updateDevice (IDeviceInformationUpdate*) = 0;
  647. bool attach (HSTRING deviceSelector, DeviceInformationKind infoKind)
  648. {
  649. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  650. if (wrtWrapper == nullptr)
  651. {
  652. JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!");
  653. return false;
  654. }
  655. auto deviceInfoFactory = wrtWrapper->getWRLFactory<IDeviceInformationStatics2> (&RuntimeClass_Windows_Devices_Enumeration_DeviceInformation[0]);
  656. if (deviceInfoFactory == nullptr)
  657. return false;
  658. // A quick way of getting an IVector<HSTRING>...
  659. auto requestedProperties = [wrtWrapper]
  660. {
  661. auto devicePicker = wrtWrapper->activateInstance<IDevicePicker> (&RuntimeClass_Windows_Devices_Enumeration_DevicePicker[0],
  662. __uuidof (IDevicePicker));
  663. jassert (devicePicker != nullptr);
  664. IVector<HSTRING>* result;
  665. auto hr = devicePicker->get_RequestedProperties (&result);
  666. jassert (SUCCEEDED (hr));
  667. hr = result->Clear();
  668. jassert (SUCCEEDED (hr));
  669. return result;
  670. }();
  671. StringArray propertyKeys ("System.Devices.ContainerId",
  672. "System.Devices.Aep.ContainerId",
  673. "System.Devices.Aep.IsConnected");
  674. for (auto& key : propertyKeys)
  675. {
  676. WinRTWrapper::ScopedHString hstr (key);
  677. auto hr = requestedProperties->Append (hstr.get());
  678. if (FAILED (hr))
  679. {
  680. jassertfalse;
  681. return false;
  682. }
  683. }
  684. ComSmartPtr<IIterable<HSTRING>> iter;
  685. auto hr = requestedProperties->QueryInterface (__uuidof (IIterable<HSTRING>), (void**) iter.resetAndGetPointerAddress());
  686. if (FAILED (hr))
  687. {
  688. jassertfalse;
  689. return false;
  690. }
  691. hr = deviceInfoFactory->CreateWatcherWithKindAqsFilterAndAdditionalProperties (deviceSelector, iter, infoKind,
  692. watcher.resetAndGetPointerAddress());
  693. if (FAILED (hr))
  694. {
  695. jassertfalse;
  696. return false;
  697. }
  698. enumerationThread.startThread();
  699. return true;
  700. };
  701. void detach()
  702. {
  703. enumerationThread.stopThread (2000);
  704. if (watcher == nullptr)
  705. return;
  706. auto hr = watcher->Stop();
  707. jassert (SUCCEEDED (hr));
  708. if (deviceAddedToken.value != 0)
  709. {
  710. hr = watcher->remove_Added (deviceAddedToken);
  711. jassert (SUCCEEDED (hr));
  712. deviceAddedToken.value = 0;
  713. }
  714. if (deviceUpdatedToken.value != 0)
  715. {
  716. hr = watcher->remove_Updated (deviceUpdatedToken);
  717. jassert (SUCCEEDED (hr));
  718. deviceUpdatedToken.value = 0;
  719. }
  720. if (deviceRemovedToken.value != 0)
  721. {
  722. hr = watcher->remove_Removed (deviceRemovedToken);
  723. jassert (SUCCEEDED (hr));
  724. deviceRemovedToken.value = 0;
  725. }
  726. watcher = nullptr;
  727. }
  728. template <typename InfoType>
  729. IInspectable* getValueFromDeviceInfo (String key, InfoType* info)
  730. {
  731. __FIMapView_2_HSTRING_IInspectable* properties;
  732. info->get_Properties (&properties);
  733. boolean found = false;
  734. WinRTWrapper::ScopedHString keyHstr (key);
  735. auto hr = properties->HasKey (keyHstr.get(), &found);
  736. if (FAILED (hr))
  737. {
  738. jassertfalse;
  739. return nullptr;
  740. }
  741. if (! found)
  742. return nullptr;
  743. IInspectable* inspectable;
  744. hr = properties->Lookup (keyHstr.get(), &inspectable);
  745. if (FAILED (hr))
  746. {
  747. jassertfalse;
  748. return nullptr;
  749. }
  750. return inspectable;
  751. }
  752. String getGUIDFromInspectable (IInspectable& inspectable)
  753. {
  754. ComSmartPtr<IReference<GUID>> guidRef;
  755. auto hr = inspectable.QueryInterface (__uuidof (IReference<GUID>),
  756. (void**) guidRef.resetAndGetPointerAddress());
  757. if (FAILED (hr))
  758. {
  759. jassertfalse;
  760. return {};
  761. }
  762. GUID result;
  763. hr = guidRef->get_Value (&result);
  764. if (FAILED (hr))
  765. {
  766. jassertfalse;
  767. return {};
  768. }
  769. OLECHAR* resultString;
  770. StringFromCLSID (result, &resultString);
  771. return resultString;
  772. }
  773. bool getBoolFromInspectable (IInspectable& inspectable)
  774. {
  775. ComSmartPtr<IReference<bool>> boolRef;
  776. auto hr = inspectable.QueryInterface (__uuidof (IReference<bool>),
  777. (void**) boolRef.resetAndGetPointerAddress());
  778. if (FAILED (hr))
  779. {
  780. jassertfalse;
  781. return false;
  782. }
  783. boolean result;
  784. hr = boolRef->get_Value (&result);
  785. if (FAILED (hr))
  786. {
  787. jassertfalse;
  788. return false;
  789. }
  790. return result;
  791. }
  792. private:
  793. //==============================================================================
  794. struct DeviceEnumerationThread : public Thread
  795. {
  796. DeviceEnumerationThread (DeviceCallbackHandler& h,
  797. ComSmartPtr<IDeviceWatcher>& w,
  798. EventRegistrationToken& added,
  799. EventRegistrationToken& removed,
  800. EventRegistrationToken& updated)
  801. : Thread ("WinRT Device Enumeration Thread"), handler (h), watcher (w),
  802. deviceAddedToken (added), deviceRemovedToken (removed), deviceUpdatedToken (updated)
  803. {}
  804. void run() override
  805. {
  806. auto handlerPtr = std::addressof (handler);
  807. watcher->add_Added (
  808. Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformation*>> (
  809. [handlerPtr] (IDeviceWatcher*, IDeviceInformation* info) { return handlerPtr->addDevice (info); }
  810. ).Get(),
  811. &deviceAddedToken);
  812. watcher->add_Removed (
  813. Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>> (
  814. [handlerPtr] (IDeviceWatcher*, IDeviceInformationUpdate* infoUpdate) { return handlerPtr->removeDevice (infoUpdate); }
  815. ).Get(),
  816. &deviceRemovedToken);
  817. watcher->add_Updated (
  818. Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>> (
  819. [handlerPtr] (IDeviceWatcher*, IDeviceInformationUpdate* infoUpdate) { return handlerPtr->updateDevice (infoUpdate); }
  820. ).Get(),
  821. &deviceUpdatedToken);
  822. watcher->Start();
  823. }
  824. DeviceCallbackHandler& handler;
  825. ComSmartPtr<IDeviceWatcher>& watcher;
  826. EventRegistrationToken& deviceAddedToken, deviceRemovedToken, deviceUpdatedToken;
  827. };
  828. //==============================================================================
  829. ComSmartPtr<IDeviceWatcher> watcher;
  830. EventRegistrationToken deviceAddedToken { 0 },
  831. deviceRemovedToken { 0 },
  832. deviceUpdatedToken { 0 };
  833. DeviceEnumerationThread enumerationThread { *this, watcher,
  834. deviceAddedToken,
  835. deviceRemovedToken,
  836. deviceUpdatedToken };
  837. };
  838. //==============================================================================
  839. struct BLEDeviceWatcher final : private DeviceCallbackHandler
  840. {
  841. struct DeviceInfo
  842. {
  843. String containerID;
  844. bool isConnected = false;
  845. };
  846. BLEDeviceWatcher() = default;
  847. ~BLEDeviceWatcher()
  848. {
  849. detach();
  850. }
  851. //==============================================================================
  852. HRESULT addDevice (IDeviceInformation* addedDeviceInfo) override
  853. {
  854. HSTRING deviceIDHst;
  855. auto hr = addedDeviceInfo->get_Id (&deviceIDHst);
  856. if (FAILED (hr))
  857. {
  858. JUCE_WINRT_MIDI_LOG ("Failed to query added BLE device ID!");
  859. return S_OK;
  860. }
  861. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  862. if (wrtWrapper == nullptr)
  863. {
  864. JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!");
  865. return false;
  866. }
  867. auto deviceID = wrtWrapper->hStringToString (deviceIDHst);
  868. JUCE_WINRT_MIDI_LOG ("Detected paired BLE device: " << deviceID);
  869. if (auto* containerIDValue = getValueFromDeviceInfo ("System.Devices.Aep.ContainerId", addedDeviceInfo))
  870. {
  871. auto containerID = getGUIDFromInspectable (*containerIDValue);
  872. if (containerID.isNotEmpty())
  873. {
  874. DeviceInfo info = { containerID };
  875. if (auto* connectedValue = getValueFromDeviceInfo ("System.Devices.Aep.IsConnected", addedDeviceInfo))
  876. info.isConnected = getBoolFromInspectable (*connectedValue);
  877. JUCE_WINRT_MIDI_LOG ("Adding BLE device: " << deviceID << " " << info.containerID
  878. << " " << (info.isConnected ? "connected" : "disconnected"));
  879. devices.set (deviceID, info);
  880. return S_OK;
  881. }
  882. }
  883. JUCE_WINRT_MIDI_LOG ("Failed to get a container ID for BLE device: " << deviceID);
  884. return S_OK;
  885. }
  886. HRESULT removeDevice (IDeviceInformationUpdate* removedDeviceInfo) override
  887. {
  888. HSTRING removedDeviceIdHstr;
  889. auto hr = removedDeviceInfo->get_Id (&removedDeviceIdHstr);
  890. if (FAILED (hr))
  891. {
  892. JUCE_WINRT_MIDI_LOG ("Failed to query removed BLE device ID!");
  893. return S_OK;
  894. }
  895. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  896. if (wrtWrapper == nullptr)
  897. {
  898. JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!");
  899. return false;
  900. }
  901. auto removedDeviceId = wrtWrapper->hStringToString (removedDeviceIdHstr);
  902. JUCE_WINRT_MIDI_LOG ("Removing BLE device: " << removedDeviceId);
  903. {
  904. const ScopedLock lock (deviceChanges);
  905. if (devices.contains (removedDeviceId))
  906. {
  907. auto& info = devices.getReference (removedDeviceId);
  908. listeners.call ([&info] (Listener& l) { l.bleDeviceDisconnected (info.containerID); });
  909. devices.remove (removedDeviceId);
  910. JUCE_WINRT_MIDI_LOG ("Removed BLE device: " << removedDeviceId);
  911. }
  912. }
  913. return S_OK;
  914. }
  915. HRESULT updateDevice (IDeviceInformationUpdate* updatedDeviceInfo) override
  916. {
  917. HSTRING updatedDeviceIdHstr;
  918. auto hr = updatedDeviceInfo->get_Id (&updatedDeviceIdHstr);
  919. if (FAILED (hr))
  920. {
  921. JUCE_WINRT_MIDI_LOG ("Failed to query updated BLE device ID!");
  922. return S_OK;
  923. }
  924. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  925. if (wrtWrapper == nullptr)
  926. {
  927. JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!");
  928. return false;
  929. }
  930. auto updatedDeviceId = wrtWrapper->hStringToString (updatedDeviceIdHstr);
  931. JUCE_WINRT_MIDI_LOG ("Updating BLE device: " << updatedDeviceId);
  932. if (auto* connectedValue = getValueFromDeviceInfo ("System.Devices.Aep.IsConnected", updatedDeviceInfo))
  933. {
  934. auto isConnected = getBoolFromInspectable (*connectedValue);
  935. {
  936. const ScopedLock lock (deviceChanges);
  937. if (! devices.contains (updatedDeviceId))
  938. return S_OK;
  939. auto& info = devices.getReference (updatedDeviceId);
  940. if (info.isConnected && ! isConnected)
  941. {
  942. JUCE_WINRT_MIDI_LOG ("BLE device connection status change: " << updatedDeviceId << " " << info.containerID << " " << (isConnected ? "connected" : "disconnected"));
  943. listeners.call ([&info] (Listener& l) { l.bleDeviceDisconnected (info.containerID); });
  944. }
  945. info.isConnected = isConnected;
  946. }
  947. }
  948. return S_OK;
  949. }
  950. //==============================================================================
  951. bool start()
  952. {
  953. WinRTWrapper::ScopedHString deviceSelector ("System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\""
  954. " AND System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True");
  955. return attach (deviceSelector.get(), DeviceInformationKind::DeviceInformationKind_AssociationEndpoint);
  956. }
  957. //==============================================================================
  958. struct Listener
  959. {
  960. virtual ~Listener() {};
  961. virtual void bleDeviceAdded (const String& containerID) = 0;
  962. virtual void bleDeviceDisconnected (const String& containerID) = 0;
  963. };
  964. void addListener (Listener* l)
  965. {
  966. listeners.add (l);
  967. }
  968. void removeListener (Listener* l)
  969. {
  970. listeners.remove (l);
  971. }
  972. //==============================================================================
  973. ListenerList<Listener> listeners;
  974. HashMap<String, DeviceInfo> devices;
  975. CriticalSection deviceChanges;
  976. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BLEDeviceWatcher);
  977. };
  978. //==============================================================================
  979. struct WinRTMIDIDeviceInfo
  980. {
  981. String deviceID, containerID, name;
  982. bool isDefault = false;
  983. };
  984. //==============================================================================
  985. template <typename COMFactoryType>
  986. struct MidiIODeviceWatcher final : private DeviceCallbackHandler
  987. {
  988. MidiIODeviceWatcher (ComSmartPtr<COMFactoryType>& comFactory)
  989. : factory (comFactory)
  990. {
  991. }
  992. ~MidiIODeviceWatcher()
  993. {
  994. detach();
  995. }
  996. HRESULT addDevice (IDeviceInformation* addedDeviceInfo) override
  997. {
  998. WinRTMIDIDeviceInfo info;
  999. HSTRING deviceID;
  1000. auto hr = addedDeviceInfo->get_Id (&deviceID);
  1001. if (FAILED (hr))
  1002. {
  1003. JUCE_WINRT_MIDI_LOG ("Failed to query added MIDI device ID!");
  1004. return S_OK;
  1005. }
  1006. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  1007. if (wrtWrapper == nullptr)
  1008. {
  1009. JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!");
  1010. return false;
  1011. }
  1012. info.deviceID = wrtWrapper->hStringToString (deviceID);
  1013. JUCE_WINRT_MIDI_LOG ("Detected MIDI device: " << info.deviceID);
  1014. boolean isEnabled = false;
  1015. hr = addedDeviceInfo->get_IsEnabled (&isEnabled);
  1016. if (FAILED (hr) || ! isEnabled)
  1017. {
  1018. JUCE_WINRT_MIDI_LOG ("MIDI device not enabled: " << info.deviceID);
  1019. return S_OK;
  1020. }
  1021. // We use the container ID to match a MIDI device with a generic BLE device, if possible
  1022. if (auto* containerIDValue = getValueFromDeviceInfo ("System.Devices.ContainerId", addedDeviceInfo))
  1023. info.containerID = getGUIDFromInspectable (*containerIDValue);
  1024. HSTRING name;
  1025. hr = addedDeviceInfo->get_Name (&name);
  1026. if (FAILED (hr))
  1027. {
  1028. JUCE_WINRT_MIDI_LOG ("Failed to query detected MIDI device name for " << info.deviceID);
  1029. return S_OK;
  1030. }
  1031. info.name = wrtWrapper->hStringToString (name);
  1032. boolean isDefault = false;
  1033. hr = addedDeviceInfo->get_IsDefault (&isDefault);
  1034. if (FAILED (hr))
  1035. {
  1036. JUCE_WINRT_MIDI_LOG ("Failed to query detected MIDI device defaultness for " << info.deviceID << " " << info.name);
  1037. return S_OK;
  1038. }
  1039. info.isDefault = isDefault;
  1040. JUCE_WINRT_MIDI_LOG ("Adding MIDI device: " << info.deviceID << " " << info.containerID << " " << info.name);
  1041. {
  1042. const ScopedLock lock (deviceChanges);
  1043. connectedDevices.add (info);
  1044. }
  1045. return S_OK;
  1046. }
  1047. HRESULT removeDevice (IDeviceInformationUpdate* removedDeviceInfo) override
  1048. {
  1049. HSTRING removedDeviceIdHstr;
  1050. auto hr = removedDeviceInfo->get_Id (&removedDeviceIdHstr);
  1051. if (FAILED (hr))
  1052. {
  1053. JUCE_WINRT_MIDI_LOG ("Failed to query removed MIDI device ID!");
  1054. return S_OK;
  1055. }
  1056. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  1057. if (wrtWrapper == nullptr)
  1058. {
  1059. JUCE_WINRT_MIDI_LOG ("Failed to get the WinRTWrapper singleton!");
  1060. return false;
  1061. }
  1062. auto removedDeviceId = wrtWrapper->hStringToString (removedDeviceIdHstr);
  1063. JUCE_WINRT_MIDI_LOG ("Removing MIDI device: " << removedDeviceId);
  1064. {
  1065. const ScopedLock lock (deviceChanges);
  1066. for (int i = 0; i < connectedDevices.size(); ++i)
  1067. {
  1068. if (connectedDevices[i].deviceID == removedDeviceId)
  1069. {
  1070. connectedDevices.remove (i);
  1071. JUCE_WINRT_MIDI_LOG ("Removed MIDI device: " << removedDeviceId);
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. return S_OK;
  1077. }
  1078. // This is never called
  1079. HRESULT updateDevice (IDeviceInformationUpdate*) override { return S_OK; }
  1080. bool start()
  1081. {
  1082. HSTRING deviceSelector;
  1083. auto hr = factory->GetDeviceSelector (&deviceSelector);
  1084. if (FAILED (hr))
  1085. {
  1086. JUCE_WINRT_MIDI_LOG ("Failed to get MIDI device selector!");
  1087. return false;
  1088. }
  1089. return attach (deviceSelector, DeviceInformationKind::DeviceInformationKind_DeviceInterface);
  1090. }
  1091. Array<MidiDeviceInfo> getAvailableDevices()
  1092. {
  1093. {
  1094. const ScopedLock lock (deviceChanges);
  1095. lastQueriedConnectedDevices = connectedDevices;
  1096. }
  1097. StringArray deviceNames, deviceIDs;
  1098. for (auto info : lastQueriedConnectedDevices.get())
  1099. {
  1100. deviceNames.add (info.name);
  1101. deviceIDs .add (info.containerID);
  1102. }
  1103. deviceNames.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
  1104. deviceIDs .appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
  1105. Array<MidiDeviceInfo> devices;
  1106. for (int i = 0; i < deviceNames.size(); ++i)
  1107. devices.add ({ deviceNames[i], deviceIDs[i] });
  1108. return devices;
  1109. }
  1110. MidiDeviceInfo getDefaultDevice()
  1111. {
  1112. auto& lastDevices = lastQueriedConnectedDevices.get();
  1113. for (auto& d : lastDevices)
  1114. if (d.isDefault)
  1115. return { d.name, d.containerID };
  1116. return {};
  1117. }
  1118. WinRTMIDIDeviceInfo getWinRTDeviceInfoForDevice (const String& deviceIdentifier)
  1119. {
  1120. auto devices = getAvailableDevices();
  1121. for (int i = 0; i < devices.size(); ++i)
  1122. if (devices.getUnchecked (i).identifier == deviceIdentifier)
  1123. return lastQueriedConnectedDevices.get()[i];
  1124. return {};
  1125. }
  1126. ComSmartPtr<COMFactoryType>& factory;
  1127. Array<WinRTMIDIDeviceInfo> connectedDevices;
  1128. CriticalSection deviceChanges;
  1129. ThreadLocalValue<Array<WinRTMIDIDeviceInfo>> lastQueriedConnectedDevices;
  1130. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiIODeviceWatcher);
  1131. };
  1132. //==============================================================================
  1133. template <typename COMType, typename COMFactoryType, typename COMInterfaceType>
  1134. static void openMidiPortThread (String threadName,
  1135. String midiDeviceID,
  1136. ComSmartPtr<COMFactoryType>& comFactory,
  1137. ComSmartPtr<COMInterfaceType>& comPort)
  1138. {
  1139. std::thread { [&]
  1140. {
  1141. Thread::setCurrentThreadName (threadName);
  1142. const WinRTWrapper::ScopedHString hDeviceId { midiDeviceID };
  1143. ComSmartPtr<IAsyncOperation<COMType*>> asyncOp;
  1144. const auto hr = comFactory->FromIdAsync (hDeviceId.get(), asyncOp.resetAndGetPointerAddress());
  1145. if (FAILED (hr))
  1146. return;
  1147. std::promise<ComSmartPtr<COMInterfaceType>> promise;
  1148. auto future = promise.get_future();
  1149. auto callback = [p = std::move (promise)] (IAsyncOperation<COMType*>* asyncOpPtr, AsyncStatus) mutable
  1150. {
  1151. if (asyncOpPtr == nullptr)
  1152. {
  1153. p.set_value (nullptr);
  1154. return E_ABORT;
  1155. }
  1156. ComSmartPtr<COMInterfaceType> result;
  1157. const auto hr = asyncOpPtr->GetResults (result.resetAndGetPointerAddress());
  1158. if (FAILED (hr))
  1159. {
  1160. p.set_value (nullptr);
  1161. return hr;
  1162. }
  1163. p.set_value (std::move (result));
  1164. return S_OK;
  1165. };
  1166. const auto ir = asyncOp->put_Completed (Callback<IAsyncOperationCompletedHandler<COMType*>> (std::move (callback)).Get());
  1167. if (FAILED (ir))
  1168. return;
  1169. if (future.wait_for (std::chrono::milliseconds (2000)) == std::future_status::ready)
  1170. comPort = future.get();
  1171. } }.join();
  1172. }
  1173. //==============================================================================
  1174. template <typename MIDIIOStaticsType, typename MIDIPort>
  1175. class WinRTIOWrapper : private BLEDeviceWatcher::Listener
  1176. {
  1177. public:
  1178. WinRTIOWrapper (BLEDeviceWatcher& bleWatcher,
  1179. MidiIODeviceWatcher<MIDIIOStaticsType>& midiDeviceWatcher,
  1180. const String& deviceIdentifier)
  1181. : bleDeviceWatcher (bleWatcher)
  1182. {
  1183. {
  1184. const ScopedLock lock (midiDeviceWatcher.deviceChanges);
  1185. deviceInfo = midiDeviceWatcher.getWinRTDeviceInfoForDevice (deviceIdentifier);
  1186. }
  1187. if (deviceInfo.deviceID.isEmpty())
  1188. throw std::runtime_error ("Invalid device index");
  1189. JUCE_WINRT_MIDI_LOG ("Creating JUCE MIDI IO: " << deviceInfo.deviceID);
  1190. if (deviceInfo.containerID.isNotEmpty())
  1191. {
  1192. bleDeviceWatcher.addListener (this);
  1193. const ScopedLock lock (bleDeviceWatcher.deviceChanges);
  1194. HashMap<String, BLEDeviceWatcher::DeviceInfo>::Iterator iter (bleDeviceWatcher.devices);
  1195. while (iter.next())
  1196. {
  1197. if (iter.getValue().containerID == deviceInfo.containerID)
  1198. {
  1199. isBLEDevice = true;
  1200. break;
  1201. }
  1202. }
  1203. }
  1204. }
  1205. virtual ~WinRTIOWrapper()
  1206. {
  1207. bleDeviceWatcher.removeListener (this);
  1208. disconnect();
  1209. }
  1210. //==============================================================================
  1211. virtual void disconnect()
  1212. {
  1213. if (midiPort != nullptr)
  1214. {
  1215. if (isBLEDevice)
  1216. midiPort->Release();
  1217. }
  1218. midiPort = nullptr;
  1219. }
  1220. private:
  1221. //==============================================================================
  1222. void bleDeviceAdded (const String& containerID) override
  1223. {
  1224. if (containerID == deviceInfo.containerID)
  1225. isBLEDevice = true;
  1226. }
  1227. void bleDeviceDisconnected (const String& containerID) override
  1228. {
  1229. if (containerID == deviceInfo.containerID)
  1230. {
  1231. JUCE_WINRT_MIDI_LOG ("Disconnecting MIDI port from BLE disconnection: " << deviceInfo.deviceID
  1232. << " " << deviceInfo.containerID << " " << deviceInfo.name);
  1233. disconnect();
  1234. }
  1235. }
  1236. protected:
  1237. //==============================================================================
  1238. BLEDeviceWatcher& bleDeviceWatcher;
  1239. WinRTMIDIDeviceInfo deviceInfo;
  1240. bool isBLEDevice = false;
  1241. ComSmartPtr<MIDIPort> midiPort;
  1242. };
  1243. //==============================================================================
  1244. struct WinRTInputWrapper final : public MidiInput::Pimpl,
  1245. private WinRTIOWrapper<IMidiInPortStatics, IMidiInPort>
  1246. {
  1247. WinRTInputWrapper (WinRTMidiService& service, MidiInput& input, const String& deviceIdentifier, MidiInputCallback& cb)
  1248. : WinRTIOWrapper <IMidiInPortStatics, IMidiInPort> (*service.bleDeviceWatcher, *service.inputDeviceWatcher, deviceIdentifier),
  1249. inputDevice (input),
  1250. callback (cb)
  1251. {
  1252. openMidiPortThread<MidiInPort> ("Open WinRT MIDI input port", deviceInfo.deviceID, service.midiInFactory, midiPort);
  1253. if (midiPort == nullptr)
  1254. {
  1255. JUCE_WINRT_MIDI_LOG ("Timed out waiting for midi input port creation");
  1256. return;
  1257. }
  1258. startTime = Time::getMillisecondCounterHiRes();
  1259. auto hr = midiPort->add_MessageReceived (
  1260. Callback<ITypedEventHandler<MidiInPort*, MidiMessageReceivedEventArgs*>> (
  1261. [self = checkedReference] (IMidiInPort*, IMidiMessageReceivedEventArgs* args)
  1262. {
  1263. HRESULT hr = S_OK;
  1264. self->access ([&hr, args] (auto* ptr)
  1265. {
  1266. if (ptr != nullptr)
  1267. hr = ptr->midiInMessageReceived (args);
  1268. });
  1269. return hr;
  1270. }
  1271. ).Get(),
  1272. &midiInMessageToken);
  1273. if (FAILED (hr))
  1274. {
  1275. JUCE_WINRT_MIDI_LOG ("Failed to set MIDI input callback");
  1276. jassertfalse;
  1277. }
  1278. }
  1279. ~WinRTInputWrapper()
  1280. {
  1281. checkedReference->clear();
  1282. disconnect();
  1283. }
  1284. //==============================================================================
  1285. void start() override
  1286. {
  1287. if (! isStarted)
  1288. {
  1289. concatenator.reset();
  1290. isStarted = true;
  1291. }
  1292. }
  1293. void stop() override
  1294. {
  1295. if (isStarted)
  1296. {
  1297. isStarted = false;
  1298. concatenator.reset();
  1299. }
  1300. }
  1301. String getDeviceIdentifier() override { return deviceInfo.containerID; }
  1302. String getDeviceName() override { return deviceInfo.name; }
  1303. //==============================================================================
  1304. void disconnect() override
  1305. {
  1306. stop();
  1307. if (midiPort != nullptr && midiInMessageToken.value != 0)
  1308. midiPort->remove_MessageReceived (midiInMessageToken);
  1309. WinRTIOWrapper<IMidiInPortStatics, IMidiInPort>::disconnect();
  1310. }
  1311. //==============================================================================
  1312. HRESULT midiInMessageReceived (IMidiMessageReceivedEventArgs* args)
  1313. {
  1314. if (! isStarted)
  1315. return S_OK;
  1316. ComSmartPtr<IMidiMessage> message;
  1317. auto hr = args->get_Message (message.resetAndGetPointerAddress());
  1318. if (FAILED (hr))
  1319. return hr;
  1320. ComSmartPtr<IBuffer> buffer;
  1321. hr = message->get_RawData (buffer.resetAndGetPointerAddress());
  1322. if (FAILED (hr))
  1323. return hr;
  1324. ComSmartPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
  1325. hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress());
  1326. if (FAILED (hr))
  1327. return hr;
  1328. uint8_t* bufferData = nullptr;
  1329. hr = bufferByteAccess->Buffer (&bufferData);
  1330. if (FAILED (hr))
  1331. return hr;
  1332. uint32_t numBytes = 0;
  1333. hr = buffer->get_Length (&numBytes);
  1334. if (FAILED (hr))
  1335. return hr;
  1336. ABI::Windows::Foundation::TimeSpan timespan;
  1337. hr = message->get_Timestamp (&timespan);
  1338. if (FAILED (hr))
  1339. return hr;
  1340. concatenator.pushMidiData (bufferData, numBytes,
  1341. convertTimeStamp (timespan.Duration),
  1342. &inputDevice, callback);
  1343. return S_OK;
  1344. }
  1345. double convertTimeStamp (int64 timestamp)
  1346. {
  1347. auto millisecondsSinceStart = static_cast<double> (timestamp) / 10000.0;
  1348. auto t = startTime + millisecondsSinceStart;
  1349. auto now = Time::getMillisecondCounterHiRes();
  1350. if (t > now)
  1351. {
  1352. if (t > now + 2.0)
  1353. startTime -= 1.0;
  1354. t = now;
  1355. }
  1356. return t * 0.001;
  1357. }
  1358. //==============================================================================
  1359. MidiInput& inputDevice;
  1360. MidiInputCallback& callback;
  1361. MidiDataConcatenator concatenator { 4096 };
  1362. EventRegistrationToken midiInMessageToken { 0 };
  1363. double startTime = 0;
  1364. bool isStarted = false;
  1365. std::shared_ptr<CheckedReference<WinRTInputWrapper>> checkedReference = createCheckedReference (this);
  1366. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTInputWrapper);
  1367. };
  1368. //==============================================================================
  1369. struct WinRTOutputWrapper final : public MidiOutput::Pimpl,
  1370. private WinRTIOWrapper <IMidiOutPortStatics, IMidiOutPort>
  1371. {
  1372. WinRTOutputWrapper (WinRTMidiService& service, const String& deviceIdentifier)
  1373. : WinRTIOWrapper <IMidiOutPortStatics, IMidiOutPort> (*service.bleDeviceWatcher, *service.outputDeviceWatcher, deviceIdentifier)
  1374. {
  1375. openMidiPortThread<IMidiOutPort> ("Open WinRT MIDI output port", deviceInfo.deviceID, service.midiOutFactory, midiPort);
  1376. if (midiPort == nullptr)
  1377. throw std::runtime_error ("Timed out waiting for midi output port creation");
  1378. auto* wrtWrapper = WinRTWrapper::getInstanceWithoutCreating();
  1379. if (wrtWrapper == nullptr)
  1380. throw std::runtime_error ("Failed to get the WinRTWrapper singleton!");
  1381. auto bufferFactory = wrtWrapper->getWRLFactory<IBufferFactory> (&RuntimeClass_Windows_Storage_Streams_Buffer[0]);
  1382. if (bufferFactory == nullptr)
  1383. throw std::runtime_error ("Failed to create output buffer factory");
  1384. auto hr = bufferFactory->Create (static_cast<UINT32> (65536), buffer.resetAndGetPointerAddress());
  1385. if (FAILED (hr))
  1386. throw std::runtime_error ("Failed to create output buffer");
  1387. hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress());
  1388. if (FAILED (hr))
  1389. throw std::runtime_error ("Failed to get buffer byte access");
  1390. hr = bufferByteAccess->Buffer (&bufferData);
  1391. if (FAILED (hr))
  1392. throw std::runtime_error ("Failed to get buffer data pointer");
  1393. }
  1394. //==============================================================================
  1395. void sendMessageNow (const MidiMessage& message) override
  1396. {
  1397. if (midiPort == nullptr)
  1398. return;
  1399. auto numBytes = message.getRawDataSize();
  1400. auto hr = buffer->put_Length (numBytes);
  1401. if (FAILED (hr))
  1402. {
  1403. jassertfalse;
  1404. return;
  1405. }
  1406. memcpy_s (bufferData, numBytes, message.getRawData(), numBytes);
  1407. midiPort->SendBuffer (buffer);
  1408. }
  1409. String getDeviceIdentifier() override { return deviceInfo.containerID; }
  1410. String getDeviceName() override { return deviceInfo.name; }
  1411. //==============================================================================
  1412. ComSmartPtr<IBuffer> buffer;
  1413. ComSmartPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
  1414. uint8_t* bufferData = nullptr;
  1415. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTOutputWrapper);
  1416. };
  1417. ComSmartPtr<IMidiInPortStatics> midiInFactory;
  1418. ComSmartPtr<IMidiOutPortStatics> midiOutFactory;
  1419. std::unique_ptr<MidiIODeviceWatcher<IMidiInPortStatics>> inputDeviceWatcher;
  1420. std::unique_ptr<MidiIODeviceWatcher<IMidiOutPortStatics>> outputDeviceWatcher;
  1421. std::unique_ptr<BLEDeviceWatcher> bleDeviceWatcher;
  1422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTMidiService)
  1423. };
  1424. #endif // JUCE_USE_WINRT_MIDI
  1425. //==============================================================================
  1426. //==============================================================================
  1427. #if ! JUCE_MINGW
  1428. extern RTL_OSVERSIONINFOW getWindowsVersionInfo();
  1429. #endif
  1430. struct MidiService : public DeletedAtShutdown
  1431. {
  1432. MidiService()
  1433. {
  1434. #if JUCE_USE_WINRT_MIDI && ! JUCE_MINGW
  1435. #if ! JUCE_FORCE_WINRT_MIDI
  1436. auto windowsVersionInfo = getWindowsVersionInfo();
  1437. if (windowsVersionInfo.dwMajorVersion >= 10 && windowsVersionInfo.dwBuildNumber >= 17763)
  1438. #endif
  1439. {
  1440. try
  1441. {
  1442. internal.reset (new WinRTMidiService());
  1443. return;
  1444. }
  1445. catch (std::runtime_error&) {}
  1446. }
  1447. #endif
  1448. internal.reset (new Win32MidiService());
  1449. }
  1450. ~MidiService()
  1451. {
  1452. clearSingletonInstance();
  1453. }
  1454. static MidiServiceType& getService()
  1455. {
  1456. jassert (getInstance()->internal != nullptr);
  1457. return *getInstance()->internal.get();
  1458. }
  1459. JUCE_DECLARE_SINGLETON (MidiService, false)
  1460. private:
  1461. std::unique_ptr<MidiServiceType> internal;
  1462. };
  1463. JUCE_IMPLEMENT_SINGLETON (MidiService)
  1464. //==============================================================================
  1465. static int findDefaultDeviceIndex (const Array<MidiDeviceInfo>& available, const MidiDeviceInfo& defaultDevice)
  1466. {
  1467. for (int i = 0; i < available.size(); ++i)
  1468. if (available.getUnchecked (i) == defaultDevice)
  1469. return i;
  1470. return 0;
  1471. }
  1472. Array<MidiDeviceInfo> MidiInput::getAvailableDevices()
  1473. {
  1474. return MidiService::getService().getAvailableDevices (true);
  1475. }
  1476. MidiDeviceInfo MidiInput::getDefaultDevice()
  1477. {
  1478. return MidiService::getService().getDefaultDevice (true);
  1479. }
  1480. std::unique_ptr<MidiInput> MidiInput::openDevice (const String& deviceIdentifier, MidiInputCallback* callback)
  1481. {
  1482. if (deviceIdentifier.isEmpty() || callback == nullptr)
  1483. return {};
  1484. std::unique_ptr<MidiInput> in (new MidiInput ({}, deviceIdentifier));
  1485. std::unique_ptr<Pimpl> wrapper;
  1486. try
  1487. {
  1488. wrapper.reset (MidiService::getService().createInputWrapper (*in, deviceIdentifier, *callback));
  1489. }
  1490. catch (std::runtime_error&)
  1491. {
  1492. return {};
  1493. }
  1494. in->setName (wrapper->getDeviceName());
  1495. in->internal = std::move (wrapper);
  1496. return in;
  1497. }
  1498. StringArray MidiInput::getDevices()
  1499. {
  1500. StringArray deviceNames;
  1501. for (auto& d : getAvailableDevices())
  1502. deviceNames.add (d.name);
  1503. return deviceNames;
  1504. }
  1505. int MidiInput::getDefaultDeviceIndex()
  1506. {
  1507. return findDefaultDeviceIndex (getAvailableDevices(), getDefaultDevice());
  1508. }
  1509. std::unique_ptr<MidiInput> MidiInput::openDevice (int index, MidiInputCallback* callback)
  1510. {
  1511. return openDevice (getAvailableDevices()[index].identifier, callback);
  1512. }
  1513. MidiInput::MidiInput (const String& deviceName, const String& deviceIdentifier)
  1514. : deviceInfo (deviceName, deviceIdentifier)
  1515. {
  1516. }
  1517. MidiInput::~MidiInput() = default;
  1518. void MidiInput::start() { internal->start(); }
  1519. void MidiInput::stop() { internal->stop(); }
  1520. //==============================================================================
  1521. Array<MidiDeviceInfo> MidiOutput::getAvailableDevices()
  1522. {
  1523. return MidiService::getService().getAvailableDevices (false);
  1524. }
  1525. MidiDeviceInfo MidiOutput::getDefaultDevice()
  1526. {
  1527. return MidiService::getService().getDefaultDevice (false);
  1528. }
  1529. std::unique_ptr<MidiOutput> MidiOutput::openDevice (const String& deviceIdentifier)
  1530. {
  1531. if (deviceIdentifier.isEmpty())
  1532. return {};
  1533. std::unique_ptr<Pimpl> wrapper;
  1534. try
  1535. {
  1536. wrapper.reset (MidiService::getService().createOutputWrapper (deviceIdentifier));
  1537. }
  1538. catch (std::runtime_error&)
  1539. {
  1540. return {};
  1541. }
  1542. std::unique_ptr<MidiOutput> out;
  1543. out.reset (new MidiOutput (wrapper->getDeviceName(), deviceIdentifier));
  1544. out->internal = std::move (wrapper);
  1545. return out;
  1546. }
  1547. StringArray MidiOutput::getDevices()
  1548. {
  1549. StringArray deviceNames;
  1550. for (auto& d : getAvailableDevices())
  1551. deviceNames.add (d.name);
  1552. return deviceNames;
  1553. }
  1554. int MidiOutput::getDefaultDeviceIndex()
  1555. {
  1556. return findDefaultDeviceIndex (getAvailableDevices(), getDefaultDevice());
  1557. }
  1558. std::unique_ptr<MidiOutput> MidiOutput::openDevice (int index)
  1559. {
  1560. return openDevice (getAvailableDevices()[index].identifier);
  1561. }
  1562. MidiOutput::~MidiOutput()
  1563. {
  1564. stopBackgroundThread();
  1565. }
  1566. void MidiOutput::sendMessageNow (const MidiMessage& message)
  1567. {
  1568. internal->sendMessageNow (message);
  1569. }
  1570. } // namespace juce