blob: 1ad6445c83d28b202b9ce99b9903aa8a43162d2f [file] [log] [blame]
toyoshimd28b59c2017-02-20 11:07:37 -08001// Copyright 2017 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
toyoshim63e32a52017-04-25 07:20:10 -07005#include "media/midi/midi_manager_win.h"
toyoshimd28b59c2017-02-20 11:07:37 -08006
7#include <windows.h>
8
toyoshim6ebf1182017-03-01 00:40:31 -08009#include <ks.h>
10#include <ksmedia.h>
toyoshimd28b59c2017-02-20 11:07:37 -080011#include <mmreg.h>
12#include <mmsystem.h>
13
14#include <algorithm>
15#include <string>
16
toyoshim8a5ad422017-02-28 21:16:18 -080017#include "base/bind_helpers.h"
toyoshimd28b59c2017-02-20 11:07:37 -080018#include "base/callback.h"
19#include "base/logging.h"
20#include "base/memory/ptr_util.h"
Gabriel Charette78f94a02017-05-16 14:03:45 -040021#include "base/single_thread_task_runner.h"
toyoshimd28b59c2017-02-20 11:07:37 -080022#include "base/strings/string16.h"
23#include "base/strings/stringprintf.h"
24#include "base/strings/utf_string_conversions.h"
25#include "base/synchronization/lock.h"
toyoshim15385b32017-04-24 23:52:01 -070026#include "base/win/windows_version.h"
toyoshim6ebf1182017-03-01 00:40:31 -080027#include "device/usb/usb_ids.h"
toyoshim8a5ad422017-02-28 21:16:18 -080028#include "media/midi/message_util.h"
toyoshim15385b32017-04-24 23:52:01 -070029#include "media/midi/midi_manager_winrt.h"
toyoshimd28b59c2017-02-20 11:07:37 -080030#include "media/midi/midi_port_info.h"
31#include "media/midi/midi_service.h"
toyoshim15385b32017-04-24 23:52:01 -070032#include "media/midi/midi_switches.h"
toyoshimd28b59c2017-02-20 11:07:37 -080033
34namespace midi {
35
toyoshim8a5ad422017-02-28 21:16:18 -080036// Forward declaration of PortManager for anonymous functions and internal
37// classes to use it.
toyoshim63e32a52017-04-25 07:20:10 -070038class MidiManagerWin::PortManager {
toyoshim8a5ad422017-02-28 21:16:18 -080039 public:
40 // Calculates event time from elapsed time that system provides.
41 base::TimeTicks CalculateInEventTime(size_t index, uint32_t elapsed_ms) const;
42
43 // Registers HMIDIIN handle to resolve port index.
44 void RegisterInHandle(HMIDIIN handle, size_t index);
45
46 // Unregisters HMIDIIN handle.
47 void UnregisterInHandle(HMIDIIN handle);
48
49 // Finds HMIDIIN handle and fullfil |out_index| with the port index.
toyoshim6d87aaa2017-02-28 22:36:44 -080050 bool FindInHandle(HMIDIIN hmi, size_t* out_index);
toyoshim8a5ad422017-02-28 21:16:18 -080051
52 // Restores used input buffer for the next data receive.
53 void RestoreInBuffer(size_t index);
54
55 // Ports accessors.
56 std::vector<std::unique_ptr<InPort>>* inputs() { return &input_ports_; }
57 std::vector<std::unique_ptr<OutPort>>* outputs() { return &output_ports_; }
58
59 // Handles MIDI input port callbacks that runs on a system provided thread.
60 static void CALLBACK HandleMidiInCallback(HMIDIIN hmi,
61 UINT msg,
62 DWORD_PTR instance,
63 DWORD_PTR param1,
64 DWORD_PTR param2);
65
toyoshim6d87aaa2017-02-28 22:36:44 -080066 // Handles MIDI output port callbacks that runs on a system provided thread.
67 static void CALLBACK HandleMidiOutCallback(HMIDIOUT hmo,
68 UINT msg,
69 DWORD_PTR instance,
70 DWORD_PTR param1,
71 DWORD_PTR param2);
72
toyoshim8a5ad422017-02-28 21:16:18 -080073 private:
74 // Holds all MIDI input or output ports connected once.
75 std::vector<std::unique_ptr<InPort>> input_ports_;
76 std::vector<std::unique_ptr<OutPort>> output_ports_;
77
78 // Map to resolve MIDI input port index from HMIDIIN.
79 std::map<HMIDIIN, size_t> hmidiin_to_index_map_;
80};
81
toyoshimd28b59c2017-02-20 11:07:37 -080082namespace {
83
toyoshimc32dd892017-02-24 02:13:14 -080084// Assumes that nullptr represents an invalid MIDI handle.
85constexpr HMIDIIN kInvalidInHandle = nullptr;
86constexpr HMIDIOUT kInvalidOutHandle = nullptr;
87
toyoshim6d87aaa2017-02-28 22:36:44 -080088// Defines SysEx message size limit.
89// TODO(crbug.com/383578): This restriction should be removed once Web MIDI
90// defines a standardized way to handle large sysex messages.
91// Note for built-in USB-MIDI driver:
92// From an observation on Windows 7/8.1 with a USB-MIDI keyboard,
93// midiOutLongMsg() will be always blocked. Sending 64 bytes or less data takes
94// roughly 300 usecs. Sending 2048 bytes or more data takes roughly
95// |message.size() / (75 * 1024)| secs in practice. Here we put 256 KB size
96// limit on SysEx message, with hoping that midiOutLongMsg will be blocked at
97// most 4 sec or so with a typical USB-MIDI device.
98// TODO(toyoshim): Consider to use linked small buffers so that midiOutReset()
99// can abort sending unhandled following buffers.
100constexpr size_t kSysExSizeLimit = 256 * 1024;
101
toyoshim8a5ad422017-02-28 21:16:18 -0800102// Defines input buffer size.
103constexpr size_t kBufferLength = 32 * 1024;
104
toyoshimd28b59c2017-02-20 11:07:37 -0800105// Global variables to identify MidiManager instance.
106constexpr int kInvalidInstanceId = -1;
107int g_active_instance_id = kInvalidInstanceId;
toyoshim63e32a52017-04-25 07:20:10 -0700108MidiManagerWin* g_manager_instance = nullptr;
toyoshimd28b59c2017-02-20 11:07:37 -0800109
110// Obtains base::Lock instance pointer to lock instance_id.
111base::Lock* GetInstanceIdLock() {
112 static base::Lock* lock = new base::Lock;
113 return lock;
114}
115
116// Issues unique MidiManager instance ID.
117int IssueNextInstanceId() {
118 static int id = kInvalidInstanceId;
119 return ++id;
120}
121
122// Use single TaskRunner for all tasks running outside the I/O thread.
123constexpr int kTaskRunner = 0;
124
125// Obtains base::Lock instance pointer to ensure tasks run safely on TaskRunner.
toyoshimc32dd892017-02-24 02:13:14 -0800126// Since all tasks on TaskRunner run behind a lock of *GetTaskLock(), we can
127// access all members even on the I/O thread if a lock of *GetTaskLock() is
128// obtained.
toyoshimd28b59c2017-02-20 11:07:37 -0800129base::Lock* GetTaskLock() {
130 static base::Lock* lock = new base::Lock;
131 return lock;
132}
133
134// Helper function to run a posted task on TaskRunner safely.
135void RunTask(int instance_id, const base::Closure& task) {
136 // Obtains task lock to ensure that the instance should not complete
137 // Finalize() while running the |task|.
138 base::AutoLock task_lock(*GetTaskLock());
139 {
140 // If Finalize() finished before the lock avobe, do nothing.
141 base::AutoLock lock(*GetInstanceIdLock());
142 if (instance_id != g_active_instance_id)
143 return;
144 }
145 task.Run();
146}
147
148// TODO(toyoshim): Factor out TaskRunner related functionaliries above, and
149// deprecate MidiScheduler. It should be available via MidiManager::scheduler().
150
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900151// Obtains base::Lock instance pointer to protect
152// |g_midi_in_get_num_devs_thread_id|.
153base::Lock* GetMidiInGetNumDevsThreadIdLock() {
154 static base::Lock* lock = new base::Lock;
155 return lock;
156}
157
158// Holds a thread id that calls midiInGetNumDevs() now. We use a platform
159// primitive to identify the thread because the following functions can be
160// called on a thread that Windows allocates internally, and Chrome or //base
161// library does not know.
162base::PlatformThreadId g_midi_in_get_num_devs_thread_id;
163
164// Prepares to call midiInGetNumDevs().
165void EnterMidiInGetNumDevs() {
166 base::AutoLock lock(*GetMidiInGetNumDevsThreadIdLock());
167 g_midi_in_get_num_devs_thread_id = base::PlatformThread::CurrentId();
168}
169
170// Finalizes to call midiInGetNumDevs().
171void LeaveMidiInGetNumDevs() {
172 base::AutoLock lock(*GetMidiInGetNumDevsThreadIdLock());
173 g_midi_in_get_num_devs_thread_id = base::PlatformThreadId();
174}
175
176// Checks if the current thread is running midiInGetNumDevs(), that means
177// current code is invoked inside midiInGetNumDevs().
178bool IsRunningInsideMidiInGetNumDevs() {
179 base::AutoLock lock(*GetMidiInGetNumDevsThreadIdLock());
180 return base::PlatformThread::CurrentId() == g_midi_in_get_num_devs_thread_id;
181}
182
toyoshim8a5ad422017-02-28 21:16:18 -0800183// Utility class to handle MIDIHDR struct safely.
184class MIDIHDRDeleter {
185 public:
186 void operator()(LPMIDIHDR header) {
187 if (!header)
188 return;
189 delete[] static_cast<char*>(header->lpData);
190 delete header;
191 }
192};
193
194using ScopedMIDIHDR = std::unique_ptr<MIDIHDR, MIDIHDRDeleter>;
195
196ScopedMIDIHDR CreateMIDIHDR(size_t size) {
197 ScopedMIDIHDR hdr(new MIDIHDR);
198 ZeroMemory(hdr.get(), sizeof(*hdr));
199 hdr->lpData = new char[size];
200 hdr->dwBufferLength = static_cast<DWORD>(size);
201 return hdr;
202}
203
toyoshim6d87aaa2017-02-28 22:36:44 -0800204ScopedMIDIHDR CreateMIDIHDR(const std::vector<uint8_t>& data) {
205 ScopedMIDIHDR hdr(CreateMIDIHDR(data.size()));
206 std::copy(data.begin(), data.end(), hdr->lpData);
207 return hdr;
208}
209
toyoshimc32dd892017-02-24 02:13:14 -0800210// Helper functions to close MIDI device handles on TaskRunner asynchronously.
toyoshim8a5ad422017-02-28 21:16:18 -0800211void FinalizeInPort(HMIDIIN handle, ScopedMIDIHDR hdr) {
212 // Resets the device. This stops receiving messages, and allows to release
213 // registered buffer headers. Otherwise, midiInUnprepareHeader() and
214 // midiInClose() will fail with MIDIERR_STILLPLAYING.
215 midiInReset(handle);
216
217 if (hdr)
218 midiInUnprepareHeader(handle, hdr.get(), sizeof(*hdr));
toyoshimc32dd892017-02-24 02:13:14 -0800219 midiInClose(handle);
220}
221
222void FinalizeOutPort(HMIDIOUT handle) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800223 // Resets inflight buffers. This will cancel sending data that system
224 // holds and were not sent yet.
225 midiOutReset(handle);
toyoshimc32dd892017-02-24 02:13:14 -0800226 midiOutClose(handle);
227}
228
toyoshim6ebf1182017-03-01 00:40:31 -0800229// Gets manufacturer name in string from identifiers.
230std::string GetManufacturerName(uint16_t id, const GUID& guid) {
231 if (IS_COMPATIBLE_USBAUDIO_MID(&guid)) {
232 const char* name =
233 device::UsbIds::GetVendorName(EXTRACT_USBAUDIO_MID(&guid));
234 if (name)
235 return std::string(name);
236 }
237 if (id == MM_MICROSOFT)
238 return "Microsoft Corporation";
239
240 // TODO(crbug.com/472341): Support other manufacture IDs.
241 return "";
242}
243
toyoshimc32dd892017-02-24 02:13:14 -0800244// All instances of Port subclasses are always accessed behind a lock of
245// *GetTaskLock(). Port and subclasses implementation do not need to
246// consider thread safety.
toyoshimd28b59c2017-02-20 11:07:37 -0800247class Port {
248 public:
249 Port(const std::string& type,
250 uint32_t device_id,
251 uint16_t manufacturer_id,
252 uint16_t product_id,
253 uint32_t driver_version,
toyoshim6ebf1182017-03-01 00:40:31 -0800254 const std::string& product_name,
255 const GUID& manufacturer_guid)
toyoshimd28b59c2017-02-20 11:07:37 -0800256 : index_(0u),
257 type_(type),
258 device_id_(device_id),
259 manufacturer_id_(manufacturer_id),
260 product_id_(product_id),
261 driver_version_(driver_version),
262 product_name_(product_name) {
toyoshim6ebf1182017-03-01 00:40:31 -0800263 info_.manufacturer =
264 GetManufacturerName(manufacturer_id, manufacturer_guid);
toyoshimd28b59c2017-02-20 11:07:37 -0800265 info_.name = product_name_;
266 info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_),
267 LOBYTE(driver_version_));
268 info_.state = mojom::PortState::DISCONNECTED;
269 }
270
271 virtual ~Port() {}
272
273 bool operator==(const Port& other) const {
274 // Should not use |device_id| for comparison because it can be changed on
275 // each enumeration.
276 // Since the GUID will be changed on each enumeration for Microsoft GS
277 // Wavetable synth and might be done for others, do not use it for device
278 // comparison.
279 return manufacturer_id_ == other.manufacturer_id_ &&
280 product_id_ == other.product_id_ &&
281 driver_version_ == other.driver_version_ &&
282 product_name_ == other.product_name_;
283 }
284
285 bool IsConnected() const {
286 return info_.state != mojom::PortState::DISCONNECTED;
287 }
288
289 void set_index(size_t index) {
290 index_ = index;
291 // TODO(toyoshim): Use hashed ID.
292 info_.id = base::StringPrintf("%s-%d", type_.c_str(), index_);
293 }
294 size_t index() { return index_; }
295 void set_device_id(uint32_t device_id) { device_id_ = device_id; }
296 uint32_t device_id() { return device_id_; }
297 const MidiPortInfo& info() { return info_; }
298
299 virtual bool Connect() {
300 if (info_.state != mojom::PortState::DISCONNECTED)
301 return false;
302
303 info_.state = mojom::PortState::CONNECTED;
304 // TODO(toyoshim) Until open() / close() are supported, open each device on
305 // connected.
306 Open();
307 return true;
308 }
309
310 virtual bool Disconnect() {
311 if (info_.state == mojom::PortState::DISCONNECTED)
312 return false;
313 info_.state = mojom::PortState::DISCONNECTED;
314 return true;
315 }
316
317 virtual void Open() { info_.state = mojom::PortState::OPENED; }
318
319 protected:
320 size_t index_;
321 std::string type_;
322 uint32_t device_id_;
323 const uint16_t manufacturer_id_;
324 const uint16_t product_id_;
325 const uint32_t driver_version_;
326 const std::string product_name_;
327 MidiPortInfo info_;
328}; // class Port
329
330} // namespace
331
toyoshim63e32a52017-04-25 07:20:10 -0700332class MidiManagerWin::InPort final : public Port {
toyoshimd28b59c2017-02-20 11:07:37 -0800333 public:
toyoshim63e32a52017-04-25 07:20:10 -0700334 InPort(MidiManagerWin* manager,
toyoshim8a5ad422017-02-28 21:16:18 -0800335 int instance_id,
336 UINT device_id,
337 const MIDIINCAPS2W& caps)
toyoshimd28b59c2017-02-20 11:07:37 -0800338 : Port("input",
339 device_id,
340 caps.wMid,
341 caps.wPid,
342 caps.vDriverVersion,
343 base::WideToUTF8(
toyoshim6ebf1182017-03-01 00:40:31 -0800344 base::string16(caps.szPname, wcslen(caps.szPname))),
345 caps.ManufacturerGuid),
toyoshim8a5ad422017-02-28 21:16:18 -0800346 manager_(manager),
347 in_handle_(kInvalidInHandle),
348 instance_id_(instance_id) {}
toyoshimd28b59c2017-02-20 11:07:37 -0800349
toyoshim8a5ad422017-02-28 21:16:18 -0800350 static std::vector<std::unique_ptr<InPort>> EnumerateActivePorts(
toyoshim63e32a52017-04-25 07:20:10 -0700351 MidiManagerWin* manager,
toyoshim8a5ad422017-02-28 21:16:18 -0800352 int instance_id) {
toyoshimd28b59c2017-02-20 11:07:37 -0800353 std::vector<std::unique_ptr<InPort>> ports;
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900354
355 // Allow callback invocations indie midiInGetNumDevs().
356 EnterMidiInGetNumDevs();
toyoshimd28b59c2017-02-20 11:07:37 -0800357 const UINT num_devices = midiInGetNumDevs();
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900358 LeaveMidiInGetNumDevs();
359
toyoshimd28b59c2017-02-20 11:07:37 -0800360 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
361 MIDIINCAPS2W caps;
362 MMRESULT result = midiInGetDevCaps(
363 device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps));
364 if (result != MMSYSERR_NOERROR) {
365 LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id;
366 continue;
367 }
toyoshim8a5ad422017-02-28 21:16:18 -0800368 ports.push_back(
369 base::MakeUnique<InPort>(manager, instance_id, device_id, caps));
toyoshimd28b59c2017-02-20 11:07:37 -0800370 }
371 return ports;
372 }
373
toyoshimc32dd892017-02-24 02:13:14 -0800374 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
375 if (in_handle_ != kInvalidInHandle) {
toyoshim63e32a52017-04-25 07:20:10 -0700376 runner->PostTask(FROM_HERE, base::Bind(&FinalizeInPort, in_handle_,
377 base::Passed(&hdr_)));
toyoshim8a5ad422017-02-28 21:16:18 -0800378 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshimc32dd892017-02-24 02:13:14 -0800379 in_handle_ = kInvalidInHandle;
380 }
381 }
382
toyoshim8a5ad422017-02-28 21:16:18 -0800383 base::TimeTicks CalculateInEventTime(uint32_t elapsed_ms) const {
384 return start_time_ + base::TimeDelta::FromMilliseconds(elapsed_ms);
385 }
386
387 void RestoreBuffer() {
388 if (in_handle_ == kInvalidInHandle || !hdr_)
389 return;
390 midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
391 }
392
toyoshim63e32a52017-04-25 07:20:10 -0700393 void NotifyPortStateSet(MidiManagerWin* manager) {
Bruce Dawson7fd26de2017-08-01 19:33:12 +0000394 manager->PostReplyTask(base::Bind(
395 &MidiManagerWin::SetInputPortState, base::Unretained(manager),
396 static_cast<uint32_t>(index_), info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800397 }
398
toyoshim63e32a52017-04-25 07:20:10 -0700399 void NotifyPortAdded(MidiManagerWin* manager) {
400 manager->PostReplyTask(base::Bind(&MidiManagerWin::AddInputPort,
401 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800402 }
toyoshimc32dd892017-02-24 02:13:14 -0800403
404 // Port overrides:
405 bool Disconnect() override {
406 if (in_handle_ != kInvalidInHandle) {
407 // Following API call may fail because device was already disconnected.
408 // But just in case.
409 midiInClose(in_handle_);
toyoshim8a5ad422017-02-28 21:16:18 -0800410 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshimc32dd892017-02-24 02:13:14 -0800411 in_handle_ = kInvalidInHandle;
412 }
413 return Port::Disconnect();
414 }
415
416 void Open() override {
toyoshim8a5ad422017-02-28 21:16:18 -0800417 MMRESULT result = midiInOpen(
418 &in_handle_, device_id_,
419 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiInCallback),
420 instance_id_, CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800421 if (result == MMSYSERR_NOERROR) {
toyoshim8a5ad422017-02-28 21:16:18 -0800422 hdr_ = CreateMIDIHDR(kBufferLength);
423 result = midiInPrepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
424 }
425 if (result != MMSYSERR_NOERROR)
426 in_handle_ = kInvalidInHandle;
427 if (result == MMSYSERR_NOERROR)
428 result = midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
429 if (result == MMSYSERR_NOERROR)
430 result = midiInStart(in_handle_);
431 if (result == MMSYSERR_NOERROR) {
432 start_time_ = base::TimeTicks::Now();
433 manager_->port_manager()->RegisterInHandle(in_handle_, index_);
toyoshimc32dd892017-02-24 02:13:14 -0800434 Port::Open();
435 } else {
toyoshim8a5ad422017-02-28 21:16:18 -0800436 if (in_handle_ != kInvalidInHandle) {
437 midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
438 hdr_.reset();
439 midiInClose(in_handle_);
440 in_handle_ = kInvalidInHandle;
441 }
toyoshimc32dd892017-02-24 02:13:14 -0800442 Disconnect();
443 }
444 }
445
446 private:
toyoshim63e32a52017-04-25 07:20:10 -0700447 MidiManagerWin* manager_;
toyoshimc32dd892017-02-24 02:13:14 -0800448 HMIDIIN in_handle_;
toyoshim8a5ad422017-02-28 21:16:18 -0800449 ScopedMIDIHDR hdr_;
450 base::TimeTicks start_time_;
451 const int instance_id_;
toyoshimd28b59c2017-02-20 11:07:37 -0800452};
453
toyoshim63e32a52017-04-25 07:20:10 -0700454class MidiManagerWin::OutPort final : public Port {
toyoshimd28b59c2017-02-20 11:07:37 -0800455 public:
456 OutPort(UINT device_id, const MIDIOUTCAPS2W& caps)
457 : Port("output",
458 device_id,
459 caps.wMid,
460 caps.wPid,
461 caps.vDriverVersion,
462 base::WideToUTF8(
toyoshim6ebf1182017-03-01 00:40:31 -0800463 base::string16(caps.szPname, wcslen(caps.szPname))),
464 caps.ManufacturerGuid),
toyoshimc32dd892017-02-24 02:13:14 -0800465 software_(caps.wTechnology == MOD_SWSYNTH),
466 out_handle_(kInvalidOutHandle) {}
toyoshimd28b59c2017-02-20 11:07:37 -0800467
468 static std::vector<std::unique_ptr<OutPort>> EnumerateActivePorts() {
469 std::vector<std::unique_ptr<OutPort>> ports;
470 const UINT num_devices = midiOutGetNumDevs();
471 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
472 MIDIOUTCAPS2W caps;
473 MMRESULT result = midiOutGetDevCaps(
474 device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps));
475 if (result != MMSYSERR_NOERROR) {
476 LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id;
477 continue;
478 }
479 ports.push_back(base::MakeUnique<OutPort>(device_id, caps));
480 }
481 return ports;
482 }
483
toyoshimc32dd892017-02-24 02:13:14 -0800484 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
485 if (out_handle_ != kInvalidOutHandle) {
486 runner->PostTask(FROM_HERE, base::Bind(&FinalizeOutPort, out_handle_));
487 out_handle_ = kInvalidOutHandle;
toyoshimd28b59c2017-02-20 11:07:37 -0800488 }
toyoshimd28b59c2017-02-20 11:07:37 -0800489 }
490
toyoshim63e32a52017-04-25 07:20:10 -0700491 void NotifyPortStateSet(MidiManagerWin* manager) {
Bruce Dawson7fd26de2017-08-01 19:33:12 +0000492 manager->PostReplyTask(base::Bind(
493 &MidiManagerWin::SetOutputPortState, base::Unretained(manager),
494 static_cast<uint32_t>(index_), info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800495 }
496
toyoshim63e32a52017-04-25 07:20:10 -0700497 void NotifyPortAdded(MidiManagerWin* manager) {
498 manager->PostReplyTask(base::Bind(&MidiManagerWin::AddOutputPort,
499 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800500 }
501
toyoshim6d87aaa2017-02-28 22:36:44 -0800502 void Send(const std::vector<uint8_t>& data) {
503 if (out_handle_ == kInvalidOutHandle)
504 return;
505
506 if (data.size() <= 3) {
507 uint32_t message = 0;
508 for (size_t i = 0; i < data.size(); ++i)
509 message |= (static_cast<uint32_t>(data[i]) << (i * 8));
510 midiOutShortMsg(out_handle_, message);
511 } else {
512 if (data.size() > kSysExSizeLimit) {
513 LOG(ERROR) << "Ignoring SysEx message due to the size limit"
514 << ", size = " << data.size();
515 // TODO(toyoshim): Consider to report metrics here.
516 return;
517 }
518 ScopedMIDIHDR hdr(CreateMIDIHDR(data));
519 MMRESULT result =
520 midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
521 if (result != MMSYSERR_NOERROR)
522 return;
523 result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr));
524 if (result != MMSYSERR_NOERROR) {
525 midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
526 } else {
527 // MIDIHDR will be released on MOM_DONE.
528 ignore_result(hdr.release());
529 }
530 }
531 }
532
toyoshimc32dd892017-02-24 02:13:14 -0800533 // Port overrides:
534 bool Connect() override {
535 // Until |software| option is supported, disable Microsoft GS Wavetable
536 // Synth that has a known security issue.
537 if (software_ && manufacturer_id_ == MM_MICROSOFT &&
538 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT ||
539 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) {
540 return false;
541 }
542 return Port::Connect();
543 }
544
545 bool Disconnect() override {
546 if (out_handle_ != kInvalidOutHandle) {
547 // Following API call may fail because device was already disconnected.
548 // But just in case.
549 midiOutClose(out_handle_);
550 out_handle_ = kInvalidOutHandle;
551 }
552 return Port::Disconnect();
553 }
554
555 void Open() override {
toyoshim6d87aaa2017-02-28 22:36:44 -0800556 MMRESULT result = midiOutOpen(
557 &out_handle_, device_id_,
558 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiOutCallback), 0,
559 CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800560 if (result == MMSYSERR_NOERROR) {
561 Port::Open();
562 } else {
563 out_handle_ = kInvalidOutHandle;
564 Disconnect();
565 }
566 }
567
toyoshimd28b59c2017-02-20 11:07:37 -0800568 const bool software_;
toyoshimc32dd892017-02-24 02:13:14 -0800569 HMIDIOUT out_handle_;
toyoshimd28b59c2017-02-20 11:07:37 -0800570};
571
toyoshim63e32a52017-04-25 07:20:10 -0700572base::TimeTicks MidiManagerWin::PortManager::CalculateInEventTime(
toyoshim8a5ad422017-02-28 21:16:18 -0800573 size_t index,
574 uint32_t elapsed_ms) const {
575 GetTaskLock()->AssertAcquired();
576 CHECK_GT(input_ports_.size(), index);
577 return input_ports_[index]->CalculateInEventTime(elapsed_ms);
578}
579
toyoshim63e32a52017-04-25 07:20:10 -0700580void MidiManagerWin::PortManager::RegisterInHandle(HMIDIIN handle,
581 size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800582 GetTaskLock()->AssertAcquired();
583 hmidiin_to_index_map_[handle] = index;
584}
585
toyoshim63e32a52017-04-25 07:20:10 -0700586void MidiManagerWin::PortManager::UnregisterInHandle(HMIDIIN handle) {
toyoshim8a5ad422017-02-28 21:16:18 -0800587 GetTaskLock()->AssertAcquired();
588 hmidiin_to_index_map_.erase(handle);
589}
590
toyoshim63e32a52017-04-25 07:20:10 -0700591bool MidiManagerWin::PortManager::FindInHandle(HMIDIIN hmi, size_t* out_index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800592 GetTaskLock()->AssertAcquired();
593 auto found = hmidiin_to_index_map_.find(hmi);
594 if (found == hmidiin_to_index_map_.end())
595 return false;
596 *out_index = found->second;
597 return true;
598}
599
toyoshim63e32a52017-04-25 07:20:10 -0700600void MidiManagerWin::PortManager::RestoreInBuffer(size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800601 GetTaskLock()->AssertAcquired();
602 CHECK_GT(input_ports_.size(), index);
603 input_ports_[index]->RestoreBuffer();
604}
605
606void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700607MidiManagerWin::PortManager::HandleMidiInCallback(HMIDIIN hmi,
608 UINT msg,
609 DWORD_PTR instance,
610 DWORD_PTR param1,
611 DWORD_PTR param2) {
toyoshim8a5ad422017-02-28 21:16:18 -0800612 if (msg != MIM_DATA && msg != MIM_LONGDATA)
613 return;
614 int instance_id = static_cast<int>(instance);
toyoshim63e32a52017-04-25 07:20:10 -0700615 MidiManagerWin* manager = nullptr;
toyoshim8a5ad422017-02-28 21:16:18 -0800616
617 // Use |g_task_lock| so to ensure the instance can keep alive while running,
618 // and to access member variables that are used on TaskRunner.
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900619 // Exceptionally, we do not take the lock when this callback is invoked inside
620 // midiInGetNumDevs() on the caller thread because the lock is already
621 // obtained by the current caller thread.
622 std::unique_ptr<base::AutoLock> task_lock;
623 if (IsRunningInsideMidiInGetNumDevs())
624 GetTaskLock()->AssertAcquired();
625 else
626 task_lock.reset(new base::AutoLock(*GetTaskLock()));
toyoshim8a5ad422017-02-28 21:16:18 -0800627 {
628 base::AutoLock lock(*GetInstanceIdLock());
629 if (instance_id != g_active_instance_id)
630 return;
631 manager = g_manager_instance;
632 }
633
634 size_t index;
toyoshim6d87aaa2017-02-28 22:36:44 -0800635 if (!manager->port_manager()->FindInHandle(hmi, &index))
toyoshim8a5ad422017-02-28 21:16:18 -0800636 return;
637
638 DCHECK(msg == MIM_DATA || msg == MIM_LONGDATA);
639 if (msg == MIM_DATA) {
640 const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff);
641 const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff);
642 const uint8_t second_data_byte =
643 static_cast<uint8_t>((param1 >> 16) & 0xff);
644 const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte};
645 const size_t len = GetMessageLength(status_byte);
646 DCHECK_LE(len, arraysize(kData));
647 std::vector<uint8_t> data;
648 data.assign(kData, kData + len);
649 manager->PostReplyTask(base::Bind(
Yutaka Hirano138dd962017-08-01 08:14:15 +0000650 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
651 static_cast<uint32_t>(index), data,
652 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800653 } else {
654 DCHECK_EQ(static_cast<UINT>(MIM_LONGDATA), msg);
655 LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1);
656 if (hdr->dwBytesRecorded > 0) {
657 const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData);
658 std::vector<uint8_t> data;
659 data.assign(src, src + hdr->dwBytesRecorded);
660 manager->PostReplyTask(base::Bind(
Yutaka Hirano138dd962017-08-01 08:14:15 +0000661 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
662 static_cast<uint32_t>(index), data,
663 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800664 }
toyoshim824deed2017-06-07 16:45:43 -0700665 manager->port_manager()->RestoreInBuffer(index);
toyoshim8a5ad422017-02-28 21:16:18 -0800666 }
667}
668
toyoshim6d87aaa2017-02-28 22:36:44 -0800669void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700670MidiManagerWin::PortManager::HandleMidiOutCallback(HMIDIOUT hmo,
671 UINT msg,
672 DWORD_PTR instance,
673 DWORD_PTR param1,
674 DWORD_PTR param2) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800675 if (msg == MOM_DONE) {
676 ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1));
677 if (!hdr)
678 return;
679 // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback.
680 // Since this callback may be invoked after the manager is destructed,
681 // and can not send a task to the TaskRunner in such case, we need to
682 // consider to track MIDIHDR per port, and clean it in port finalization
683 // steps, too.
684 midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr));
685 }
686}
687
toyoshim63e32a52017-04-25 07:20:10 -0700688MidiManagerWin::MidiManagerWin(MidiService* service)
toyoshim8a5ad422017-02-28 21:16:18 -0800689 : MidiManager(service),
690 instance_id_(IssueNextInstanceId()),
691 port_manager_(base::MakeUnique<PortManager>()) {
toyoshimd28b59c2017-02-20 11:07:37 -0800692 base::AutoLock lock(*GetInstanceIdLock());
693 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
694
695 // Obtains the task runner for the current thread that hosts this instnace.
696 thread_runner_ = base::ThreadTaskRunnerHandle::Get();
697}
698
toyoshim63e32a52017-04-25 07:20:10 -0700699MidiManagerWin::~MidiManagerWin() {
toyoshimd28b59c2017-02-20 11:07:37 -0800700 base::AutoLock lock(*GetInstanceIdLock());
701 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
702 CHECK(thread_runner_->BelongsToCurrentThread());
703}
704
toyoshim63e32a52017-04-25 07:20:10 -0700705void MidiManagerWin::StartInitialization() {
toyoshimd28b59c2017-02-20 11:07:37 -0800706 {
707 base::AutoLock lock(*GetInstanceIdLock());
708 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
709 g_active_instance_id = instance_id_;
710 CHECK_EQ(nullptr, g_manager_instance);
711 g_manager_instance = this;
712 }
713 // Registers on the I/O thread to be notified on the I/O thread.
714 CHECK(thread_runner_->BelongsToCurrentThread());
715 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
716
717 // Starts asynchronous initialization on TaskRunner.
toyoshim63e32a52017-04-25 07:20:10 -0700718 PostTask(base::Bind(&MidiManagerWin::InitializeOnTaskRunner,
719 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800720}
721
toyoshim63e32a52017-04-25 07:20:10 -0700722void MidiManagerWin::Finalize() {
toyoshimd28b59c2017-02-20 11:07:37 -0800723 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more.
724 CHECK(thread_runner_->BelongsToCurrentThread());
725 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
726 {
727 base::AutoLock lock(*GetInstanceIdLock());
728 CHECK_EQ(instance_id_, g_active_instance_id);
729 g_active_instance_id = kInvalidInstanceId;
730 CHECK_EQ(this, g_manager_instance);
731 g_manager_instance = nullptr;
732 }
733
734 // Ensures that no task runs on TaskRunner so to destruct the instance safely.
735 // Tasks that did not started yet will do nothing after invalidate the
736 // instance ID above.
toyoshimc32dd892017-02-24 02:13:14 -0800737 // Behind the lock below, we can safely access all members for finalization
738 // even on the I/O thread.
toyoshimd28b59c2017-02-20 11:07:37 -0800739 base::AutoLock lock(*GetTaskLock());
toyoshimc32dd892017-02-24 02:13:14 -0800740
741 // Posts tasks that finalize each device port without MidiManager instance
742 // on TaskRunner. If another MidiManager instance is created, its
743 // initialization runs on the same task runner after all tasks posted here
744 // finish.
toyoshim8a5ad422017-02-28 21:16:18 -0800745 for (const auto& port : *port_manager_->inputs())
toyoshimc32dd892017-02-24 02:13:14 -0800746 port->Finalize(service()->GetTaskRunner(kTaskRunner));
toyoshim8a5ad422017-02-28 21:16:18 -0800747 for (const auto& port : *port_manager_->outputs())
toyoshimc32dd892017-02-24 02:13:14 -0800748 port->Finalize(service()->GetTaskRunner(kTaskRunner));
toyoshimd28b59c2017-02-20 11:07:37 -0800749}
750
toyoshim63e32a52017-04-25 07:20:10 -0700751void MidiManagerWin::DispatchSendMidiData(MidiManagerClient* client,
752 uint32_t port_index,
753 const std::vector<uint8_t>& data,
754 double timestamp) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800755 if (timestamp != 0.0) {
toyoshim63e32a52017-04-25 07:20:10 -0700756 base::TimeTicks time =
757 base::TimeTicks() + base::TimeDelta::FromMicroseconds(
758 timestamp * base::Time::kMicrosecondsPerSecond);
toyoshim6d87aaa2017-02-28 22:36:44 -0800759 base::TimeTicks now = base::TimeTicks::Now();
760 if (now < time) {
761 PostDelayedTask(
toyoshim63e32a52017-04-25 07:20:10 -0700762 base::Bind(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
763 client, port_index, data),
toyoshim6d87aaa2017-02-28 22:36:44 -0800764 time - now);
765 return;
766 }
767 }
toyoshim63e32a52017-04-25 07:20:10 -0700768 PostTask(base::Bind(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
769 client, port_index, data));
toyoshimd28b59c2017-02-20 11:07:37 -0800770}
771
toyoshim63e32a52017-04-25 07:20:10 -0700772void MidiManagerWin::OnDevicesChanged(
toyoshimd28b59c2017-02-20 11:07:37 -0800773 base::SystemMonitor::DeviceType device_type) {
774 // Notified on the I/O thread.
775 CHECK(thread_runner_->BelongsToCurrentThread());
776
777 switch (device_type) {
778 case base::SystemMonitor::DEVTYPE_AUDIO:
779 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
780 // Add case of other unrelated device types here.
781 return;
782 case base::SystemMonitor::DEVTYPE_UNKNOWN: {
toyoshim63e32a52017-04-25 07:20:10 -0700783 PostTask(base::Bind(&MidiManagerWin::UpdateDeviceListOnTaskRunner,
784 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800785 break;
786 }
787 }
788}
789
toyoshim63e32a52017-04-25 07:20:10 -0700790void MidiManagerWin::ReceiveMidiData(uint32_t index,
791 const std::vector<uint8_t>& data,
792 base::TimeTicks time) {
toyoshim8a5ad422017-02-28 21:16:18 -0800793 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
794}
795
toyoshim63e32a52017-04-25 07:20:10 -0700796void MidiManagerWin::PostTask(const base::Closure& task) {
toyoshimd28b59c2017-02-20 11:07:37 -0800797 service()
798 ->GetTaskRunner(kTaskRunner)
799 ->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
800}
801
toyoshim63e32a52017-04-25 07:20:10 -0700802void MidiManagerWin::PostDelayedTask(const base::Closure& task,
803 base::TimeDelta delay) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800804 service()
805 ->GetTaskRunner(kTaskRunner)
806 ->PostDelayedTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task),
807 delay);
808}
809
toyoshim63e32a52017-04-25 07:20:10 -0700810void MidiManagerWin::PostReplyTask(const base::Closure& task) {
toyoshim8a5ad422017-02-28 21:16:18 -0800811 thread_runner_->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
812}
813
toyoshim63e32a52017-04-25 07:20:10 -0700814void MidiManagerWin::InitializeOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800815 UpdateDeviceListOnTaskRunner();
toyoshim63e32a52017-04-25 07:20:10 -0700816 PostReplyTask(base::Bind(&MidiManagerWin::CompleteInitialization,
817 base::Unretained(this), mojom::Result::OK));
toyoshimd28b59c2017-02-20 11:07:37 -0800818}
819
toyoshim63e32a52017-04-25 07:20:10 -0700820void MidiManagerWin::UpdateDeviceListOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800821 std::vector<std::unique_ptr<InPort>> active_input_ports =
toyoshim8a5ad422017-02-28 21:16:18 -0800822 InPort::EnumerateActivePorts(this, instance_id_);
823 ReflectActiveDeviceList(this, port_manager_->inputs(), &active_input_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800824
825 std::vector<std::unique_ptr<OutPort>> active_output_ports =
826 OutPort::EnumerateActivePorts();
toyoshim8a5ad422017-02-28 21:16:18 -0800827 ReflectActiveDeviceList(this, port_manager_->outputs(), &active_output_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800828
829 // TODO(toyoshim): This method may run before internal MIDI device lists that
830 // Windows manages were updated. This may be because MIDI driver may be loaded
831 // after the raw device list was updated. To avoid this problem, we may want
832 // to retry device check later if no changes are detected here.
833}
834
835template <typename T>
toyoshim63e32a52017-04-25 07:20:10 -0700836void MidiManagerWin::ReflectActiveDeviceList(MidiManagerWin* manager,
837 std::vector<T>* known_ports,
838 std::vector<T>* active_ports) {
toyoshimd28b59c2017-02-20 11:07:37 -0800839 // Update existing port states.
840 for (const auto& port : *known_ports) {
841 const auto& it = std::find_if(
842 active_ports->begin(), active_ports->end(),
843 [&port](const auto& candidate) { return *candidate == *port; });
844 if (it == active_ports->end()) {
845 if (port->Disconnect())
846 port->NotifyPortStateSet(this);
847 } else {
848 port->set_device_id((*it)->device_id());
849 if (port->Connect())
850 port->NotifyPortStateSet(this);
851 }
852 }
853
854 // Find new ports from active ports and append them to known ports.
855 for (auto& port : *active_ports) {
856 if (std::find_if(known_ports->begin(), known_ports->end(),
857 [&port](const auto& candidate) {
858 return *candidate == *port;
859 }) == known_ports->end()) {
860 size_t index = known_ports->size();
861 port->set_index(index);
862 known_ports->push_back(std::move(port));
863 (*known_ports)[index]->Connect();
864 (*known_ports)[index]->NotifyPortAdded(this);
865 }
866 }
867}
868
toyoshim63e32a52017-04-25 07:20:10 -0700869void MidiManagerWin::SendOnTaskRunner(MidiManagerClient* client,
870 uint32_t port_index,
871 const std::vector<uint8_t>& data) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800872 CHECK_GT(port_manager_->outputs()->size(), port_index);
873 (*port_manager_->outputs())[port_index]->Send(data);
874 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
toyoshim63e32a52017-04-25 07:20:10 -0700875 PostReplyTask(base::Bind(&MidiManagerWin::AccumulateMidiBytesSent,
876 base::Unretained(this), client, data.size()));
toyoshim6d87aaa2017-02-28 22:36:44 -0800877}
878
toyoshim15385b32017-04-24 23:52:01 -0700879MidiManager* MidiManager::Create(MidiService* service) {
880 if (base::FeatureList::IsEnabled(features::kMidiManagerWinrt) &&
toyoshim63e32a52017-04-25 07:20:10 -0700881 base::win::GetVersion() >= base::win::VERSION_WIN10) {
toyoshim15385b32017-04-24 23:52:01 -0700882 return new MidiManagerWinrt(service);
toyoshim63e32a52017-04-25 07:20:10 -0700883 }
884 return new MidiManagerWin(service);
toyoshim15385b32017-04-24 23:52:01 -0700885}
886
toyoshimd28b59c2017-02-20 11:07:37 -0800887} // namespace midi