blob: 8bd84b97b9330f013c556147807a65e2961863b5 [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.
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000135void RunTask(int instance_id, base::OnceClosure task) {
toyoshimd28b59c2017-02-20 11:07:37 -0800136 // 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 }
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000145 std::move(task).Run();
toyoshimd28b59c2017-02-20 11:07:37 -0800146}
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.
Bruce Dawson66ae7db2017-08-04 17:57:45 +0000292 info_.id = base::StringPrintf("%s-%zd", type_.c_str(), index_);
toyoshimd28b59c2017-02-20 11:07:37 -0800293 }
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) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000376 runner->PostTask(FROM_HERE, base::BindOnce(&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) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000394 manager->PostReplyTask(base::BindOnce(
Bruce Dawson7fd26de2017-08-01 19:33:12 +0000395 &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) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000400 manager->PostReplyTask(base::BindOnce(&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) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000486 runner->PostTask(FROM_HERE,
487 base::BindOnce(&FinalizeOutPort, out_handle_));
toyoshimc32dd892017-02-24 02:13:14 -0800488 out_handle_ = kInvalidOutHandle;
toyoshimd28b59c2017-02-20 11:07:37 -0800489 }
toyoshimd28b59c2017-02-20 11:07:37 -0800490 }
491
toyoshim63e32a52017-04-25 07:20:10 -0700492 void NotifyPortStateSet(MidiManagerWin* manager) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000493 manager->PostReplyTask(base::BindOnce(
Bruce Dawson7fd26de2017-08-01 19:33:12 +0000494 &MidiManagerWin::SetOutputPortState, base::Unretained(manager),
495 static_cast<uint32_t>(index_), info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800496 }
497
toyoshim63e32a52017-04-25 07:20:10 -0700498 void NotifyPortAdded(MidiManagerWin* manager) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000499 manager->PostReplyTask(base::BindOnce(&MidiManagerWin::AddOutputPort,
500 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800501 }
502
toyoshim6d87aaa2017-02-28 22:36:44 -0800503 void Send(const std::vector<uint8_t>& data) {
504 if (out_handle_ == kInvalidOutHandle)
505 return;
506
507 if (data.size() <= 3) {
508 uint32_t message = 0;
509 for (size_t i = 0; i < data.size(); ++i)
510 message |= (static_cast<uint32_t>(data[i]) << (i * 8));
511 midiOutShortMsg(out_handle_, message);
512 } else {
513 if (data.size() > kSysExSizeLimit) {
514 LOG(ERROR) << "Ignoring SysEx message due to the size limit"
515 << ", size = " << data.size();
516 // TODO(toyoshim): Consider to report metrics here.
517 return;
518 }
519 ScopedMIDIHDR hdr(CreateMIDIHDR(data));
520 MMRESULT result =
521 midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
522 if (result != MMSYSERR_NOERROR)
523 return;
524 result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr));
525 if (result != MMSYSERR_NOERROR) {
526 midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
527 } else {
528 // MIDIHDR will be released on MOM_DONE.
529 ignore_result(hdr.release());
530 }
531 }
532 }
533
toyoshimc32dd892017-02-24 02:13:14 -0800534 // Port overrides:
535 bool Connect() override {
536 // Until |software| option is supported, disable Microsoft GS Wavetable
537 // Synth that has a known security issue.
538 if (software_ && manufacturer_id_ == MM_MICROSOFT &&
539 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT ||
540 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) {
541 return false;
542 }
543 return Port::Connect();
544 }
545
546 bool Disconnect() override {
547 if (out_handle_ != kInvalidOutHandle) {
548 // Following API call may fail because device was already disconnected.
549 // But just in case.
550 midiOutClose(out_handle_);
551 out_handle_ = kInvalidOutHandle;
552 }
553 return Port::Disconnect();
554 }
555
556 void Open() override {
toyoshim6d87aaa2017-02-28 22:36:44 -0800557 MMRESULT result = midiOutOpen(
558 &out_handle_, device_id_,
559 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiOutCallback), 0,
560 CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800561 if (result == MMSYSERR_NOERROR) {
562 Port::Open();
563 } else {
564 out_handle_ = kInvalidOutHandle;
565 Disconnect();
566 }
567 }
568
toyoshimd28b59c2017-02-20 11:07:37 -0800569 const bool software_;
toyoshimc32dd892017-02-24 02:13:14 -0800570 HMIDIOUT out_handle_;
toyoshimd28b59c2017-02-20 11:07:37 -0800571};
572
toyoshim63e32a52017-04-25 07:20:10 -0700573base::TimeTicks MidiManagerWin::PortManager::CalculateInEventTime(
toyoshim8a5ad422017-02-28 21:16:18 -0800574 size_t index,
575 uint32_t elapsed_ms) const {
576 GetTaskLock()->AssertAcquired();
577 CHECK_GT(input_ports_.size(), index);
578 return input_ports_[index]->CalculateInEventTime(elapsed_ms);
579}
580
toyoshim63e32a52017-04-25 07:20:10 -0700581void MidiManagerWin::PortManager::RegisterInHandle(HMIDIIN handle,
582 size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800583 GetTaskLock()->AssertAcquired();
584 hmidiin_to_index_map_[handle] = index;
585}
586
toyoshim63e32a52017-04-25 07:20:10 -0700587void MidiManagerWin::PortManager::UnregisterInHandle(HMIDIIN handle) {
toyoshim8a5ad422017-02-28 21:16:18 -0800588 GetTaskLock()->AssertAcquired();
589 hmidiin_to_index_map_.erase(handle);
590}
591
toyoshim63e32a52017-04-25 07:20:10 -0700592bool MidiManagerWin::PortManager::FindInHandle(HMIDIIN hmi, size_t* out_index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800593 GetTaskLock()->AssertAcquired();
594 auto found = hmidiin_to_index_map_.find(hmi);
595 if (found == hmidiin_to_index_map_.end())
596 return false;
597 *out_index = found->second;
598 return true;
599}
600
toyoshim63e32a52017-04-25 07:20:10 -0700601void MidiManagerWin::PortManager::RestoreInBuffer(size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800602 GetTaskLock()->AssertAcquired();
603 CHECK_GT(input_ports_.size(), index);
604 input_ports_[index]->RestoreBuffer();
605}
606
607void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700608MidiManagerWin::PortManager::HandleMidiInCallback(HMIDIIN hmi,
609 UINT msg,
610 DWORD_PTR instance,
611 DWORD_PTR param1,
612 DWORD_PTR param2) {
toyoshim8a5ad422017-02-28 21:16:18 -0800613 if (msg != MIM_DATA && msg != MIM_LONGDATA)
614 return;
615 int instance_id = static_cast<int>(instance);
toyoshim63e32a52017-04-25 07:20:10 -0700616 MidiManagerWin* manager = nullptr;
toyoshim8a5ad422017-02-28 21:16:18 -0800617
618 // Use |g_task_lock| so to ensure the instance can keep alive while running,
619 // and to access member variables that are used on TaskRunner.
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900620 // Exceptionally, we do not take the lock when this callback is invoked inside
621 // midiInGetNumDevs() on the caller thread because the lock is already
622 // obtained by the current caller thread.
623 std::unique_ptr<base::AutoLock> task_lock;
624 if (IsRunningInsideMidiInGetNumDevs())
625 GetTaskLock()->AssertAcquired();
626 else
627 task_lock.reset(new base::AutoLock(*GetTaskLock()));
toyoshim8a5ad422017-02-28 21:16:18 -0800628 {
629 base::AutoLock lock(*GetInstanceIdLock());
630 if (instance_id != g_active_instance_id)
631 return;
632 manager = g_manager_instance;
633 }
634
635 size_t index;
toyoshim6d87aaa2017-02-28 22:36:44 -0800636 if (!manager->port_manager()->FindInHandle(hmi, &index))
toyoshim8a5ad422017-02-28 21:16:18 -0800637 return;
638
639 DCHECK(msg == MIM_DATA || msg == MIM_LONGDATA);
640 if (msg == MIM_DATA) {
641 const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff);
642 const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff);
643 const uint8_t second_data_byte =
644 static_cast<uint8_t>((param1 >> 16) & 0xff);
645 const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte};
646 const size_t len = GetMessageLength(status_byte);
647 DCHECK_LE(len, arraysize(kData));
648 std::vector<uint8_t> data;
649 data.assign(kData, kData + len);
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000650 manager->PostReplyTask(base::BindOnce(
Yutaka Hirano138dd962017-08-01 08:14:15 +0000651 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
652 static_cast<uint32_t>(index), data,
653 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800654 } else {
655 DCHECK_EQ(static_cast<UINT>(MIM_LONGDATA), msg);
656 LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1);
657 if (hdr->dwBytesRecorded > 0) {
658 const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData);
659 std::vector<uint8_t> data;
660 data.assign(src, src + hdr->dwBytesRecorded);
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000661 manager->PostReplyTask(base::BindOnce(
Yutaka Hirano138dd962017-08-01 08:14:15 +0000662 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
663 static_cast<uint32_t>(index), data,
664 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800665 }
toyoshim824deed2017-06-07 16:45:43 -0700666 manager->port_manager()->RestoreInBuffer(index);
toyoshim8a5ad422017-02-28 21:16:18 -0800667 }
668}
669
toyoshim6d87aaa2017-02-28 22:36:44 -0800670void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700671MidiManagerWin::PortManager::HandleMidiOutCallback(HMIDIOUT hmo,
672 UINT msg,
673 DWORD_PTR instance,
674 DWORD_PTR param1,
675 DWORD_PTR param2) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800676 if (msg == MOM_DONE) {
677 ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1));
678 if (!hdr)
679 return;
680 // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback.
681 // Since this callback may be invoked after the manager is destructed,
682 // and can not send a task to the TaskRunner in such case, we need to
683 // consider to track MIDIHDR per port, and clean it in port finalization
684 // steps, too.
685 midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr));
686 }
687}
688
toyoshim63e32a52017-04-25 07:20:10 -0700689MidiManagerWin::MidiManagerWin(MidiService* service)
toyoshim8a5ad422017-02-28 21:16:18 -0800690 : MidiManager(service),
691 instance_id_(IssueNextInstanceId()),
692 port_manager_(base::MakeUnique<PortManager>()) {
toyoshimd28b59c2017-02-20 11:07:37 -0800693 base::AutoLock lock(*GetInstanceIdLock());
694 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
695
696 // Obtains the task runner for the current thread that hosts this instnace.
697 thread_runner_ = base::ThreadTaskRunnerHandle::Get();
698}
699
toyoshim63e32a52017-04-25 07:20:10 -0700700MidiManagerWin::~MidiManagerWin() {
toyoshimd28b59c2017-02-20 11:07:37 -0800701 base::AutoLock lock(*GetInstanceIdLock());
702 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
703 CHECK(thread_runner_->BelongsToCurrentThread());
704}
705
toyoshim63e32a52017-04-25 07:20:10 -0700706void MidiManagerWin::StartInitialization() {
toyoshimd28b59c2017-02-20 11:07:37 -0800707 {
708 base::AutoLock lock(*GetInstanceIdLock());
709 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
710 g_active_instance_id = instance_id_;
711 CHECK_EQ(nullptr, g_manager_instance);
712 g_manager_instance = this;
713 }
714 // Registers on the I/O thread to be notified on the I/O thread.
715 CHECK(thread_runner_->BelongsToCurrentThread());
716 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
717
718 // Starts asynchronous initialization on TaskRunner.
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000719 PostTask(base::BindOnce(&MidiManagerWin::InitializeOnTaskRunner,
720 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800721}
722
toyoshim63e32a52017-04-25 07:20:10 -0700723void MidiManagerWin::Finalize() {
toyoshimd28b59c2017-02-20 11:07:37 -0800724 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more.
725 CHECK(thread_runner_->BelongsToCurrentThread());
726 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
727 {
728 base::AutoLock lock(*GetInstanceIdLock());
729 CHECK_EQ(instance_id_, g_active_instance_id);
730 g_active_instance_id = kInvalidInstanceId;
731 CHECK_EQ(this, g_manager_instance);
732 g_manager_instance = nullptr;
733 }
734
735 // Ensures that no task runs on TaskRunner so to destruct the instance safely.
736 // Tasks that did not started yet will do nothing after invalidate the
737 // instance ID above.
toyoshimc32dd892017-02-24 02:13:14 -0800738 // Behind the lock below, we can safely access all members for finalization
739 // even on the I/O thread.
toyoshimd28b59c2017-02-20 11:07:37 -0800740 base::AutoLock lock(*GetTaskLock());
toyoshimc32dd892017-02-24 02:13:14 -0800741
742 // Posts tasks that finalize each device port without MidiManager instance
743 // on TaskRunner. If another MidiManager instance is created, its
744 // initialization runs on the same task runner after all tasks posted here
745 // finish.
toyoshim8a5ad422017-02-28 21:16:18 -0800746 for (const auto& port : *port_manager_->inputs())
toyoshimc32dd892017-02-24 02:13:14 -0800747 port->Finalize(service()->GetTaskRunner(kTaskRunner));
toyoshim8a5ad422017-02-28 21:16:18 -0800748 for (const auto& port : *port_manager_->outputs())
toyoshimc32dd892017-02-24 02:13:14 -0800749 port->Finalize(service()->GetTaskRunner(kTaskRunner));
toyoshimd28b59c2017-02-20 11:07:37 -0800750}
751
toyoshim63e32a52017-04-25 07:20:10 -0700752void MidiManagerWin::DispatchSendMidiData(MidiManagerClient* client,
753 uint32_t port_index,
754 const std::vector<uint8_t>& data,
755 double timestamp) {
Takashi Toyoshimaafb27d52017-09-13 11:50:41 +0000756 PostDelayedTask(
757 base::BindOnce(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
758 client, port_index, data),
759 MidiService::TimestampToTimeDeltaDelay(timestamp));
toyoshimd28b59c2017-02-20 11:07:37 -0800760}
761
toyoshim63e32a52017-04-25 07:20:10 -0700762void MidiManagerWin::OnDevicesChanged(
toyoshimd28b59c2017-02-20 11:07:37 -0800763 base::SystemMonitor::DeviceType device_type) {
764 // Notified on the I/O thread.
765 CHECK(thread_runner_->BelongsToCurrentThread());
766
767 switch (device_type) {
768 case base::SystemMonitor::DEVTYPE_AUDIO:
769 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
770 // Add case of other unrelated device types here.
771 return;
772 case base::SystemMonitor::DEVTYPE_UNKNOWN: {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000773 PostTask(base::BindOnce(&MidiManagerWin::UpdateDeviceListOnTaskRunner,
774 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800775 break;
776 }
777 }
778}
779
toyoshim63e32a52017-04-25 07:20:10 -0700780void MidiManagerWin::ReceiveMidiData(uint32_t index,
781 const std::vector<uint8_t>& data,
782 base::TimeTicks time) {
toyoshim8a5ad422017-02-28 21:16:18 -0800783 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
784}
785
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000786void MidiManagerWin::PostTask(base::OnceClosure task) {
toyoshimd28b59c2017-02-20 11:07:37 -0800787 service()
788 ->GetTaskRunner(kTaskRunner)
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000789 ->PostTask(FROM_HERE,
790 base::BindOnce(&RunTask, instance_id_, std::move(task)));
toyoshimd28b59c2017-02-20 11:07:37 -0800791}
792
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000793void MidiManagerWin::PostDelayedTask(base::OnceClosure task,
toyoshim63e32a52017-04-25 07:20:10 -0700794 base::TimeDelta delay) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800795 service()
796 ->GetTaskRunner(kTaskRunner)
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000797 ->PostDelayedTask(FROM_HERE,
798 base::BindOnce(&RunTask, instance_id_, std::move(task)),
toyoshim6d87aaa2017-02-28 22:36:44 -0800799 delay);
800}
801
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000802void MidiManagerWin::PostReplyTask(base::OnceClosure task) {
803 thread_runner_->PostTask(
804 FROM_HERE, base::BindOnce(&RunTask, instance_id_, std::move(task)));
toyoshim8a5ad422017-02-28 21:16:18 -0800805}
806
toyoshim63e32a52017-04-25 07:20:10 -0700807void MidiManagerWin::InitializeOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800808 UpdateDeviceListOnTaskRunner();
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000809 PostReplyTask(base::BindOnce(&MidiManagerWin::CompleteInitialization,
810 base::Unretained(this), mojom::Result::OK));
toyoshimd28b59c2017-02-20 11:07:37 -0800811}
812
toyoshim63e32a52017-04-25 07:20:10 -0700813void MidiManagerWin::UpdateDeviceListOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800814 std::vector<std::unique_ptr<InPort>> active_input_ports =
toyoshim8a5ad422017-02-28 21:16:18 -0800815 InPort::EnumerateActivePorts(this, instance_id_);
816 ReflectActiveDeviceList(this, port_manager_->inputs(), &active_input_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800817
818 std::vector<std::unique_ptr<OutPort>> active_output_ports =
819 OutPort::EnumerateActivePorts();
toyoshim8a5ad422017-02-28 21:16:18 -0800820 ReflectActiveDeviceList(this, port_manager_->outputs(), &active_output_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800821
822 // TODO(toyoshim): This method may run before internal MIDI device lists that
823 // Windows manages were updated. This may be because MIDI driver may be loaded
824 // after the raw device list was updated. To avoid this problem, we may want
825 // to retry device check later if no changes are detected here.
826}
827
828template <typename T>
toyoshim63e32a52017-04-25 07:20:10 -0700829void MidiManagerWin::ReflectActiveDeviceList(MidiManagerWin* manager,
830 std::vector<T>* known_ports,
831 std::vector<T>* active_ports) {
toyoshimd28b59c2017-02-20 11:07:37 -0800832 // Update existing port states.
833 for (const auto& port : *known_ports) {
834 const auto& it = std::find_if(
835 active_ports->begin(), active_ports->end(),
836 [&port](const auto& candidate) { return *candidate == *port; });
837 if (it == active_ports->end()) {
838 if (port->Disconnect())
839 port->NotifyPortStateSet(this);
840 } else {
841 port->set_device_id((*it)->device_id());
842 if (port->Connect())
843 port->NotifyPortStateSet(this);
844 }
845 }
846
847 // Find new ports from active ports and append them to known ports.
848 for (auto& port : *active_ports) {
849 if (std::find_if(known_ports->begin(), known_ports->end(),
850 [&port](const auto& candidate) {
851 return *candidate == *port;
852 }) == known_ports->end()) {
853 size_t index = known_ports->size();
854 port->set_index(index);
855 known_ports->push_back(std::move(port));
856 (*known_ports)[index]->Connect();
857 (*known_ports)[index]->NotifyPortAdded(this);
858 }
859 }
860}
861
toyoshim63e32a52017-04-25 07:20:10 -0700862void MidiManagerWin::SendOnTaskRunner(MidiManagerClient* client,
863 uint32_t port_index,
864 const std::vector<uint8_t>& data) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800865 CHECK_GT(port_manager_->outputs()->size(), port_index);
866 (*port_manager_->outputs())[port_index]->Send(data);
867 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000868 PostReplyTask(base::BindOnce(&MidiManagerWin::AccumulateMidiBytesSent,
869 base::Unretained(this), client, data.size()));
toyoshim6d87aaa2017-02-28 22:36:44 -0800870}
871
toyoshim15385b32017-04-24 23:52:01 -0700872MidiManager* MidiManager::Create(MidiService* service) {
873 if (base::FeatureList::IsEnabled(features::kMidiManagerWinrt) &&
toyoshim63e32a52017-04-25 07:20:10 -0700874 base::win::GetVersion() >= base::win::VERSION_WIN10) {
toyoshim15385b32017-04-24 23:52:01 -0700875 return new MidiManagerWinrt(service);
toyoshim63e32a52017-04-25 07:20:10 -0700876 }
877 return new MidiManagerWin(service);
toyoshim15385b32017-04-24 23:52:01 -0700878}
879
toyoshimd28b59c2017-02-20 11:07:37 -0800880} // namespace midi