Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1233 lines
40KB

  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. class WindowsMidiService : public MidiServiceType
  44. {
  45. private:
  46. struct WindowsInputWrapper : public InputWrapper
  47. {
  48. struct MidiInCollector
  49. {
  50. MidiInCollector (WindowsMidiService& s,
  51. MidiInput* const inputDevice,
  52. MidiInputCallback& cb)
  53. : midiService (s),
  54. input (inputDevice),
  55. callback (cb)
  56. {
  57. }
  58. ~MidiInCollector()
  59. {
  60. stop();
  61. if (deviceHandle != 0)
  62. {
  63. for (int count = 5; --count >= 0;)
  64. {
  65. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  66. break;
  67. Sleep (20);
  68. }
  69. }
  70. }
  71. void handleMessage (const uint8* bytes, const uint32 timeStamp)
  72. {
  73. if (bytes[0] >= 0x80 && isStarted)
  74. {
  75. concatenator.pushMidiData (bytes,
  76. MidiMessage::getMessageLengthFromFirstByte (bytes[0]),
  77. convertTimeStamp (timeStamp),
  78. input,
  79. callback);
  80. writeFinishedBlocks();
  81. }
  82. }
  83. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  84. {
  85. if (isStarted && hdr->dwBytesRecorded > 0)
  86. {
  87. concatenator.pushMidiData (hdr->lpData, (int) hdr->dwBytesRecorded,
  88. convertTimeStamp (timeStamp), input, callback);
  89. writeFinishedBlocks();
  90. }
  91. }
  92. void start()
  93. {
  94. if (deviceHandle != 0 && ! isStarted)
  95. {
  96. midiService.activeMidiCollectors.addIfNotAlreadyThere (this);
  97. for (int i = 0; i < (int) numHeaders; ++i)
  98. {
  99. headers[i].prepare (deviceHandle);
  100. headers[i].write (deviceHandle);
  101. }
  102. startTime = Time::getMillisecondCounterHiRes();
  103. MMRESULT res = midiInStart (deviceHandle);
  104. if (res == MMSYSERR_NOERROR)
  105. {
  106. concatenator.reset();
  107. isStarted = true;
  108. }
  109. else
  110. {
  111. unprepareAllHeaders();
  112. }
  113. }
  114. }
  115. void stop()
  116. {
  117. if (isStarted)
  118. {
  119. isStarted = false;
  120. midiInReset (deviceHandle);
  121. midiInStop (deviceHandle);
  122. midiService.activeMidiCollectors.removeFirstMatchingValue (this);
  123. unprepareAllHeaders();
  124. concatenator.reset();
  125. }
  126. }
  127. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance,
  128. DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  129. {
  130. auto* collector = reinterpret_cast<MidiInCollector*> (dwInstance);
  131. if (collector->midiService.activeMidiCollectors.contains (collector))
  132. {
  133. if (uMsg == MIM_DATA)
  134. collector->handleMessage ((const uint8*) &midiMessage, (uint32) timeStamp);
  135. else if (uMsg == MIM_LONGDATA)
  136. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  137. }
  138. }
  139. HMIDIIN deviceHandle = 0;
  140. private:
  141. WindowsMidiService& midiService;
  142. MidiInput* input;
  143. MidiInputCallback& callback;
  144. MidiDataConcatenator concatenator { 4096 };
  145. bool volatile isStarted = false;
  146. double startTime = 0;
  147. struct MidiHeader
  148. {
  149. MidiHeader() {}
  150. void prepare (HMIDIIN device)
  151. {
  152. zerostruct (hdr);
  153. hdr.lpData = data;
  154. hdr.dwBufferLength = (DWORD) numElementsInArray (data);
  155. midiInPrepareHeader (device, &hdr, sizeof (hdr));
  156. }
  157. void unprepare (HMIDIIN device)
  158. {
  159. if ((hdr.dwFlags & WHDR_DONE) != 0)
  160. {
  161. int c = 10;
  162. while (--c >= 0 && midiInUnprepareHeader (device, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  163. Thread::sleep (20);
  164. jassert (c >= 0);
  165. }
  166. }
  167. void write (HMIDIIN device)
  168. {
  169. hdr.dwBytesRecorded = 0;
  170. midiInAddBuffer (device, &hdr, sizeof (hdr));
  171. }
  172. void writeIfFinished (HMIDIIN device)
  173. {
  174. if ((hdr.dwFlags & WHDR_DONE) != 0)
  175. write (device);
  176. }
  177. MIDIHDR hdr;
  178. char data [256];
  179. JUCE_DECLARE_NON_COPYABLE (MidiHeader)
  180. };
  181. enum { numHeaders = 32 };
  182. MidiHeader headers [numHeaders];
  183. void writeFinishedBlocks()
  184. {
  185. for (int i = 0; i < (int) numHeaders; ++i)
  186. headers[i].writeIfFinished (deviceHandle);
  187. }
  188. void unprepareAllHeaders()
  189. {
  190. for (int i = 0; i < (int) numHeaders; ++i)
  191. headers[i].unprepare (deviceHandle);
  192. }
  193. double convertTimeStamp (uint32 timeStamp)
  194. {
  195. auto t = startTime + timeStamp;
  196. auto now = Time::getMillisecondCounterHiRes();
  197. if (t > now)
  198. {
  199. if (t > now + 2.0)
  200. startTime -= 1.0;
  201. t = now;
  202. }
  203. return t * 0.001;
  204. }
  205. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector)
  206. };
  207. //==============================================================================
  208. WindowsInputWrapper (WindowsMidiService& parentService,
  209. MidiInput* const input,
  210. const int index,
  211. MidiInputCallback* const callback)
  212. {
  213. auto names = getDevices();
  214. UINT deviceId = MIDI_MAPPER;
  215. if (isPositiveAndBelow (index, names.size()))
  216. {
  217. deviceName = names[index];
  218. deviceId = index;
  219. }
  220. collector = new MidiInCollector (parentService, input, *callback);
  221. HMIDIIN h;
  222. MMRESULT err = midiInOpen (&h, deviceId,
  223. (DWORD_PTR) &MidiInCollector::midiInCallback,
  224. (DWORD_PTR) (MidiInCollector*) collector.get(),
  225. CALLBACK_FUNCTION);
  226. if (err != MMSYSERR_NOERROR)
  227. throw std::runtime_error ("Failed to create Windows input device wrapper");
  228. collector->deviceHandle = h;
  229. }
  230. ~WindowsInputWrapper() {}
  231. static StringArray getDevices()
  232. {
  233. StringArray s;
  234. const UINT num = midiInGetNumDevs();
  235. for (UINT i = 0; i < num; ++i)
  236. {
  237. MIDIINCAPS mc = { 0 };
  238. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  239. s.add (String (mc.szPname, (size_t) numElementsInArray (mc.szPname)));
  240. }
  241. s.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
  242. return s;
  243. }
  244. static int getDefaultDeviceIndex()
  245. {
  246. return 0;
  247. }
  248. void start() override { collector->start(); }
  249. void stop() override { collector->stop(); }
  250. String getDeviceName() override
  251. {
  252. return deviceName;
  253. }
  254. String deviceName;
  255. ScopedPointer<MidiInCollector> collector;
  256. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsInputWrapper)
  257. };
  258. //==============================================================================
  259. struct WindowsOutputWrapper : public OutputWrapper
  260. {
  261. struct MidiOutHandle
  262. {
  263. int refCount;
  264. UINT deviceId;
  265. HMIDIOUT handle;
  266. JUCE_LEAK_DETECTOR (MidiOutHandle)
  267. };
  268. WindowsOutputWrapper (WindowsMidiService& p, int index) : parent (p)
  269. {
  270. auto names = getDevices();
  271. UINT deviceId = MIDI_MAPPER;
  272. if (isPositiveAndBelow (index, names.size()))
  273. {
  274. deviceName = names[index];
  275. deviceId = index;
  276. }
  277. if (deviceId == MIDI_MAPPER)
  278. {
  279. // use the microsoft sw synth as a default - best not to allow deviceId
  280. // to be MIDI_MAPPER, or else device sharing breaks
  281. for (int i = 0; i < names.size(); ++i)
  282. if (names[i].containsIgnoreCase ("microsoft"))
  283. deviceId = (UINT) i;
  284. }
  285. for (int i = parent.activeOutputHandles.size(); --i >= 0;)
  286. {
  287. auto* activeHandle = parent.activeOutputHandles.getUnchecked (i);
  288. if (activeHandle->deviceId == deviceId)
  289. {
  290. activeHandle->refCount++;
  291. han = activeHandle;
  292. return;
  293. }
  294. }
  295. for (int i = 4; --i >= 0;)
  296. {
  297. HMIDIOUT h = 0;
  298. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  299. if (res == MMSYSERR_NOERROR)
  300. {
  301. han = new MidiOutHandle();
  302. han->deviceId = deviceId;
  303. han->refCount = 1;
  304. han->handle = h;
  305. parent.activeOutputHandles.add (han);
  306. return;
  307. }
  308. if (res == MMSYSERR_ALLOCATED)
  309. Sleep (100);
  310. else
  311. break;
  312. }
  313. throw std::runtime_error ("Failed to create Windows output device wrapper");
  314. }
  315. ~WindowsOutputWrapper()
  316. {
  317. if (parent.activeOutputHandles.contains (han.get()) && --(han->refCount) == 0)
  318. {
  319. midiOutClose (han->handle);
  320. parent.activeOutputHandles.removeFirstMatchingValue (han.get());
  321. }
  322. }
  323. void sendMessageNow (const MidiMessage& message) override
  324. {
  325. if (message.getRawDataSize() > 3 || message.isSysEx())
  326. {
  327. MIDIHDR h = { 0 };
  328. h.lpData = (char*) message.getRawData();
  329. h.dwBytesRecorded = h.dwBufferLength = (DWORD) message.getRawDataSize();
  330. if (midiOutPrepareHeader (han->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  331. {
  332. MMRESULT res = midiOutLongMsg (han->handle, &h, sizeof (MIDIHDR));
  333. if (res == MMSYSERR_NOERROR)
  334. {
  335. while ((h.dwFlags & MHDR_DONE) == 0)
  336. Sleep (1);
  337. int count = 500; // 1 sec timeout
  338. while (--count >= 0)
  339. {
  340. res = midiOutUnprepareHeader (han->handle, &h, sizeof (MIDIHDR));
  341. if (res == MIDIERR_STILLPLAYING)
  342. Sleep (2);
  343. else
  344. break;
  345. }
  346. }
  347. }
  348. }
  349. else
  350. {
  351. for (int i = 0; i < 50; ++i)
  352. {
  353. if (midiOutShortMsg (han->handle, *(unsigned int*) message.getRawData()) != MIDIERR_NOTREADY)
  354. break;
  355. Sleep (1);
  356. }
  357. }
  358. }
  359. static Array<MIDIOUTCAPS> getDeviceCaps()
  360. {
  361. Array<MIDIOUTCAPS> devices;
  362. const UINT num = midiOutGetNumDevs();
  363. for (UINT i = 0; i < num; ++i)
  364. {
  365. MIDIOUTCAPS mc = { 0 };
  366. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  367. devices.add (mc);
  368. }
  369. return devices;
  370. }
  371. static StringArray getDevices()
  372. {
  373. StringArray s;
  374. for (auto& mc : getDeviceCaps())
  375. s.add (String (mc.szPname, (size_t) numElementsInArray (mc.szPname)));
  376. s.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
  377. return s;
  378. }
  379. static int getDefaultDeviceIndex()
  380. {
  381. int n = 0;
  382. for (auto& mc : getDeviceCaps())
  383. {
  384. if ((mc.wTechnology & MOD_MAPPER) != 0)
  385. return n;
  386. ++n;
  387. }
  388. return 0;
  389. }
  390. String getDeviceName() override
  391. {
  392. return deviceName;
  393. }
  394. WindowsMidiService& parent;
  395. String deviceName;
  396. ScopedPointer<MidiOutHandle> han;
  397. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsOutputWrapper)
  398. };
  399. public:
  400. WindowsMidiService() {}
  401. StringArray getDevices (bool isInput) override
  402. {
  403. return isInput ? WindowsInputWrapper::getDevices()
  404. : WindowsOutputWrapper::getDevices();
  405. }
  406. int getDefaultDeviceIndex (bool isInput) override
  407. {
  408. return isInput ? WindowsInputWrapper::getDefaultDeviceIndex()
  409. : WindowsOutputWrapper::getDefaultDeviceIndex();
  410. }
  411. InputWrapper* createInputWrapper (MidiInput* input, int index, MidiInputCallback* callback) override
  412. {
  413. return new WindowsInputWrapper (*this, input, index, callback);
  414. }
  415. OutputWrapper* createOutputWrapper (int index) override
  416. {
  417. return new WindowsOutputWrapper (*this, index);
  418. }
  419. private:
  420. Array<WindowsInputWrapper::MidiInCollector*, CriticalSection> activeMidiCollectors;
  421. Array<WindowsOutputWrapper::MidiOutHandle*> activeOutputHandles;
  422. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsMidiService)
  423. };
  424. //==============================================================================
  425. #if JUCE_USE_WINRT_MIDI
  426. using namespace Microsoft::WRL;
  427. using namespace ABI::Windows::Foundation;
  428. using namespace ABI::Windows::Devices::Midi;
  429. using namespace ABI::Windows::Devices::Enumeration;
  430. using namespace ABI::Windows::Storage::Streams;
  431. class WinRTMidiService : public MidiServiceType
  432. {
  433. private:
  434. template <typename COMFactoryType>
  435. struct MidiIODeviceWatcher
  436. {
  437. struct DeviceInfo
  438. {
  439. String name;
  440. String id;
  441. bool isDefault = false;
  442. };
  443. MidiIODeviceWatcher (ComSmartPtr<COMFactoryType>& comFactory)
  444. : factory (comFactory)
  445. {
  446. }
  447. ~MidiIODeviceWatcher()
  448. {
  449. stop();
  450. }
  451. bool start()
  452. {
  453. HSTRING deviceSelector;
  454. HRESULT hr = factory->GetDeviceSelector (&deviceSelector);
  455. if (FAILED (hr))
  456. return false;
  457. auto deviceInformationFactory = WinRTWrapper::getInstance()->getWRLFactory<IDeviceInformationStatics> (&RuntimeClass_Windows_Devices_Enumeration_DeviceInformation[0]);
  458. if (deviceInformationFactory == nullptr)
  459. return false;
  460. hr = deviceInformationFactory->CreateWatcherAqsFilter (deviceSelector, watcher.resetAndGetPointerAddress());
  461. if (FAILED (hr))
  462. return false;
  463. class DeviceEnumerationThread : public Thread
  464. {
  465. public:
  466. DeviceEnumerationThread (String threadName, MidiIODeviceWatcher<COMFactoryType>& p)
  467. : Thread (threadName), parent (p)
  468. {}
  469. void run() override
  470. {
  471. auto parentPtr = &parent;
  472. parent.watcher->add_Added (
  473. Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformation*>> (
  474. [parentPtr](IDeviceWatcher*, IDeviceInformation* info) { return parentPtr->addDevice (info); }
  475. ).Get(),
  476. &parent.deviceAddedToken);
  477. parent.watcher->add_Removed (
  478. Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>> (
  479. [parentPtr](IDeviceWatcher*, IDeviceInformationUpdate* info) { return parentPtr->removeDevice (info); }
  480. ).Get(),
  481. &parent.deviceRemovedToken);
  482. EventRegistrationToken deviceEnumerationCompletedToken { 0 };
  483. parent.watcher->add_EnumerationCompleted (
  484. Callback<ITypedEventHandler<DeviceWatcher*, IInspectable*>> (
  485. [this](IDeviceWatcher*, IInspectable*) { enumerationCompleted.signal(); return S_OK; }
  486. ).Get(),
  487. &deviceEnumerationCompletedToken);
  488. parent.watcher->Start();
  489. enumerationCompleted.wait();
  490. if (deviceEnumerationCompletedToken.value != 0)
  491. parent.watcher->remove_EnumerationCompleted (deviceEnumerationCompletedToken);
  492. }
  493. private:
  494. MidiIODeviceWatcher<COMFactoryType>& parent;
  495. WaitableEvent enumerationCompleted;
  496. };
  497. DeviceEnumerationThread enumerationThread ("WinRT Device Enumeration Thread", *this);
  498. enumerationThread.startThread();
  499. enumerationThread.waitForThreadToExit (4000);
  500. return true;
  501. }
  502. bool stop()
  503. {
  504. if (watcher == nullptr)
  505. return true;
  506. if (deviceAddedToken.value != 0)
  507. {
  508. HRESULT hr = watcher->remove_Added (deviceAddedToken);
  509. if (FAILED (hr))
  510. return false;
  511. deviceAddedToken.value = 0;
  512. }
  513. if (deviceRemovedToken.value != 0)
  514. {
  515. HRESULT hr = watcher->remove_Removed (deviceRemovedToken);
  516. if (FAILED (hr))
  517. return false;
  518. deviceRemovedToken.value = 0;
  519. }
  520. HRESULT hr = watcher->Stop();
  521. if (FAILED (hr))
  522. return false;
  523. watcher = nullptr;
  524. return true;
  525. }
  526. HRESULT addDevice (IDeviceInformation* addedDeviceInfo)
  527. {
  528. boolean isEnabled;
  529. HRESULT hr = addedDeviceInfo->get_IsEnabled (&isEnabled);
  530. if (FAILED (hr))
  531. return S_OK;
  532. if (! isEnabled)
  533. return S_OK;
  534. const ScopedLock lock (deviceChanges);
  535. DeviceInfo info;
  536. HSTRING name;
  537. hr = addedDeviceInfo->get_Name (&name);
  538. if (FAILED (hr))
  539. return S_OK;
  540. info.name = WinRTWrapper::getInstance()->hStringToString (name);
  541. HSTRING id;
  542. hr = addedDeviceInfo->get_Id (&id);
  543. if (FAILED (hr))
  544. return S_OK;
  545. info.id = WinRTWrapper::getInstance()->hStringToString (id);
  546. boolean isDefault;
  547. hr = addedDeviceInfo->get_IsDefault (&isDefault);
  548. if (FAILED (hr))
  549. return S_OK;
  550. info.isDefault = isDefault != 0;
  551. connectedDevices.add (info);
  552. return S_OK;
  553. }
  554. HRESULT removeDevice (IDeviceInformationUpdate* removedDeviceInfo)
  555. {
  556. const ScopedLock lock (deviceChanges);
  557. HSTRING removedDeviceIdHstr;
  558. removedDeviceInfo->get_Id (&removedDeviceIdHstr);
  559. String removedDeviceId = WinRTWrapper::getInstance()->hStringToString (removedDeviceIdHstr);
  560. for (int i = 0; i < connectedDevices.size(); ++i)
  561. {
  562. if (connectedDevices[i].id == removedDeviceId)
  563. {
  564. connectedDevices.remove (i);
  565. break;
  566. }
  567. }
  568. return S_OK;
  569. }
  570. StringArray getDevices()
  571. {
  572. {
  573. const ScopedLock lock (deviceChanges);
  574. lastQueriedConnectedDevices = connectedDevices;
  575. }
  576. StringArray result;
  577. for (auto info : lastQueriedConnectedDevices.get())
  578. result.add (info.name);
  579. return result;
  580. }
  581. int getDefaultDeviceIndex()
  582. {
  583. auto& lastDevices = lastQueriedConnectedDevices.get();
  584. for (int i = 0; i < lastDevices.size(); ++i)
  585. if (lastDevices[i].isDefault)
  586. return i;
  587. return 0;
  588. }
  589. String getDeviceNameFromIndex (const int index)
  590. {
  591. if (isPositiveAndBelow (index, lastQueriedConnectedDevices.get().size()))
  592. return lastQueriedConnectedDevices.get()[index].name;
  593. return {};
  594. }
  595. String getDeviceID (const String name)
  596. {
  597. const ScopedLock lock (deviceChanges);
  598. for (auto info : connectedDevices)
  599. if (info.name == name)
  600. return info.id;
  601. return {};
  602. }
  603. ComSmartPtr<COMFactoryType>& factory;
  604. EventRegistrationToken deviceAddedToken { 0 },
  605. deviceRemovedToken { 0 };
  606. ComSmartPtr<IDeviceWatcher> watcher;
  607. Array<DeviceInfo> connectedDevices;
  608. CriticalSection deviceChanges;
  609. ThreadLocalValue<Array<DeviceInfo>> lastQueriedConnectedDevices;
  610. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiIODeviceWatcher);
  611. };
  612. template <typename COMFactoryType, typename COMInterfaceType, typename COMType>
  613. class OpenMidiPortThread : public Thread
  614. {
  615. public:
  616. OpenMidiPortThread (String threadName,
  617. String midiDeviceId,
  618. ComSmartPtr<COMFactoryType>& comFactory,
  619. ComSmartPtr<COMInterfaceType>& comPort)
  620. : Thread (threadName),
  621. deviceId (midiDeviceId),
  622. factory (comFactory),
  623. port (comPort)
  624. {
  625. }
  626. ~OpenMidiPortThread()
  627. {
  628. }
  629. void run() override
  630. {
  631. WinRTWrapper::ScopedHString hDeviceId (deviceId);
  632. ComSmartPtr<IAsyncOperation<COMType*>> asyncOp;
  633. HRESULT hr = factory->FromIdAsync (hDeviceId.get(), asyncOp.resetAndGetPointerAddress());
  634. if (FAILED (hr))
  635. return;
  636. hr = asyncOp->put_Completed (Callback<IAsyncOperationCompletedHandler<COMType*>> (
  637. [this] (IAsyncOperation<COMType*>* asyncOpPtr, AsyncStatus)
  638. {
  639. if (asyncOpPtr == nullptr)
  640. return E_ABORT;
  641. HRESULT hr = asyncOpPtr->GetResults (port.resetAndGetPointerAddress());
  642. if (FAILED (hr))
  643. return hr;
  644. portOpened.signal();
  645. return S_OK;
  646. }
  647. ).Get());
  648. // When using Bluetooth the asynchronous port opening operation will occasionally
  649. // hang, so we use a timeout. We will be able to remove this when Microsoft
  650. // improves the Bluetooth MIDI stack.
  651. portOpened.wait (2000);
  652. }
  653. const String deviceId;
  654. ComSmartPtr<COMFactoryType>& factory;
  655. ComSmartPtr<COMInterfaceType>& port;
  656. WaitableEvent portOpened { true };
  657. };
  658. struct WinRTInputWrapper : public InputWrapper
  659. {
  660. WinRTInputWrapper (WinRTMidiService& service,
  661. MidiInput* const input,
  662. const int index,
  663. MidiInputCallback& cb)
  664. : inputDevice (input),
  665. callback (cb),
  666. concatenator (4096)
  667. {
  668. const ScopedLock lock (service.inputDeviceWatcher->deviceChanges);
  669. deviceName = service.inputDeviceWatcher->getDeviceNameFromIndex (index);
  670. if (deviceName.isEmpty())
  671. throw std::runtime_error ("Invalid device index");
  672. const auto deviceID = service.inputDeviceWatcher->getDeviceID (deviceName);
  673. if (deviceID.isEmpty())
  674. throw std::runtime_error ("Device unavailable");
  675. OpenMidiPortThread<IMidiInPortStatics, IMidiInPort, MidiInPort> portThread ("Open WinRT MIDI input port",
  676. deviceID,
  677. service.midiInFactory,
  678. midiInPort);
  679. portThread.startThread();
  680. portThread.waitForThreadToExit (-1);
  681. if (midiInPort == nullptr)
  682. throw std::runtime_error ("Timed out waiting for midi input port creation");
  683. startTime = Time::getMillisecondCounterHiRes();
  684. HRESULT hr = midiInPort->add_MessageReceived (
  685. Callback<ITypedEventHandler<MidiInPort*, MidiMessageReceivedEventArgs*>> (
  686. [this] (IMidiInPort*, IMidiMessageReceivedEventArgs* args) { return midiInMessageReceived (args); }
  687. ).Get(),
  688. &midiInMessageToken);
  689. if (FAILED (hr))
  690. throw std::runtime_error ("Failed to set midi input callback");
  691. }
  692. ~WinRTInputWrapper()
  693. {
  694. if (midiInMessageToken.value != 0)
  695. midiInPort->remove_MessageReceived (midiInMessageToken);
  696. midiInPort = nullptr;
  697. }
  698. void start() override
  699. {
  700. if (!isStarted)
  701. {
  702. concatenator.reset();
  703. isStarted = true;
  704. }
  705. }
  706. void stop() override
  707. {
  708. if (isStarted)
  709. {
  710. isStarted = false;
  711. concatenator.reset();
  712. }
  713. }
  714. String getDeviceName() override
  715. {
  716. return deviceName;
  717. }
  718. HRESULT midiInMessageReceived (IMidiMessageReceivedEventArgs* args)
  719. {
  720. if (! isStarted)
  721. return S_OK;
  722. ComSmartPtr<IMidiMessage> message;
  723. HRESULT hr = args->get_Message (message.resetAndGetPointerAddress());
  724. if (FAILED (hr))
  725. return hr;
  726. ComSmartPtr<IBuffer> buffer;
  727. hr = message->get_RawData (buffer.resetAndGetPointerAddress());
  728. if (FAILED (hr))
  729. return hr;
  730. ComSmartPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
  731. hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress());
  732. if (FAILED (hr))
  733. return hr;
  734. uint8_t* bufferData = nullptr;
  735. hr = bufferByteAccess->Buffer (&bufferData);
  736. if (FAILED (hr))
  737. return hr;
  738. uint32_t numBytes = 0;
  739. hr = buffer->get_Length (&numBytes);
  740. if (FAILED (hr))
  741. return hr;
  742. ABI::Windows::Foundation::TimeSpan timespan;
  743. hr = message->get_Timestamp (&timespan);
  744. if (FAILED (hr))
  745. return hr;
  746. concatenator.pushMidiData (bufferData,
  747. numBytes,
  748. convertTimeStamp (timespan.Duration),
  749. inputDevice,
  750. callback);
  751. return S_OK;
  752. }
  753. double convertTimeStamp (int64 timestamp)
  754. {
  755. const auto millisecondsSinceStart = static_cast<double> (timestamp) / 10000.0;
  756. double t = startTime + millisecondsSinceStart;
  757. const double now = Time::getMillisecondCounterHiRes();
  758. if (t > now)
  759. {
  760. if (t > now + 2.0)
  761. startTime -= 1.0;
  762. t = now;
  763. }
  764. return t * 0.001;
  765. }
  766. MidiInput* inputDevice;
  767. MidiInputCallback& callback;
  768. String deviceName;
  769. MidiDataConcatenator concatenator;
  770. ComSmartPtr<IMidiInPort> midiInPort;
  771. EventRegistrationToken midiInMessageToken { 0 };
  772. double startTime = 0;
  773. bool isStarted = false;
  774. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTInputWrapper);
  775. };
  776. struct WinRTOutputWrapper : public OutputWrapper
  777. {
  778. WinRTOutputWrapper (WinRTMidiService& service, const int index)
  779. {
  780. const ScopedLock lock (service.outputDeviceWatcher->deviceChanges);
  781. deviceName = service.outputDeviceWatcher->getDeviceNameFromIndex (index);
  782. if (deviceName.isEmpty())
  783. throw std::runtime_error ("Invalid device index");
  784. const auto deviceID = service.outputDeviceWatcher->getDeviceID (deviceName);
  785. if (deviceID.isEmpty())
  786. throw std::runtime_error ("Device unavailable");
  787. OpenMidiPortThread<IMidiOutPortStatics, IMidiOutPort, IMidiOutPort> portThread ("Open WinRT MIDI output port",
  788. deviceID,
  789. service.midiOutFactory,
  790. midiOutPort);
  791. portThread.startThread();
  792. portThread.waitForThreadToExit (-1);
  793. if (midiOutPort == nullptr)
  794. throw std::runtime_error ("Timed out waiting for midi output port creation");
  795. auto bufferFactory = WinRTWrapper::getInstance()->getWRLFactory<IBufferFactory> (&RuntimeClass_Windows_Storage_Streams_Buffer[0]);
  796. if (bufferFactory == nullptr)
  797. throw std::runtime_error ("Failed to create output buffer factory");
  798. HRESULT hr = bufferFactory->Create (static_cast<UINT32> (65536), buffer.resetAndGetPointerAddress());
  799. if (FAILED (hr))
  800. throw std::runtime_error ("Failed to create output buffer");
  801. hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress());
  802. if (FAILED (hr))
  803. throw std::runtime_error ("Failed to get buffer byte access");
  804. hr = bufferByteAccess->Buffer (&bufferData);
  805. if (FAILED (hr))
  806. throw std::runtime_error ("Failed to get buffer data pointer");
  807. }
  808. ~WinRTOutputWrapper() {}
  809. void sendMessageNow (const MidiMessage& message) override
  810. {
  811. const UINT32 numBytes = message.getRawDataSize();
  812. HRESULT hr = buffer->put_Length (numBytes);
  813. if (FAILED (hr))
  814. jassertfalse;
  815. memcpy_s (bufferData, numBytes, message.getRawData(), numBytes);
  816. midiOutPort->SendBuffer (buffer);
  817. }
  818. String getDeviceName() override
  819. {
  820. return deviceName;
  821. }
  822. String deviceName;
  823. ComSmartPtr<IMidiOutPort> midiOutPort;
  824. ComSmartPtr<IBuffer> buffer;
  825. ComSmartPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
  826. uint8_t* bufferData = nullptr;
  827. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTOutputWrapper);
  828. };
  829. public:
  830. WinRTMidiService()
  831. {
  832. if (! WinRTWrapper::getInstance()->isInitialised())
  833. throw std::runtime_error ("Failed to initialise the WinRT wrapper");
  834. midiInFactory = WinRTWrapper::getInstance()->getWRLFactory<IMidiInPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiInPort[0]);
  835. if (midiInFactory == nullptr)
  836. throw std::runtime_error ("Failed to create midi in factory");
  837. midiOutFactory = WinRTWrapper::getInstance()->getWRLFactory<IMidiOutPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiOutPort[0]);
  838. if (midiOutFactory == nullptr)
  839. throw std::runtime_error ("Failed to create midi out factory");
  840. inputDeviceWatcher = new MidiIODeviceWatcher<IMidiInPortStatics> (midiInFactory);
  841. if (! inputDeviceWatcher->start())
  842. throw std::runtime_error ("Failed to start midi input device watcher");
  843. outputDeviceWatcher = new MidiIODeviceWatcher<IMidiOutPortStatics> (midiOutFactory);
  844. if (! outputDeviceWatcher->start())
  845. throw std::runtime_error ("Failed to start midi output device watcher");
  846. }
  847. ~WinRTMidiService()
  848. {
  849. }
  850. StringArray getDevices (bool isInput) override
  851. {
  852. return isInput ? inputDeviceWatcher ->getDevices()
  853. : outputDeviceWatcher->getDevices();
  854. }
  855. int getDefaultDeviceIndex (bool isInput) override
  856. {
  857. return isInput ? inputDeviceWatcher ->getDefaultDeviceIndex()
  858. : outputDeviceWatcher->getDefaultDeviceIndex();
  859. }
  860. InputWrapper* createInputWrapper (MidiInput* input, int index, MidiInputCallback* callback) override
  861. {
  862. return new WinRTInputWrapper (*this, input, index, *callback);
  863. }
  864. OutputWrapper* createOutputWrapper (int index) override
  865. {
  866. return new WinRTOutputWrapper (*this, index);
  867. }
  868. ComSmartPtr<IMidiInPortStatics> midiInFactory;
  869. ComSmartPtr<IMidiOutPortStatics> midiOutFactory;
  870. ScopedPointer<MidiIODeviceWatcher<IMidiInPortStatics>> inputDeviceWatcher;
  871. ScopedPointer<MidiIODeviceWatcher<IMidiOutPortStatics>> outputDeviceWatcher;
  872. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTMidiService)
  873. };
  874. #endif // JUCE_USE_WINRT_MIDI
  875. //==============================================================================
  876. class MidiService : public DeletedAtShutdown
  877. {
  878. public:
  879. ~MidiService();
  880. MidiServiceType* getService();
  881. juce_DeclareSingleton (MidiService, false)
  882. private:
  883. MidiService();
  884. ScopedPointer<MidiServiceType> internal;
  885. };
  886. juce_ImplementSingleton (MidiService)
  887. MidiService::~MidiService()
  888. {
  889. clearSingletonInstance();
  890. }
  891. MidiServiceType* MidiService::getService()
  892. {
  893. return internal.get();
  894. }
  895. MidiService::MidiService()
  896. {
  897. #if JUCE_USE_WINRT_MIDI
  898. try
  899. {
  900. internal = new WinRTMidiService();
  901. return;
  902. }
  903. catch (std::runtime_error&)
  904. {
  905. }
  906. #endif
  907. internal = new WindowsMidiService();
  908. }
  909. //==============================================================================
  910. StringArray MidiInput::getDevices()
  911. {
  912. return MidiService::getInstance()->getService()->getDevices (true);
  913. }
  914. int MidiInput::getDefaultDeviceIndex()
  915. {
  916. return MidiService::getInstance()->getService()->getDefaultDeviceIndex (true);
  917. }
  918. MidiInput::MidiInput (const String& deviceName)
  919. : name (deviceName)
  920. {
  921. }
  922. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  923. {
  924. if (callback == nullptr)
  925. return nullptr;
  926. ScopedPointer<MidiInput> in (new MidiInput ({}));
  927. ScopedPointer<MidiServiceType::InputWrapper> wrapper;
  928. try
  929. {
  930. wrapper = MidiService::getInstance()->getService()->createInputWrapper (in, index, callback);
  931. }
  932. catch (std::runtime_error&)
  933. {
  934. return nullptr;
  935. }
  936. in->setName (wrapper->getDeviceName());
  937. in->internal = wrapper.release();
  938. return in.release();
  939. }
  940. MidiInput::~MidiInput()
  941. {
  942. delete static_cast<MidiServiceType::InputWrapper*> (internal);
  943. }
  944. void MidiInput::start() { static_cast<MidiServiceType::InputWrapper*> (internal)->start(); }
  945. void MidiInput::stop() { static_cast<MidiServiceType::InputWrapper*> (internal)->stop(); }
  946. //==============================================================================
  947. StringArray MidiOutput::getDevices()
  948. {
  949. return MidiService::getInstance()->getService()->getDevices (false);
  950. }
  951. int MidiOutput::getDefaultDeviceIndex()
  952. {
  953. return MidiService::getInstance()->getService()->getDefaultDeviceIndex (false);
  954. }
  955. MidiOutput* MidiOutput::openDevice (const int index)
  956. {
  957. ScopedPointer<MidiServiceType::OutputWrapper> wrapper;
  958. try
  959. {
  960. wrapper = MidiService::getInstance()->getService()->createOutputWrapper (index);
  961. }
  962. catch (std::runtime_error&)
  963. {
  964. return nullptr;
  965. }
  966. ScopedPointer<MidiOutput> out (new MidiOutput (wrapper->getDeviceName()));
  967. out->internal = wrapper.release();
  968. return out.release();
  969. }
  970. MidiOutput::~MidiOutput()
  971. {
  972. stopBackgroundThread();
  973. delete static_cast<MidiServiceType::OutputWrapper*> (internal);
  974. }
  975. void MidiOutput::sendMessageNow (const MidiMessage& message)
  976. {
  977. static_cast<MidiServiceType::OutputWrapper*> (internal)->sendMessageNow (message);
  978. }
  979. } // namespace juce