[go: nahoru, domu]

blob: 902399f011b71b442759a4ed8dcd11107712edfd [file] [log] [blame]
toyoshimbe814a02017-02-20 19:07:371// 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
toyoshim60350512017-04-25 14:20:105#include "media/midi/midi_manager_win.h"
toyoshimbe814a02017-02-20 19:07:376
7#include <windows.h>
8
toyoshimd4acd5042017-03-01 08:40:319#include <ks.h>
10#include <ksmedia.h>
toyoshimbe814a02017-02-20 19:07:3711#include <mmreg.h>
12#include <mmsystem.h>
13
14#include <algorithm>
15#include <string>
16
toyoshim6d4bb282017-03-01 05:16:1817#include "base/bind_helpers.h"
toyoshimbe814a02017-02-20 19:07:3718#include "base/callback.h"
19#include "base/logging.h"
Gabriel Charette5ff87ce2017-05-16 18:03:4520#include "base/single_thread_task_runner.h"
Avi Drissmanfa9bed42018-12-25 20:26:3921#include "base/stl_util.h"
toyoshimbe814a02017-02-20 19:07:3722#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"
toyoshim43994142017-04-25 06:52:0126#include "base/win/windows_version.h"
toyoshimd4acd5042017-03-01 08:40:3127#include "device/usb/usb_ids.h"
toyoshim6d4bb282017-03-01 05:16:1828#include "media/midi/message_util.h"
toyoshim43994142017-04-25 06:52:0129#include "media/midi/midi_manager_winrt.h"
toyoshimbe814a02017-02-20 19:07:3730#include "media/midi/midi_service.h"
Adithya Srinivasanbebaf722018-10-17 15:59:4031#include "media/midi/midi_service.mojom.h"
toyoshim43994142017-04-25 06:52:0132#include "media/midi/midi_switches.h"
toyoshimbe814a02017-02-20 19:07:3733
34namespace midi {
35
toyoshim6d4bb282017-03-01 05:16:1836// Forward declaration of PortManager for anonymous functions and internal
37// classes to use it.
toyoshim60350512017-04-25 14:20:1038class MidiManagerWin::PortManager {
toyoshim6d4bb282017-03-01 05:16:1839 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.
toyoshimeaeaade2017-03-01 06:36:4450 bool FindInHandle(HMIDIIN hmi, size_t* out_index);
toyoshim6d4bb282017-03-01 05:16:1851
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
toyoshimeaeaade2017-03-01 06:36:4466 // 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
toyoshim6d4bb282017-03-01 05:16:1873 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
toyoshimbe814a02017-02-20 19:07:3782namespace {
83
toyoshime2624212017-02-24 10:13:1484// Assumes that nullptr represents an invalid MIDI handle.
85constexpr HMIDIIN kInvalidInHandle = nullptr;
86constexpr HMIDIOUT kInvalidOutHandle = nullptr;
87
toyoshimeaeaade2017-03-01 06:36:4488// 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
toyoshim6d4bb282017-03-01 05:16:18102// Defines input buffer size.
103constexpr size_t kBufferLength = 32 * 1024;
104
toyoshimbe814a02017-02-20 19:07:37105// Global variables to identify MidiManager instance.
106constexpr int kInvalidInstanceId = -1;
107int g_active_instance_id = kInvalidInstanceId;
toyoshim60350512017-04-25 14:20:10108MidiManagerWin* g_manager_instance = nullptr;
toyoshimbe814a02017-02-20 19:07:37109
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.
toyoshime2624212017-02-24 10:13:14126// 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.
toyoshimbe814a02017-02-20 19:07:37129base::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 Toyoshima806606e82017-09-13 10:02:54135void RunTask(int instance_id, base::OnceClosure task) {
toyoshimbe814a02017-02-20 19:07:37136 // Obtains task lock to ensure that the instance should not complete
137 // Finalize() while running the |task|.
138 base::AutoLock task_lock(*GetTaskLock());
139 {
Takashi Toyoshima9151f222018-10-03 09:30:11140 // If destructor finished before the lock avobe, do nothing.
toyoshimbe814a02017-02-20 19:07:37141 base::AutoLock lock(*GetInstanceIdLock());
142 if (instance_id != g_active_instance_id)
143 return;
144 }
Takashi Toyoshima806606e82017-09-13 10:02:54145 std::move(task).Run();
toyoshimbe814a02017-02-20 19:07:37146}
147
Takashi Toyoshima9151f222018-10-03 09:30:11148// TODO(toyoshim): Use midi::TaskService and deprecate its prototype
149// implementation above that is still used in this MidiManagerWin class.
toyoshimbe814a02017-02-20 19:07:37150
Takashi Toyoshima8f7cc6442017-06-01 09:49:34151// 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
toyoshim6d4bb282017-03-01 05:16:18183// 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
toyoshimeaeaade2017-03-01 06:36:44204ScopedMIDIHDR 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
toyoshime2624212017-02-24 10:13:14210// Helper functions to close MIDI device handles on TaskRunner asynchronously.
toyoshim6d4bb282017-03-01 05:16:18211void 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));
toyoshime2624212017-02-24 10:13:14219 midiInClose(handle);
220}
221
222void FinalizeOutPort(HMIDIOUT handle) {
toyoshimeaeaade2017-03-01 06:36:44223 // Resets inflight buffers. This will cancel sending data that system
224 // holds and were not sent yet.
225 midiOutReset(handle);
toyoshime2624212017-02-24 10:13:14226 midiOutClose(handle);
227}
228
toyoshimd4acd5042017-03-01 08:40:31229// 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
toyoshime2624212017-02-24 10:13:14244// 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.
toyoshimbe814a02017-02-20 19:07:37247class 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,
toyoshimd4acd5042017-03-01 08:40:31254 const std::string& product_name,
255 const GUID& manufacturer_guid)
toyoshimbe814a02017-02-20 19:07:37256 : 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) {
toyoshimd4acd5042017-03-01 08:40:31263 info_.manufacturer =
264 GetManufacturerName(manufacturer_id, manufacturer_guid);
toyoshimbe814a02017-02-20 19:07:37265 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 Dawson6c9a5dd72017-08-04 17:57:45292 info_.id = base::StringPrintf("%s-%zd", type_.c_str(), index_);
toyoshimbe814a02017-02-20 19:07:37293 }
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_; }
Adithya Srinivasanbebaf722018-10-17 15:59:40297 const mojom::PortInfo& info() { return info_; }
toyoshimbe814a02017-02-20 19:07:37298
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_;
Adithya Srinivasanbebaf722018-10-17 15:59:40327 mojom::PortInfo info_;
toyoshimbe814a02017-02-20 19:07:37328}; // class Port
329
330} // namespace
331
toyoshim60350512017-04-25 14:20:10332class MidiManagerWin::InPort final : public Port {
toyoshimbe814a02017-02-20 19:07:37333 public:
toyoshim60350512017-04-25 14:20:10334 InPort(MidiManagerWin* manager,
toyoshim6d4bb282017-03-01 05:16:18335 int instance_id,
336 UINT device_id,
337 const MIDIINCAPS2W& caps)
toyoshimbe814a02017-02-20 19:07:37338 : Port("input",
339 device_id,
340 caps.wMid,
341 caps.wPid,
342 caps.vDriverVersion,
343 base::WideToUTF8(
toyoshimd4acd5042017-03-01 08:40:31344 base::string16(caps.szPname, wcslen(caps.szPname))),
345 caps.ManufacturerGuid),
toyoshim6d4bb282017-03-01 05:16:18346 manager_(manager),
347 in_handle_(kInvalidInHandle),
348 instance_id_(instance_id) {}
toyoshimbe814a02017-02-20 19:07:37349
toyoshim6d4bb282017-03-01 05:16:18350 static std::vector<std::unique_ptr<InPort>> EnumerateActivePorts(
toyoshim60350512017-04-25 14:20:10351 MidiManagerWin* manager,
toyoshim6d4bb282017-03-01 05:16:18352 int instance_id) {
toyoshimbe814a02017-02-20 19:07:37353 std::vector<std::unique_ptr<InPort>> ports;
Takashi Toyoshima8f7cc6442017-06-01 09:49:34354
355 // Allow callback invocations indie midiInGetNumDevs().
356 EnterMidiInGetNumDevs();
toyoshimbe814a02017-02-20 19:07:37357 const UINT num_devices = midiInGetNumDevs();
Takashi Toyoshima8f7cc6442017-06-01 09:49:34358 LeaveMidiInGetNumDevs();
359
toyoshimbe814a02017-02-20 19:07:37360 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 }
toyoshim6d4bb282017-03-01 05:16:18368 ports.push_back(
Gyuyoung Kim62a5de42018-01-10 09:48:42369 std::make_unique<InPort>(manager, instance_id, device_id, caps));
toyoshimbe814a02017-02-20 19:07:37370 }
371 return ports;
372 }
373
toyoshime2624212017-02-24 10:13:14374 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
375 if (in_handle_ != kInvalidInHandle) {
Takashi Toyoshima806606e82017-09-13 10:02:54376 runner->PostTask(FROM_HERE, base::BindOnce(&FinalizeInPort, in_handle_,
377 base::Passed(&hdr_)));
toyoshim6d4bb282017-03-01 05:16:18378 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshime2624212017-02-24 10:13:14379 in_handle_ = kInvalidInHandle;
380 }
381 }
382
toyoshim6d4bb282017-03-01 05:16:18383 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
toyoshim60350512017-04-25 14:20:10393 void NotifyPortStateSet(MidiManagerWin* manager) {
Takashi Toyoshima806606e82017-09-13 10:02:54394 manager->PostReplyTask(base::BindOnce(
Bruce Dawson0c548f42017-08-01 19:33:12395 &MidiManagerWin::SetInputPortState, base::Unretained(manager),
396 static_cast<uint32_t>(index_), info_.state));
toyoshimbe814a02017-02-20 19:07:37397 }
398
toyoshim60350512017-04-25 14:20:10399 void NotifyPortAdded(MidiManagerWin* manager) {
Takashi Toyoshima806606e82017-09-13 10:02:54400 manager->PostReplyTask(base::BindOnce(&MidiManagerWin::AddInputPort,
401 base::Unretained(manager), info_));
toyoshimbe814a02017-02-20 19:07:37402 }
toyoshime2624212017-02-24 10:13:14403
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_);
toyoshim6d4bb282017-03-01 05:16:18410 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshime2624212017-02-24 10:13:14411 in_handle_ = kInvalidInHandle;
412 }
413 return Port::Disconnect();
414 }
415
416 void Open() override {
toyoshim6d4bb282017-03-01 05:16:18417 MMRESULT result = midiInOpen(
418 &in_handle_, device_id_,
419 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiInCallback),
420 instance_id_, CALLBACK_FUNCTION);
toyoshime2624212017-02-24 10:13:14421 if (result == MMSYSERR_NOERROR) {
toyoshim6d4bb282017-03-01 05:16:18422 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_);
toyoshime2624212017-02-24 10:13:14434 Port::Open();
435 } else {
toyoshim6d4bb282017-03-01 05:16:18436 if (in_handle_ != kInvalidInHandle) {
437 midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
438 hdr_.reset();
439 midiInClose(in_handle_);
440 in_handle_ = kInvalidInHandle;
441 }
toyoshime2624212017-02-24 10:13:14442 Disconnect();
443 }
444 }
445
446 private:
toyoshim60350512017-04-25 14:20:10447 MidiManagerWin* manager_;
toyoshime2624212017-02-24 10:13:14448 HMIDIIN in_handle_;
toyoshim6d4bb282017-03-01 05:16:18449 ScopedMIDIHDR hdr_;
450 base::TimeTicks start_time_;
451 const int instance_id_;
toyoshimbe814a02017-02-20 19:07:37452};
453
toyoshim60350512017-04-25 14:20:10454class MidiManagerWin::OutPort final : public Port {
toyoshimbe814a02017-02-20 19:07:37455 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(
toyoshimd4acd5042017-03-01 08:40:31463 base::string16(caps.szPname, wcslen(caps.szPname))),
464 caps.ManufacturerGuid),
toyoshime2624212017-02-24 10:13:14465 software_(caps.wTechnology == MOD_SWSYNTH),
466 out_handle_(kInvalidOutHandle) {}
toyoshimbe814a02017-02-20 19:07:37467
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 }
Gyuyoung Kim62a5de42018-01-10 09:48:42479 ports.push_back(std::make_unique<OutPort>(device_id, caps));
toyoshimbe814a02017-02-20 19:07:37480 }
481 return ports;
482 }
483
toyoshime2624212017-02-24 10:13:14484 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
485 if (out_handle_ != kInvalidOutHandle) {
Takashi Toyoshima806606e82017-09-13 10:02:54486 runner->PostTask(FROM_HERE,
487 base::BindOnce(&FinalizeOutPort, out_handle_));
toyoshime2624212017-02-24 10:13:14488 out_handle_ = kInvalidOutHandle;
toyoshimbe814a02017-02-20 19:07:37489 }
toyoshimbe814a02017-02-20 19:07:37490 }
491
toyoshim60350512017-04-25 14:20:10492 void NotifyPortStateSet(MidiManagerWin* manager) {
Takashi Toyoshima806606e82017-09-13 10:02:54493 manager->PostReplyTask(base::BindOnce(
Bruce Dawson0c548f42017-08-01 19:33:12494 &MidiManagerWin::SetOutputPortState, base::Unretained(manager),
495 static_cast<uint32_t>(index_), info_.state));
toyoshimbe814a02017-02-20 19:07:37496 }
497
toyoshim60350512017-04-25 14:20:10498 void NotifyPortAdded(MidiManagerWin* manager) {
Takashi Toyoshima806606e82017-09-13 10:02:54499 manager->PostReplyTask(base::BindOnce(&MidiManagerWin::AddOutputPort,
500 base::Unretained(manager), info_));
toyoshimbe814a02017-02-20 19:07:37501 }
502
toyoshimeaeaade2017-03-01 06:36:44503 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
toyoshime2624212017-02-24 10:13:14534 // 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 {
toyoshimeaeaade2017-03-01 06:36:44557 MMRESULT result = midiOutOpen(
558 &out_handle_, device_id_,
559 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiOutCallback), 0,
560 CALLBACK_FUNCTION);
toyoshime2624212017-02-24 10:13:14561 if (result == MMSYSERR_NOERROR) {
562 Port::Open();
563 } else {
564 out_handle_ = kInvalidOutHandle;
565 Disconnect();
566 }
567 }
568
toyoshimbe814a02017-02-20 19:07:37569 const bool software_;
toyoshime2624212017-02-24 10:13:14570 HMIDIOUT out_handle_;
toyoshimbe814a02017-02-20 19:07:37571};
572
toyoshim60350512017-04-25 14:20:10573base::TimeTicks MidiManagerWin::PortManager::CalculateInEventTime(
toyoshim6d4bb282017-03-01 05:16:18574 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
toyoshim60350512017-04-25 14:20:10581void MidiManagerWin::PortManager::RegisterInHandle(HMIDIIN handle,
582 size_t index) {
toyoshim6d4bb282017-03-01 05:16:18583 GetTaskLock()->AssertAcquired();
584 hmidiin_to_index_map_[handle] = index;
585}
586
toyoshim60350512017-04-25 14:20:10587void MidiManagerWin::PortManager::UnregisterInHandle(HMIDIIN handle) {
toyoshim6d4bb282017-03-01 05:16:18588 GetTaskLock()->AssertAcquired();
589 hmidiin_to_index_map_.erase(handle);
590}
591
toyoshim60350512017-04-25 14:20:10592bool MidiManagerWin::PortManager::FindInHandle(HMIDIIN hmi, size_t* out_index) {
toyoshim6d4bb282017-03-01 05:16:18593 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
toyoshim60350512017-04-25 14:20:10601void MidiManagerWin::PortManager::RestoreInBuffer(size_t index) {
toyoshim6d4bb282017-03-01 05:16:18602 GetTaskLock()->AssertAcquired();
603 CHECK_GT(input_ports_.size(), index);
604 input_ports_[index]->RestoreBuffer();
605}
606
607void CALLBACK
toyoshim60350512017-04-25 14:20:10608MidiManagerWin::PortManager::HandleMidiInCallback(HMIDIIN hmi,
609 UINT msg,
610 DWORD_PTR instance,
611 DWORD_PTR param1,
612 DWORD_PTR param2) {
toyoshim6d4bb282017-03-01 05:16:18613 if (msg != MIM_DATA && msg != MIM_LONGDATA)
614 return;
615 int instance_id = static_cast<int>(instance);
toyoshim60350512017-04-25 14:20:10616 MidiManagerWin* manager = nullptr;
toyoshim6d4bb282017-03-01 05:16:18617
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 Toyoshima8f7cc6442017-06-01 09:49:34620 // 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()));
toyoshim6d4bb282017-03-01 05:16:18628 {
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;
toyoshimeaeaade2017-03-01 06:36:44636 if (!manager->port_manager()->FindInHandle(hmi, &index))
toyoshim6d4bb282017-03-01 05:16:18637 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);
Avi Drissmanfa9bed42018-12-25 20:26:39647 DCHECK_LE(len, base::size(kData));
toyoshim6d4bb282017-03-01 05:16:18648 std::vector<uint8_t> data;
649 data.assign(kData, kData + len);
Takashi Toyoshima806606e82017-09-13 10:02:54650 manager->PostReplyTask(base::BindOnce(
Yutaka Hirano32da0122017-08-01 08:14:15651 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
652 static_cast<uint32_t>(index), data,
653 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim6d4bb282017-03-01 05:16:18654 } 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 Toyoshima806606e82017-09-13 10:02:54661 manager->PostReplyTask(base::BindOnce(
Yutaka Hirano32da0122017-08-01 08:14:15662 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
663 static_cast<uint32_t>(index), data,
664 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim6d4bb282017-03-01 05:16:18665 }
toyoshim1814e6a2017-06-07 23:45:43666 manager->port_manager()->RestoreInBuffer(index);
toyoshim6d4bb282017-03-01 05:16:18667 }
668}
669
toyoshimeaeaade2017-03-01 06:36:44670void CALLBACK
toyoshim60350512017-04-25 14:20:10671MidiManagerWin::PortManager::HandleMidiOutCallback(HMIDIOUT hmo,
672 UINT msg,
673 DWORD_PTR instance,
674 DWORD_PTR param1,
675 DWORD_PTR param2) {
toyoshimeaeaade2017-03-01 06:36:44676 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
toyoshim60350512017-04-25 14:20:10689MidiManagerWin::MidiManagerWin(MidiService* service)
toyoshim6d4bb282017-03-01 05:16:18690 : MidiManager(service),
691 instance_id_(IssueNextInstanceId()),
Gyuyoung Kim62a5de42018-01-10 09:48:42692 port_manager_(std::make_unique<PortManager>()) {
toyoshimbe814a02017-02-20 19:07:37693 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
toyoshim60350512017-04-25 14:20:10700MidiManagerWin::~MidiManagerWin() {
Takashi Toyoshima9151f222018-10-03 09:30:11701 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more.
toyoshimbe814a02017-02-20 19:07:37702 CHECK(thread_runner_->BelongsToCurrentThread());
Takashi Toyoshima9151f222018-10-03 09:30:11703 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
704
705 // Posts tasks that finalize each device port without MidiManager instance
706 // on TaskRunner. If another MidiManager instance is created, its
707 // initialization runs on the same task runner after all tasks posted here
708 // finish.
709 for (const auto& port : *port_manager_->inputs())
710 port->Finalize(service()->GetTaskRunner(kTaskRunner));
711 for (const auto& port : *port_manager_->outputs())
712 port->Finalize(service()->GetTaskRunner(kTaskRunner));
713
714 // Invalidate instance bound tasks.
715 {
716 base::AutoLock lock(*GetInstanceIdLock());
717 CHECK_EQ(instance_id_, g_active_instance_id);
718 g_active_instance_id = kInvalidInstanceId;
719 CHECK_EQ(this, g_manager_instance);
720 g_manager_instance = nullptr;
721 }
722
723 // Ensures that no bound task runs on TaskRunner so to destruct the instance
724 // safely.
725 // Tasks that did not started yet will do nothing after invalidate the
726 // instance ID above.
727 // Behind the lock below, we can safely access all members for finalization
728 // even on the I/O thread.
729 base::AutoLock lock(*GetTaskLock());
toyoshimbe814a02017-02-20 19:07:37730}
731
toyoshim60350512017-04-25 14:20:10732void MidiManagerWin::StartInitialization() {
toyoshimbe814a02017-02-20 19:07:37733 {
734 base::AutoLock lock(*GetInstanceIdLock());
735 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
736 g_active_instance_id = instance_id_;
737 CHECK_EQ(nullptr, g_manager_instance);
738 g_manager_instance = this;
739 }
740 // Registers on the I/O thread to be notified on the I/O thread.
741 CHECK(thread_runner_->BelongsToCurrentThread());
742 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
743
744 // Starts asynchronous initialization on TaskRunner.
Takashi Toyoshima806606e82017-09-13 10:02:54745 PostTask(base::BindOnce(&MidiManagerWin::InitializeOnTaskRunner,
746 base::Unretained(this)));
toyoshimbe814a02017-02-20 19:07:37747}
748
toyoshim60350512017-04-25 14:20:10749void MidiManagerWin::DispatchSendMidiData(MidiManagerClient* client,
750 uint32_t port_index,
751 const std::vector<uint8_t>& data,
tzikd70a05192018-02-02 07:39:45752 base::TimeTicks timestamp) {
Takashi Toyoshimae7eb8b92017-09-13 11:50:41753 PostDelayedTask(
754 base::BindOnce(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
755 client, port_index, data),
756 MidiService::TimestampToTimeDeltaDelay(timestamp));
toyoshimbe814a02017-02-20 19:07:37757}
758
toyoshim60350512017-04-25 14:20:10759void MidiManagerWin::OnDevicesChanged(
toyoshimbe814a02017-02-20 19:07:37760 base::SystemMonitor::DeviceType device_type) {
761 // Notified on the I/O thread.
762 CHECK(thread_runner_->BelongsToCurrentThread());
763
764 switch (device_type) {
765 case base::SystemMonitor::DEVTYPE_AUDIO:
766 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
767 // Add case of other unrelated device types here.
768 return;
769 case base::SystemMonitor::DEVTYPE_UNKNOWN: {
Takashi Toyoshima806606e82017-09-13 10:02:54770 PostTask(base::BindOnce(&MidiManagerWin::UpdateDeviceListOnTaskRunner,
771 base::Unretained(this)));
toyoshimbe814a02017-02-20 19:07:37772 break;
773 }
774 }
775}
776
toyoshim60350512017-04-25 14:20:10777void MidiManagerWin::ReceiveMidiData(uint32_t index,
778 const std::vector<uint8_t>& data,
779 base::TimeTicks time) {
toyoshim6d4bb282017-03-01 05:16:18780 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
781}
782
Takashi Toyoshima806606e82017-09-13 10:02:54783void MidiManagerWin::PostTask(base::OnceClosure task) {
toyoshimbe814a02017-02-20 19:07:37784 service()
785 ->GetTaskRunner(kTaskRunner)
Takashi Toyoshima806606e82017-09-13 10:02:54786 ->PostTask(FROM_HERE,
787 base::BindOnce(&RunTask, instance_id_, std::move(task)));
toyoshimbe814a02017-02-20 19:07:37788}
789
Takashi Toyoshima806606e82017-09-13 10:02:54790void MidiManagerWin::PostDelayedTask(base::OnceClosure task,
toyoshim60350512017-04-25 14:20:10791 base::TimeDelta delay) {
toyoshimeaeaade2017-03-01 06:36:44792 service()
793 ->GetTaskRunner(kTaskRunner)
Takashi Toyoshima806606e82017-09-13 10:02:54794 ->PostDelayedTask(FROM_HERE,
795 base::BindOnce(&RunTask, instance_id_, std::move(task)),
toyoshimeaeaade2017-03-01 06:36:44796 delay);
797}
798
Takashi Toyoshima806606e82017-09-13 10:02:54799void MidiManagerWin::PostReplyTask(base::OnceClosure task) {
800 thread_runner_->PostTask(
801 FROM_HERE, base::BindOnce(&RunTask, instance_id_, std::move(task)));
toyoshim6d4bb282017-03-01 05:16:18802}
803
toyoshim60350512017-04-25 14:20:10804void MidiManagerWin::InitializeOnTaskRunner() {
toyoshimbe814a02017-02-20 19:07:37805 UpdateDeviceListOnTaskRunner();
Takashi Toyoshima806606e82017-09-13 10:02:54806 PostReplyTask(base::BindOnce(&MidiManagerWin::CompleteInitialization,
807 base::Unretained(this), mojom::Result::OK));
toyoshimbe814a02017-02-20 19:07:37808}
809
toyoshim60350512017-04-25 14:20:10810void MidiManagerWin::UpdateDeviceListOnTaskRunner() {
toyoshimbe814a02017-02-20 19:07:37811 std::vector<std::unique_ptr<InPort>> active_input_ports =
toyoshim6d4bb282017-03-01 05:16:18812 InPort::EnumerateActivePorts(this, instance_id_);
813 ReflectActiveDeviceList(this, port_manager_->inputs(), &active_input_ports);
toyoshimbe814a02017-02-20 19:07:37814
815 std::vector<std::unique_ptr<OutPort>> active_output_ports =
816 OutPort::EnumerateActivePorts();
toyoshim6d4bb282017-03-01 05:16:18817 ReflectActiveDeviceList(this, port_manager_->outputs(), &active_output_ports);
toyoshimbe814a02017-02-20 19:07:37818
819 // TODO(toyoshim): This method may run before internal MIDI device lists that
820 // Windows manages were updated. This may be because MIDI driver may be loaded
821 // after the raw device list was updated. To avoid this problem, we may want
822 // to retry device check later if no changes are detected here.
823}
824
825template <typename T>
toyoshim60350512017-04-25 14:20:10826void MidiManagerWin::ReflectActiveDeviceList(MidiManagerWin* manager,
827 std::vector<T>* known_ports,
828 std::vector<T>* active_ports) {
toyoshimbe814a02017-02-20 19:07:37829 // Update existing port states.
830 for (const auto& port : *known_ports) {
831 const auto& it = std::find_if(
832 active_ports->begin(), active_ports->end(),
833 [&port](const auto& candidate) { return *candidate == *port; });
834 if (it == active_ports->end()) {
835 if (port->Disconnect())
836 port->NotifyPortStateSet(this);
837 } else {
838 port->set_device_id((*it)->device_id());
839 if (port->Connect())
840 port->NotifyPortStateSet(this);
841 }
842 }
843
844 // Find new ports from active ports and append them to known ports.
845 for (auto& port : *active_ports) {
846 if (std::find_if(known_ports->begin(), known_ports->end(),
847 [&port](const auto& candidate) {
848 return *candidate == *port;
849 }) == known_ports->end()) {
850 size_t index = known_ports->size();
851 port->set_index(index);
852 known_ports->push_back(std::move(port));
853 (*known_ports)[index]->Connect();
854 (*known_ports)[index]->NotifyPortAdded(this);
855 }
856 }
857}
858
toyoshim60350512017-04-25 14:20:10859void MidiManagerWin::SendOnTaskRunner(MidiManagerClient* client,
860 uint32_t port_index,
861 const std::vector<uint8_t>& data) {
toyoshimeaeaade2017-03-01 06:36:44862 CHECK_GT(port_manager_->outputs()->size(), port_index);
863 (*port_manager_->outputs())[port_index]->Send(data);
864 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
Takashi Toyoshima806606e82017-09-13 10:02:54865 PostReplyTask(base::BindOnce(&MidiManagerWin::AccumulateMidiBytesSent,
866 base::Unretained(this), client, data.size()));
toyoshimeaeaade2017-03-01 06:36:44867}
868
toyoshim43994142017-04-25 06:52:01869MidiManager* MidiManager::Create(MidiService* service) {
870 if (base::FeatureList::IsEnabled(features::kMidiManagerWinrt) &&
toyoshim60350512017-04-25 14:20:10871 base::win::GetVersion() >= base::win::VERSION_WIN10) {
toyoshim43994142017-04-25 06:52:01872 return new MidiManagerWinrt(service);
toyoshim60350512017-04-25 14:20:10873 }
874 return new MidiManagerWin(service);
toyoshim43994142017-04-25 06:52:01875}
876
toyoshimbe814a02017-02-20 19:07:37877} // namespace midi