|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232 |
- /*
- ==============================================================================
-
- This file is part of the JUCE library.
- Copyright (c) 2017 - ROLI Ltd.
-
- JUCE is an open source library subject to commercial or open-source
- licensing.
-
- The code included in this file is provided under the terms of the ISC license
- http://www.isc.org/downloads/software-support-policy/isc-license. Permission
- To use, copy, modify, and/or distribute this software for any purpose with or
- without fee is hereby granted provided that the above copyright notice and
- this permission notice appear in all copies.
-
- JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
- EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
- DISCLAIMED.
-
- ==============================================================================
- */
-
- namespace juce
- {
-
- struct MidiServiceType
- {
- struct InputWrapper
- {
- virtual ~InputWrapper() {}
-
- virtual String getDeviceName() = 0;
- virtual void start() = 0;
- virtual void stop() = 0;
- };
-
- struct OutputWrapper
- {
- virtual ~OutputWrapper() {}
-
- virtual String getDeviceName() = 0;
- virtual void sendMessageNow (const MidiMessage&) = 0;
- };
-
- MidiServiceType() {}
- virtual ~MidiServiceType() {}
-
- virtual StringArray getDevices (bool) = 0;
- virtual int getDefaultDeviceIndex (bool) = 0;
-
- virtual InputWrapper* createInputWrapper (MidiInput*, int, MidiInputCallback*) = 0;
- virtual OutputWrapper* createOutputWrapper (int) = 0;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiServiceType)
- };
-
- //==============================================================================
- class WindowsMidiService : public MidiServiceType
- {
- private:
- struct WindowsInputWrapper : public InputWrapper
- {
- struct MidiInCollector
- {
- MidiInCollector (WindowsMidiService& s,
- MidiInput* const inputDevice,
- MidiInputCallback& cb)
- : midiService (s),
- input (inputDevice),
- callback (cb)
- {
- }
-
- ~MidiInCollector()
- {
- stop();
-
- if (deviceHandle != 0)
- {
- for (int count = 5; --count >= 0;)
- {
- if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
- break;
-
- Sleep (20);
- }
- }
- }
-
- void handleMessage (const uint8* bytes, const uint32 timeStamp)
- {
- if (bytes[0] >= 0x80 && isStarted)
- {
- concatenator.pushMidiData (bytes,
- MidiMessage::getMessageLengthFromFirstByte (bytes[0]),
- convertTimeStamp (timeStamp),
- input,
- callback);
- writeFinishedBlocks();
- }
- }
-
- void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
- {
- if (isStarted && hdr->dwBytesRecorded > 0)
- {
- concatenator.pushMidiData (hdr->lpData, (int) hdr->dwBytesRecorded,
- convertTimeStamp (timeStamp), input, callback);
- writeFinishedBlocks();
- }
- }
-
- void start()
- {
- if (deviceHandle != 0 && ! isStarted)
- {
- midiService.activeMidiCollectors.addIfNotAlreadyThere (this);
-
- for (int i = 0; i < (int) numHeaders; ++i)
- {
- headers[i].prepare (deviceHandle);
- headers[i].write (deviceHandle);
- }
-
- startTime = Time::getMillisecondCounterHiRes();
- MMRESULT res = midiInStart (deviceHandle);
-
- if (res == MMSYSERR_NOERROR)
- {
- concatenator.reset();
- isStarted = true;
- }
- else
- {
- unprepareAllHeaders();
- }
- }
- }
-
- void stop()
- {
- if (isStarted)
- {
- isStarted = false;
- midiInReset (deviceHandle);
- midiInStop (deviceHandle);
- midiService.activeMidiCollectors.removeFirstMatchingValue (this);
- unprepareAllHeaders();
- concatenator.reset();
- }
- }
-
- static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance,
- DWORD_PTR midiMessage, DWORD_PTR timeStamp)
- {
- auto* collector = reinterpret_cast<MidiInCollector*> (dwInstance);
-
- if (collector->midiService.activeMidiCollectors.contains (collector))
- {
- if (uMsg == MIM_DATA)
- collector->handleMessage ((const uint8*) &midiMessage, (uint32) timeStamp);
- else if (uMsg == MIM_LONGDATA)
- collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
- }
- }
-
- HMIDIIN deviceHandle = 0;
-
- private:
- WindowsMidiService& midiService;
- MidiInput* input;
- MidiInputCallback& callback;
- MidiDataConcatenator concatenator { 4096 };
- bool volatile isStarted = false;
- double startTime = 0;
-
- struct MidiHeader
- {
- MidiHeader() {}
-
- void prepare (HMIDIIN device)
- {
- zerostruct (hdr);
- hdr.lpData = data;
- hdr.dwBufferLength = (DWORD) numElementsInArray (data);
-
- midiInPrepareHeader (device, &hdr, sizeof (hdr));
- }
-
- void unprepare (HMIDIIN device)
- {
- if ((hdr.dwFlags & WHDR_DONE) != 0)
- {
- int c = 10;
- while (--c >= 0 && midiInUnprepareHeader (device, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
- Thread::sleep (20);
-
- jassert (c >= 0);
- }
- }
-
- void write (HMIDIIN device)
- {
- hdr.dwBytesRecorded = 0;
- midiInAddBuffer (device, &hdr, sizeof (hdr));
- }
-
- void writeIfFinished (HMIDIIN device)
- {
- if ((hdr.dwFlags & WHDR_DONE) != 0)
- write (device);
- }
-
- MIDIHDR hdr;
- char data [256];
-
- JUCE_DECLARE_NON_COPYABLE (MidiHeader)
- };
-
- enum { numHeaders = 32 };
- MidiHeader headers [numHeaders];
-
- void writeFinishedBlocks()
- {
- for (int i = 0; i < (int) numHeaders; ++i)
- headers[i].writeIfFinished (deviceHandle);
- }
-
- void unprepareAllHeaders()
- {
- for (int i = 0; i < (int) numHeaders; ++i)
- headers[i].unprepare (deviceHandle);
- }
-
- double convertTimeStamp (uint32 timeStamp)
- {
- auto t = startTime + timeStamp;
- auto now = Time::getMillisecondCounterHiRes();
-
- if (t > now)
- {
- if (t > now + 2.0)
- startTime -= 1.0;
-
- t = now;
- }
-
- return t * 0.001;
- }
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInCollector)
- };
-
- //==============================================================================
- WindowsInputWrapper (WindowsMidiService& parentService,
- MidiInput* const input,
- const int index,
- MidiInputCallback* const callback)
- {
- auto names = getDevices();
- UINT deviceId = MIDI_MAPPER;
-
- if (isPositiveAndBelow (index, names.size()))
- {
- deviceName = names[index];
- deviceId = index;
- }
-
- collector = new MidiInCollector (parentService, input, *callback);
-
- HMIDIIN h;
- MMRESULT err = midiInOpen (&h, deviceId,
- (DWORD_PTR) &MidiInCollector::midiInCallback,
- (DWORD_PTR) (MidiInCollector*) collector.get(),
- CALLBACK_FUNCTION);
-
- if (err != MMSYSERR_NOERROR)
- throw std::runtime_error ("Failed to create Windows input device wrapper");
-
- collector->deviceHandle = h;
- }
-
- ~WindowsInputWrapper() {}
-
- static StringArray getDevices()
- {
- StringArray s;
- const UINT num = midiInGetNumDevs();
-
- for (UINT i = 0; i < num; ++i)
- {
- MIDIINCAPS mc = { 0 };
-
- if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
- s.add (String (mc.szPname, (size_t) numElementsInArray (mc.szPname)));
- }
-
- s.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
- return s;
- }
-
- static int getDefaultDeviceIndex()
- {
- return 0;
- }
-
- void start() override { collector->start(); }
- void stop() override { collector->stop(); }
-
- String getDeviceName() override
- {
- return deviceName;
- }
-
- String deviceName;
- ScopedPointer<MidiInCollector> collector;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsInputWrapper)
- };
-
- //==============================================================================
- struct WindowsOutputWrapper : public OutputWrapper
- {
- struct MidiOutHandle
- {
- int refCount;
- UINT deviceId;
- HMIDIOUT handle;
-
- JUCE_LEAK_DETECTOR (MidiOutHandle)
- };
-
- WindowsOutputWrapper (WindowsMidiService& p, int index) : parent (p)
- {
- auto names = getDevices();
- UINT deviceId = MIDI_MAPPER;
-
- if (isPositiveAndBelow (index, names.size()))
- {
- deviceName = names[index];
- deviceId = index;
- }
-
- if (deviceId == MIDI_MAPPER)
- {
- // use the microsoft sw synth as a default - best not to allow deviceId
- // to be MIDI_MAPPER, or else device sharing breaks
- for (int i = 0; i < names.size(); ++i)
- if (names[i].containsIgnoreCase ("microsoft"))
- deviceId = (UINT) i;
- }
-
- for (int i = parent.activeOutputHandles.size(); --i >= 0;)
- {
- auto* activeHandle = parent.activeOutputHandles.getUnchecked (i);
-
- if (activeHandle->deviceId == deviceId)
- {
- activeHandle->refCount++;
- han = activeHandle;
- return;
- }
- }
-
- for (int i = 4; --i >= 0;)
- {
- HMIDIOUT h = 0;
- MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
-
- if (res == MMSYSERR_NOERROR)
- {
- han = new MidiOutHandle();
- han->deviceId = deviceId;
- han->refCount = 1;
- han->handle = h;
- parent.activeOutputHandles.add (han);
- return;
- }
-
- if (res == MMSYSERR_ALLOCATED)
- Sleep (100);
- else
- break;
- }
-
- throw std::runtime_error ("Failed to create Windows output device wrapper");
- }
-
- ~WindowsOutputWrapper()
- {
- if (parent.activeOutputHandles.contains (han.get()) && --(han->refCount) == 0)
- {
- midiOutClose (han->handle);
- parent.activeOutputHandles.removeFirstMatchingValue (han.get());
- }
- }
-
- void sendMessageNow (const MidiMessage& message) override
- {
- if (message.getRawDataSize() > 3 || message.isSysEx())
- {
- MIDIHDR h = { 0 };
-
- h.lpData = (char*) message.getRawData();
- h.dwBytesRecorded = h.dwBufferLength = (DWORD) message.getRawDataSize();
-
- if (midiOutPrepareHeader (han->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
- {
- MMRESULT res = midiOutLongMsg (han->handle, &h, sizeof (MIDIHDR));
-
- if (res == MMSYSERR_NOERROR)
- {
- while ((h.dwFlags & MHDR_DONE) == 0)
- Sleep (1);
-
- int count = 500; // 1 sec timeout
-
- while (--count >= 0)
- {
- res = midiOutUnprepareHeader (han->handle, &h, sizeof (MIDIHDR));
-
- if (res == MIDIERR_STILLPLAYING)
- Sleep (2);
- else
- break;
- }
- }
- }
- }
- else
- {
- for (int i = 0; i < 50; ++i)
- {
- if (midiOutShortMsg (han->handle, *(unsigned int*) message.getRawData()) != MIDIERR_NOTREADY)
- break;
-
- Sleep (1);
- }
- }
- }
-
- static Array<MIDIOUTCAPS> getDeviceCaps()
- {
- Array<MIDIOUTCAPS> devices;
- const UINT num = midiOutGetNumDevs();
-
- for (UINT i = 0; i < num; ++i)
- {
- MIDIOUTCAPS mc = { 0 };
-
- if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
- devices.add (mc);
- }
-
- return devices;
- }
-
- static StringArray getDevices()
- {
- StringArray s;
-
- for (auto& mc : getDeviceCaps())
- s.add (String (mc.szPname, (size_t) numElementsInArray (mc.szPname)));
-
- s.appendNumbersToDuplicates (false, false, CharPointer_UTF8 ("-"), CharPointer_UTF8 (""));
- return s;
- }
-
- static int getDefaultDeviceIndex()
- {
- int n = 0;
-
- for (auto& mc : getDeviceCaps())
- {
- if ((mc.wTechnology & MOD_MAPPER) != 0)
- return n;
-
- ++n;
- }
-
- return 0;
- }
-
- String getDeviceName() override
- {
- return deviceName;
- }
-
- WindowsMidiService& parent;
- String deviceName;
-
- ScopedPointer<MidiOutHandle> han;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsOutputWrapper)
- };
-
- public:
- WindowsMidiService() {}
-
- StringArray getDevices (bool isInput) override
- {
- return isInput ? WindowsInputWrapper::getDevices()
- : WindowsOutputWrapper::getDevices();
- }
-
- int getDefaultDeviceIndex (bool isInput) override
- {
- return isInput ? WindowsInputWrapper::getDefaultDeviceIndex()
- : WindowsOutputWrapper::getDefaultDeviceIndex();
- }
-
- InputWrapper* createInputWrapper (MidiInput* input, int index, MidiInputCallback* callback) override
- {
- return new WindowsInputWrapper (*this, input, index, callback);
- }
-
- OutputWrapper* createOutputWrapper (int index) override
- {
- return new WindowsOutputWrapper (*this, index);
- }
-
- private:
- Array<WindowsInputWrapper::MidiInCollector*, CriticalSection> activeMidiCollectors;
- Array<WindowsOutputWrapper::MidiOutHandle*> activeOutputHandles;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsMidiService)
- };
-
- //==============================================================================
- #if JUCE_USE_WINRT_MIDI
-
- using namespace Microsoft::WRL;
-
- using namespace ABI::Windows::Foundation;
- using namespace ABI::Windows::Devices::Midi;
- using namespace ABI::Windows::Devices::Enumeration;
- using namespace ABI::Windows::Storage::Streams;
-
- class WinRTMidiService : public MidiServiceType
- {
- private:
- template <typename COMFactoryType>
- struct MidiIODeviceWatcher
- {
- struct DeviceInfo
- {
- String name;
- String id;
- bool isDefault = false;
- };
-
- MidiIODeviceWatcher (ComSmartPtr<COMFactoryType>& comFactory)
- : factory (comFactory)
- {
- }
-
- ~MidiIODeviceWatcher()
- {
- stop();
- }
-
- bool start()
- {
- HSTRING deviceSelector;
- HRESULT hr = factory->GetDeviceSelector (&deviceSelector);
- if (FAILED (hr))
- return false;
-
- auto deviceInformationFactory = WinRTWrapper::getInstance()->getWRLFactory<IDeviceInformationStatics> (&RuntimeClass_Windows_Devices_Enumeration_DeviceInformation[0]);
- if (deviceInformationFactory == nullptr)
- return false;
-
- hr = deviceInformationFactory->CreateWatcherAqsFilter (deviceSelector, watcher.resetAndGetPointerAddress());
- if (FAILED (hr))
- return false;
-
- class DeviceEnumerationThread : public Thread
- {
- public:
- DeviceEnumerationThread (String threadName, MidiIODeviceWatcher<COMFactoryType>& p)
- : Thread (threadName), parent (p)
- {}
-
- void run() override
- {
- auto parentPtr = &parent;
-
- parent.watcher->add_Added (
- Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformation*>> (
- [parentPtr](IDeviceWatcher*, IDeviceInformation* info) { return parentPtr->addDevice (info); }
- ).Get(),
- &parent.deviceAddedToken);
-
- parent.watcher->add_Removed (
- Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>> (
- [parentPtr](IDeviceWatcher*, IDeviceInformationUpdate* info) { return parentPtr->removeDevice (info); }
- ).Get(),
- &parent.deviceRemovedToken);
-
- EventRegistrationToken deviceEnumerationCompletedToken { 0 };
- parent.watcher->add_EnumerationCompleted (
- Callback<ITypedEventHandler<DeviceWatcher*, IInspectable*>> (
- [this](IDeviceWatcher*, IInspectable*) { enumerationCompleted.signal(); return S_OK; }
- ).Get(),
- &deviceEnumerationCompletedToken);
-
- parent.watcher->Start();
- enumerationCompleted.wait();
-
- if (deviceEnumerationCompletedToken.value != 0)
- parent.watcher->remove_EnumerationCompleted (deviceEnumerationCompletedToken);
- }
-
- private:
- MidiIODeviceWatcher<COMFactoryType>& parent;
- WaitableEvent enumerationCompleted;
- };
-
- DeviceEnumerationThread enumerationThread ("WinRT Device Enumeration Thread", *this);
- enumerationThread.startThread();
- enumerationThread.waitForThreadToExit (4000);
-
- return true;
- }
-
- bool stop()
- {
- if (watcher == nullptr)
- return true;
-
- if (deviceAddedToken.value != 0)
- {
- HRESULT hr = watcher->remove_Added (deviceAddedToken);
- if (FAILED (hr))
- return false;
-
- deviceAddedToken.value = 0;
- }
-
- if (deviceRemovedToken.value != 0)
- {
- HRESULT hr = watcher->remove_Removed (deviceRemovedToken);
- if (FAILED (hr))
- return false;
-
- deviceRemovedToken.value = 0;
- }
-
- HRESULT hr = watcher->Stop();
- if (FAILED (hr))
- return false;
-
- watcher = nullptr;
- return true;
- }
-
- HRESULT addDevice (IDeviceInformation* addedDeviceInfo)
- {
- boolean isEnabled;
- HRESULT hr = addedDeviceInfo->get_IsEnabled (&isEnabled);
- if (FAILED (hr))
- return S_OK;
-
- if (! isEnabled)
- return S_OK;
-
- const ScopedLock lock (deviceChanges);
-
- DeviceInfo info;
-
- HSTRING name;
- hr = addedDeviceInfo->get_Name (&name);
- if (FAILED (hr))
- return S_OK;
-
- info.name = WinRTWrapper::getInstance()->hStringToString (name);
-
- HSTRING id;
- hr = addedDeviceInfo->get_Id (&id);
- if (FAILED (hr))
- return S_OK;
-
- info.id = WinRTWrapper::getInstance()->hStringToString (id);
-
- boolean isDefault;
- hr = addedDeviceInfo->get_IsDefault (&isDefault);
- if (FAILED (hr))
- return S_OK;
-
- info.isDefault = isDefault != 0;
-
- connectedDevices.add (info);
-
- return S_OK;
- }
-
- HRESULT removeDevice (IDeviceInformationUpdate* removedDeviceInfo)
- {
- const ScopedLock lock (deviceChanges);
-
- HSTRING removedDeviceIdHstr;
- removedDeviceInfo->get_Id (&removedDeviceIdHstr);
- String removedDeviceId = WinRTWrapper::getInstance()->hStringToString (removedDeviceIdHstr);
-
- for (int i = 0; i < connectedDevices.size(); ++i)
- {
- if (connectedDevices[i].id == removedDeviceId)
- {
- connectedDevices.remove (i);
- break;
- }
- }
-
- return S_OK;
- }
-
- StringArray getDevices()
- {
- {
- const ScopedLock lock (deviceChanges);
- lastQueriedConnectedDevices = connectedDevices;
- }
-
- StringArray result;
- for (auto info : lastQueriedConnectedDevices.get())
- result.add (info.name);
-
- return result;
- }
-
- int getDefaultDeviceIndex()
- {
- auto& lastDevices = lastQueriedConnectedDevices.get();
- for (int i = 0; i < lastDevices.size(); ++i)
- if (lastDevices[i].isDefault)
- return i;
-
- return 0;
- }
-
- String getDeviceNameFromIndex (const int index)
- {
- if (isPositiveAndBelow (index, lastQueriedConnectedDevices.get().size()))
- return lastQueriedConnectedDevices.get()[index].name;
-
- return {};
- }
-
- String getDeviceID (const String name)
- {
- const ScopedLock lock (deviceChanges);
-
- for (auto info : connectedDevices)
- if (info.name == name)
- return info.id;
-
- return {};
- }
-
- ComSmartPtr<COMFactoryType>& factory;
-
- EventRegistrationToken deviceAddedToken { 0 },
- deviceRemovedToken { 0 };
-
- ComSmartPtr<IDeviceWatcher> watcher;
-
- Array<DeviceInfo> connectedDevices;
- CriticalSection deviceChanges;
- ThreadLocalValue<Array<DeviceInfo>> lastQueriedConnectedDevices;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiIODeviceWatcher);
- };
-
- template <typename COMFactoryType, typename COMInterfaceType, typename COMType>
- class OpenMidiPortThread : public Thread
- {
- public:
- OpenMidiPortThread (String threadName,
- String midiDeviceId,
- ComSmartPtr<COMFactoryType>& comFactory,
- ComSmartPtr<COMInterfaceType>& comPort)
- : Thread (threadName),
- deviceId (midiDeviceId),
- factory (comFactory),
- port (comPort)
- {
- }
-
- ~OpenMidiPortThread()
- {
- }
-
- void run() override
- {
- WinRTWrapper::ScopedHString hDeviceId (deviceId);
- ComSmartPtr<IAsyncOperation<COMType*>> asyncOp;
- HRESULT hr = factory->FromIdAsync (hDeviceId.get(), asyncOp.resetAndGetPointerAddress());
- if (FAILED (hr))
- return;
-
- hr = asyncOp->put_Completed (Callback<IAsyncOperationCompletedHandler<COMType*>> (
- [this] (IAsyncOperation<COMType*>* asyncOpPtr, AsyncStatus)
- {
- if (asyncOpPtr == nullptr)
- return E_ABORT;
-
- HRESULT hr = asyncOpPtr->GetResults (port.resetAndGetPointerAddress());
- if (FAILED (hr))
- return hr;
-
- portOpened.signal();
- return S_OK;
- }
- ).Get());
-
- // When using Bluetooth the asynchronous port opening operation will occasionally
- // hang, so we use a timeout. We will be able to remove this when Microsoft
- // improves the Bluetooth MIDI stack.
- portOpened.wait (2000);
- }
-
- const String deviceId;
- ComSmartPtr<COMFactoryType>& factory;
- ComSmartPtr<COMInterfaceType>& port;
-
- WaitableEvent portOpened { true };
- };
-
- struct WinRTInputWrapper : public InputWrapper
- {
- WinRTInputWrapper (WinRTMidiService& service,
- MidiInput* const input,
- const int index,
- MidiInputCallback& cb)
- : inputDevice (input),
- callback (cb),
- concatenator (4096)
- {
- const ScopedLock lock (service.inputDeviceWatcher->deviceChanges);
-
- deviceName = service.inputDeviceWatcher->getDeviceNameFromIndex (index);
- if (deviceName.isEmpty())
- throw std::runtime_error ("Invalid device index");
-
- const auto deviceID = service.inputDeviceWatcher->getDeviceID (deviceName);
- if (deviceID.isEmpty())
- throw std::runtime_error ("Device unavailable");
-
- OpenMidiPortThread<IMidiInPortStatics, IMidiInPort, MidiInPort> portThread ("Open WinRT MIDI input port",
- deviceID,
- service.midiInFactory,
- midiInPort);
- portThread.startThread();
- portThread.waitForThreadToExit (-1);
- if (midiInPort == nullptr)
- throw std::runtime_error ("Timed out waiting for midi input port creation");
-
- startTime = Time::getMillisecondCounterHiRes();
-
- HRESULT hr = midiInPort->add_MessageReceived (
- Callback<ITypedEventHandler<MidiInPort*, MidiMessageReceivedEventArgs*>> (
- [this] (IMidiInPort*, IMidiMessageReceivedEventArgs* args) { return midiInMessageReceived (args); }
- ).Get(),
- &midiInMessageToken);
- if (FAILED (hr))
- throw std::runtime_error ("Failed to set midi input callback");
- }
-
- ~WinRTInputWrapper()
- {
- if (midiInMessageToken.value != 0)
- midiInPort->remove_MessageReceived (midiInMessageToken);
-
- midiInPort = nullptr;
- }
-
- void start() override
- {
- if (!isStarted)
- {
- concatenator.reset();
- isStarted = true;
- }
- }
-
- void stop() override
- {
- if (isStarted)
- {
- isStarted = false;
- concatenator.reset();
- }
- }
-
- String getDeviceName() override
- {
- return deviceName;
- }
-
- HRESULT midiInMessageReceived (IMidiMessageReceivedEventArgs* args)
- {
- if (! isStarted)
- return S_OK;
-
- ComSmartPtr<IMidiMessage> message;
- HRESULT hr = args->get_Message (message.resetAndGetPointerAddress());
- if (FAILED (hr))
- return hr;
-
- ComSmartPtr<IBuffer> buffer;
- hr = message->get_RawData (buffer.resetAndGetPointerAddress());
- if (FAILED (hr))
- return hr;
-
- ComSmartPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
- hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress());
- if (FAILED (hr))
- return hr;
-
- uint8_t* bufferData = nullptr;
- hr = bufferByteAccess->Buffer (&bufferData);
- if (FAILED (hr))
- return hr;
-
- uint32_t numBytes = 0;
- hr = buffer->get_Length (&numBytes);
- if (FAILED (hr))
- return hr;
-
- ABI::Windows::Foundation::TimeSpan timespan;
- hr = message->get_Timestamp (×pan);
- if (FAILED (hr))
- return hr;
-
- concatenator.pushMidiData (bufferData,
- numBytes,
- convertTimeStamp (timespan.Duration),
- inputDevice,
- callback);
-
- return S_OK;
- }
-
- double convertTimeStamp (int64 timestamp)
- {
- const auto millisecondsSinceStart = static_cast<double> (timestamp) / 10000.0;
- double t = startTime + millisecondsSinceStart;
-
- const double now = Time::getMillisecondCounterHiRes();
- if (t > now)
- {
- if (t > now + 2.0)
- startTime -= 1.0;
-
- t = now;
- }
-
- return t * 0.001;
- }
-
- MidiInput* inputDevice;
- MidiInputCallback& callback;
- String deviceName;
- MidiDataConcatenator concatenator;
- ComSmartPtr<IMidiInPort> midiInPort;
- EventRegistrationToken midiInMessageToken { 0 };
-
- double startTime = 0;
- bool isStarted = false;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTInputWrapper);
- };
-
- struct WinRTOutputWrapper : public OutputWrapper
- {
- WinRTOutputWrapper (WinRTMidiService& service, const int index)
- {
- const ScopedLock lock (service.outputDeviceWatcher->deviceChanges);
-
- deviceName = service.outputDeviceWatcher->getDeviceNameFromIndex (index);
- if (deviceName.isEmpty())
- throw std::runtime_error ("Invalid device index");
-
- const auto deviceID = service.outputDeviceWatcher->getDeviceID (deviceName);
- if (deviceID.isEmpty())
- throw std::runtime_error ("Device unavailable");
-
- OpenMidiPortThread<IMidiOutPortStatics, IMidiOutPort, IMidiOutPort> portThread ("Open WinRT MIDI output port",
- deviceID,
- service.midiOutFactory,
- midiOutPort);
- portThread.startThread();
- portThread.waitForThreadToExit (-1);
- if (midiOutPort == nullptr)
- throw std::runtime_error ("Timed out waiting for midi output port creation");
-
- auto bufferFactory = WinRTWrapper::getInstance()->getWRLFactory<IBufferFactory> (&RuntimeClass_Windows_Storage_Streams_Buffer[0]);
- if (bufferFactory == nullptr)
- throw std::runtime_error ("Failed to create output buffer factory");
-
- HRESULT hr = bufferFactory->Create (static_cast<UINT32> (65536), buffer.resetAndGetPointerAddress());
- if (FAILED (hr))
- throw std::runtime_error ("Failed to create output buffer");
-
- hr = buffer->QueryInterface (bufferByteAccess.resetAndGetPointerAddress());
- if (FAILED (hr))
- throw std::runtime_error ("Failed to get buffer byte access");
-
- hr = bufferByteAccess->Buffer (&bufferData);
- if (FAILED (hr))
- throw std::runtime_error ("Failed to get buffer data pointer");
- }
-
- ~WinRTOutputWrapper() {}
-
- void sendMessageNow (const MidiMessage& message) override
- {
- const UINT32 numBytes = message.getRawDataSize();
- HRESULT hr = buffer->put_Length (numBytes);
- if (FAILED (hr))
- jassertfalse;
-
- memcpy_s (bufferData, numBytes, message.getRawData(), numBytes);
-
- midiOutPort->SendBuffer (buffer);
- }
-
- String getDeviceName() override
- {
- return deviceName;
- }
-
- String deviceName;
- ComSmartPtr<IMidiOutPort> midiOutPort;
- ComSmartPtr<IBuffer> buffer;
- ComSmartPtr<Windows::Storage::Streams::IBufferByteAccess> bufferByteAccess;
- uint8_t* bufferData = nullptr;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTOutputWrapper);
- };
-
- public:
- WinRTMidiService()
- {
- if (! WinRTWrapper::getInstance()->isInitialised())
- throw std::runtime_error ("Failed to initialise the WinRT wrapper");
-
- midiInFactory = WinRTWrapper::getInstance()->getWRLFactory<IMidiInPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiInPort[0]);
- if (midiInFactory == nullptr)
- throw std::runtime_error ("Failed to create midi in factory");
-
- midiOutFactory = WinRTWrapper::getInstance()->getWRLFactory<IMidiOutPortStatics> (&RuntimeClass_Windows_Devices_Midi_MidiOutPort[0]);
- if (midiOutFactory == nullptr)
- throw std::runtime_error ("Failed to create midi out factory");
-
- inputDeviceWatcher = new MidiIODeviceWatcher<IMidiInPortStatics> (midiInFactory);
- if (! inputDeviceWatcher->start())
- throw std::runtime_error ("Failed to start midi input device watcher");
-
- outputDeviceWatcher = new MidiIODeviceWatcher<IMidiOutPortStatics> (midiOutFactory);
- if (! outputDeviceWatcher->start())
- throw std::runtime_error ("Failed to start midi output device watcher");
- }
-
- ~WinRTMidiService()
- {
- }
-
- StringArray getDevices (bool isInput) override
- {
- return isInput ? inputDeviceWatcher ->getDevices()
- : outputDeviceWatcher->getDevices();
- }
-
- int getDefaultDeviceIndex (bool isInput) override
- {
- return isInput ? inputDeviceWatcher ->getDefaultDeviceIndex()
- : outputDeviceWatcher->getDefaultDeviceIndex();
- }
-
- InputWrapper* createInputWrapper (MidiInput* input, int index, MidiInputCallback* callback) override
- {
- return new WinRTInputWrapper (*this, input, index, *callback);
- }
-
- OutputWrapper* createOutputWrapper (int index) override
- {
- return new WinRTOutputWrapper (*this, index);
- }
-
- ComSmartPtr<IMidiInPortStatics> midiInFactory;
- ComSmartPtr<IMidiOutPortStatics> midiOutFactory;
-
- ScopedPointer<MidiIODeviceWatcher<IMidiInPortStatics>> inputDeviceWatcher;
- ScopedPointer<MidiIODeviceWatcher<IMidiOutPortStatics>> outputDeviceWatcher;
-
- JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WinRTMidiService)
- };
-
- #endif // JUCE_USE_WINRT_MIDI
-
- //==============================================================================
- class MidiService : public DeletedAtShutdown
- {
- public:
- ~MidiService();
-
- MidiServiceType* getService();
-
- juce_DeclareSingleton (MidiService, false)
-
- private:
- MidiService();
-
- ScopedPointer<MidiServiceType> internal;
- };
-
- juce_ImplementSingleton (MidiService)
-
- MidiService::~MidiService()
- {
- clearSingletonInstance();
- }
-
- MidiServiceType* MidiService::getService()
- {
- return internal.get();
- }
-
- MidiService::MidiService()
- {
- #if JUCE_USE_WINRT_MIDI
- try
- {
- internal = new WinRTMidiService();
- return;
- }
- catch (std::runtime_error&)
- {
- }
- #endif
-
- internal = new WindowsMidiService();
- }
-
- //==============================================================================
- StringArray MidiInput::getDevices()
- {
- return MidiService::getInstance()->getService()->getDevices (true);
- }
-
- int MidiInput::getDefaultDeviceIndex()
- {
- return MidiService::getInstance()->getService()->getDefaultDeviceIndex (true);
- }
-
- MidiInput::MidiInput (const String& deviceName)
- : name (deviceName)
- {
- }
-
- MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
- {
- if (callback == nullptr)
- return nullptr;
-
- ScopedPointer<MidiInput> in (new MidiInput ({}));
- ScopedPointer<MidiServiceType::InputWrapper> wrapper;
-
- try
- {
- wrapper = MidiService::getInstance()->getService()->createInputWrapper (in, index, callback);
- }
- catch (std::runtime_error&)
- {
- return nullptr;
- }
-
- in->setName (wrapper->getDeviceName());
- in->internal = wrapper.release();
- return in.release();
- }
-
- MidiInput::~MidiInput()
- {
- delete static_cast<MidiServiceType::InputWrapper*> (internal);
- }
-
- void MidiInput::start() { static_cast<MidiServiceType::InputWrapper*> (internal)->start(); }
- void MidiInput::stop() { static_cast<MidiServiceType::InputWrapper*> (internal)->stop(); }
-
- //==============================================================================
- StringArray MidiOutput::getDevices()
- {
- return MidiService::getInstance()->getService()->getDevices (false);
- }
-
- int MidiOutput::getDefaultDeviceIndex()
- {
- return MidiService::getInstance()->getService()->getDefaultDeviceIndex (false);
- }
-
- MidiOutput* MidiOutput::openDevice (const int index)
- {
- ScopedPointer<MidiServiceType::OutputWrapper> wrapper;
-
- try
- {
- wrapper = MidiService::getInstance()->getService()->createOutputWrapper (index);
- }
- catch (std::runtime_error&)
- {
- return nullptr;
- }
-
- ScopedPointer<MidiOutput> out (new MidiOutput (wrapper->getDeviceName()));
- out->internal = wrapper.release();
- return out.release();
- }
-
- MidiOutput::~MidiOutput()
- {
- stopBackgroundThread();
- delete static_cast<MidiServiceType::OutputWrapper*> (internal);
- }
-
- void MidiOutput::sendMessageNow (const MidiMessage& message)
- {
- static_cast<MidiServiceType::OutputWrapper*> (internal)->sendMessageNow (message);
- }
-
- } // namespace juce
|