1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/midi/midi_manager_win.h"
11 // Prevent unnecessary functions from being included from <mmsystem.h>
28 #include "base/bind.h"
29 #include "base/containers/hash_tables.h"
30 #include "base/message_loop/message_loop.h"
31 #include "base/strings/string16.h"
32 #include "base/strings/string_number_conversions.h"
33 #include "base/strings/string_piece.h"
34 #include "base/strings/stringprintf.h"
35 #include "base/strings/utf_string_conversions.h"
36 #include "base/system_monitor/system_monitor.h"
37 #include "base/threading/thread_checker.h"
38 #include "base/timer/timer.h"
39 #include "base/win/message_window.h"
40 #include "device/usb/usb_ids.h"
41 #include "media/midi/midi_message_queue.h"
42 #include "media/midi/midi_message_util.h"
43 #include "media/midi/midi_port_info.h"
49 static const size_t kBufferLength
= 32 * 1024;
51 // We assume that nullpter represents an invalid MIDI handle.
52 const HMIDIIN kInvalidMidiInHandle
= nullptr;
53 const HMIDIOUT kInvalidMidiOutHandle
= nullptr;
55 std::string
GetInErrorMessage(MMRESULT result
) {
56 wchar_t text
[MAXERRORLENGTH
];
57 MMRESULT get_result
= midiInGetErrorText(result
, text
, arraysize(text
));
58 if (get_result
!= MMSYSERR_NOERROR
) {
59 DLOG(ERROR
) << "Failed to get error message."
60 << " original error: " << result
61 << " midiInGetErrorText error: " << get_result
;
64 return base::WideToUTF8(text
);
67 std::string
GetOutErrorMessage(MMRESULT result
) {
68 wchar_t text
[MAXERRORLENGTH
];
69 MMRESULT get_result
= midiOutGetErrorText(result
, text
, arraysize(text
));
70 if (get_result
!= MMSYSERR_NOERROR
) {
71 DLOG(ERROR
) << "Failed to get error message."
72 << " original error: " << result
73 << " midiOutGetErrorText error: " << get_result
;
76 return base::WideToUTF8(text
);
79 std::string
MmversionToString(MMVERSION version
) {
80 return base::StringPrintf("%d.%d", HIBYTE(version
), LOBYTE(version
));
83 class MIDIHDRDeleter
{
85 void operator()(MIDIHDR
* header
) {
88 delete[] static_cast<char*>(header
->lpData
);
89 header
->lpData
= NULL
;
90 header
->dwBufferLength
= 0;
95 typedef scoped_ptr
<MIDIHDR
, MIDIHDRDeleter
> ScopedMIDIHDR
;
97 ScopedMIDIHDR
CreateMIDIHDR(size_t size
) {
98 ScopedMIDIHDR
header(new MIDIHDR
);
99 ZeroMemory(header
.get(), sizeof(*header
));
100 header
->lpData
= new char[size
];
101 header
->dwBufferLength
= static_cast<DWORD
>(size
);
102 return header
.Pass();
105 void SendShortMidiMessageInternal(HMIDIOUT midi_out_handle
,
106 const std::vector
<uint8
>& message
) {
107 DCHECK_LE(message
.size(), static_cast<size_t>(3))
108 << "A short MIDI message should be up to 3 bytes.";
110 DWORD packed_message
= 0;
111 for (size_t i
= 0; i
< message
.size(); ++i
)
112 packed_message
|= (static_cast<uint32
>(message
[i
]) << (i
* 8));
113 MMRESULT result
= midiOutShortMsg(midi_out_handle
, packed_message
);
114 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
115 << "Failed to output short message: " << GetOutErrorMessage(result
);
118 void SendLongMidiMessageInternal(HMIDIOUT midi_out_handle
,
119 const std::vector
<uint8
>& message
) {
120 // Implementation note:
121 // Sending a long MIDI message can be performed synchronously or
122 // asynchronously depending on the driver. There are 2 options to support both
124 // 1) Call midiOutLongMsg() API and wait for its completion within this
125 // function. In this approach, we can avoid memory copy by directly pointing
126 // |message| as the data buffer to be sent.
127 // 2) Allocate a buffer and copy |message| to it, then call midiOutLongMsg()
128 // API. The buffer will be freed in the MOM_DONE event hander, which tells
129 // us that the task of midiOutLongMsg() API is completed.
130 // Here we choose option 2) in favor of asynchronous design.
132 // Note for built-in USB-MIDI driver:
133 // From an observation on Windows 7/8.1 with a USB-MIDI keyboard,
134 // midiOutLongMsg() will be always blocked. Sending 64 bytes or less data
135 // takes roughly 300 usecs. Sending 2048 bytes or more data takes roughly
136 // |message.size() / (75 * 1024)| secs in practice. Here we put 60 KB size
137 // limit on SysEx message, with hoping that midiOutLongMsg will be blocked at
138 // most 1 sec or so with a typical USB-MIDI device.
139 const size_t kSysExSizeLimit
= 60 * 1024;
140 if (message
.size() >= kSysExSizeLimit
) {
141 DVLOG(1) << "Ingnoreing SysEx message due to the size limit"
142 << ", size = " << message
.size();
146 ScopedMIDIHDR
midi_header(CreateMIDIHDR(message
.size()));
147 std::copy(message
.begin(), message
.end(), midi_header
->lpData
);
149 MMRESULT result
= midiOutPrepareHeader(midi_out_handle
, midi_header
.get(),
150 sizeof(*midi_header
));
151 if (result
!= MMSYSERR_NOERROR
) {
152 DLOG(ERROR
) << "Failed to prepare output buffer: "
153 << GetOutErrorMessage(result
);
158 midiOutLongMsg(midi_out_handle
, midi_header
.get(), sizeof(*midi_header
));
159 if (result
!= MMSYSERR_NOERROR
) {
160 DLOG(ERROR
) << "Failed to output long message: "
161 << GetOutErrorMessage(result
);
162 result
= midiOutUnprepareHeader(midi_out_handle
, midi_header
.get(),
163 sizeof(*midi_header
));
164 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
165 << "Failed to uninitialize output buffer: "
166 << GetOutErrorMessage(result
);
170 // The ownership of |midi_header| is moved to MOM_DONE event handler.
171 midi_header
.release();
174 template <size_t array_size
>
175 base::string16
AsString16(const wchar_t(&buffer
)[array_size
]) {
177 for (len
= 0; len
< array_size
; ++len
) {
178 if (buffer
[len
] == L
'\0')
181 return base::string16(buffer
, len
);
184 struct MidiDeviceInfo final
{
185 explicit MidiDeviceInfo(const MIDIINCAPS2W
& caps
)
186 : manufacturer_id(caps
.wMid
),
187 product_id(caps
.wPid
),
188 driver_version(caps
.vDriverVersion
),
189 product_name(AsString16(caps
.szPname
)),
190 usb_vendor_id(ExtractUsbVendorIdIfExists(caps
)),
191 usb_product_id(ExtractUsbProductIdIfExists(caps
)),
192 is_usb_device(IsUsbDevice(caps
)) {}
193 explicit MidiDeviceInfo(const MIDIOUTCAPS2W
& caps
)
194 : manufacturer_id(caps
.wMid
),
195 product_id(caps
.wPid
),
196 driver_version(caps
.vDriverVersion
),
197 product_name(AsString16(caps
.szPname
)),
198 usb_vendor_id(ExtractUsbVendorIdIfExists(caps
)),
199 usb_product_id(ExtractUsbProductIdIfExists(caps
)),
200 is_usb_device(IsUsbDevice(caps
)) {}
201 explicit MidiDeviceInfo(const MidiDeviceInfo
& info
)
202 : manufacturer_id(info
.manufacturer_id
),
203 product_id(info
.product_id
),
204 driver_version(info
.driver_version
),
205 product_name(info
.product_name
),
206 usb_vendor_id(info
.usb_vendor_id
),
207 usb_product_id(info
.usb_product_id
),
208 is_usb_device(info
.is_usb_device
) {}
209 // Currently only following entities are considered when testing the equality
210 // of two MIDI devices.
211 // TODO(toyoshim): Consider to calculate MIDIPort.id here and use it as the
212 // key. See crbug.com/467448. Then optimize the data for |MidiPortInfo|.
213 const uint16 manufacturer_id
;
214 const uint16 product_id
;
215 const uint32 driver_version
;
216 const base::string16 product_name
;
217 const uint16 usb_vendor_id
;
218 const uint16 usb_product_id
;
219 const bool is_usb_device
;
221 // Required to be used as the key of base::hash_map.
222 bool operator==(const MidiDeviceInfo
& that
) const {
223 return manufacturer_id
== that
.manufacturer_id
&&
224 product_id
== that
.product_id
&&
225 driver_version
== that
.driver_version
&&
226 product_name
== that
.product_name
&&
227 is_usb_device
== that
.is_usb_device
&&
228 (is_usb_device
&& usb_vendor_id
== that
.usb_vendor_id
&&
229 usb_product_id
== that
.usb_product_id
);
232 // Hash function to be used in base::hash_map.
234 size_t operator()(const MidiDeviceInfo
& info
) const {
235 size_t hash
= info
.manufacturer_id
;
237 hash
+= info
.product_id
;
239 hash
+= info
.driver_version
;
241 hash
+= info
.product_name
.size();
243 if (!info
.product_name
.empty()) {
244 hash
+= info
.product_name
[0];
247 hash
+= info
.usb_vendor_id
;
249 hash
+= info
.usb_product_id
;
255 static bool IsUsbDevice(const MIDIINCAPS2W
& caps
) {
256 return IS_COMPATIBLE_USBAUDIO_MID(&caps
.ManufacturerGuid
) &&
257 IS_COMPATIBLE_USBAUDIO_PID(&caps
.ProductGuid
);
259 static bool IsUsbDevice(const MIDIOUTCAPS2W
& caps
) {
260 return IS_COMPATIBLE_USBAUDIO_MID(&caps
.ManufacturerGuid
) &&
261 IS_COMPATIBLE_USBAUDIO_PID(&caps
.ProductGuid
);
263 static uint16
ExtractUsbVendorIdIfExists(const MIDIINCAPS2W
& caps
) {
264 if (!IS_COMPATIBLE_USBAUDIO_MID(&caps
.ManufacturerGuid
))
266 return EXTRACT_USBAUDIO_MID(&caps
.ManufacturerGuid
);
268 static uint16
ExtractUsbVendorIdIfExists(const MIDIOUTCAPS2W
& caps
) {
269 if (!IS_COMPATIBLE_USBAUDIO_MID(&caps
.ManufacturerGuid
))
271 return EXTRACT_USBAUDIO_MID(&caps
.ManufacturerGuid
);
273 static uint16
ExtractUsbProductIdIfExists(const MIDIINCAPS2W
& caps
) {
274 if (!IS_COMPATIBLE_USBAUDIO_PID(&caps
.ProductGuid
))
276 return EXTRACT_USBAUDIO_PID(&caps
.ProductGuid
);
278 static uint16
ExtractUsbProductIdIfExists(const MIDIOUTCAPS2W
& caps
) {
279 if (!IS_COMPATIBLE_USBAUDIO_PID(&caps
.ProductGuid
))
281 return EXTRACT_USBAUDIO_PID(&caps
.ProductGuid
);
285 std::string
GetManufacturerName(const MidiDeviceInfo
& info
) {
286 if (info
.is_usb_device
) {
287 const char* name
= device::UsbIds::GetVendorName(info
.usb_vendor_id
);
288 return std::string(name
? name
: "");
291 switch (info
.manufacturer_id
) {
293 return "Microsoft Corporation";
295 // TODO(toyoshim): Support other manufacture IDs. crbug.com/472341.
300 bool IsUnsupportedDevice(const MidiDeviceInfo
& info
) {
301 return info
.manufacturer_id
== MM_MICROSOFT
&&
302 (info
.product_id
== MM_MSFT_WDMAUDIO_MIDIOUT
||
303 info
.product_id
== MM_MSFT_GENERIC_MIDISYNTH
);
306 using PortNumberCache
= base::hash_map
<
308 std::priority_queue
<uint32
, std::vector
<uint32
>, std::greater
<uint32
>>,
309 MidiDeviceInfo::Hasher
>;
311 struct MidiInputDeviceState final
: base::RefCounted
<MidiInputDeviceState
> {
312 explicit MidiInputDeviceState(const MidiDeviceInfo
& device_info
)
313 : device_info(device_info
),
314 midi_handle(kInvalidMidiInHandle
),
317 start_time_initialized(false) {}
319 const MidiDeviceInfo device_info
;
321 ScopedMIDIHDR midi_header
;
322 // Since Win32 multimedia system uses a relative time offset from when
323 // |midiInStart| API is called, we need to record when it is called.
324 base::TimeTicks start_time
;
325 // 0-based port index. We will try to reuse the previous port index when the
326 // MIDI device is closed then reopened.
328 // A sequence number which represents how many times |port_index| is reused.
329 // We can remove this field if we decide not to clear unsent events
330 // when the device is disconnected.
331 // See https://github.com/WebAudio/web-midi-api/issues/133
333 // True if |start_time| is initialized. This field is not used so far, but
334 // kept for the debugging purpose.
335 bool start_time_initialized
;
338 friend class base::RefCounted
<MidiInputDeviceState
>;
339 ~MidiInputDeviceState() {}
342 struct MidiOutputDeviceState final
: base::RefCounted
<MidiOutputDeviceState
> {
343 explicit MidiOutputDeviceState(const MidiDeviceInfo
& device_info
)
344 : device_info(device_info
),
345 midi_handle(kInvalidMidiOutHandle
),
350 const MidiDeviceInfo device_info
;
351 HMIDIOUT midi_handle
;
352 // 0-based port index. We will try to reuse the previous port index when the
353 // MIDI device is closed then reopened.
355 // A sequence number which represents how many times |port_index| is reused.
356 // We can remove this field if we decide not to clear unsent events
357 // when the device is disconnected.
358 // See https://github.com/WebAudio/web-midi-api/issues/133
360 // True if the device is already closed and |midi_handle| is considered to be
362 // TODO(toyoshim): Use std::atomic<bool> when it is allowed in Chromium
364 volatile bool closed
;
367 friend class base::RefCounted
<MidiOutputDeviceState
>;
368 ~MidiOutputDeviceState() {}
371 // The core logic of MIDI device handling for Windows. Basically this class is
372 // shared among following 4 threads:
373 // 1. Chrome IO Thread
374 // 2. OS Multimedia Thread
379 // MidiManager runs on Chrome IO thread. Device change notification is
380 // delivered to the thread through the SystemMonitor service.
381 // OnDevicesChanged() callback is invoked to update the MIDI device list.
382 // Note that in the current implementation we will try to open all the
383 // existing devices in practice. This is OK because trying to reopen a MIDI
384 // device that is already opened would simply fail, and there is no unwilling
387 // OS Multimedia Thread:
388 // This thread is maintained by the OS as a part of MIDI runtime, and
389 // responsible for receiving all the system initiated events such as device
390 // close, and receiving data. For performance reasons, most of potentially
391 // blocking operations will be dispatched into Task Thread.
394 // This thread will be used to call back following methods of MidiManager.
395 // - MidiManager::CompleteInitialization
396 // - MidiManager::AddInputPort
397 // - MidiManager::AddOutputPort
398 // - MidiManager::SetInputPortState
399 // - MidiManager::SetOutputPortState
400 // - MidiManager::ReceiveMidiData
403 // This thread will be used to call Win32 APIs to send MIDI message at the
404 // specified time. We don't want to call MIDI send APIs on Task Thread
405 // because those APIs could be performed synchronously, hence they could block
406 // the caller thread for a while. See the comment in
407 // SendLongMidiMessageInternal for details. Currently we expect that the
408 // blocking time would be less than 1 second.
409 class MidiServiceWinImpl
: public MidiServiceWin
,
410 public base::SystemMonitor::DevicesChangedObserver
{
413 : delegate_(nullptr),
414 sender_thread_("Windows MIDI sender thread"),
415 task_thread_("Windows MIDI task thread"),
416 destructor_started(false) {}
418 ~MidiServiceWinImpl() final
{
419 // Start() and Stop() of the threads, and AddDevicesChangeObserver() and
420 // RemoveDevicesChangeObserver() should be called on the same thread.
421 CHECK(thread_checker_
.CalledOnValidThread());
423 destructor_started
= true;
424 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
426 std::vector
<HMIDIIN
> input_devices
;
428 base::AutoLock
auto_lock(input_ports_lock_
);
429 for (auto it
: input_device_map_
)
430 input_devices
.push_back(it
.first
);
433 for (const auto handle
: input_devices
) {
434 MMRESULT result
= midiInClose(handle
);
435 if (result
== MIDIERR_STILLPLAYING
) {
436 result
= midiInReset(handle
);
437 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
438 << "midiInReset failed: " << GetInErrorMessage(result
);
439 result
= midiInClose(handle
);
441 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
442 << "midiInClose failed: " << GetInErrorMessage(result
);
447 std::vector
<HMIDIOUT
> output_devices
;
449 base::AutoLock
auto_lock(output_ports_lock_
);
450 for (auto it
: output_device_map_
)
451 output_devices
.push_back(it
.first
);
454 for (const auto handle
: output_devices
) {
455 MMRESULT result
= midiOutClose(handle
);
456 if (result
== MIDIERR_STILLPLAYING
) {
457 result
= midiOutReset(handle
);
458 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
459 << "midiOutReset failed: " << GetOutErrorMessage(result
);
460 result
= midiOutClose(handle
);
462 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
463 << "midiOutClose failed: " << GetOutErrorMessage(result
);
467 sender_thread_
.Stop();
471 // MidiServiceWin overrides:
472 void InitializeAsync(MidiServiceWinDelegate
* delegate
) final
{
473 // Start() and Stop() of the threads, and AddDevicesChangeObserver() and
474 // RemoveDevicesChangeObserver() should be called on the same thread.
475 CHECK(thread_checker_
.CalledOnValidThread());
477 delegate_
= delegate
;
479 sender_thread_
.Start();
480 task_thread_
.Start();
482 // Start monitoring device changes. This should start before the
483 // following UpdateDeviceList() call not to miss the event happening
484 // between the call and the observer registration.
485 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
489 task_thread_
.message_loop()->PostTask(
491 base::Bind(&MidiServiceWinImpl::CompleteInitializationOnTaskThread
,
492 base::Unretained(this), MIDI_OK
));
495 void SendMidiDataAsync(uint32 port_number
,
496 const std::vector
<uint8
>& data
,
497 base::TimeTicks time
) final
{
498 if (destructor_started
) {
499 LOG(ERROR
) << "ThreadSafeSendData failed because MidiServiceWinImpl is "
500 "being destructed. port: " << port_number
;
503 auto state
= GetOutputDeviceFromPort(port_number
);
505 LOG(ERROR
) << "ThreadSafeSendData failed due to an invalid port number. "
506 << "port: " << port_number
;
511 << "ThreadSafeSendData failed because target port is already closed."
512 << "port: " << port_number
;
515 const auto now
= base::TimeTicks::Now();
517 sender_thread_
.message_loop()->PostDelayedTask(
518 FROM_HERE
, base::Bind(&MidiServiceWinImpl::SendOnSenderThread
,
519 base::Unretained(this), port_number
,
520 state
->port_age
, data
, time
),
523 sender_thread_
.message_loop()->PostTask(
524 FROM_HERE
, base::Bind(&MidiServiceWinImpl::SendOnSenderThread
,
525 base::Unretained(this), port_number
,
526 state
->port_age
, data
, time
));
530 // base::SystemMonitor::DevicesChangedObserver overrides:
531 void OnDevicesChanged(base::SystemMonitor::DeviceType device_type
) final
{
532 CHECK(thread_checker_
.CalledOnValidThread());
533 if (destructor_started
)
536 switch (device_type
) {
537 case base::SystemMonitor::DEVTYPE_AUDIO_CAPTURE
:
538 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE
:
539 // Add case of other unrelated device types here.
541 case base::SystemMonitor::DEVTYPE_UNKNOWN
:
542 // Interested in MIDI devices. Try updating the device list.
545 // No default here to capture new DeviceType by compile time.
550 scoped_refptr
<MidiInputDeviceState
> GetInputDeviceFromHandle(
551 HMIDIIN midi_handle
) {
552 base::AutoLock
auto_lock(input_ports_lock_
);
553 const auto it
= input_device_map_
.find(midi_handle
);
554 return (it
!= input_device_map_
.end() ? it
->second
: nullptr);
557 scoped_refptr
<MidiOutputDeviceState
> GetOutputDeviceFromHandle(
558 HMIDIOUT midi_handle
) {
559 base::AutoLock
auto_lock(output_ports_lock_
);
560 const auto it
= output_device_map_
.find(midi_handle
);
561 return (it
!= output_device_map_
.end() ? it
->second
: nullptr);
564 scoped_refptr
<MidiOutputDeviceState
> GetOutputDeviceFromPort(
565 uint32 port_number
) {
566 base::AutoLock
auto_lock(output_ports_lock_
);
567 if (output_ports_
.size() <= port_number
)
569 return output_ports_
[port_number
];
572 void UpdateDeviceList() {
573 task_thread_
.message_loop()->PostTask(
574 FROM_HERE
, base::Bind(&MidiServiceWinImpl::UpdateDeviceListOnTaskThread
,
575 base::Unretained(this)));
578 /////////////////////////////////////////////////////////////////////////////
579 // Callbacks on the OS multimedia thread.
580 /////////////////////////////////////////////////////////////////////////////
583 OnMidiInEventOnMainlyMultimediaThread(HMIDIIN midi_in_handle
,
588 MidiServiceWinImpl
* self
= reinterpret_cast<MidiServiceWinImpl
*>(instance
);
593 self
->OnMidiInOpen(midi_in_handle
);
596 self
->OnMidiInDataOnMultimediaThread(midi_in_handle
, param1
, param2
);
599 self
->OnMidiInLongDataOnMultimediaThread(midi_in_handle
, param1
,
603 self
->OnMidiInCloseOnMultimediaThread(midi_in_handle
);
608 void OnMidiInOpen(HMIDIIN midi_in_handle
) {
610 MMRESULT result
= midiInGetID(midi_in_handle
, &device_id
);
611 if (result
!= MMSYSERR_NOERROR
) {
612 DLOG(ERROR
) << "midiInGetID failed: " << GetInErrorMessage(result
);
615 MIDIINCAPS2W caps
= {};
616 result
= midiInGetDevCaps(device_id
, reinterpret_cast<LPMIDIINCAPSW
>(&caps
),
618 if (result
!= MMSYSERR_NOERROR
) {
619 DLOG(ERROR
) << "midiInGetDevCaps failed: " << GetInErrorMessage(result
);
623 make_scoped_refptr(new MidiInputDeviceState(MidiDeviceInfo(caps
)));
624 state
->midi_handle
= midi_in_handle
;
625 state
->midi_header
= CreateMIDIHDR(kBufferLength
);
626 const auto& state_device_info
= state
->device_info
;
627 bool add_new_port
= false;
628 uint32 port_number
= 0;
630 base::AutoLock
auto_lock(input_ports_lock_
);
631 const auto it
= unused_input_ports_
.find(state_device_info
);
632 if (it
== unused_input_ports_
.end()) {
633 port_number
= static_cast<uint32
>(input_ports_
.size());
635 input_ports_
.push_back(nullptr);
636 input_ports_ages_
.push_back(0);
638 port_number
= it
->second
.top();
640 if (it
->second
.empty()) {
641 unused_input_ports_
.erase(it
);
644 input_ports_
[port_number
] = state
;
646 input_ports_ages_
[port_number
] += 1;
647 input_device_map_
[input_ports_
[port_number
]->midi_handle
] =
648 input_ports_
[port_number
];
649 input_ports_
[port_number
]->port_index
= port_number
;
650 input_ports_
[port_number
]->port_age
= input_ports_ages_
[port_number
];
652 // Several initial startup tasks cannot be done in MIM_OPEN handler.
653 task_thread_
.message_loop()->PostTask(
654 FROM_HERE
, base::Bind(&MidiServiceWinImpl::StartInputDeviceOnTaskThread
,
655 base::Unretained(this), midi_in_handle
));
657 const MidiPortInfo
port_info(
658 // TODO(toyoshim): Use a hash ID insted crbug.com/467448
659 base::IntToString(static_cast<int>(port_number
)),
660 GetManufacturerName(state_device_info
),
661 base::WideToUTF8(state_device_info
.product_name
),
662 MmversionToString(state_device_info
.driver_version
),
664 task_thread_
.message_loop()->PostTask(
665 FROM_HERE
, base::Bind(&MidiServiceWinImpl::AddInputPortOnTaskThread
,
666 base::Unretained(this), port_info
));
668 task_thread_
.message_loop()->PostTask(
670 base::Bind(&MidiServiceWinImpl::SetInputPortStateOnTaskThread
,
671 base::Unretained(this), port_number
,
672 MidiPortState::MIDI_PORT_CONNECTED
));
676 void OnMidiInDataOnMultimediaThread(HMIDIIN midi_in_handle
,
679 auto state
= GetInputDeviceFromHandle(midi_in_handle
);
682 const uint8 status_byte
= static_cast<uint8
>(param1
& 0xff);
683 const uint8 first_data_byte
= static_cast<uint8
>((param1
>> 8) & 0xff);
684 const uint8 second_data_byte
= static_cast<uint8
>((param1
>> 16) & 0xff);
685 const DWORD elapsed_ms
= param2
;
686 const size_t len
= GetMidiMessageLength(status_byte
);
687 const uint8 kData
[] = {status_byte
, first_data_byte
, second_data_byte
};
688 std::vector
<uint8
> data
;
689 data
.assign(kData
, kData
+ len
);
690 DCHECK_LE(len
, arraysize(kData
));
691 // MIM_DATA/MIM_LONGDATA message treats the time when midiInStart() is
692 // called as the origin of |elapsed_ms|.
693 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd757284.aspx
694 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd757286.aspx
695 const base::TimeTicks event_time
=
696 state
->start_time
+ base::TimeDelta::FromMilliseconds(elapsed_ms
);
697 task_thread_
.message_loop()->PostTask(
698 FROM_HERE
, base::Bind(&MidiServiceWinImpl::ReceiveMidiDataOnTaskThread
,
699 base::Unretained(this), state
->port_index
, data
,
703 void OnMidiInLongDataOnMultimediaThread(HMIDIIN midi_in_handle
,
706 auto state
= GetInputDeviceFromHandle(midi_in_handle
);
709 MIDIHDR
* header
= reinterpret_cast<MIDIHDR
*>(param1
);
710 const DWORD elapsed_ms
= param2
;
711 MMRESULT result
= MMSYSERR_NOERROR
;
712 if (destructor_started
) {
713 if (state
->midi_header
&&
714 (state
->midi_header
->dwFlags
& MHDR_PREPARED
) == MHDR_PREPARED
) {
716 midiInUnprepareHeader(state
->midi_handle
, state
->midi_header
.get(),
717 sizeof(*state
->midi_header
));
718 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
719 << "Failed to uninitialize input buffer: "
720 << GetInErrorMessage(result
);
724 if (header
->dwBytesRecorded
> 0) {
725 const uint8
* src
= reinterpret_cast<const uint8
*>(header
->lpData
);
726 std::vector
<uint8
> data
;
727 data
.assign(src
, src
+ header
->dwBytesRecorded
);
728 // MIM_DATA/MIM_LONGDATA message treats the time when midiInStart() is
729 // called as the origin of |elapsed_ms|.
730 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd757284.aspx
731 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd757286.aspx
732 const base::TimeTicks event_time
=
733 state
->start_time
+ base::TimeDelta::FromMilliseconds(elapsed_ms
);
734 task_thread_
.message_loop()->PostTask(
736 base::Bind(&MidiServiceWinImpl::ReceiveMidiDataOnTaskThread
,
737 base::Unretained(this), state
->port_index
, data
,
740 result
= midiInAddBuffer(state
->midi_handle
, header
, sizeof(*header
));
741 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
742 << "Failed to attach input buffer: " << GetInErrorMessage(result
)
743 << "port number:" << state
->port_index
;
746 void OnMidiInCloseOnMultimediaThread(HMIDIIN midi_in_handle
) {
747 auto state
= GetInputDeviceFromHandle(midi_in_handle
);
750 const uint32 port_number
= state
->port_index
;
751 const auto device_info(state
->device_info
);
753 base::AutoLock
auto_lock(input_ports_lock_
);
754 input_device_map_
.erase(state
->midi_handle
);
755 input_ports_
[port_number
] = nullptr;
756 input_ports_ages_
[port_number
] += 1;
757 unused_input_ports_
[device_info
].push(port_number
);
759 task_thread_
.message_loop()->PostTask(
761 base::Bind(&MidiServiceWinImpl::SetInputPortStateOnTaskThread
,
762 base::Unretained(this), port_number
,
763 MIDI_PORT_DISCONNECTED
));
767 OnMidiOutEventOnMainlyMultimediaThread(HMIDIOUT midi_out_handle
,
772 MidiServiceWinImpl
* self
= reinterpret_cast<MidiServiceWinImpl
*>(instance
);
777 self
->OnMidiOutOpen(midi_out_handle
, param1
, param2
);
780 self
->OnMidiOutDoneOnMultimediaThread(midi_out_handle
, param1
);
783 self
->OnMidiOutCloseOnMultimediaThread(midi_out_handle
);
788 void OnMidiOutOpen(HMIDIOUT midi_out_handle
,
792 MMRESULT result
= midiOutGetID(midi_out_handle
, &device_id
);
793 if (result
!= MMSYSERR_NOERROR
) {
794 DLOG(ERROR
) << "midiOutGetID failed: " << GetOutErrorMessage(result
);
797 MIDIOUTCAPS2W caps
= {};
798 result
= midiOutGetDevCaps(
799 device_id
, reinterpret_cast<LPMIDIOUTCAPSW
>(&caps
), sizeof(caps
));
800 if (result
!= MMSYSERR_NOERROR
) {
801 DLOG(ERROR
) << "midiInGetDevCaps failed: " << GetOutErrorMessage(result
);
805 make_scoped_refptr(new MidiOutputDeviceState(MidiDeviceInfo(caps
)));
806 state
->midi_handle
= midi_out_handle
;
807 const auto& state_device_info
= state
->device_info
;
808 if (IsUnsupportedDevice(state_device_info
))
810 bool add_new_port
= false;
811 uint32 port_number
= 0;
813 base::AutoLock
auto_lock(output_ports_lock_
);
814 const auto it
= unused_output_ports_
.find(state_device_info
);
815 if (it
== unused_output_ports_
.end()) {
816 port_number
= static_cast<uint32
>(output_ports_
.size());
818 output_ports_
.push_back(nullptr);
819 output_ports_ages_
.push_back(0);
821 port_number
= it
->second
.top();
823 if (it
->second
.empty())
824 unused_output_ports_
.erase(it
);
826 output_ports_
[port_number
] = state
;
827 output_ports_ages_
[port_number
] += 1;
828 output_device_map_
[output_ports_
[port_number
]->midi_handle
] =
829 output_ports_
[port_number
];
830 output_ports_
[port_number
]->port_index
= port_number
;
831 output_ports_
[port_number
]->port_age
= output_ports_ages_
[port_number
];
834 const MidiPortInfo
port_info(
835 // TODO(toyoshim): Use a hash ID insted. crbug.com/467448
836 base::IntToString(static_cast<int>(port_number
)),
837 GetManufacturerName(state_device_info
),
838 base::WideToUTF8(state_device_info
.product_name
),
839 MmversionToString(state_device_info
.driver_version
),
841 task_thread_
.message_loop()->PostTask(
842 FROM_HERE
, base::Bind(&MidiServiceWinImpl::AddOutputPortOnTaskThread
,
843 base::Unretained(this), port_info
));
845 task_thread_
.message_loop()->PostTask(
847 base::Bind(&MidiServiceWinImpl::SetOutputPortStateOnTaskThread
,
848 base::Unretained(this), port_number
, MIDI_PORT_CONNECTED
));
852 void OnMidiOutDoneOnMultimediaThread(HMIDIOUT midi_out_handle
,
854 auto state
= GetOutputDeviceFromHandle(midi_out_handle
);
857 // Take ownership of the MIDIHDR object.
858 ScopedMIDIHDR
header(reinterpret_cast<MIDIHDR
*>(param1
));
861 MMRESULT result
= midiOutUnprepareHeader(state
->midi_handle
, header
.get(),
863 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
)
864 << "Failed to uninitialize output buffer: "
865 << GetOutErrorMessage(result
);
868 void OnMidiOutCloseOnMultimediaThread(HMIDIOUT midi_out_handle
) {
869 auto state
= GetOutputDeviceFromHandle(midi_out_handle
);
872 const uint32 port_number
= state
->port_index
;
873 const auto device_info(state
->device_info
);
875 base::AutoLock
auto_lock(output_ports_lock_
);
876 output_device_map_
.erase(state
->midi_handle
);
877 output_ports_
[port_number
] = nullptr;
878 output_ports_ages_
[port_number
] += 1;
879 unused_output_ports_
[device_info
].push(port_number
);
880 state
->closed
= true;
882 task_thread_
.message_loop()->PostTask(
884 base::Bind(&MidiServiceWinImpl::SetOutputPortStateOnTaskThread
,
885 base::Unretained(this), port_number
,
886 MIDI_PORT_DISCONNECTED
));
889 /////////////////////////////////////////////////////////////////////////////
890 // Callbacks on the sender thread.
891 /////////////////////////////////////////////////////////////////////////////
893 void AssertOnSenderThread() {
894 DCHECK_EQ(sender_thread_
.thread_id(), base::PlatformThread::CurrentId());
897 void SendOnSenderThread(uint32 port_number
,
899 const std::vector
<uint8
>& data
,
900 base::TimeTicks time
) {
901 AssertOnSenderThread();
902 if (destructor_started
) {
903 LOG(ERROR
) << "ThreadSafeSendData failed because MidiServiceWinImpl is "
904 "being destructed. port: " << port_number
;
906 auto state
= GetOutputDeviceFromPort(port_number
);
908 LOG(ERROR
) << "ThreadSafeSendData failed due to an invalid port number. "
909 << "port: " << port_number
;
914 << "ThreadSafeSendData failed because target port is already closed."
915 << "port: " << port_number
;
918 if (state
->port_age
!= port_age
) {
920 << "ThreadSafeSendData failed because target port is being closed."
921 << "port: " << port_number
<< "expected port age: " << port_age
922 << "actual port age: " << state
->port_age
;
925 // MIDI Running status must be filtered out.
926 MidiMessageQueue
message_queue(false);
927 message_queue
.Add(data
);
928 std::vector
<uint8
> message
;
930 if (destructor_started
)
934 message_queue
.Get(&message
);
937 // SendShortMidiMessageInternal can send a MIDI message up to 3 bytes.
938 if (message
.size() <= 3)
939 SendShortMidiMessageInternal(state
->midi_handle
, message
);
941 SendLongMidiMessageInternal(state
->midi_handle
, message
);
945 /////////////////////////////////////////////////////////////////////////////
946 // Callbacks on the task thread.
947 /////////////////////////////////////////////////////////////////////////////
949 void AssertOnTaskThread() {
950 DCHECK_EQ(task_thread_
.thread_id(), base::PlatformThread::CurrentId());
953 void UpdateDeviceListOnTaskThread() {
954 AssertOnTaskThread();
955 const UINT num_in_devices
= midiInGetNumDevs();
956 for (UINT device_id
= 0; device_id
< num_in_devices
; ++device_id
) {
957 // Here we use |CALLBACK_FUNCTION| to subscribe MIM_DATA, MIM_LONGDATA,
958 // MIM_OPEN, and MIM_CLOSE events.
959 // - MIM_DATA: This is the only way to get a short MIDI message with
960 // timestamp information.
961 // - MIM_LONGDATA: This is the only way to get a long MIDI message with
962 // timestamp information.
963 // - MIM_OPEN: This event is sent the input device is opened. Note that
964 // this message is called on the caller thread.
965 // - MIM_CLOSE: This event is sent when 1) midiInClose() is called, or 2)
966 // the MIDI device becomes unavailable for some reasons, e.g., the
967 // cable is disconnected. As for the former case, HMIDIOUT will be
968 // invalidated soon after the callback is finished. As for the later
969 // case, however, HMIDIOUT continues to be valid until midiInClose()
971 HMIDIIN midi_handle
= kInvalidMidiInHandle
;
972 const MMRESULT result
= midiInOpen(
973 &midi_handle
, device_id
,
974 reinterpret_cast<DWORD_PTR
>(&OnMidiInEventOnMainlyMultimediaThread
),
975 reinterpret_cast<DWORD_PTR
>(this), CALLBACK_FUNCTION
);
976 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
&& result
!= MMSYSERR_ALLOCATED
)
977 << "Failed to open output device. "
978 << " id: " << device_id
<< " message: " << GetInErrorMessage(result
);
981 const UINT num_out_devices
= midiOutGetNumDevs();
982 for (UINT device_id
= 0; device_id
< num_out_devices
; ++device_id
) {
983 // Here we use |CALLBACK_FUNCTION| to subscribe MOM_DONE, MOM_OPEN, and
985 // - MOM_DONE: SendLongMidiMessageInternal() relies on this event to clean
986 // up the backing store where a long MIDI message is stored.
987 // - MOM_OPEN: This event is sent the output device is opened. Note that
988 // this message is called on the caller thread.
989 // - MOM_CLOSE: This event is sent when 1) midiOutClose() is called, or 2)
990 // the MIDI device becomes unavailable for some reasons, e.g., the
991 // cable is disconnected. As for the former case, HMIDIOUT will be
992 // invalidated soon after the callback is finished. As for the later
993 // case, however, HMIDIOUT continues to be valid until midiOutClose()
995 HMIDIOUT midi_handle
= kInvalidMidiOutHandle
;
996 const MMRESULT result
= midiOutOpen(
997 &midi_handle
, device_id
,
998 reinterpret_cast<DWORD_PTR
>(&OnMidiOutEventOnMainlyMultimediaThread
),
999 reinterpret_cast<DWORD_PTR
>(this), CALLBACK_FUNCTION
);
1000 DLOG_IF(ERROR
, result
!= MMSYSERR_NOERROR
&& result
!= MMSYSERR_ALLOCATED
)
1001 << "Failed to open output device. "
1002 << " id: " << device_id
<< " message: " << GetOutErrorMessage(result
);
1006 void StartInputDeviceOnTaskThread(HMIDIIN midi_in_handle
) {
1007 AssertOnTaskThread();
1008 auto state
= GetInputDeviceFromHandle(midi_in_handle
);
1012 midiInPrepareHeader(state
->midi_handle
, state
->midi_header
.get(),
1013 sizeof(*state
->midi_header
));
1014 if (result
!= MMSYSERR_NOERROR
) {
1015 DLOG(ERROR
) << "Failed to initialize input buffer: "
1016 << GetInErrorMessage(result
);
1019 result
= midiInAddBuffer(state
->midi_handle
, state
->midi_header
.get(),
1020 sizeof(*state
->midi_header
));
1021 if (result
!= MMSYSERR_NOERROR
) {
1022 DLOG(ERROR
) << "Failed to attach input buffer: "
1023 << GetInErrorMessage(result
);
1026 result
= midiInStart(state
->midi_handle
);
1027 if (result
!= MMSYSERR_NOERROR
) {
1028 DLOG(ERROR
) << "Failed to start input port: "
1029 << GetInErrorMessage(result
);
1032 state
->start_time
= base::TimeTicks::Now();
1033 state
->start_time_initialized
= true;
1036 void CompleteInitializationOnTaskThread(MidiResult result
) {
1037 AssertOnTaskThread();
1038 delegate_
->OnCompleteInitialization(result
);
1041 void ReceiveMidiDataOnTaskThread(uint32 port_index
,
1042 std::vector
<uint8
> data
,
1043 base::TimeTicks time
) {
1044 AssertOnTaskThread();
1045 delegate_
->OnReceiveMidiData(port_index
, data
, time
);
1048 void AddInputPortOnTaskThread(MidiPortInfo info
) {
1049 AssertOnTaskThread();
1050 delegate_
->OnAddInputPort(info
);
1053 void AddOutputPortOnTaskThread(MidiPortInfo info
) {
1054 AssertOnTaskThread();
1055 delegate_
->OnAddOutputPort(info
);
1058 void SetInputPortStateOnTaskThread(uint32 port_index
, MidiPortState state
) {
1059 AssertOnTaskThread();
1060 delegate_
->OnSetInputPortState(port_index
, state
);
1063 void SetOutputPortStateOnTaskThread(uint32 port_index
, MidiPortState state
) {
1064 AssertOnTaskThread();
1065 delegate_
->OnSetOutputPortState(port_index
, state
);
1068 /////////////////////////////////////////////////////////////////////////////
1070 /////////////////////////////////////////////////////////////////////////////
1072 // Does not take ownership.
1073 MidiServiceWinDelegate
* delegate_
;
1075 base::ThreadChecker thread_checker_
;
1077 base::Thread sender_thread_
;
1078 base::Thread task_thread_
;
1080 base::Lock input_ports_lock_
;
1081 base::hash_map
<HMIDIIN
, scoped_refptr
<MidiInputDeviceState
>>
1082 input_device_map_
; // GUARDED_BY(input_ports_lock_)
1083 PortNumberCache unused_input_ports_
; // GUARDED_BY(input_ports_lock_)
1084 std::vector
<scoped_refptr
<MidiInputDeviceState
>>
1085 input_ports_
; // GUARDED_BY(input_ports_lock_)
1086 std::vector
<uint64
> input_ports_ages_
; // GUARDED_BY(input_ports_lock_)
1088 base::Lock output_ports_lock_
;
1089 base::hash_map
<HMIDIOUT
, scoped_refptr
<MidiOutputDeviceState
>>
1090 output_device_map_
; // GUARDED_BY(output_ports_lock_)
1091 PortNumberCache unused_output_ports_
; // GUARDED_BY(output_ports_lock_)
1092 std::vector
<scoped_refptr
<MidiOutputDeviceState
>>
1093 output_ports_
; // GUARDED_BY(output_ports_lock_)
1094 std::vector
<uint64
> output_ports_ages_
; // GUARDED_BY(output_ports_lock_)
1096 // True if one thread reached MidiServiceWinImpl::~MidiServiceWinImpl(). Note
1097 // that MidiServiceWinImpl::~MidiServiceWinImpl() is blocked until
1098 // |sender_thread_|, and |task_thread_| are stopped.
1099 // This flag can be used as the signal that when background tasks must be
1101 // TODO(toyoshim): Use std::atomic<bool> when it is allowed.
1102 volatile bool destructor_started
;
1104 DISALLOW_COPY_AND_ASSIGN(MidiServiceWinImpl
);
1109 MidiManagerWin::MidiManagerWin() {
1112 MidiManagerWin::~MidiManagerWin() {
1113 midi_service_
.reset();
1116 void MidiManagerWin::StartInitialization() {
1117 midi_service_
.reset(new MidiServiceWinImpl
);
1118 // Note that |CompleteInitialization()| will be called from the callback.
1119 midi_service_
->InitializeAsync(this);
1122 void MidiManagerWin::DispatchSendMidiData(MidiManagerClient
* client
,
1124 const std::vector
<uint8
>& data
,
1129 base::TimeTicks time_to_send
= base::TimeTicks::Now();
1130 if (timestamp
!= 0.0) {
1132 base::TimeTicks() + base::TimeDelta::FromMicroseconds(
1133 timestamp
* base::Time::kMicrosecondsPerSecond
);
1135 midi_service_
->SendMidiDataAsync(port_index
, data
, time_to_send
);
1137 // TOOD(toyoshim): This calculation should be done when the date is actually
1139 client
->AccumulateMidiBytesSent(data
.size());
1142 void MidiManagerWin::OnCompleteInitialization(MidiResult result
) {
1143 CompleteInitialization(result
);
1146 void MidiManagerWin::OnAddInputPort(MidiPortInfo info
) {
1150 void MidiManagerWin::OnAddOutputPort(MidiPortInfo info
) {
1151 AddOutputPort(info
);
1154 void MidiManagerWin::OnSetInputPortState(uint32 port_index
,
1155 MidiPortState state
) {
1156 SetInputPortState(port_index
, state
);
1159 void MidiManagerWin::OnSetOutputPortState(uint32 port_index
,
1160 MidiPortState state
) {
1161 SetOutputPortState(port_index
, state
);
1164 void MidiManagerWin::OnReceiveMidiData(uint32 port_index
,
1165 const std::vector
<uint8
>& data
,
1166 base::TimeTicks time
) {
1167 ReceiveMidiData(port_index
, &data
[0], data
.size(), time
);
1170 MidiManager
* MidiManager::Create() {
1171 return new MidiManagerWin();
1175 } // namespace media