blob: c14d6383792ef6c45334b340f65e8a6afb48993f [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
toyoshim8a5ad422017-02-28 21:16:18 -0800151// Utility class to handle MIDIHDR struct safely.
152class MIDIHDRDeleter {
153 public:
154 void operator()(LPMIDIHDR header) {
155 if (!header)
156 return;
157 delete[] static_cast<char*>(header->lpData);
158 delete header;
159 }
160};
161
162using ScopedMIDIHDR = std::unique_ptr<MIDIHDR, MIDIHDRDeleter>;
163
164ScopedMIDIHDR CreateMIDIHDR(size_t size) {
165 ScopedMIDIHDR hdr(new MIDIHDR);
166 ZeroMemory(hdr.get(), sizeof(*hdr));
167 hdr->lpData = new char[size];
168 hdr->dwBufferLength = static_cast<DWORD>(size);
169 return hdr;
170}
171
toyoshim6d87aaa2017-02-28 22:36:44 -0800172ScopedMIDIHDR CreateMIDIHDR(const std::vector<uint8_t>& data) {
173 ScopedMIDIHDR hdr(CreateMIDIHDR(data.size()));
174 std::copy(data.begin(), data.end(), hdr->lpData);
175 return hdr;
176}
177
toyoshimc32dd892017-02-24 02:13:14 -0800178// Helper functions to close MIDI device handles on TaskRunner asynchronously.
toyoshim8a5ad422017-02-28 21:16:18 -0800179void FinalizeInPort(HMIDIIN handle, ScopedMIDIHDR hdr) {
180 // Resets the device. This stops receiving messages, and allows to release
181 // registered buffer headers. Otherwise, midiInUnprepareHeader() and
182 // midiInClose() will fail with MIDIERR_STILLPLAYING.
183 midiInReset(handle);
184
185 if (hdr)
186 midiInUnprepareHeader(handle, hdr.get(), sizeof(*hdr));
toyoshimc32dd892017-02-24 02:13:14 -0800187 midiInClose(handle);
188}
189
190void FinalizeOutPort(HMIDIOUT handle) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800191 // Resets inflight buffers. This will cancel sending data that system
192 // holds and were not sent yet.
193 midiOutReset(handle);
toyoshimc32dd892017-02-24 02:13:14 -0800194 midiOutClose(handle);
195}
196
toyoshim6ebf1182017-03-01 00:40:31 -0800197// Gets manufacturer name in string from identifiers.
198std::string GetManufacturerName(uint16_t id, const GUID& guid) {
199 if (IS_COMPATIBLE_USBAUDIO_MID(&guid)) {
200 const char* name =
201 device::UsbIds::GetVendorName(EXTRACT_USBAUDIO_MID(&guid));
202 if (name)
203 return std::string(name);
204 }
205 if (id == MM_MICROSOFT)
206 return "Microsoft Corporation";
207
208 // TODO(crbug.com/472341): Support other manufacture IDs.
209 return "";
210}
211
toyoshimc32dd892017-02-24 02:13:14 -0800212// All instances of Port subclasses are always accessed behind a lock of
213// *GetTaskLock(). Port and subclasses implementation do not need to
214// consider thread safety.
toyoshimd28b59c2017-02-20 11:07:37 -0800215class Port {
216 public:
217 Port(const std::string& type,
218 uint32_t device_id,
219 uint16_t manufacturer_id,
220 uint16_t product_id,
221 uint32_t driver_version,
toyoshim6ebf1182017-03-01 00:40:31 -0800222 const std::string& product_name,
223 const GUID& manufacturer_guid)
toyoshimd28b59c2017-02-20 11:07:37 -0800224 : index_(0u),
225 type_(type),
226 device_id_(device_id),
227 manufacturer_id_(manufacturer_id),
228 product_id_(product_id),
229 driver_version_(driver_version),
230 product_name_(product_name) {
toyoshim6ebf1182017-03-01 00:40:31 -0800231 info_.manufacturer =
232 GetManufacturerName(manufacturer_id, manufacturer_guid);
toyoshimd28b59c2017-02-20 11:07:37 -0800233 info_.name = product_name_;
234 info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_),
235 LOBYTE(driver_version_));
236 info_.state = mojom::PortState::DISCONNECTED;
237 }
238
239 virtual ~Port() {}
240
241 bool operator==(const Port& other) const {
242 // Should not use |device_id| for comparison because it can be changed on
243 // each enumeration.
244 // Since the GUID will be changed on each enumeration for Microsoft GS
245 // Wavetable synth and might be done for others, do not use it for device
246 // comparison.
247 return manufacturer_id_ == other.manufacturer_id_ &&
248 product_id_ == other.product_id_ &&
249 driver_version_ == other.driver_version_ &&
250 product_name_ == other.product_name_;
251 }
252
253 bool IsConnected() const {
254 return info_.state != mojom::PortState::DISCONNECTED;
255 }
256
257 void set_index(size_t index) {
258 index_ = index;
259 // TODO(toyoshim): Use hashed ID.
260 info_.id = base::StringPrintf("%s-%d", type_.c_str(), index_);
261 }
262 size_t index() { return index_; }
263 void set_device_id(uint32_t device_id) { device_id_ = device_id; }
264 uint32_t device_id() { return device_id_; }
265 const MidiPortInfo& info() { return info_; }
266
267 virtual bool Connect() {
268 if (info_.state != mojom::PortState::DISCONNECTED)
269 return false;
270
271 info_.state = mojom::PortState::CONNECTED;
272 // TODO(toyoshim) Until open() / close() are supported, open each device on
273 // connected.
274 Open();
275 return true;
276 }
277
278 virtual bool Disconnect() {
279 if (info_.state == mojom::PortState::DISCONNECTED)
280 return false;
281 info_.state = mojom::PortState::DISCONNECTED;
282 return true;
283 }
284
285 virtual void Open() { info_.state = mojom::PortState::OPENED; }
286
287 protected:
288 size_t index_;
289 std::string type_;
290 uint32_t device_id_;
291 const uint16_t manufacturer_id_;
292 const uint16_t product_id_;
293 const uint32_t driver_version_;
294 const std::string product_name_;
295 MidiPortInfo info_;
296}; // class Port
297
298} // namespace
299
toyoshim63e32a52017-04-25 07:20:10 -0700300class MidiManagerWin::InPort final : public Port {
toyoshimd28b59c2017-02-20 11:07:37 -0800301 public:
toyoshim63e32a52017-04-25 07:20:10 -0700302 InPort(MidiManagerWin* manager,
toyoshim8a5ad422017-02-28 21:16:18 -0800303 int instance_id,
304 UINT device_id,
305 const MIDIINCAPS2W& caps)
toyoshimd28b59c2017-02-20 11:07:37 -0800306 : Port("input",
307 device_id,
308 caps.wMid,
309 caps.wPid,
310 caps.vDriverVersion,
311 base::WideToUTF8(
toyoshim6ebf1182017-03-01 00:40:31 -0800312 base::string16(caps.szPname, wcslen(caps.szPname))),
313 caps.ManufacturerGuid),
toyoshim8a5ad422017-02-28 21:16:18 -0800314 manager_(manager),
315 in_handle_(kInvalidInHandle),
316 instance_id_(instance_id) {}
toyoshimd28b59c2017-02-20 11:07:37 -0800317
toyoshim8a5ad422017-02-28 21:16:18 -0800318 static std::vector<std::unique_ptr<InPort>> EnumerateActivePorts(
toyoshim63e32a52017-04-25 07:20:10 -0700319 MidiManagerWin* manager,
toyoshim8a5ad422017-02-28 21:16:18 -0800320 int instance_id) {
toyoshimd28b59c2017-02-20 11:07:37 -0800321 std::vector<std::unique_ptr<InPort>> ports;
322 const UINT num_devices = midiInGetNumDevs();
323 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
324 MIDIINCAPS2W caps;
325 MMRESULT result = midiInGetDevCaps(
326 device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps));
327 if (result != MMSYSERR_NOERROR) {
328 LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id;
329 continue;
330 }
toyoshim8a5ad422017-02-28 21:16:18 -0800331 ports.push_back(
332 base::MakeUnique<InPort>(manager, instance_id, device_id, caps));
toyoshimd28b59c2017-02-20 11:07:37 -0800333 }
334 return ports;
335 }
336
toyoshimc32dd892017-02-24 02:13:14 -0800337 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
338 if (in_handle_ != kInvalidInHandle) {
toyoshim63e32a52017-04-25 07:20:10 -0700339 runner->PostTask(FROM_HERE, base::Bind(&FinalizeInPort, in_handle_,
340 base::Passed(&hdr_)));
toyoshim8a5ad422017-02-28 21:16:18 -0800341 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshimc32dd892017-02-24 02:13:14 -0800342 in_handle_ = kInvalidInHandle;
343 }
344 }
345
toyoshim8a5ad422017-02-28 21:16:18 -0800346 base::TimeTicks CalculateInEventTime(uint32_t elapsed_ms) const {
347 return start_time_ + base::TimeDelta::FromMilliseconds(elapsed_ms);
348 }
349
350 void RestoreBuffer() {
351 if (in_handle_ == kInvalidInHandle || !hdr_)
352 return;
353 midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
354 }
355
toyoshim63e32a52017-04-25 07:20:10 -0700356 void NotifyPortStateSet(MidiManagerWin* manager) {
357 manager->PostReplyTask(base::Bind(&MidiManagerWin::SetInputPortState,
358 base::Unretained(manager), index_,
359 info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800360 }
361
toyoshim63e32a52017-04-25 07:20:10 -0700362 void NotifyPortAdded(MidiManagerWin* manager) {
363 manager->PostReplyTask(base::Bind(&MidiManagerWin::AddInputPort,
364 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800365 }
toyoshimc32dd892017-02-24 02:13:14 -0800366
367 // Port overrides:
368 bool Disconnect() override {
369 if (in_handle_ != kInvalidInHandle) {
370 // Following API call may fail because device was already disconnected.
371 // But just in case.
372 midiInClose(in_handle_);
toyoshim8a5ad422017-02-28 21:16:18 -0800373 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshimc32dd892017-02-24 02:13:14 -0800374 in_handle_ = kInvalidInHandle;
375 }
376 return Port::Disconnect();
377 }
378
379 void Open() override {
toyoshim8a5ad422017-02-28 21:16:18 -0800380 MMRESULT result = midiInOpen(
381 &in_handle_, device_id_,
382 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiInCallback),
383 instance_id_, CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800384 if (result == MMSYSERR_NOERROR) {
toyoshim8a5ad422017-02-28 21:16:18 -0800385 hdr_ = CreateMIDIHDR(kBufferLength);
386 result = midiInPrepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
387 }
388 if (result != MMSYSERR_NOERROR)
389 in_handle_ = kInvalidInHandle;
390 if (result == MMSYSERR_NOERROR)
391 result = midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
392 if (result == MMSYSERR_NOERROR)
393 result = midiInStart(in_handle_);
394 if (result == MMSYSERR_NOERROR) {
395 start_time_ = base::TimeTicks::Now();
396 manager_->port_manager()->RegisterInHandle(in_handle_, index_);
toyoshimc32dd892017-02-24 02:13:14 -0800397 Port::Open();
398 } else {
toyoshim8a5ad422017-02-28 21:16:18 -0800399 if (in_handle_ != kInvalidInHandle) {
400 midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
401 hdr_.reset();
402 midiInClose(in_handle_);
403 in_handle_ = kInvalidInHandle;
404 }
toyoshimc32dd892017-02-24 02:13:14 -0800405 Disconnect();
406 }
407 }
408
409 private:
toyoshim63e32a52017-04-25 07:20:10 -0700410 MidiManagerWin* manager_;
toyoshimc32dd892017-02-24 02:13:14 -0800411 HMIDIIN in_handle_;
toyoshim8a5ad422017-02-28 21:16:18 -0800412 ScopedMIDIHDR hdr_;
413 base::TimeTicks start_time_;
414 const int instance_id_;
toyoshimd28b59c2017-02-20 11:07:37 -0800415};
416
toyoshim63e32a52017-04-25 07:20:10 -0700417class MidiManagerWin::OutPort final : public Port {
toyoshimd28b59c2017-02-20 11:07:37 -0800418 public:
419 OutPort(UINT device_id, const MIDIOUTCAPS2W& caps)
420 : Port("output",
421 device_id,
422 caps.wMid,
423 caps.wPid,
424 caps.vDriverVersion,
425 base::WideToUTF8(
toyoshim6ebf1182017-03-01 00:40:31 -0800426 base::string16(caps.szPname, wcslen(caps.szPname))),
427 caps.ManufacturerGuid),
toyoshimc32dd892017-02-24 02:13:14 -0800428 software_(caps.wTechnology == MOD_SWSYNTH),
429 out_handle_(kInvalidOutHandle) {}
toyoshimd28b59c2017-02-20 11:07:37 -0800430
431 static std::vector<std::unique_ptr<OutPort>> EnumerateActivePorts() {
432 std::vector<std::unique_ptr<OutPort>> ports;
433 const UINT num_devices = midiOutGetNumDevs();
434 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
435 MIDIOUTCAPS2W caps;
436 MMRESULT result = midiOutGetDevCaps(
437 device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps));
438 if (result != MMSYSERR_NOERROR) {
439 LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id;
440 continue;
441 }
442 ports.push_back(base::MakeUnique<OutPort>(device_id, caps));
443 }
444 return ports;
445 }
446
toyoshimc32dd892017-02-24 02:13:14 -0800447 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
448 if (out_handle_ != kInvalidOutHandle) {
449 runner->PostTask(FROM_HERE, base::Bind(&FinalizeOutPort, out_handle_));
450 out_handle_ = kInvalidOutHandle;
toyoshimd28b59c2017-02-20 11:07:37 -0800451 }
toyoshimd28b59c2017-02-20 11:07:37 -0800452 }
453
toyoshim63e32a52017-04-25 07:20:10 -0700454 void NotifyPortStateSet(MidiManagerWin* manager) {
455 manager->PostReplyTask(base::Bind(&MidiManagerWin::SetOutputPortState,
456 base::Unretained(manager), index_,
457 info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800458 }
459
toyoshim63e32a52017-04-25 07:20:10 -0700460 void NotifyPortAdded(MidiManagerWin* manager) {
461 manager->PostReplyTask(base::Bind(&MidiManagerWin::AddOutputPort,
462 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800463 }
464
toyoshim6d87aaa2017-02-28 22:36:44 -0800465 void Send(const std::vector<uint8_t>& data) {
466 if (out_handle_ == kInvalidOutHandle)
467 return;
468
469 if (data.size() <= 3) {
470 uint32_t message = 0;
471 for (size_t i = 0; i < data.size(); ++i)
472 message |= (static_cast<uint32_t>(data[i]) << (i * 8));
473 midiOutShortMsg(out_handle_, message);
474 } else {
475 if (data.size() > kSysExSizeLimit) {
476 LOG(ERROR) << "Ignoring SysEx message due to the size limit"
477 << ", size = " << data.size();
478 // TODO(toyoshim): Consider to report metrics here.
479 return;
480 }
481 ScopedMIDIHDR hdr(CreateMIDIHDR(data));
482 MMRESULT result =
483 midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
484 if (result != MMSYSERR_NOERROR)
485 return;
486 result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr));
487 if (result != MMSYSERR_NOERROR) {
488 midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
489 } else {
490 // MIDIHDR will be released on MOM_DONE.
491 ignore_result(hdr.release());
492 }
493 }
494 }
495
toyoshimc32dd892017-02-24 02:13:14 -0800496 // Port overrides:
497 bool Connect() override {
498 // Until |software| option is supported, disable Microsoft GS Wavetable
499 // Synth that has a known security issue.
500 if (software_ && manufacturer_id_ == MM_MICROSOFT &&
501 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT ||
502 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) {
503 return false;
504 }
505 return Port::Connect();
506 }
507
508 bool Disconnect() override {
509 if (out_handle_ != kInvalidOutHandle) {
510 // Following API call may fail because device was already disconnected.
511 // But just in case.
512 midiOutClose(out_handle_);
513 out_handle_ = kInvalidOutHandle;
514 }
515 return Port::Disconnect();
516 }
517
518 void Open() override {
toyoshim6d87aaa2017-02-28 22:36:44 -0800519 MMRESULT result = midiOutOpen(
520 &out_handle_, device_id_,
521 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiOutCallback), 0,
522 CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800523 if (result == MMSYSERR_NOERROR) {
524 Port::Open();
525 } else {
526 out_handle_ = kInvalidOutHandle;
527 Disconnect();
528 }
529 }
530
toyoshimd28b59c2017-02-20 11:07:37 -0800531 const bool software_;
toyoshimc32dd892017-02-24 02:13:14 -0800532 HMIDIOUT out_handle_;
toyoshimd28b59c2017-02-20 11:07:37 -0800533};
534
toyoshim63e32a52017-04-25 07:20:10 -0700535base::TimeTicks MidiManagerWin::PortManager::CalculateInEventTime(
toyoshim8a5ad422017-02-28 21:16:18 -0800536 size_t index,
537 uint32_t elapsed_ms) const {
538 GetTaskLock()->AssertAcquired();
539 CHECK_GT(input_ports_.size(), index);
540 return input_ports_[index]->CalculateInEventTime(elapsed_ms);
541}
542
toyoshim63e32a52017-04-25 07:20:10 -0700543void MidiManagerWin::PortManager::RegisterInHandle(HMIDIIN handle,
544 size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800545 GetTaskLock()->AssertAcquired();
546 hmidiin_to_index_map_[handle] = index;
547}
548
toyoshim63e32a52017-04-25 07:20:10 -0700549void MidiManagerWin::PortManager::UnregisterInHandle(HMIDIIN handle) {
toyoshim8a5ad422017-02-28 21:16:18 -0800550 GetTaskLock()->AssertAcquired();
551 hmidiin_to_index_map_.erase(handle);
552}
553
toyoshim63e32a52017-04-25 07:20:10 -0700554bool MidiManagerWin::PortManager::FindInHandle(HMIDIIN hmi, size_t* out_index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800555 GetTaskLock()->AssertAcquired();
556 auto found = hmidiin_to_index_map_.find(hmi);
557 if (found == hmidiin_to_index_map_.end())
558 return false;
559 *out_index = found->second;
560 return true;
561}
562
toyoshim63e32a52017-04-25 07:20:10 -0700563void MidiManagerWin::PortManager::RestoreInBuffer(size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800564 GetTaskLock()->AssertAcquired();
565 CHECK_GT(input_ports_.size(), index);
566 input_ports_[index]->RestoreBuffer();
567}
568
569void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700570MidiManagerWin::PortManager::HandleMidiInCallback(HMIDIIN hmi,
571 UINT msg,
572 DWORD_PTR instance,
573 DWORD_PTR param1,
574 DWORD_PTR param2) {
toyoshim8a5ad422017-02-28 21:16:18 -0800575 if (msg != MIM_DATA && msg != MIM_LONGDATA)
576 return;
577 int instance_id = static_cast<int>(instance);
toyoshim63e32a52017-04-25 07:20:10 -0700578 MidiManagerWin* manager = nullptr;
toyoshim8a5ad422017-02-28 21:16:18 -0800579
580 // Use |g_task_lock| so to ensure the instance can keep alive while running,
581 // and to access member variables that are used on TaskRunner.
582 base::AutoLock task_lock(*GetTaskLock());
583 {
584 base::AutoLock lock(*GetInstanceIdLock());
585 if (instance_id != g_active_instance_id)
586 return;
587 manager = g_manager_instance;
588 }
589
590 size_t index;
toyoshim6d87aaa2017-02-28 22:36:44 -0800591 if (!manager->port_manager()->FindInHandle(hmi, &index))
toyoshim8a5ad422017-02-28 21:16:18 -0800592 return;
593
594 DCHECK(msg == MIM_DATA || msg == MIM_LONGDATA);
595 if (msg == MIM_DATA) {
596 const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff);
597 const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff);
598 const uint8_t second_data_byte =
599 static_cast<uint8_t>((param1 >> 16) & 0xff);
600 const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte};
601 const size_t len = GetMessageLength(status_byte);
602 DCHECK_LE(len, arraysize(kData));
603 std::vector<uint8_t> data;
604 data.assign(kData, kData + len);
605 manager->PostReplyTask(base::Bind(
toyoshim63e32a52017-04-25 07:20:10 -0700606 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager), index,
607 data, manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800608 } else {
609 DCHECK_EQ(static_cast<UINT>(MIM_LONGDATA), msg);
610 LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1);
611 if (hdr->dwBytesRecorded > 0) {
612 const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData);
613 std::vector<uint8_t> data;
614 data.assign(src, src + hdr->dwBytesRecorded);
615 manager->PostReplyTask(base::Bind(
toyoshim63e32a52017-04-25 07:20:10 -0700616 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager), index,
617 data, manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800618 }
toyoshim63e32a52017-04-25 07:20:10 -0700619 manager->PostTask(base::Bind(&MidiManagerWin::PortManager::RestoreInBuffer,
620 base::Unretained(manager->port_manager()),
621 index));
toyoshim8a5ad422017-02-28 21:16:18 -0800622 }
623}
624
toyoshim6d87aaa2017-02-28 22:36:44 -0800625void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700626MidiManagerWin::PortManager::HandleMidiOutCallback(HMIDIOUT hmo,
627 UINT msg,
628 DWORD_PTR instance,
629 DWORD_PTR param1,
630 DWORD_PTR param2) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800631 if (msg == MOM_DONE) {
632 ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1));
633 if (!hdr)
634 return;
635 // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback.
636 // Since this callback may be invoked after the manager is destructed,
637 // and can not send a task to the TaskRunner in such case, we need to
638 // consider to track MIDIHDR per port, and clean it in port finalization
639 // steps, too.
640 midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr));
641 }
642}
643
toyoshim63e32a52017-04-25 07:20:10 -0700644MidiManagerWin::MidiManagerWin(MidiService* service)
toyoshim8a5ad422017-02-28 21:16:18 -0800645 : MidiManager(service),
646 instance_id_(IssueNextInstanceId()),
647 port_manager_(base::MakeUnique<PortManager>()) {
toyoshimd28b59c2017-02-20 11:07:37 -0800648 base::AutoLock lock(*GetInstanceIdLock());
649 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
650
651 // Obtains the task runner for the current thread that hosts this instnace.
652 thread_runner_ = base::ThreadTaskRunnerHandle::Get();
653}
654
toyoshim63e32a52017-04-25 07:20:10 -0700655MidiManagerWin::~MidiManagerWin() {
toyoshimd28b59c2017-02-20 11:07:37 -0800656 base::AutoLock lock(*GetInstanceIdLock());
657 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
658 CHECK(thread_runner_->BelongsToCurrentThread());
659}
660
toyoshim63e32a52017-04-25 07:20:10 -0700661void MidiManagerWin::StartInitialization() {
toyoshimd28b59c2017-02-20 11:07:37 -0800662 {
663 base::AutoLock lock(*GetInstanceIdLock());
664 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
665 g_active_instance_id = instance_id_;
666 CHECK_EQ(nullptr, g_manager_instance);
667 g_manager_instance = this;
668 }
669 // Registers on the I/O thread to be notified on the I/O thread.
670 CHECK(thread_runner_->BelongsToCurrentThread());
671 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
672
673 // Starts asynchronous initialization on TaskRunner.
toyoshim63e32a52017-04-25 07:20:10 -0700674 PostTask(base::Bind(&MidiManagerWin::InitializeOnTaskRunner,
675 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800676}
677
toyoshim63e32a52017-04-25 07:20:10 -0700678void MidiManagerWin::Finalize() {
toyoshimd28b59c2017-02-20 11:07:37 -0800679 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more.
680 CHECK(thread_runner_->BelongsToCurrentThread());
681 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
682 {
683 base::AutoLock lock(*GetInstanceIdLock());
684 CHECK_EQ(instance_id_, g_active_instance_id);
685 g_active_instance_id = kInvalidInstanceId;
686 CHECK_EQ(this, g_manager_instance);
687 g_manager_instance = nullptr;
688 }
689
690 // Ensures that no task runs on TaskRunner so to destruct the instance safely.
691 // Tasks that did not started yet will do nothing after invalidate the
692 // instance ID above.
toyoshimc32dd892017-02-24 02:13:14 -0800693 // Behind the lock below, we can safely access all members for finalization
694 // even on the I/O thread.
toyoshimd28b59c2017-02-20 11:07:37 -0800695 base::AutoLock lock(*GetTaskLock());
toyoshimc32dd892017-02-24 02:13:14 -0800696
697 // Posts tasks that finalize each device port without MidiManager instance
698 // on TaskRunner. If another MidiManager instance is created, its
699 // initialization runs on the same task runner after all tasks posted here
700 // finish.
toyoshim8a5ad422017-02-28 21:16:18 -0800701 for (const auto& port : *port_manager_->inputs())
toyoshimc32dd892017-02-24 02:13:14 -0800702 port->Finalize(service()->GetTaskRunner(kTaskRunner));
toyoshim8a5ad422017-02-28 21:16:18 -0800703 for (const auto& port : *port_manager_->outputs())
toyoshimc32dd892017-02-24 02:13:14 -0800704 port->Finalize(service()->GetTaskRunner(kTaskRunner));
toyoshimd28b59c2017-02-20 11:07:37 -0800705}
706
toyoshim63e32a52017-04-25 07:20:10 -0700707void MidiManagerWin::DispatchSendMidiData(MidiManagerClient* client,
708 uint32_t port_index,
709 const std::vector<uint8_t>& data,
710 double timestamp) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800711 if (timestamp != 0.0) {
toyoshim63e32a52017-04-25 07:20:10 -0700712 base::TimeTicks time =
713 base::TimeTicks() + base::TimeDelta::FromMicroseconds(
714 timestamp * base::Time::kMicrosecondsPerSecond);
toyoshim6d87aaa2017-02-28 22:36:44 -0800715 base::TimeTicks now = base::TimeTicks::Now();
716 if (now < time) {
717 PostDelayedTask(
toyoshim63e32a52017-04-25 07:20:10 -0700718 base::Bind(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
719 client, port_index, data),
toyoshim6d87aaa2017-02-28 22:36:44 -0800720 time - now);
721 return;
722 }
723 }
toyoshim63e32a52017-04-25 07:20:10 -0700724 PostTask(base::Bind(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
725 client, port_index, data));
toyoshimd28b59c2017-02-20 11:07:37 -0800726}
727
toyoshim63e32a52017-04-25 07:20:10 -0700728void MidiManagerWin::OnDevicesChanged(
toyoshimd28b59c2017-02-20 11:07:37 -0800729 base::SystemMonitor::DeviceType device_type) {
730 // Notified on the I/O thread.
731 CHECK(thread_runner_->BelongsToCurrentThread());
732
733 switch (device_type) {
734 case base::SystemMonitor::DEVTYPE_AUDIO:
735 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
736 // Add case of other unrelated device types here.
737 return;
738 case base::SystemMonitor::DEVTYPE_UNKNOWN: {
toyoshim63e32a52017-04-25 07:20:10 -0700739 PostTask(base::Bind(&MidiManagerWin::UpdateDeviceListOnTaskRunner,
740 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800741 break;
742 }
743 }
744}
745
toyoshim63e32a52017-04-25 07:20:10 -0700746void MidiManagerWin::ReceiveMidiData(uint32_t index,
747 const std::vector<uint8_t>& data,
748 base::TimeTicks time) {
toyoshim8a5ad422017-02-28 21:16:18 -0800749 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
750}
751
toyoshim63e32a52017-04-25 07:20:10 -0700752void MidiManagerWin::PostTask(const base::Closure& task) {
toyoshimd28b59c2017-02-20 11:07:37 -0800753 service()
754 ->GetTaskRunner(kTaskRunner)
755 ->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
756}
757
toyoshim63e32a52017-04-25 07:20:10 -0700758void MidiManagerWin::PostDelayedTask(const base::Closure& task,
759 base::TimeDelta delay) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800760 service()
761 ->GetTaskRunner(kTaskRunner)
762 ->PostDelayedTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task),
763 delay);
764}
765
toyoshim63e32a52017-04-25 07:20:10 -0700766void MidiManagerWin::PostReplyTask(const base::Closure& task) {
toyoshim8a5ad422017-02-28 21:16:18 -0800767 thread_runner_->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
768}
769
toyoshim63e32a52017-04-25 07:20:10 -0700770void MidiManagerWin::InitializeOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800771 UpdateDeviceListOnTaskRunner();
toyoshim63e32a52017-04-25 07:20:10 -0700772 PostReplyTask(base::Bind(&MidiManagerWin::CompleteInitialization,
773 base::Unretained(this), mojom::Result::OK));
toyoshimd28b59c2017-02-20 11:07:37 -0800774}
775
toyoshim63e32a52017-04-25 07:20:10 -0700776void MidiManagerWin::UpdateDeviceListOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800777 std::vector<std::unique_ptr<InPort>> active_input_ports =
toyoshim8a5ad422017-02-28 21:16:18 -0800778 InPort::EnumerateActivePorts(this, instance_id_);
779 ReflectActiveDeviceList(this, port_manager_->inputs(), &active_input_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800780
781 std::vector<std::unique_ptr<OutPort>> active_output_ports =
782 OutPort::EnumerateActivePorts();
toyoshim8a5ad422017-02-28 21:16:18 -0800783 ReflectActiveDeviceList(this, port_manager_->outputs(), &active_output_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800784
785 // TODO(toyoshim): This method may run before internal MIDI device lists that
786 // Windows manages were updated. This may be because MIDI driver may be loaded
787 // after the raw device list was updated. To avoid this problem, we may want
788 // to retry device check later if no changes are detected here.
789}
790
791template <typename T>
toyoshim63e32a52017-04-25 07:20:10 -0700792void MidiManagerWin::ReflectActiveDeviceList(MidiManagerWin* manager,
793 std::vector<T>* known_ports,
794 std::vector<T>* active_ports) {
toyoshimd28b59c2017-02-20 11:07:37 -0800795 // Update existing port states.
796 for (const auto& port : *known_ports) {
797 const auto& it = std::find_if(
798 active_ports->begin(), active_ports->end(),
799 [&port](const auto& candidate) { return *candidate == *port; });
800 if (it == active_ports->end()) {
801 if (port->Disconnect())
802 port->NotifyPortStateSet(this);
803 } else {
804 port->set_device_id((*it)->device_id());
805 if (port->Connect())
806 port->NotifyPortStateSet(this);
807 }
808 }
809
810 // Find new ports from active ports and append them to known ports.
811 for (auto& port : *active_ports) {
812 if (std::find_if(known_ports->begin(), known_ports->end(),
813 [&port](const auto& candidate) {
814 return *candidate == *port;
815 }) == known_ports->end()) {
816 size_t index = known_ports->size();
817 port->set_index(index);
818 known_ports->push_back(std::move(port));
819 (*known_ports)[index]->Connect();
820 (*known_ports)[index]->NotifyPortAdded(this);
821 }
822 }
823}
824
toyoshim63e32a52017-04-25 07:20:10 -0700825void MidiManagerWin::SendOnTaskRunner(MidiManagerClient* client,
826 uint32_t port_index,
827 const std::vector<uint8_t>& data) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800828 CHECK_GT(port_manager_->outputs()->size(), port_index);
829 (*port_manager_->outputs())[port_index]->Send(data);
830 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
toyoshim63e32a52017-04-25 07:20:10 -0700831 PostReplyTask(base::Bind(&MidiManagerWin::AccumulateMidiBytesSent,
832 base::Unretained(this), client, data.size()));
toyoshim6d87aaa2017-02-28 22:36:44 -0800833}
834
toyoshim15385b32017-04-24 23:52:01 -0700835MidiManager* MidiManager::Create(MidiService* service) {
836 if (base::FeatureList::IsEnabled(features::kMidiManagerWinrt) &&
toyoshim63e32a52017-04-25 07:20:10 -0700837 base::win::GetVersion() >= base::win::VERSION_WIN10) {
toyoshim15385b32017-04-24 23:52:01 -0700838 return new MidiManagerWinrt(service);
toyoshim63e32a52017-04-25 07:20:10 -0700839 }
840 return new MidiManagerWin(service);
toyoshim15385b32017-04-24 23:52:01 -0700841}
842
toyoshimd28b59c2017-02-20 11:07:37 -0800843} // namespace midi