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.

juce_win32_Midi.cpp 66KB

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