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.

1806 lines
60KB

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