blob: 9f9a99c2efbef4e7c2ecdcaf7f466f7b15e69508 [file] [log] [blame]
shaochuane58f9c72016-08-30 22:27:08 -07001// Copyright 2016 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.
4
5#include "media/midi/midi_manager_winrt.h"
6
qiankun.miao53f2d662016-09-02 17:44:08 -07007#pragma warning(disable : 4467)
shaochuan80f1fba2016-09-01 20:44:51 -07008
shaochuan4eff30e2016-09-09 01:24:14 -07009#include <initguid.h> // Required by <devpkey.h>
10
11#include <cfgmgr32.h>
shaochuane58f9c72016-08-30 22:27:08 -070012#include <comdef.h>
shaochuan4eff30e2016-09-09 01:24:14 -070013#include <devpkey.h>
robliao048b1572017-04-21 12:46:39 -070014#include <objbase.h>
shaochuane58f9c72016-08-30 22:27:08 -070015#include <robuffer.h>
16#include <windows.devices.enumeration.h>
17#include <windows.devices.midi.h>
18#include <wrl/event.h>
19
20#include <iomanip>
21#include <unordered_map>
22#include <unordered_set>
23
24#include "base/bind.h"
shaochuan9ff63b82016-09-01 01:58:44 -070025#include "base/scoped_generic.h"
Gabriel Charette78f94a02017-05-16 14:03:45 -040026#include "base/single_thread_task_runner.h"
shaochuan17bc4a02016-09-06 01:42:12 -070027#include "base/strings/string_util.h"
shaochuane58f9c72016-08-30 22:27:08 -070028#include "base/strings/utf_string_conversions.h"
29#include "base/threading/thread_checker.h"
30#include "base/threading/thread_task_runner_handle.h"
31#include "base/timer/timer.h"
32#include "base/win/scoped_comptr.h"
shaochuane58f9c72016-08-30 22:27:08 -070033#include "media/midi/midi_scheduler.h"
34
shaochuane58f9c72016-08-30 22:27:08 -070035namespace midi {
36namespace {
37
38namespace WRL = Microsoft::WRL;
39
40using namespace ABI::Windows::Devices::Enumeration;
41using namespace ABI::Windows::Devices::Midi;
42using namespace ABI::Windows::Foundation;
43using namespace ABI::Windows::Storage::Streams;
44
45using base::win::ScopedComPtr;
toyoshimec2570a2016-10-21 02:15:27 -070046using mojom::PortState;
toyoshim2f3a48f2016-10-17 01:54:13 -070047using mojom::Result;
shaochuane58f9c72016-08-30 22:27:08 -070048
49// Helpers for printing HRESULTs.
50struct PrintHr {
51 PrintHr(HRESULT hr) : hr(hr) {}
52 HRESULT hr;
53};
54
55std::ostream& operator<<(std::ostream& os, const PrintHr& phr) {
56 std::ios_base::fmtflags ff = os.flags();
57 os << _com_error(phr.hr).ErrorMessage() << " (0x" << std::hex
58 << std::uppercase << std::setfill('0') << std::setw(8) << phr.hr << ")";
59 os.flags(ff);
60 return os;
61}
62
shaochuan9ff63b82016-09-01 01:58:44 -070063// Provides access to functions in combase.dll which may not be available on
64// Windows 7. Loads functions dynamically at runtime to prevent library
dalecurtis3f5ce942017-02-10 18:08:18 -080065// dependencies.
shaochuan9ff63b82016-09-01 01:58:44 -070066class CombaseFunctions {
67 public:
68 CombaseFunctions() = default;
69
70 ~CombaseFunctions() {
71 if (combase_dll_)
72 ::FreeLibrary(combase_dll_);
73 }
74
75 bool LoadFunctions() {
76 combase_dll_ = ::LoadLibrary(L"combase.dll");
77 if (!combase_dll_)
78 return false;
79
80 get_factory_func_ = reinterpret_cast<decltype(&::RoGetActivationFactory)>(
81 ::GetProcAddress(combase_dll_, "RoGetActivationFactory"));
82 if (!get_factory_func_)
83 return false;
84
85 create_string_func_ = reinterpret_cast<decltype(&::WindowsCreateString)>(
86 ::GetProcAddress(combase_dll_, "WindowsCreateString"));
87 if (!create_string_func_)
88 return false;
89
90 delete_string_func_ = reinterpret_cast<decltype(&::WindowsDeleteString)>(
91 ::GetProcAddress(combase_dll_, "WindowsDeleteString"));
92 if (!delete_string_func_)
93 return false;
94
95 get_string_raw_buffer_func_ =
96 reinterpret_cast<decltype(&::WindowsGetStringRawBuffer)>(
97 ::GetProcAddress(combase_dll_, "WindowsGetStringRawBuffer"));
98 if (!get_string_raw_buffer_func_)
99 return false;
100
101 return true;
102 }
103
104 HRESULT RoGetActivationFactory(HSTRING class_id,
105 const IID& iid,
106 void** out_factory) {
107 DCHECK(get_factory_func_);
108 return get_factory_func_(class_id, iid, out_factory);
109 }
110
111 HRESULT WindowsCreateString(const base::char16* src,
112 uint32_t len,
113 HSTRING* out_hstr) {
114 DCHECK(create_string_func_);
115 return create_string_func_(src, len, out_hstr);
116 }
117
118 HRESULT WindowsDeleteString(HSTRING hstr) {
119 DCHECK(delete_string_func_);
120 return delete_string_func_(hstr);
121 }
122
123 const base::char16* WindowsGetStringRawBuffer(HSTRING hstr,
124 uint32_t* out_len) {
125 DCHECK(get_string_raw_buffer_func_);
126 return get_string_raw_buffer_func_(hstr, out_len);
127 }
128
129 private:
130 HMODULE combase_dll_ = nullptr;
131
132 decltype(&::RoGetActivationFactory) get_factory_func_ = nullptr;
133 decltype(&::WindowsCreateString) create_string_func_ = nullptr;
134 decltype(&::WindowsDeleteString) delete_string_func_ = nullptr;
135 decltype(&::WindowsGetStringRawBuffer) get_string_raw_buffer_func_ = nullptr;
136};
137
dalecurtis3f5ce942017-02-10 18:08:18 -0800138CombaseFunctions* GetCombaseFunctions() {
139 static CombaseFunctions* functions = new CombaseFunctions();
140 return functions;
141}
shaochuan9ff63b82016-09-01 01:58:44 -0700142
143// Scoped HSTRING class to maintain lifetime of HSTRINGs allocated with
144// WindowsCreateString().
145class ScopedHStringTraits {
146 public:
147 static HSTRING InvalidValue() { return nullptr; }
148
149 static void Free(HSTRING hstr) {
dalecurtis3f5ce942017-02-10 18:08:18 -0800150 GetCombaseFunctions()->WindowsDeleteString(hstr);
shaochuan9ff63b82016-09-01 01:58:44 -0700151 }
152};
153
154class ScopedHString : public base::ScopedGeneric<HSTRING, ScopedHStringTraits> {
155 public:
156 explicit ScopedHString(const base::char16* str) : ScopedGeneric(nullptr) {
157 HSTRING hstr;
dalecurtis3f5ce942017-02-10 18:08:18 -0800158 HRESULT hr = GetCombaseFunctions()->WindowsCreateString(
shaochuan9ff63b82016-09-01 01:58:44 -0700159 str, static_cast<uint32_t>(wcslen(str)), &hstr);
160 if (FAILED(hr))
161 VLOG(1) << "WindowsCreateString failed: " << PrintHr(hr);
162 else
163 reset(hstr);
164 }
165};
166
shaochuane58f9c72016-08-30 22:27:08 -0700167// Factory functions that activate and create WinRT components. The caller takes
168// ownership of the returning ComPtr.
169template <typename InterfaceType, base::char16 const* runtime_class_id>
170ScopedComPtr<InterfaceType> WrlStaticsFactory() {
171 ScopedComPtr<InterfaceType> com_ptr;
172
shaochuan9ff63b82016-09-01 01:58:44 -0700173 ScopedHString class_id_hstring(runtime_class_id);
174 if (!class_id_hstring.is_valid()) {
175 com_ptr = nullptr;
176 return com_ptr;
177 }
178
dalecurtis3f5ce942017-02-10 18:08:18 -0800179 HRESULT hr = GetCombaseFunctions()->RoGetActivationFactory(
robliao048b1572017-04-21 12:46:39 -0700180 class_id_hstring.get(), IID_PPV_ARGS(&com_ptr));
shaochuane58f9c72016-08-30 22:27:08 -0700181 if (FAILED(hr)) {
shaochuan9ff63b82016-09-01 01:58:44 -0700182 VLOG(1) << "RoGetActivationFactory failed: " << PrintHr(hr);
shaochuane58f9c72016-08-30 22:27:08 -0700183 com_ptr = nullptr;
184 }
185
186 return com_ptr;
187}
188
shaochuan80f1fba2016-09-01 20:44:51 -0700189std::string HStringToString(HSTRING hstr) {
shaochuane58f9c72016-08-30 22:27:08 -0700190 // Note: empty HSTRINGs are represent as nullptr, and instantiating
191 // std::string with nullptr (in base::WideToUTF8) is undefined behavior.
shaochuan9ff63b82016-09-01 01:58:44 -0700192 const base::char16* buffer =
dalecurtis3f5ce942017-02-10 18:08:18 -0800193 GetCombaseFunctions()->WindowsGetStringRawBuffer(hstr, nullptr);
shaochuane58f9c72016-08-30 22:27:08 -0700194 if (buffer)
195 return base::WideToUTF8(buffer);
196 return std::string();
197}
198
199template <typename T>
200std::string GetIdString(T* obj) {
shaochuan80f1fba2016-09-01 20:44:51 -0700201 HSTRING result;
202 HRESULT hr = obj->get_Id(&result);
203 if (FAILED(hr)) {
204 VLOG(1) << "get_Id failed: " << PrintHr(hr);
205 return std::string();
206 }
207 return HStringToString(result);
shaochuane58f9c72016-08-30 22:27:08 -0700208}
209
210template <typename T>
211std::string GetDeviceIdString(T* obj) {
shaochuan80f1fba2016-09-01 20:44:51 -0700212 HSTRING result;
213 HRESULT hr = obj->get_DeviceId(&result);
214 if (FAILED(hr)) {
215 VLOG(1) << "get_DeviceId failed: " << PrintHr(hr);
216 return std::string();
217 }
218 return HStringToString(result);
shaochuane58f9c72016-08-30 22:27:08 -0700219}
220
221std::string GetNameString(IDeviceInformation* info) {
shaochuan80f1fba2016-09-01 20:44:51 -0700222 HSTRING result;
223 HRESULT hr = info->get_Name(&result);
224 if (FAILED(hr)) {
225 VLOG(1) << "get_Name failed: " << PrintHr(hr);
226 return std::string();
227 }
228 return HStringToString(result);
shaochuane58f9c72016-08-30 22:27:08 -0700229}
230
231HRESULT GetPointerToBufferData(IBuffer* buffer, uint8_t** out) {
232 ScopedComPtr<Windows::Storage::Streams::IBufferByteAccess> buffer_byte_access;
233
robliao026fda22017-05-17 12:10:54 -0700234 HRESULT hr = buffer->QueryInterface(IID_PPV_ARGS(&buffer_byte_access));
shaochuane58f9c72016-08-30 22:27:08 -0700235 if (FAILED(hr)) {
236 VLOG(1) << "QueryInterface failed: " << PrintHr(hr);
237 return hr;
238 }
239
240 // Lifetime of the pointing buffer is controlled by the buffer object.
241 hr = buffer_byte_access->Buffer(out);
242 if (FAILED(hr)) {
243 VLOG(1) << "Buffer failed: " << PrintHr(hr);
244 return hr;
245 }
246
247 return S_OK;
248}
249
shaochuan110262b2016-08-31 02:15:16 -0700250// Checks if given DeviceInformation represent a Microsoft GS Wavetable Synth
251// instance.
252bool IsMicrosoftSynthesizer(IDeviceInformation* info) {
253 auto midi_synthesizer_statics =
254 WrlStaticsFactory<IMidiSynthesizerStatics,
255 RuntimeClass_Windows_Devices_Midi_MidiSynthesizer>();
256 boolean result = FALSE;
257 HRESULT hr = midi_synthesizer_statics->IsSynthesizer(info, &result);
258 VLOG_IF(1, FAILED(hr)) << "IsSynthesizer failed: " << PrintHr(hr);
259 return result != FALSE;
260}
261
shaochuan4eff30e2016-09-09 01:24:14 -0700262void GetDevPropString(DEVINST handle,
263 const DEVPROPKEY* devprop_key,
264 std::string* out) {
265 DEVPROPTYPE devprop_type;
266 unsigned long buffer_size = 0;
shaochuan17bc4a02016-09-06 01:42:12 -0700267
shaochuan4eff30e2016-09-09 01:24:14 -0700268 // Retrieve |buffer_size| and allocate buffer later for receiving data.
269 CONFIGRET cr = CM_Get_DevNode_Property(handle, devprop_key, &devprop_type,
270 nullptr, &buffer_size, 0);
271 if (cr != CR_BUFFER_SMALL) {
272 // Here we print error codes in hex instead of using PrintHr() with
273 // HRESULT_FROM_WIN32() and CM_MapCrToWin32Err(), since only a minor set of
274 // CONFIGRET values are mapped to Win32 errors. Same for following VLOG()s.
275 VLOG(1) << "CM_Get_DevNode_Property failed: CONFIGRET 0x" << std::hex << cr;
276 return;
shaochuan17bc4a02016-09-06 01:42:12 -0700277 }
shaochuan4eff30e2016-09-09 01:24:14 -0700278 if (devprop_type != DEVPROP_TYPE_STRING) {
279 VLOG(1) << "CM_Get_DevNode_Property returns wrong data type, "
280 << "expected DEVPROP_TYPE_STRING";
281 return;
282 }
shaochuan17bc4a02016-09-06 01:42:12 -0700283
shaochuan4eff30e2016-09-09 01:24:14 -0700284 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
285
286 // Receive property data.
287 cr = CM_Get_DevNode_Property(handle, devprop_key, &devprop_type, buffer.get(),
288 &buffer_size, 0);
289 if (cr != CR_SUCCESS)
290 VLOG(1) << "CM_Get_DevNode_Property failed: CONFIGRET 0x" << std::hex << cr;
291 else
292 *out = base::WideToUTF8(reinterpret_cast<base::char16*>(buffer.get()));
293}
shaochuan17bc4a02016-09-06 01:42:12 -0700294
295// Retrieves manufacturer (provider) and version information of underlying
shaochuan4eff30e2016-09-09 01:24:14 -0700296// device driver through PnP Configuration Manager, given device (interface) ID
297// provided by WinRT. |out_manufacturer| and |out_driver_version| won't be
298// modified if retrieval fails.
shaochuan17bc4a02016-09-06 01:42:12 -0700299//
300// Device instance ID is extracted from device (interface) ID provided by WinRT
301// APIs, for example from the following interface ID:
302// \\?\SWD#MMDEVAPI#MIDII_60F39FCA.P_0002#{504be32c-ccf6-4d2c-b73f-6f8b3747e22b}
303// we extract the device instance ID: SWD\MMDEVAPI\MIDII_60F39FCA.P_0002
shaochuan4eff30e2016-09-09 01:24:14 -0700304//
305// However the extracted device instance ID represent a "software device"
306// provided by Microsoft, which is an interface on top of the hardware for each
307// input/output port. Therefore we further locate its parent device, which is
308// the actual hardware device, for driver information.
shaochuan17bc4a02016-09-06 01:42:12 -0700309void GetDriverInfoFromDeviceId(const std::string& dev_id,
310 std::string* out_manufacturer,
311 std::string* out_driver_version) {
312 base::string16 dev_instance_id =
313 base::UTF8ToWide(dev_id.substr(4, dev_id.size() - 43));
314 base::ReplaceChars(dev_instance_id, L"#", L"\\", &dev_instance_id);
315
shaochuan4eff30e2016-09-09 01:24:14 -0700316 DEVINST dev_instance_handle;
317 CONFIGRET cr = CM_Locate_DevNode(&dev_instance_handle, &dev_instance_id[0],
318 CM_LOCATE_DEVNODE_NORMAL);
319 if (cr != CR_SUCCESS) {
320 VLOG(1) << "CM_Locate_DevNode failed: CONFIGRET 0x" << std::hex << cr;
shaochuan17bc4a02016-09-06 01:42:12 -0700321 return;
322 }
323
shaochuan4eff30e2016-09-09 01:24:14 -0700324 DEVINST parent_handle;
325 cr = CM_Get_Parent(&parent_handle, dev_instance_handle, 0);
326 if (cr != CR_SUCCESS) {
327 VLOG(1) << "CM_Get_Parent failed: CONFIGRET 0x" << std::hex << cr;
shaochuan17bc4a02016-09-06 01:42:12 -0700328 return;
329 }
330
shaochuan4eff30e2016-09-09 01:24:14 -0700331 GetDevPropString(parent_handle, &DEVPKEY_Device_DriverProvider,
332 out_manufacturer);
333 GetDevPropString(parent_handle, &DEVPKEY_Device_DriverVersion,
334 out_driver_version);
shaochuan17bc4a02016-09-06 01:42:12 -0700335}
336
shaochuane58f9c72016-08-30 22:27:08 -0700337// Tokens with value = 0 are considered invalid (as in <wrl/event.h>).
338const int64_t kInvalidTokenValue = 0;
339
340template <typename InterfaceType>
341struct MidiPort {
342 MidiPort() = default;
343
344 uint32_t index;
345 ScopedComPtr<InterfaceType> handle;
346 EventRegistrationToken token_MessageReceived;
347
348 private:
349 DISALLOW_COPY_AND_ASSIGN(MidiPort);
350};
351
352} // namespace
353
354template <typename InterfaceType,
355 typename RuntimeType,
356 typename StaticsInterfaceType,
357 base::char16 const* runtime_class_id>
358class MidiManagerWinrt::MidiPortManager {
359 public:
360 // MidiPortManager instances should be constructed on the COM thread.
361 MidiPortManager(MidiManagerWinrt* midi_manager)
362 : midi_manager_(midi_manager),
363 task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
364
365 virtual ~MidiPortManager() { DCHECK(thread_checker_.CalledOnValidThread()); }
366
367 bool StartWatcher() {
368 DCHECK(thread_checker_.CalledOnValidThread());
369
370 HRESULT hr;
371
372 midi_port_statics_ =
373 WrlStaticsFactory<StaticsInterfaceType, runtime_class_id>();
374 if (!midi_port_statics_)
375 return false;
376
377 HSTRING device_selector = nullptr;
378 hr = midi_port_statics_->GetDeviceSelector(&device_selector);
379 if (FAILED(hr)) {
380 VLOG(1) << "GetDeviceSelector failed: " << PrintHr(hr);
381 return false;
382 }
383
384 auto dev_info_statics = WrlStaticsFactory<
385 IDeviceInformationStatics,
386 RuntimeClass_Windows_Devices_Enumeration_DeviceInformation>();
387 if (!dev_info_statics)
388 return false;
389
390 hr = dev_info_statics->CreateWatcherAqsFilter(device_selector,
robliao8d08e692017-05-11 10:14:00 -0700391 watcher_.GetAddressOf());
shaochuane58f9c72016-08-30 22:27:08 -0700392 if (FAILED(hr)) {
393 VLOG(1) << "CreateWatcherAqsFilter failed: " << PrintHr(hr);
394 return false;
395 }
396
397 // Register callbacks to WinRT that post state-modifying jobs back to COM
398 // thread. |weak_ptr| and |task_runner| are captured by lambda callbacks for
399 // posting jobs. Note that WinRT callback arguments should not be passed
400 // outside the callback since the pointers may be unavailable afterwards.
401 base::WeakPtr<MidiPortManager> weak_ptr = GetWeakPtrFromFactory();
402 scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_runner_;
403
404 hr = watcher_->add_Added(
405 WRL::Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformation*>>(
406 [weak_ptr, task_runner](IDeviceWatcher* watcher,
407 IDeviceInformation* info) {
shaochuanc2894522016-09-20 01:10:50 -0700408 if (!info) {
409 VLOG(1) << "DeviceWatcher.Added callback provides null "
410 "pointer, ignoring";
411 return S_OK;
412 }
413
shaochuan110262b2016-08-31 02:15:16 -0700414 // Disable Microsoft GS Wavetable Synth due to security reasons.
415 // http://crbug.com/499279
416 if (IsMicrosoftSynthesizer(info))
417 return S_OK;
418
shaochuane58f9c72016-08-30 22:27:08 -0700419 std::string dev_id = GetIdString(info),
420 dev_name = GetNameString(info);
421
422 task_runner->PostTask(
423 FROM_HERE, base::Bind(&MidiPortManager::OnAdded, weak_ptr,
424 dev_id, dev_name));
425
426 return S_OK;
427 })
428 .Get(),
429 &token_Added_);
430 if (FAILED(hr)) {
431 VLOG(1) << "add_Added failed: " << PrintHr(hr);
432 return false;
433 }
434
435 hr = watcher_->add_EnumerationCompleted(
436 WRL::Callback<ITypedEventHandler<DeviceWatcher*, IInspectable*>>(
437 [weak_ptr, task_runner](IDeviceWatcher* watcher,
438 IInspectable* insp) {
439 task_runner->PostTask(
440 FROM_HERE,
441 base::Bind(&MidiPortManager::OnEnumerationCompleted,
442 weak_ptr));
443
444 return S_OK;
445 })
446 .Get(),
447 &token_EnumerationCompleted_);
448 if (FAILED(hr)) {
449 VLOG(1) << "add_EnumerationCompleted failed: " << PrintHr(hr);
450 return false;
451 }
452
453 hr = watcher_->add_Removed(
454 WRL::Callback<
455 ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>>(
456 [weak_ptr, task_runner](IDeviceWatcher* watcher,
457 IDeviceInformationUpdate* update) {
shaochuanc2894522016-09-20 01:10:50 -0700458 if (!update) {
459 VLOG(1) << "DeviceWatcher.Removed callback provides null "
460 "pointer, ignoring";
461 return S_OK;
462 }
463
shaochuane58f9c72016-08-30 22:27:08 -0700464 std::string dev_id = GetIdString(update);
465
466 task_runner->PostTask(
467 FROM_HERE,
468 base::Bind(&MidiPortManager::OnRemoved, weak_ptr, dev_id));
469
470 return S_OK;
471 })
472 .Get(),
473 &token_Removed_);
474 if (FAILED(hr)) {
475 VLOG(1) << "add_Removed failed: " << PrintHr(hr);
476 return false;
477 }
478
479 hr = watcher_->add_Stopped(
480 WRL::Callback<ITypedEventHandler<DeviceWatcher*, IInspectable*>>(
481 [](IDeviceWatcher* watcher, IInspectable* insp) {
482 // Placeholder, does nothing for now.
483 return S_OK;
484 })
485 .Get(),
486 &token_Stopped_);
487 if (FAILED(hr)) {
488 VLOG(1) << "add_Stopped failed: " << PrintHr(hr);
489 return false;
490 }
491
492 hr = watcher_->add_Updated(
493 WRL::Callback<
494 ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>>(
495 [](IDeviceWatcher* watcher, IDeviceInformationUpdate* update) {
496 // TODO(shaochuan): Check for fields to be updated here.
497 return S_OK;
498 })
499 .Get(),
500 &token_Updated_);
501 if (FAILED(hr)) {
502 VLOG(1) << "add_Updated failed: " << PrintHr(hr);
503 return false;
504 }
505
506 hr = watcher_->Start();
507 if (FAILED(hr)) {
508 VLOG(1) << "Start failed: " << PrintHr(hr);
509 return false;
510 }
511
512 is_initialized_ = true;
513 return true;
514 }
515
516 void StopWatcher() {
517 DCHECK(thread_checker_.CalledOnValidThread());
518
519 HRESULT hr;
520
521 for (const auto& entry : ports_)
522 RemovePortEventHandlers(entry.second.get());
523
524 if (token_Added_.value != kInvalidTokenValue) {
525 hr = watcher_->remove_Added(token_Added_);
526 VLOG_IF(1, FAILED(hr)) << "remove_Added failed: " << PrintHr(hr);
527 token_Added_.value = kInvalidTokenValue;
528 }
529 if (token_EnumerationCompleted_.value != kInvalidTokenValue) {
530 hr = watcher_->remove_EnumerationCompleted(token_EnumerationCompleted_);
531 VLOG_IF(1, FAILED(hr)) << "remove_EnumerationCompleted failed: "
532 << PrintHr(hr);
533 token_EnumerationCompleted_.value = kInvalidTokenValue;
534 }
535 if (token_Removed_.value != kInvalidTokenValue) {
536 hr = watcher_->remove_Removed(token_Removed_);
537 VLOG_IF(1, FAILED(hr)) << "remove_Removed failed: " << PrintHr(hr);
538 token_Removed_.value = kInvalidTokenValue;
539 }
540 if (token_Stopped_.value != kInvalidTokenValue) {
541 hr = watcher_->remove_Stopped(token_Stopped_);
542 VLOG_IF(1, FAILED(hr)) << "remove_Stopped failed: " << PrintHr(hr);
543 token_Stopped_.value = kInvalidTokenValue;
544 }
545 if (token_Updated_.value != kInvalidTokenValue) {
546 hr = watcher_->remove_Updated(token_Updated_);
547 VLOG_IF(1, FAILED(hr)) << "remove_Updated failed: " << PrintHr(hr);
548 token_Updated_.value = kInvalidTokenValue;
549 }
550
551 if (is_initialized_) {
552 hr = watcher_->Stop();
553 VLOG_IF(1, FAILED(hr)) << "Stop failed: " << PrintHr(hr);
554 is_initialized_ = false;
555 }
556 }
557
558 MidiPort<InterfaceType>* GetPortByDeviceId(std::string dev_id) {
559 DCHECK(thread_checker_.CalledOnValidThread());
560 CHECK(is_initialized_);
561
562 auto it = ports_.find(dev_id);
563 if (it == ports_.end())
564 return nullptr;
565 return it->second.get();
566 }
567
568 MidiPort<InterfaceType>* GetPortByIndex(uint32_t port_index) {
569 DCHECK(thread_checker_.CalledOnValidThread());
570 CHECK(is_initialized_);
571
572 return GetPortByDeviceId(port_ids_[port_index]);
573 }
574
575 protected:
576 // Points to the MidiManagerWinrt instance, which is expected to outlive the
577 // MidiPortManager instance.
578 MidiManagerWinrt* midi_manager_;
579
580 // Task runner of the COM thread.
581 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
582
583 // Ensures all methods are called on the COM thread.
584 base::ThreadChecker thread_checker_;
585
586 private:
587 // DeviceWatcher callbacks:
588 void OnAdded(std::string dev_id, std::string dev_name) {
589 DCHECK(thread_checker_.CalledOnValidThread());
590 CHECK(is_initialized_);
591
shaochuane58f9c72016-08-30 22:27:08 -0700592 port_names_[dev_id] = dev_name;
593
shaochuan9ff63b82016-09-01 01:58:44 -0700594 ScopedHString dev_id_hstring(base::UTF8ToWide(dev_id).c_str());
595 if (!dev_id_hstring.is_valid())
shaochuane58f9c72016-08-30 22:27:08 -0700596 return;
shaochuane58f9c72016-08-30 22:27:08 -0700597
598 IAsyncOperation<RuntimeType*>* async_op;
599
shaochuan9ff63b82016-09-01 01:58:44 -0700600 HRESULT hr =
601 midi_port_statics_->FromIdAsync(dev_id_hstring.get(), &async_op);
shaochuane58f9c72016-08-30 22:27:08 -0700602 if (FAILED(hr)) {
603 VLOG(1) << "FromIdAsync failed: " << PrintHr(hr);
604 return;
605 }
606
607 base::WeakPtr<MidiPortManager> weak_ptr = GetWeakPtrFromFactory();
608 scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_runner_;
609
610 hr = async_op->put_Completed(
611 WRL::Callback<IAsyncOperationCompletedHandler<RuntimeType*>>(
612 [weak_ptr, task_runner](IAsyncOperation<RuntimeType*>* async_op,
613 AsyncStatus status) {
shaochuane58f9c72016-08-30 22:27:08 -0700614 // A reference to |async_op| is kept in |async_ops_|, safe to pass
615 // outside.
616 task_runner->PostTask(
617 FROM_HERE,
618 base::Bind(&MidiPortManager::OnCompletedGetPortFromIdAsync,
shaochuanc2894522016-09-20 01:10:50 -0700619 weak_ptr, async_op));
shaochuane58f9c72016-08-30 22:27:08 -0700620
621 return S_OK;
622 })
623 .Get());
624 if (FAILED(hr)) {
625 VLOG(1) << "put_Completed failed: " << PrintHr(hr);
626 return;
627 }
628
629 // Keep a reference to incompleted |async_op| for releasing later.
630 async_ops_.insert(async_op);
631 }
632
633 void OnEnumerationCompleted() {
634 DCHECK(thread_checker_.CalledOnValidThread());
635 CHECK(is_initialized_);
636
637 if (async_ops_.empty())
638 midi_manager_->OnPortManagerReady();
639 else
640 enumeration_completed_not_ready_ = true;
641 }
642
643 void OnRemoved(std::string dev_id) {
644 DCHECK(thread_checker_.CalledOnValidThread());
645 CHECK(is_initialized_);
646
shaochuan110262b2016-08-31 02:15:16 -0700647 // Note: in case Microsoft GS Wavetable Synth triggers this event for some
648 // reason, it will be ignored here with log emitted.
shaochuane58f9c72016-08-30 22:27:08 -0700649 MidiPort<InterfaceType>* port = GetPortByDeviceId(dev_id);
650 if (!port) {
651 VLOG(1) << "Removing non-existent port " << dev_id;
652 return;
653 }
654
toyoshimec2570a2016-10-21 02:15:27 -0700655 SetPortState(port->index, PortState::DISCONNECTED);
shaochuane58f9c72016-08-30 22:27:08 -0700656
657 RemovePortEventHandlers(port);
658 port->handle = nullptr;
659 }
660
shaochuanc2894522016-09-20 01:10:50 -0700661 void OnCompletedGetPortFromIdAsync(IAsyncOperation<RuntimeType*>* async_op) {
shaochuane58f9c72016-08-30 22:27:08 -0700662 DCHECK(thread_checker_.CalledOnValidThread());
663 CHECK(is_initialized_);
664
shaochuanc2894522016-09-20 01:10:50 -0700665 InterfaceType* handle = nullptr;
666 HRESULT hr = async_op->GetResults(&handle);
667 if (FAILED(hr)) {
668 VLOG(1) << "GetResults failed: " << PrintHr(hr);
669 return;
670 }
671
672 // Manually release COM interface to completed |async_op|.
673 auto it = async_ops_.find(async_op);
674 CHECK(it != async_ops_.end());
675 (*it)->Release();
676 async_ops_.erase(it);
677
678 if (!handle) {
679 VLOG(1) << "Midi{In,Out}Port.FromIdAsync callback provides null pointer, "
680 "ignoring";
681 return;
682 }
683
shaochuane58f9c72016-08-30 22:27:08 -0700684 EventRegistrationToken token = {kInvalidTokenValue};
685 if (!RegisterOnMessageReceived(handle, &token))
686 return;
687
688 std::string dev_id = GetDeviceIdString(handle);
689
690 MidiPort<InterfaceType>* port = GetPortByDeviceId(dev_id);
691
692 if (port == nullptr) {
shaochuan17bc4a02016-09-06 01:42:12 -0700693 std::string manufacturer = "Unknown", driver_version = "Unknown";
694 GetDriverInfoFromDeviceId(dev_id, &manufacturer, &driver_version);
695
696 AddPort(MidiPortInfo(dev_id, manufacturer, port_names_[dev_id],
toyoshimec2570a2016-10-21 02:15:27 -0700697 driver_version, PortState::OPENED));
shaochuane58f9c72016-08-30 22:27:08 -0700698
699 port = new MidiPort<InterfaceType>;
700 port->index = static_cast<uint32_t>(port_ids_.size());
701
702 ports_[dev_id].reset(port);
703 port_ids_.push_back(dev_id);
704 } else {
toyoshimec2570a2016-10-21 02:15:27 -0700705 SetPortState(port->index, PortState::CONNECTED);
shaochuane58f9c72016-08-30 22:27:08 -0700706 }
707
708 port->handle = handle;
709 port->token_MessageReceived = token;
710
shaochuane58f9c72016-08-30 22:27:08 -0700711 if (enumeration_completed_not_ready_ && async_ops_.empty()) {
712 midi_manager_->OnPortManagerReady();
713 enumeration_completed_not_ready_ = false;
714 }
715 }
716
717 // Overrided by MidiInPortManager to listen to input ports.
718 virtual bool RegisterOnMessageReceived(InterfaceType* handle,
719 EventRegistrationToken* p_token) {
720 return true;
721 }
722
723 // Overrided by MidiInPortManager to remove MessageReceived event handler.
724 virtual void RemovePortEventHandlers(MidiPort<InterfaceType>* port) {}
725
726 // Calls midi_manager_->Add{Input,Output}Port.
727 virtual void AddPort(MidiPortInfo info) = 0;
728
729 // Calls midi_manager_->Set{Input,Output}PortState.
toyoshimec2570a2016-10-21 02:15:27 -0700730 virtual void SetPortState(uint32_t port_index, PortState state) = 0;
shaochuane58f9c72016-08-30 22:27:08 -0700731
732 // WeakPtrFactory has to be declared in derived class, use this method to
733 // retrieve upcasted WeakPtr for posting tasks.
734 virtual base::WeakPtr<MidiPortManager> GetWeakPtrFromFactory() = 0;
735
736 // Midi{In,Out}PortStatics instance.
737 ScopedComPtr<StaticsInterfaceType> midi_port_statics_;
738
739 // DeviceWatcher instance and event registration tokens for unsubscribing
740 // events in destructor.
741 ScopedComPtr<IDeviceWatcher> watcher_;
742 EventRegistrationToken token_Added_ = {kInvalidTokenValue},
743 token_EnumerationCompleted_ = {kInvalidTokenValue},
744 token_Removed_ = {kInvalidTokenValue},
745 token_Stopped_ = {kInvalidTokenValue},
746 token_Updated_ = {kInvalidTokenValue};
747
748 // All manipulations to these fields should be done on COM thread.
749 std::unordered_map<std::string, std::unique_ptr<MidiPort<InterfaceType>>>
750 ports_;
751 std::vector<std::string> port_ids_;
752 std::unordered_map<std::string, std::string> port_names_;
753
754 // Keeps AsyncOperation references before the operation completes. Note that
755 // raw pointers are used here and the COM interfaces should be released
756 // manually.
757 std::unordered_set<IAsyncOperation<RuntimeType*>*> async_ops_;
758
759 // Set when device enumeration is completed but OnPortManagerReady() is not
760 // called since some ports are not yet ready (i.e. |async_ops_| is not empty).
761 // In such cases, OnPortManagerReady() will be called in
762 // OnCompletedGetPortFromIdAsync() when the last pending port is ready.
763 bool enumeration_completed_not_ready_ = false;
764
765 // Set if the instance is initialized without error. Should be checked in all
766 // methods on COM thread except StartWatcher().
767 bool is_initialized_ = false;
768};
769
770class MidiManagerWinrt::MidiInPortManager final
771 : public MidiPortManager<IMidiInPort,
772 MidiInPort,
773 IMidiInPortStatics,
774 RuntimeClass_Windows_Devices_Midi_MidiInPort> {
775 public:
776 MidiInPortManager(MidiManagerWinrt* midi_manager)
777 : MidiPortManager(midi_manager), weak_factory_(this) {}
778
779 private:
780 // MidiPortManager overrides:
781 bool RegisterOnMessageReceived(IMidiInPort* handle,
782 EventRegistrationToken* p_token) override {
783 DCHECK(thread_checker_.CalledOnValidThread());
784
785 base::WeakPtr<MidiInPortManager> weak_ptr = weak_factory_.GetWeakPtr();
786 scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_runner_;
787
788 HRESULT hr = handle->add_MessageReceived(
789 WRL::Callback<
790 ITypedEventHandler<MidiInPort*, MidiMessageReceivedEventArgs*>>(
791 [weak_ptr, task_runner](IMidiInPort* handle,
792 IMidiMessageReceivedEventArgs* args) {
793 const base::TimeTicks now = base::TimeTicks::Now();
794
795 std::string dev_id = GetDeviceIdString(handle);
796
797 ScopedComPtr<IMidiMessage> message;
robliao8d08e692017-05-11 10:14:00 -0700798 HRESULT hr = args->get_Message(message.GetAddressOf());
shaochuane58f9c72016-08-30 22:27:08 -0700799 if (FAILED(hr)) {
800 VLOG(1) << "get_Message failed: " << PrintHr(hr);
801 return hr;
802 }
803
804 ScopedComPtr<IBuffer> buffer;
robliao8d08e692017-05-11 10:14:00 -0700805 hr = message->get_RawData(buffer.GetAddressOf());
shaochuane58f9c72016-08-30 22:27:08 -0700806 if (FAILED(hr)) {
807 VLOG(1) << "get_RawData failed: " << PrintHr(hr);
808 return hr;
809 }
810
811 uint8_t* p_buffer_data = nullptr;
robliao3566d1a2017-04-18 17:28:09 -0700812 hr = GetPointerToBufferData(buffer.Get(), &p_buffer_data);
shaochuane58f9c72016-08-30 22:27:08 -0700813 if (FAILED(hr))
814 return hr;
815
816 uint32_t data_length = 0;
817 hr = buffer->get_Length(&data_length);
818 if (FAILED(hr)) {
819 VLOG(1) << "get_Length failed: " << PrintHr(hr);
820 return hr;
821 }
822
823 std::vector<uint8_t> data(p_buffer_data,
824 p_buffer_data + data_length);
825
826 task_runner->PostTask(
827 FROM_HERE, base::Bind(&MidiInPortManager::OnMessageReceived,
828 weak_ptr, dev_id, data, now));
829
830 return S_OK;
831 })
832 .Get(),
833 p_token);
834 if (FAILED(hr)) {
835 VLOG(1) << "add_MessageReceived failed: " << PrintHr(hr);
836 return false;
837 }
838
839 return true;
840 }
841
842 void RemovePortEventHandlers(MidiPort<IMidiInPort>* port) override {
843 if (!(port->handle &&
844 port->token_MessageReceived.value != kInvalidTokenValue))
845 return;
846
847 HRESULT hr =
848 port->handle->remove_MessageReceived(port->token_MessageReceived);
849 VLOG_IF(1, FAILED(hr)) << "remove_MessageReceived failed: " << PrintHr(hr);
850 port->token_MessageReceived.value = kInvalidTokenValue;
851 }
852
853 void AddPort(MidiPortInfo info) final { midi_manager_->AddInputPort(info); }
854
toyoshimec2570a2016-10-21 02:15:27 -0700855 void SetPortState(uint32_t port_index, PortState state) final {
shaochuane58f9c72016-08-30 22:27:08 -0700856 midi_manager_->SetInputPortState(port_index, state);
857 }
858
859 base::WeakPtr<MidiPortManager> GetWeakPtrFromFactory() final {
860 DCHECK(thread_checker_.CalledOnValidThread());
861
862 return weak_factory_.GetWeakPtr();
863 }
864
865 // Callback on receiving MIDI input message.
866 void OnMessageReceived(std::string dev_id,
867 std::vector<uint8_t> data,
868 base::TimeTicks time) {
869 DCHECK(thread_checker_.CalledOnValidThread());
870
871 MidiPort<IMidiInPort>* port = GetPortByDeviceId(dev_id);
872 CHECK(port);
873
874 midi_manager_->ReceiveMidiData(port->index, &data[0], data.size(), time);
875 }
876
877 // Last member to ensure destructed first.
878 base::WeakPtrFactory<MidiInPortManager> weak_factory_;
879
880 DISALLOW_COPY_AND_ASSIGN(MidiInPortManager);
881};
882
883class MidiManagerWinrt::MidiOutPortManager final
884 : public MidiPortManager<IMidiOutPort,
885 IMidiOutPort,
886 IMidiOutPortStatics,
887 RuntimeClass_Windows_Devices_Midi_MidiOutPort> {
888 public:
889 MidiOutPortManager(MidiManagerWinrt* midi_manager)
890 : MidiPortManager(midi_manager), weak_factory_(this) {}
891
892 private:
893 // MidiPortManager overrides:
894 void AddPort(MidiPortInfo info) final { midi_manager_->AddOutputPort(info); }
895
toyoshimec2570a2016-10-21 02:15:27 -0700896 void SetPortState(uint32_t port_index, PortState state) final {
shaochuane58f9c72016-08-30 22:27:08 -0700897 midi_manager_->SetOutputPortState(port_index, state);
898 }
899
900 base::WeakPtr<MidiPortManager> GetWeakPtrFromFactory() final {
901 DCHECK(thread_checker_.CalledOnValidThread());
902
903 return weak_factory_.GetWeakPtr();
904 }
905
906 // Last member to ensure destructed first.
907 base::WeakPtrFactory<MidiOutPortManager> weak_factory_;
908
909 DISALLOW_COPY_AND_ASSIGN(MidiOutPortManager);
910};
911
toyoshimf4d61522017-02-10 02:03:32 -0800912MidiManagerWinrt::MidiManagerWinrt(MidiService* service)
913 : MidiManager(service), com_thread_("Windows MIDI COM Thread") {}
shaochuane58f9c72016-08-30 22:27:08 -0700914
915MidiManagerWinrt::~MidiManagerWinrt() {
916 base::AutoLock auto_lock(lazy_init_member_lock_);
917
918 CHECK(!com_thread_checker_);
919 CHECK(!port_manager_in_);
920 CHECK(!port_manager_out_);
921 CHECK(!scheduler_);
922}
923
924void MidiManagerWinrt::StartInitialization() {
shaochuane58f9c72016-08-30 22:27:08 -0700925 com_thread_.init_com_with_mta(true);
926 com_thread_.Start();
927
928 com_thread_.task_runner()->PostTask(
929 FROM_HERE, base::Bind(&MidiManagerWinrt::InitializeOnComThread,
930 base::Unretained(this)));
931}
932
933void MidiManagerWinrt::Finalize() {
934 com_thread_.task_runner()->PostTask(
935 FROM_HERE, base::Bind(&MidiManagerWinrt::FinalizeOnComThread,
936 base::Unretained(this)));
937
938 // Blocks until FinalizeOnComThread() returns. Delayed MIDI send data tasks
939 // will be ignored.
940 com_thread_.Stop();
941}
942
943void MidiManagerWinrt::DispatchSendMidiData(MidiManagerClient* client,
944 uint32_t port_index,
945 const std::vector<uint8_t>& data,
946 double timestamp) {
947 CHECK(scheduler_);
948
949 scheduler_->PostSendDataTask(
950 client, data.size(), timestamp,
951 base::Bind(&MidiManagerWinrt::SendOnComThread, base::Unretained(this),
952 port_index, data));
953}
954
955void MidiManagerWinrt::InitializeOnComThread() {
956 base::AutoLock auto_lock(lazy_init_member_lock_);
957
958 com_thread_checker_.reset(new base::ThreadChecker);
959
dalecurtis3f5ce942017-02-10 18:08:18 -0800960 if (!GetCombaseFunctions()->LoadFunctions()) {
shaochuan9ff63b82016-09-01 01:58:44 -0700961 VLOG(1) << "Failed loading functions from combase.dll: "
962 << PrintHr(HRESULT_FROM_WIN32(GetLastError()));
963 CompleteInitialization(Result::INITIALIZATION_ERROR);
964 return;
965 }
966
shaochuane58f9c72016-08-30 22:27:08 -0700967 port_manager_in_.reset(new MidiInPortManager(this));
968 port_manager_out_.reset(new MidiOutPortManager(this));
969
970 scheduler_.reset(new MidiScheduler(this));
971
972 if (!(port_manager_in_->StartWatcher() &&
973 port_manager_out_->StartWatcher())) {
974 port_manager_in_->StopWatcher();
975 port_manager_out_->StopWatcher();
976 CompleteInitialization(Result::INITIALIZATION_ERROR);
977 }
978}
979
980void MidiManagerWinrt::FinalizeOnComThread() {
981 base::AutoLock auto_lock(lazy_init_member_lock_);
982
983 DCHECK(com_thread_checker_->CalledOnValidThread());
984
985 scheduler_.reset();
986
shaochuan9ff63b82016-09-01 01:58:44 -0700987 if (port_manager_in_) {
988 port_manager_in_->StopWatcher();
989 port_manager_in_.reset();
990 }
991
992 if (port_manager_out_) {
993 port_manager_out_->StopWatcher();
994 port_manager_out_.reset();
995 }
shaochuane58f9c72016-08-30 22:27:08 -0700996
997 com_thread_checker_.reset();
998}
999
1000void MidiManagerWinrt::SendOnComThread(uint32_t port_index,
1001 const std::vector<uint8_t>& data) {
1002 DCHECK(com_thread_checker_->CalledOnValidThread());
1003
1004 MidiPort<IMidiOutPort>* port = port_manager_out_->GetPortByIndex(port_index);
1005 if (!(port && port->handle)) {
1006 VLOG(1) << "Port not available: " << port_index;
1007 return;
1008 }
1009
1010 auto buffer_factory =
1011 WrlStaticsFactory<IBufferFactory,
1012 RuntimeClass_Windows_Storage_Streams_Buffer>();
1013 if (!buffer_factory)
1014 return;
1015
1016 ScopedComPtr<IBuffer> buffer;
1017 HRESULT hr = buffer_factory->Create(static_cast<UINT32>(data.size()),
robliao8d08e692017-05-11 10:14:00 -07001018 buffer.GetAddressOf());
shaochuane58f9c72016-08-30 22:27:08 -07001019 if (FAILED(hr)) {
1020 VLOG(1) << "Create failed: " << PrintHr(hr);
1021 return;
1022 }
1023
1024 hr = buffer->put_Length(static_cast<UINT32>(data.size()));
1025 if (FAILED(hr)) {
1026 VLOG(1) << "put_Length failed: " << PrintHr(hr);
1027 return;
1028 }
1029
1030 uint8_t* p_buffer_data = nullptr;
robliao3566d1a2017-04-18 17:28:09 -07001031 hr = GetPointerToBufferData(buffer.Get(), &p_buffer_data);
shaochuane58f9c72016-08-30 22:27:08 -07001032 if (FAILED(hr))
1033 return;
1034
1035 std::copy(data.begin(), data.end(), p_buffer_data);
1036
robliao3566d1a2017-04-18 17:28:09 -07001037 hr = port->handle->SendBuffer(buffer.Get());
shaochuane58f9c72016-08-30 22:27:08 -07001038 if (FAILED(hr)) {
1039 VLOG(1) << "SendBuffer failed: " << PrintHr(hr);
1040 return;
1041 }
1042}
1043
1044void MidiManagerWinrt::OnPortManagerReady() {
1045 DCHECK(com_thread_checker_->CalledOnValidThread());
1046 DCHECK(port_manager_ready_count_ < 2);
1047
1048 if (++port_manager_ready_count_ == 2)
1049 CompleteInitialization(Result::OK);
1050}
1051
shaochuane58f9c72016-08-30 22:27:08 -07001052} // namespace midi