blob: 339f588a16e32e8c003f30e064dccf0447113c62 [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>
shaochuane58f9c72016-08-30 22:27:08 -070014#include <robuffer.h>
15#include <windows.devices.enumeration.h>
16#include <windows.devices.midi.h>
17#include <wrl/event.h>
18
19#include <iomanip>
20#include <unordered_map>
21#include <unordered_set>
22
23#include "base/bind.h"
shaochuan9ff63b82016-09-01 01:58:44 -070024#include "base/lazy_instance.h"
25#include "base/scoped_generic.h"
shaochuan17bc4a02016-09-06 01:42:12 -070026#include "base/strings/string_util.h"
shaochuane58f9c72016-08-30 22:27:08 -070027#include "base/strings/utf_string_conversions.h"
28#include "base/threading/thread_checker.h"
29#include "base/threading/thread_task_runner_handle.h"
30#include "base/timer/timer.h"
31#include "base/win/scoped_comptr.h"
shaochuane58f9c72016-08-30 22:27:08 -070032#include "media/midi/midi_scheduler.h"
33
34namespace media {
35namespace 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;
46
47// Helpers for printing HRESULTs.
48struct PrintHr {
49 PrintHr(HRESULT hr) : hr(hr) {}
50 HRESULT hr;
51};
52
53std::ostream& operator<<(std::ostream& os, const PrintHr& phr) {
54 std::ios_base::fmtflags ff = os.flags();
55 os << _com_error(phr.hr).ErrorMessage() << " (0x" << std::hex
56 << std::uppercase << std::setfill('0') << std::setw(8) << phr.hr << ")";
57 os.flags(ff);
58 return os;
59}
60
shaochuan9ff63b82016-09-01 01:58:44 -070061// Provides access to functions in combase.dll which may not be available on
62// Windows 7. Loads functions dynamically at runtime to prevent library
63// dependencies. Use this class through the global LazyInstance
64// |g_combase_functions|.
65class CombaseFunctions {
66 public:
67 CombaseFunctions() = default;
68
69 ~CombaseFunctions() {
70 if (combase_dll_)
71 ::FreeLibrary(combase_dll_);
72 }
73
74 bool LoadFunctions() {
75 combase_dll_ = ::LoadLibrary(L"combase.dll");
76 if (!combase_dll_)
77 return false;
78
79 get_factory_func_ = reinterpret_cast<decltype(&::RoGetActivationFactory)>(
80 ::GetProcAddress(combase_dll_, "RoGetActivationFactory"));
81 if (!get_factory_func_)
82 return false;
83
84 create_string_func_ = reinterpret_cast<decltype(&::WindowsCreateString)>(
85 ::GetProcAddress(combase_dll_, "WindowsCreateString"));
86 if (!create_string_func_)
87 return false;
88
89 delete_string_func_ = reinterpret_cast<decltype(&::WindowsDeleteString)>(
90 ::GetProcAddress(combase_dll_, "WindowsDeleteString"));
91 if (!delete_string_func_)
92 return false;
93
94 get_string_raw_buffer_func_ =
95 reinterpret_cast<decltype(&::WindowsGetStringRawBuffer)>(
96 ::GetProcAddress(combase_dll_, "WindowsGetStringRawBuffer"));
97 if (!get_string_raw_buffer_func_)
98 return false;
99
100 return true;
101 }
102
103 HRESULT RoGetActivationFactory(HSTRING class_id,
104 const IID& iid,
105 void** out_factory) {
106 DCHECK(get_factory_func_);
107 return get_factory_func_(class_id, iid, out_factory);
108 }
109
110 HRESULT WindowsCreateString(const base::char16* src,
111 uint32_t len,
112 HSTRING* out_hstr) {
113 DCHECK(create_string_func_);
114 return create_string_func_(src, len, out_hstr);
115 }
116
117 HRESULT WindowsDeleteString(HSTRING hstr) {
118 DCHECK(delete_string_func_);
119 return delete_string_func_(hstr);
120 }
121
122 const base::char16* WindowsGetStringRawBuffer(HSTRING hstr,
123 uint32_t* out_len) {
124 DCHECK(get_string_raw_buffer_func_);
125 return get_string_raw_buffer_func_(hstr, out_len);
126 }
127
128 private:
129 HMODULE combase_dll_ = nullptr;
130
131 decltype(&::RoGetActivationFactory) get_factory_func_ = nullptr;
132 decltype(&::WindowsCreateString) create_string_func_ = nullptr;
133 decltype(&::WindowsDeleteString) delete_string_func_ = nullptr;
134 decltype(&::WindowsGetStringRawBuffer) get_string_raw_buffer_func_ = nullptr;
135};
136
137base::LazyInstance<CombaseFunctions> g_combase_functions =
138 LAZY_INSTANCE_INITIALIZER;
139
140// Scoped HSTRING class to maintain lifetime of HSTRINGs allocated with
141// WindowsCreateString().
142class ScopedHStringTraits {
143 public:
144 static HSTRING InvalidValue() { return nullptr; }
145
146 static void Free(HSTRING hstr) {
147 g_combase_functions.Get().WindowsDeleteString(hstr);
148 }
149};
150
151class ScopedHString : public base::ScopedGeneric<HSTRING, ScopedHStringTraits> {
152 public:
153 explicit ScopedHString(const base::char16* str) : ScopedGeneric(nullptr) {
154 HSTRING hstr;
155 HRESULT hr = g_combase_functions.Get().WindowsCreateString(
156 str, static_cast<uint32_t>(wcslen(str)), &hstr);
157 if (FAILED(hr))
158 VLOG(1) << "WindowsCreateString failed: " << PrintHr(hr);
159 else
160 reset(hstr);
161 }
162};
163
shaochuane58f9c72016-08-30 22:27:08 -0700164// Factory functions that activate and create WinRT components. The caller takes
165// ownership of the returning ComPtr.
166template <typename InterfaceType, base::char16 const* runtime_class_id>
167ScopedComPtr<InterfaceType> WrlStaticsFactory() {
168 ScopedComPtr<InterfaceType> com_ptr;
169
shaochuan9ff63b82016-09-01 01:58:44 -0700170 ScopedHString class_id_hstring(runtime_class_id);
171 if (!class_id_hstring.is_valid()) {
172 com_ptr = nullptr;
173 return com_ptr;
174 }
175
176 HRESULT hr = g_combase_functions.Get().RoGetActivationFactory(
177 class_id_hstring.get(), __uuidof(InterfaceType), com_ptr.ReceiveVoid());
shaochuane58f9c72016-08-30 22:27:08 -0700178 if (FAILED(hr)) {
shaochuan9ff63b82016-09-01 01:58:44 -0700179 VLOG(1) << "RoGetActivationFactory failed: " << PrintHr(hr);
shaochuane58f9c72016-08-30 22:27:08 -0700180 com_ptr = nullptr;
181 }
182
183 return com_ptr;
184}
185
shaochuan80f1fba2016-09-01 20:44:51 -0700186std::string HStringToString(HSTRING hstr) {
shaochuane58f9c72016-08-30 22:27:08 -0700187 // Note: empty HSTRINGs are represent as nullptr, and instantiating
188 // std::string with nullptr (in base::WideToUTF8) is undefined behavior.
shaochuan9ff63b82016-09-01 01:58:44 -0700189 const base::char16* buffer =
shaochuan80f1fba2016-09-01 20:44:51 -0700190 g_combase_functions.Get().WindowsGetStringRawBuffer(hstr, nullptr);
shaochuane58f9c72016-08-30 22:27:08 -0700191 if (buffer)
192 return base::WideToUTF8(buffer);
193 return std::string();
194}
195
196template <typename T>
197std::string GetIdString(T* obj) {
shaochuan80f1fba2016-09-01 20:44:51 -0700198 HSTRING result;
199 HRESULT hr = obj->get_Id(&result);
200 if (FAILED(hr)) {
201 VLOG(1) << "get_Id failed: " << PrintHr(hr);
202 return std::string();
203 }
204 return HStringToString(result);
shaochuane58f9c72016-08-30 22:27:08 -0700205}
206
207template <typename T>
208std::string GetDeviceIdString(T* obj) {
shaochuan80f1fba2016-09-01 20:44:51 -0700209 HSTRING result;
210 HRESULT hr = obj->get_DeviceId(&result);
211 if (FAILED(hr)) {
212 VLOG(1) << "get_DeviceId failed: " << PrintHr(hr);
213 return std::string();
214 }
215 return HStringToString(result);
shaochuane58f9c72016-08-30 22:27:08 -0700216}
217
218std::string GetNameString(IDeviceInformation* info) {
shaochuan80f1fba2016-09-01 20:44:51 -0700219 HSTRING result;
220 HRESULT hr = info->get_Name(&result);
221 if (FAILED(hr)) {
222 VLOG(1) << "get_Name failed: " << PrintHr(hr);
223 return std::string();
224 }
225 return HStringToString(result);
shaochuane58f9c72016-08-30 22:27:08 -0700226}
227
228HRESULT GetPointerToBufferData(IBuffer* buffer, uint8_t** out) {
229 ScopedComPtr<Windows::Storage::Streams::IBufferByteAccess> buffer_byte_access;
230
231 HRESULT hr = buffer_byte_access.QueryFrom(buffer);
232 if (FAILED(hr)) {
233 VLOG(1) << "QueryInterface failed: " << PrintHr(hr);
234 return hr;
235 }
236
237 // Lifetime of the pointing buffer is controlled by the buffer object.
238 hr = buffer_byte_access->Buffer(out);
239 if (FAILED(hr)) {
240 VLOG(1) << "Buffer failed: " << PrintHr(hr);
241 return hr;
242 }
243
244 return S_OK;
245}
246
shaochuan110262b2016-08-31 02:15:16 -0700247// Checks if given DeviceInformation represent a Microsoft GS Wavetable Synth
248// instance.
249bool IsMicrosoftSynthesizer(IDeviceInformation* info) {
250 auto midi_synthesizer_statics =
251 WrlStaticsFactory<IMidiSynthesizerStatics,
252 RuntimeClass_Windows_Devices_Midi_MidiSynthesizer>();
253 boolean result = FALSE;
254 HRESULT hr = midi_synthesizer_statics->IsSynthesizer(info, &result);
255 VLOG_IF(1, FAILED(hr)) << "IsSynthesizer failed: " << PrintHr(hr);
256 return result != FALSE;
257}
258
shaochuan4eff30e2016-09-09 01:24:14 -0700259void GetDevPropString(DEVINST handle,
260 const DEVPROPKEY* devprop_key,
261 std::string* out) {
262 DEVPROPTYPE devprop_type;
263 unsigned long buffer_size = 0;
shaochuan17bc4a02016-09-06 01:42:12 -0700264
shaochuan4eff30e2016-09-09 01:24:14 -0700265 // Retrieve |buffer_size| and allocate buffer later for receiving data.
266 CONFIGRET cr = CM_Get_DevNode_Property(handle, devprop_key, &devprop_type,
267 nullptr, &buffer_size, 0);
268 if (cr != CR_BUFFER_SMALL) {
269 // Here we print error codes in hex instead of using PrintHr() with
270 // HRESULT_FROM_WIN32() and CM_MapCrToWin32Err(), since only a minor set of
271 // CONFIGRET values are mapped to Win32 errors. Same for following VLOG()s.
272 VLOG(1) << "CM_Get_DevNode_Property failed: CONFIGRET 0x" << std::hex << cr;
273 return;
shaochuan17bc4a02016-09-06 01:42:12 -0700274 }
shaochuan4eff30e2016-09-09 01:24:14 -0700275 if (devprop_type != DEVPROP_TYPE_STRING) {
276 VLOG(1) << "CM_Get_DevNode_Property returns wrong data type, "
277 << "expected DEVPROP_TYPE_STRING";
278 return;
279 }
shaochuan17bc4a02016-09-06 01:42:12 -0700280
shaochuan4eff30e2016-09-09 01:24:14 -0700281 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
282
283 // Receive property data.
284 cr = CM_Get_DevNode_Property(handle, devprop_key, &devprop_type, buffer.get(),
285 &buffer_size, 0);
286 if (cr != CR_SUCCESS)
287 VLOG(1) << "CM_Get_DevNode_Property failed: CONFIGRET 0x" << std::hex << cr;
288 else
289 *out = base::WideToUTF8(reinterpret_cast<base::char16*>(buffer.get()));
290}
shaochuan17bc4a02016-09-06 01:42:12 -0700291
292// Retrieves manufacturer (provider) and version information of underlying
shaochuan4eff30e2016-09-09 01:24:14 -0700293// device driver through PnP Configuration Manager, given device (interface) ID
294// provided by WinRT. |out_manufacturer| and |out_driver_version| won't be
295// modified if retrieval fails.
shaochuan17bc4a02016-09-06 01:42:12 -0700296//
297// Device instance ID is extracted from device (interface) ID provided by WinRT
298// APIs, for example from the following interface ID:
299// \\?\SWD#MMDEVAPI#MIDII_60F39FCA.P_0002#{504be32c-ccf6-4d2c-b73f-6f8b3747e22b}
300// we extract the device instance ID: SWD\MMDEVAPI\MIDII_60F39FCA.P_0002
shaochuan4eff30e2016-09-09 01:24:14 -0700301//
302// However the extracted device instance ID represent a "software device"
303// provided by Microsoft, which is an interface on top of the hardware for each
304// input/output port. Therefore we further locate its parent device, which is
305// the actual hardware device, for driver information.
shaochuan17bc4a02016-09-06 01:42:12 -0700306void GetDriverInfoFromDeviceId(const std::string& dev_id,
307 std::string* out_manufacturer,
308 std::string* out_driver_version) {
309 base::string16 dev_instance_id =
310 base::UTF8ToWide(dev_id.substr(4, dev_id.size() - 43));
311 base::ReplaceChars(dev_instance_id, L"#", L"\\", &dev_instance_id);
312
shaochuan4eff30e2016-09-09 01:24:14 -0700313 DEVINST dev_instance_handle;
314 CONFIGRET cr = CM_Locate_DevNode(&dev_instance_handle, &dev_instance_id[0],
315 CM_LOCATE_DEVNODE_NORMAL);
316 if (cr != CR_SUCCESS) {
317 VLOG(1) << "CM_Locate_DevNode failed: CONFIGRET 0x" << std::hex << cr;
shaochuan17bc4a02016-09-06 01:42:12 -0700318 return;
319 }
320
shaochuan4eff30e2016-09-09 01:24:14 -0700321 DEVINST parent_handle;
322 cr = CM_Get_Parent(&parent_handle, dev_instance_handle, 0);
323 if (cr != CR_SUCCESS) {
324 VLOG(1) << "CM_Get_Parent failed: CONFIGRET 0x" << std::hex << cr;
shaochuan17bc4a02016-09-06 01:42:12 -0700325 return;
326 }
327
shaochuan4eff30e2016-09-09 01:24:14 -0700328 GetDevPropString(parent_handle, &DEVPKEY_Device_DriverProvider,
329 out_manufacturer);
330 GetDevPropString(parent_handle, &DEVPKEY_Device_DriverVersion,
331 out_driver_version);
shaochuan17bc4a02016-09-06 01:42:12 -0700332}
333
shaochuane58f9c72016-08-30 22:27:08 -0700334// Tokens with value = 0 are considered invalid (as in <wrl/event.h>).
335const int64_t kInvalidTokenValue = 0;
336
337template <typename InterfaceType>
338struct MidiPort {
339 MidiPort() = default;
340
341 uint32_t index;
342 ScopedComPtr<InterfaceType> handle;
343 EventRegistrationToken token_MessageReceived;
344
345 private:
346 DISALLOW_COPY_AND_ASSIGN(MidiPort);
347};
348
349} // namespace
350
351template <typename InterfaceType,
352 typename RuntimeType,
353 typename StaticsInterfaceType,
354 base::char16 const* runtime_class_id>
355class MidiManagerWinrt::MidiPortManager {
356 public:
357 // MidiPortManager instances should be constructed on the COM thread.
358 MidiPortManager(MidiManagerWinrt* midi_manager)
359 : midi_manager_(midi_manager),
360 task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
361
362 virtual ~MidiPortManager() { DCHECK(thread_checker_.CalledOnValidThread()); }
363
364 bool StartWatcher() {
365 DCHECK(thread_checker_.CalledOnValidThread());
366
367 HRESULT hr;
368
369 midi_port_statics_ =
370 WrlStaticsFactory<StaticsInterfaceType, runtime_class_id>();
371 if (!midi_port_statics_)
372 return false;
373
374 HSTRING device_selector = nullptr;
375 hr = midi_port_statics_->GetDeviceSelector(&device_selector);
376 if (FAILED(hr)) {
377 VLOG(1) << "GetDeviceSelector failed: " << PrintHr(hr);
378 return false;
379 }
380
381 auto dev_info_statics = WrlStaticsFactory<
382 IDeviceInformationStatics,
383 RuntimeClass_Windows_Devices_Enumeration_DeviceInformation>();
384 if (!dev_info_statics)
385 return false;
386
387 hr = dev_info_statics->CreateWatcherAqsFilter(device_selector,
388 watcher_.Receive());
389 if (FAILED(hr)) {
390 VLOG(1) << "CreateWatcherAqsFilter failed: " << PrintHr(hr);
391 return false;
392 }
393
394 // Register callbacks to WinRT that post state-modifying jobs back to COM
395 // thread. |weak_ptr| and |task_runner| are captured by lambda callbacks for
396 // posting jobs. Note that WinRT callback arguments should not be passed
397 // outside the callback since the pointers may be unavailable afterwards.
398 base::WeakPtr<MidiPortManager> weak_ptr = GetWeakPtrFromFactory();
399 scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_runner_;
400
401 hr = watcher_->add_Added(
402 WRL::Callback<ITypedEventHandler<DeviceWatcher*, DeviceInformation*>>(
403 [weak_ptr, task_runner](IDeviceWatcher* watcher,
404 IDeviceInformation* info) {
shaochuan110262b2016-08-31 02:15:16 -0700405 // Disable Microsoft GS Wavetable Synth due to security reasons.
406 // http://crbug.com/499279
407 if (IsMicrosoftSynthesizer(info))
408 return S_OK;
409
shaochuane58f9c72016-08-30 22:27:08 -0700410 std::string dev_id = GetIdString(info),
411 dev_name = GetNameString(info);
412
413 task_runner->PostTask(
414 FROM_HERE, base::Bind(&MidiPortManager::OnAdded, weak_ptr,
415 dev_id, dev_name));
416
417 return S_OK;
418 })
419 .Get(),
420 &token_Added_);
421 if (FAILED(hr)) {
422 VLOG(1) << "add_Added failed: " << PrintHr(hr);
423 return false;
424 }
425
426 hr = watcher_->add_EnumerationCompleted(
427 WRL::Callback<ITypedEventHandler<DeviceWatcher*, IInspectable*>>(
428 [weak_ptr, task_runner](IDeviceWatcher* watcher,
429 IInspectable* insp) {
430 task_runner->PostTask(
431 FROM_HERE,
432 base::Bind(&MidiPortManager::OnEnumerationCompleted,
433 weak_ptr));
434
435 return S_OK;
436 })
437 .Get(),
438 &token_EnumerationCompleted_);
439 if (FAILED(hr)) {
440 VLOG(1) << "add_EnumerationCompleted failed: " << PrintHr(hr);
441 return false;
442 }
443
444 hr = watcher_->add_Removed(
445 WRL::Callback<
446 ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>>(
447 [weak_ptr, task_runner](IDeviceWatcher* watcher,
448 IDeviceInformationUpdate* update) {
449 std::string dev_id = GetIdString(update);
450
451 task_runner->PostTask(
452 FROM_HERE,
453 base::Bind(&MidiPortManager::OnRemoved, weak_ptr, dev_id));
454
455 return S_OK;
456 })
457 .Get(),
458 &token_Removed_);
459 if (FAILED(hr)) {
460 VLOG(1) << "add_Removed failed: " << PrintHr(hr);
461 return false;
462 }
463
464 hr = watcher_->add_Stopped(
465 WRL::Callback<ITypedEventHandler<DeviceWatcher*, IInspectable*>>(
466 [](IDeviceWatcher* watcher, IInspectable* insp) {
467 // Placeholder, does nothing for now.
468 return S_OK;
469 })
470 .Get(),
471 &token_Stopped_);
472 if (FAILED(hr)) {
473 VLOG(1) << "add_Stopped failed: " << PrintHr(hr);
474 return false;
475 }
476
477 hr = watcher_->add_Updated(
478 WRL::Callback<
479 ITypedEventHandler<DeviceWatcher*, DeviceInformationUpdate*>>(
480 [](IDeviceWatcher* watcher, IDeviceInformationUpdate* update) {
481 // TODO(shaochuan): Check for fields to be updated here.
482 return S_OK;
483 })
484 .Get(),
485 &token_Updated_);
486 if (FAILED(hr)) {
487 VLOG(1) << "add_Updated failed: " << PrintHr(hr);
488 return false;
489 }
490
491 hr = watcher_->Start();
492 if (FAILED(hr)) {
493 VLOG(1) << "Start failed: " << PrintHr(hr);
494 return false;
495 }
496
497 is_initialized_ = true;
498 return true;
499 }
500
501 void StopWatcher() {
502 DCHECK(thread_checker_.CalledOnValidThread());
503
504 HRESULT hr;
505
506 for (const auto& entry : ports_)
507 RemovePortEventHandlers(entry.second.get());
508
509 if (token_Added_.value != kInvalidTokenValue) {
510 hr = watcher_->remove_Added(token_Added_);
511 VLOG_IF(1, FAILED(hr)) << "remove_Added failed: " << PrintHr(hr);
512 token_Added_.value = kInvalidTokenValue;
513 }
514 if (token_EnumerationCompleted_.value != kInvalidTokenValue) {
515 hr = watcher_->remove_EnumerationCompleted(token_EnumerationCompleted_);
516 VLOG_IF(1, FAILED(hr)) << "remove_EnumerationCompleted failed: "
517 << PrintHr(hr);
518 token_EnumerationCompleted_.value = kInvalidTokenValue;
519 }
520 if (token_Removed_.value != kInvalidTokenValue) {
521 hr = watcher_->remove_Removed(token_Removed_);
522 VLOG_IF(1, FAILED(hr)) << "remove_Removed failed: " << PrintHr(hr);
523 token_Removed_.value = kInvalidTokenValue;
524 }
525 if (token_Stopped_.value != kInvalidTokenValue) {
526 hr = watcher_->remove_Stopped(token_Stopped_);
527 VLOG_IF(1, FAILED(hr)) << "remove_Stopped failed: " << PrintHr(hr);
528 token_Stopped_.value = kInvalidTokenValue;
529 }
530 if (token_Updated_.value != kInvalidTokenValue) {
531 hr = watcher_->remove_Updated(token_Updated_);
532 VLOG_IF(1, FAILED(hr)) << "remove_Updated failed: " << PrintHr(hr);
533 token_Updated_.value = kInvalidTokenValue;
534 }
535
536 if (is_initialized_) {
537 hr = watcher_->Stop();
538 VLOG_IF(1, FAILED(hr)) << "Stop failed: " << PrintHr(hr);
539 is_initialized_ = false;
540 }
541 }
542
543 MidiPort<InterfaceType>* GetPortByDeviceId(std::string dev_id) {
544 DCHECK(thread_checker_.CalledOnValidThread());
545 CHECK(is_initialized_);
546
547 auto it = ports_.find(dev_id);
548 if (it == ports_.end())
549 return nullptr;
550 return it->second.get();
551 }
552
553 MidiPort<InterfaceType>* GetPortByIndex(uint32_t port_index) {
554 DCHECK(thread_checker_.CalledOnValidThread());
555 CHECK(is_initialized_);
556
557 return GetPortByDeviceId(port_ids_[port_index]);
558 }
559
560 protected:
561 // Points to the MidiManagerWinrt instance, which is expected to outlive the
562 // MidiPortManager instance.
563 MidiManagerWinrt* midi_manager_;
564
565 // Task runner of the COM thread.
566 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
567
568 // Ensures all methods are called on the COM thread.
569 base::ThreadChecker thread_checker_;
570
571 private:
572 // DeviceWatcher callbacks:
573 void OnAdded(std::string dev_id, std::string dev_name) {
574 DCHECK(thread_checker_.CalledOnValidThread());
575 CHECK(is_initialized_);
576
shaochuane58f9c72016-08-30 22:27:08 -0700577 port_names_[dev_id] = dev_name;
578
shaochuan9ff63b82016-09-01 01:58:44 -0700579 ScopedHString dev_id_hstring(base::UTF8ToWide(dev_id).c_str());
580 if (!dev_id_hstring.is_valid())
shaochuane58f9c72016-08-30 22:27:08 -0700581 return;
shaochuane58f9c72016-08-30 22:27:08 -0700582
583 IAsyncOperation<RuntimeType*>* async_op;
584
shaochuan9ff63b82016-09-01 01:58:44 -0700585 HRESULT hr =
586 midi_port_statics_->FromIdAsync(dev_id_hstring.get(), &async_op);
shaochuane58f9c72016-08-30 22:27:08 -0700587 if (FAILED(hr)) {
588 VLOG(1) << "FromIdAsync failed: " << PrintHr(hr);
589 return;
590 }
591
592 base::WeakPtr<MidiPortManager> weak_ptr = GetWeakPtrFromFactory();
593 scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_runner_;
594
595 hr = async_op->put_Completed(
596 WRL::Callback<IAsyncOperationCompletedHandler<RuntimeType*>>(
597 [weak_ptr, task_runner](IAsyncOperation<RuntimeType*>* async_op,
598 AsyncStatus status) {
599 InterfaceType* handle;
600 HRESULT hr = async_op->GetResults(&handle);
601 if (FAILED(hr)) {
602 VLOG(1) << "GetResults failed: " << PrintHr(hr);
603 return hr;
604 }
605
606 // A reference to |async_op| is kept in |async_ops_|, safe to pass
607 // outside.
608 task_runner->PostTask(
609 FROM_HERE,
610 base::Bind(&MidiPortManager::OnCompletedGetPortFromIdAsync,
611 weak_ptr, handle, async_op));
612
613 return S_OK;
614 })
615 .Get());
616 if (FAILED(hr)) {
617 VLOG(1) << "put_Completed failed: " << PrintHr(hr);
618 return;
619 }
620
621 // Keep a reference to incompleted |async_op| for releasing later.
622 async_ops_.insert(async_op);
623 }
624
625 void OnEnumerationCompleted() {
626 DCHECK(thread_checker_.CalledOnValidThread());
627 CHECK(is_initialized_);
628
629 if (async_ops_.empty())
630 midi_manager_->OnPortManagerReady();
631 else
632 enumeration_completed_not_ready_ = true;
633 }
634
635 void OnRemoved(std::string dev_id) {
636 DCHECK(thread_checker_.CalledOnValidThread());
637 CHECK(is_initialized_);
638
shaochuan110262b2016-08-31 02:15:16 -0700639 // Note: in case Microsoft GS Wavetable Synth triggers this event for some
640 // reason, it will be ignored here with log emitted.
shaochuane58f9c72016-08-30 22:27:08 -0700641 MidiPort<InterfaceType>* port = GetPortByDeviceId(dev_id);
642 if (!port) {
643 VLOG(1) << "Removing non-existent port " << dev_id;
644 return;
645 }
646
647 SetPortState(port->index, MIDI_PORT_DISCONNECTED);
648
649 RemovePortEventHandlers(port);
650 port->handle = nullptr;
651 }
652
653 void OnCompletedGetPortFromIdAsync(InterfaceType* handle,
654 IAsyncOperation<RuntimeType*>* async_op) {
655 DCHECK(thread_checker_.CalledOnValidThread());
656 CHECK(is_initialized_);
657
658 EventRegistrationToken token = {kInvalidTokenValue};
659 if (!RegisterOnMessageReceived(handle, &token))
660 return;
661
662 std::string dev_id = GetDeviceIdString(handle);
663
664 MidiPort<InterfaceType>* port = GetPortByDeviceId(dev_id);
665
666 if (port == nullptr) {
shaochuan17bc4a02016-09-06 01:42:12 -0700667 std::string manufacturer = "Unknown", driver_version = "Unknown";
668 GetDriverInfoFromDeviceId(dev_id, &manufacturer, &driver_version);
669
670 AddPort(MidiPortInfo(dev_id, manufacturer, port_names_[dev_id],
671 driver_version, MIDI_PORT_OPENED));
shaochuane58f9c72016-08-30 22:27:08 -0700672
673 port = new MidiPort<InterfaceType>;
674 port->index = static_cast<uint32_t>(port_ids_.size());
675
676 ports_[dev_id].reset(port);
677 port_ids_.push_back(dev_id);
678 } else {
679 SetPortState(port->index, MIDI_PORT_CONNECTED);
680 }
681
682 port->handle = handle;
683 port->token_MessageReceived = token;
684
685 // Manually release COM interface to completed |async_op|.
686 auto it = async_ops_.find(async_op);
687 CHECK(it != async_ops_.end());
688 (*it)->Release();
689 async_ops_.erase(it);
690
691 if (enumeration_completed_not_ready_ && async_ops_.empty()) {
692 midi_manager_->OnPortManagerReady();
693 enumeration_completed_not_ready_ = false;
694 }
695 }
696
697 // Overrided by MidiInPortManager to listen to input ports.
698 virtual bool RegisterOnMessageReceived(InterfaceType* handle,
699 EventRegistrationToken* p_token) {
700 return true;
701 }
702
703 // Overrided by MidiInPortManager to remove MessageReceived event handler.
704 virtual void RemovePortEventHandlers(MidiPort<InterfaceType>* port) {}
705
706 // Calls midi_manager_->Add{Input,Output}Port.
707 virtual void AddPort(MidiPortInfo info) = 0;
708
709 // Calls midi_manager_->Set{Input,Output}PortState.
710 virtual void SetPortState(uint32_t port_index, MidiPortState state) = 0;
711
712 // WeakPtrFactory has to be declared in derived class, use this method to
713 // retrieve upcasted WeakPtr for posting tasks.
714 virtual base::WeakPtr<MidiPortManager> GetWeakPtrFromFactory() = 0;
715
716 // Midi{In,Out}PortStatics instance.
717 ScopedComPtr<StaticsInterfaceType> midi_port_statics_;
718
719 // DeviceWatcher instance and event registration tokens for unsubscribing
720 // events in destructor.
721 ScopedComPtr<IDeviceWatcher> watcher_;
722 EventRegistrationToken token_Added_ = {kInvalidTokenValue},
723 token_EnumerationCompleted_ = {kInvalidTokenValue},
724 token_Removed_ = {kInvalidTokenValue},
725 token_Stopped_ = {kInvalidTokenValue},
726 token_Updated_ = {kInvalidTokenValue};
727
728 // All manipulations to these fields should be done on COM thread.
729 std::unordered_map<std::string, std::unique_ptr<MidiPort<InterfaceType>>>
730 ports_;
731 std::vector<std::string> port_ids_;
732 std::unordered_map<std::string, std::string> port_names_;
733
734 // Keeps AsyncOperation references before the operation completes. Note that
735 // raw pointers are used here and the COM interfaces should be released
736 // manually.
737 std::unordered_set<IAsyncOperation<RuntimeType*>*> async_ops_;
738
739 // Set when device enumeration is completed but OnPortManagerReady() is not
740 // called since some ports are not yet ready (i.e. |async_ops_| is not empty).
741 // In such cases, OnPortManagerReady() will be called in
742 // OnCompletedGetPortFromIdAsync() when the last pending port is ready.
743 bool enumeration_completed_not_ready_ = false;
744
745 // Set if the instance is initialized without error. Should be checked in all
746 // methods on COM thread except StartWatcher().
747 bool is_initialized_ = false;
748};
749
750class MidiManagerWinrt::MidiInPortManager final
751 : public MidiPortManager<IMidiInPort,
752 MidiInPort,
753 IMidiInPortStatics,
754 RuntimeClass_Windows_Devices_Midi_MidiInPort> {
755 public:
756 MidiInPortManager(MidiManagerWinrt* midi_manager)
757 : MidiPortManager(midi_manager), weak_factory_(this) {}
758
759 private:
760 // MidiPortManager overrides:
761 bool RegisterOnMessageReceived(IMidiInPort* handle,
762 EventRegistrationToken* p_token) override {
763 DCHECK(thread_checker_.CalledOnValidThread());
764
765 base::WeakPtr<MidiInPortManager> weak_ptr = weak_factory_.GetWeakPtr();
766 scoped_refptr<base::SingleThreadTaskRunner> task_runner = task_runner_;
767
768 HRESULT hr = handle->add_MessageReceived(
769 WRL::Callback<
770 ITypedEventHandler<MidiInPort*, MidiMessageReceivedEventArgs*>>(
771 [weak_ptr, task_runner](IMidiInPort* handle,
772 IMidiMessageReceivedEventArgs* args) {
773 const base::TimeTicks now = base::TimeTicks::Now();
774
775 std::string dev_id = GetDeviceIdString(handle);
776
777 ScopedComPtr<IMidiMessage> message;
778 HRESULT hr = args->get_Message(message.Receive());
779 if (FAILED(hr)) {
780 VLOG(1) << "get_Message failed: " << PrintHr(hr);
781 return hr;
782 }
783
784 ScopedComPtr<IBuffer> buffer;
785 hr = message->get_RawData(buffer.Receive());
786 if (FAILED(hr)) {
787 VLOG(1) << "get_RawData failed: " << PrintHr(hr);
788 return hr;
789 }
790
791 uint8_t* p_buffer_data = nullptr;
792 hr = GetPointerToBufferData(buffer.get(), &p_buffer_data);
793 if (FAILED(hr))
794 return hr;
795
796 uint32_t data_length = 0;
797 hr = buffer->get_Length(&data_length);
798 if (FAILED(hr)) {
799 VLOG(1) << "get_Length failed: " << PrintHr(hr);
800 return hr;
801 }
802
803 std::vector<uint8_t> data(p_buffer_data,
804 p_buffer_data + data_length);
805
806 task_runner->PostTask(
807 FROM_HERE, base::Bind(&MidiInPortManager::OnMessageReceived,
808 weak_ptr, dev_id, data, now));
809
810 return S_OK;
811 })
812 .Get(),
813 p_token);
814 if (FAILED(hr)) {
815 VLOG(1) << "add_MessageReceived failed: " << PrintHr(hr);
816 return false;
817 }
818
819 return true;
820 }
821
822 void RemovePortEventHandlers(MidiPort<IMidiInPort>* port) override {
823 if (!(port->handle &&
824 port->token_MessageReceived.value != kInvalidTokenValue))
825 return;
826
827 HRESULT hr =
828 port->handle->remove_MessageReceived(port->token_MessageReceived);
829 VLOG_IF(1, FAILED(hr)) << "remove_MessageReceived failed: " << PrintHr(hr);
830 port->token_MessageReceived.value = kInvalidTokenValue;
831 }
832
833 void AddPort(MidiPortInfo info) final { midi_manager_->AddInputPort(info); }
834
835 void SetPortState(uint32_t port_index, MidiPortState state) final {
836 midi_manager_->SetInputPortState(port_index, state);
837 }
838
839 base::WeakPtr<MidiPortManager> GetWeakPtrFromFactory() final {
840 DCHECK(thread_checker_.CalledOnValidThread());
841
842 return weak_factory_.GetWeakPtr();
843 }
844
845 // Callback on receiving MIDI input message.
846 void OnMessageReceived(std::string dev_id,
847 std::vector<uint8_t> data,
848 base::TimeTicks time) {
849 DCHECK(thread_checker_.CalledOnValidThread());
850
851 MidiPort<IMidiInPort>* port = GetPortByDeviceId(dev_id);
852 CHECK(port);
853
854 midi_manager_->ReceiveMidiData(port->index, &data[0], data.size(), time);
855 }
856
857 // Last member to ensure destructed first.
858 base::WeakPtrFactory<MidiInPortManager> weak_factory_;
859
860 DISALLOW_COPY_AND_ASSIGN(MidiInPortManager);
861};
862
863class MidiManagerWinrt::MidiOutPortManager final
864 : public MidiPortManager<IMidiOutPort,
865 IMidiOutPort,
866 IMidiOutPortStatics,
867 RuntimeClass_Windows_Devices_Midi_MidiOutPort> {
868 public:
869 MidiOutPortManager(MidiManagerWinrt* midi_manager)
870 : MidiPortManager(midi_manager), weak_factory_(this) {}
871
872 private:
873 // MidiPortManager overrides:
874 void AddPort(MidiPortInfo info) final { midi_manager_->AddOutputPort(info); }
875
876 void SetPortState(uint32_t port_index, MidiPortState state) final {
877 midi_manager_->SetOutputPortState(port_index, state);
878 }
879
880 base::WeakPtr<MidiPortManager> GetWeakPtrFromFactory() final {
881 DCHECK(thread_checker_.CalledOnValidThread());
882
883 return weak_factory_.GetWeakPtr();
884 }
885
886 // Last member to ensure destructed first.
887 base::WeakPtrFactory<MidiOutPortManager> weak_factory_;
888
889 DISALLOW_COPY_AND_ASSIGN(MidiOutPortManager);
890};
891
892MidiManagerWinrt::MidiManagerWinrt() : com_thread_("Windows MIDI COM Thread") {}
893
894MidiManagerWinrt::~MidiManagerWinrt() {
895 base::AutoLock auto_lock(lazy_init_member_lock_);
896
897 CHECK(!com_thread_checker_);
898 CHECK(!port_manager_in_);
899 CHECK(!port_manager_out_);
900 CHECK(!scheduler_);
901}
902
903void MidiManagerWinrt::StartInitialization() {
shaochuane58f9c72016-08-30 22:27:08 -0700904 com_thread_.init_com_with_mta(true);
905 com_thread_.Start();
906
907 com_thread_.task_runner()->PostTask(
908 FROM_HERE, base::Bind(&MidiManagerWinrt::InitializeOnComThread,
909 base::Unretained(this)));
910}
911
912void MidiManagerWinrt::Finalize() {
913 com_thread_.task_runner()->PostTask(
914 FROM_HERE, base::Bind(&MidiManagerWinrt::FinalizeOnComThread,
915 base::Unretained(this)));
916
917 // Blocks until FinalizeOnComThread() returns. Delayed MIDI send data tasks
918 // will be ignored.
919 com_thread_.Stop();
920}
921
922void MidiManagerWinrt::DispatchSendMidiData(MidiManagerClient* client,
923 uint32_t port_index,
924 const std::vector<uint8_t>& data,
925 double timestamp) {
926 CHECK(scheduler_);
927
928 scheduler_->PostSendDataTask(
929 client, data.size(), timestamp,
930 base::Bind(&MidiManagerWinrt::SendOnComThread, base::Unretained(this),
931 port_index, data));
932}
933
934void MidiManagerWinrt::InitializeOnComThread() {
935 base::AutoLock auto_lock(lazy_init_member_lock_);
936
937 com_thread_checker_.reset(new base::ThreadChecker);
938
shaochuan9ff63b82016-09-01 01:58:44 -0700939 if (!g_combase_functions.Get().LoadFunctions()) {
940 VLOG(1) << "Failed loading functions from combase.dll: "
941 << PrintHr(HRESULT_FROM_WIN32(GetLastError()));
942 CompleteInitialization(Result::INITIALIZATION_ERROR);
943 return;
944 }
945
shaochuane58f9c72016-08-30 22:27:08 -0700946 port_manager_in_.reset(new MidiInPortManager(this));
947 port_manager_out_.reset(new MidiOutPortManager(this));
948
949 scheduler_.reset(new MidiScheduler(this));
950
951 if (!(port_manager_in_->StartWatcher() &&
952 port_manager_out_->StartWatcher())) {
953 port_manager_in_->StopWatcher();
954 port_manager_out_->StopWatcher();
955 CompleteInitialization(Result::INITIALIZATION_ERROR);
956 }
957}
958
959void MidiManagerWinrt::FinalizeOnComThread() {
960 base::AutoLock auto_lock(lazy_init_member_lock_);
961
962 DCHECK(com_thread_checker_->CalledOnValidThread());
963
964 scheduler_.reset();
965
shaochuan9ff63b82016-09-01 01:58:44 -0700966 if (port_manager_in_) {
967 port_manager_in_->StopWatcher();
968 port_manager_in_.reset();
969 }
970
971 if (port_manager_out_) {
972 port_manager_out_->StopWatcher();
973 port_manager_out_.reset();
974 }
shaochuane58f9c72016-08-30 22:27:08 -0700975
976 com_thread_checker_.reset();
977}
978
979void MidiManagerWinrt::SendOnComThread(uint32_t port_index,
980 const std::vector<uint8_t>& data) {
981 DCHECK(com_thread_checker_->CalledOnValidThread());
982
983 MidiPort<IMidiOutPort>* port = port_manager_out_->GetPortByIndex(port_index);
984 if (!(port && port->handle)) {
985 VLOG(1) << "Port not available: " << port_index;
986 return;
987 }
988
989 auto buffer_factory =
990 WrlStaticsFactory<IBufferFactory,
991 RuntimeClass_Windows_Storage_Streams_Buffer>();
992 if (!buffer_factory)
993 return;
994
995 ScopedComPtr<IBuffer> buffer;
996 HRESULT hr = buffer_factory->Create(static_cast<UINT32>(data.size()),
997 buffer.Receive());
998 if (FAILED(hr)) {
999 VLOG(1) << "Create failed: " << PrintHr(hr);
1000 return;
1001 }
1002
1003 hr = buffer->put_Length(static_cast<UINT32>(data.size()));
1004 if (FAILED(hr)) {
1005 VLOG(1) << "put_Length failed: " << PrintHr(hr);
1006 return;
1007 }
1008
1009 uint8_t* p_buffer_data = nullptr;
1010 hr = GetPointerToBufferData(buffer.get(), &p_buffer_data);
1011 if (FAILED(hr))
1012 return;
1013
1014 std::copy(data.begin(), data.end(), p_buffer_data);
1015
1016 hr = port->handle->SendBuffer(buffer.get());
1017 if (FAILED(hr)) {
1018 VLOG(1) << "SendBuffer failed: " << PrintHr(hr);
1019 return;
1020 }
1021}
1022
1023void MidiManagerWinrt::OnPortManagerReady() {
1024 DCHECK(com_thread_checker_->CalledOnValidThread());
1025 DCHECK(port_manager_ready_count_ < 2);
1026
1027 if (++port_manager_ready_count_ == 2)
1028 CompleteInitialization(Result::OK);
1029}
1030
shaochuane58f9c72016-08-30 22:27:08 -07001031} // namespace midi
1032} // namespace media