blob: e21a853b1678e86f513f731e38aa336723bdebfe [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"
Gabriel Charette78f94a02017-05-16 14:03:45 -040020#include "base/single_thread_task_runner.h"
toyoshimd28b59c2017-02-20 11:07:37 -080021#include "base/strings/string16.h"
22#include "base/strings/stringprintf.h"
23#include "base/strings/utf_string_conversions.h"
24#include "base/synchronization/lock.h"
toyoshim15385b32017-04-24 23:52:01 -070025#include "base/win/windows_version.h"
toyoshim6ebf1182017-03-01 00:40:31 -080026#include "device/usb/usb_ids.h"
toyoshim8a5ad422017-02-28 21:16:18 -080027#include "media/midi/message_util.h"
toyoshim15385b32017-04-24 23:52:01 -070028#include "media/midi/midi_manager_winrt.h"
toyoshimd28b59c2017-02-20 11:07:37 -080029#include "media/midi/midi_service.h"
Adithya Srinivasan33252732018-10-17 15:59:40 +000030#include "media/midi/midi_service.mojom.h"
toyoshim15385b32017-04-24 23:52:01 -070031#include "media/midi/midi_switches.h"
toyoshimd28b59c2017-02-20 11:07:37 -080032
33namespace midi {
34
toyoshim8a5ad422017-02-28 21:16:18 -080035// Forward declaration of PortManager for anonymous functions and internal
36// classes to use it.
toyoshim63e32a52017-04-25 07:20:10 -070037class MidiManagerWin::PortManager {
toyoshim8a5ad422017-02-28 21:16:18 -080038 public:
39 // Calculates event time from elapsed time that system provides.
40 base::TimeTicks CalculateInEventTime(size_t index, uint32_t elapsed_ms) const;
41
42 // Registers HMIDIIN handle to resolve port index.
43 void RegisterInHandle(HMIDIIN handle, size_t index);
44
45 // Unregisters HMIDIIN handle.
46 void UnregisterInHandle(HMIDIIN handle);
47
48 // Finds HMIDIIN handle and fullfil |out_index| with the port index.
toyoshim6d87aaa2017-02-28 22:36:44 -080049 bool FindInHandle(HMIDIIN hmi, size_t* out_index);
toyoshim8a5ad422017-02-28 21:16:18 -080050
51 // Restores used input buffer for the next data receive.
52 void RestoreInBuffer(size_t index);
53
54 // Ports accessors.
55 std::vector<std::unique_ptr<InPort>>* inputs() { return &input_ports_; }
56 std::vector<std::unique_ptr<OutPort>>* outputs() { return &output_ports_; }
57
58 // Handles MIDI input port callbacks that runs on a system provided thread.
59 static void CALLBACK HandleMidiInCallback(HMIDIIN hmi,
60 UINT msg,
61 DWORD_PTR instance,
62 DWORD_PTR param1,
63 DWORD_PTR param2);
64
toyoshim6d87aaa2017-02-28 22:36:44 -080065 // Handles MIDI output port callbacks that runs on a system provided thread.
66 static void CALLBACK HandleMidiOutCallback(HMIDIOUT hmo,
67 UINT msg,
68 DWORD_PTR instance,
69 DWORD_PTR param1,
70 DWORD_PTR param2);
71
toyoshim8a5ad422017-02-28 21:16:18 -080072 private:
73 // Holds all MIDI input or output ports connected once.
74 std::vector<std::unique_ptr<InPort>> input_ports_;
75 std::vector<std::unique_ptr<OutPort>> output_ports_;
76
77 // Map to resolve MIDI input port index from HMIDIIN.
78 std::map<HMIDIIN, size_t> hmidiin_to_index_map_;
79};
80
toyoshimd28b59c2017-02-20 11:07:37 -080081namespace {
82
toyoshimc32dd892017-02-24 02:13:14 -080083// Assumes that nullptr represents an invalid MIDI handle.
84constexpr HMIDIIN kInvalidInHandle = nullptr;
85constexpr HMIDIOUT kInvalidOutHandle = nullptr;
86
toyoshim6d87aaa2017-02-28 22:36:44 -080087// Defines SysEx message size limit.
88// TODO(crbug.com/383578): This restriction should be removed once Web MIDI
89// defines a standardized way to handle large sysex messages.
90// Note for built-in USB-MIDI driver:
91// From an observation on Windows 7/8.1 with a USB-MIDI keyboard,
92// midiOutLongMsg() will be always blocked. Sending 64 bytes or less data takes
93// roughly 300 usecs. Sending 2048 bytes or more data takes roughly
94// |message.size() / (75 * 1024)| secs in practice. Here we put 256 KB size
95// limit on SysEx message, with hoping that midiOutLongMsg will be blocked at
96// most 4 sec or so with a typical USB-MIDI device.
97// TODO(toyoshim): Consider to use linked small buffers so that midiOutReset()
98// can abort sending unhandled following buffers.
99constexpr size_t kSysExSizeLimit = 256 * 1024;
100
toyoshim8a5ad422017-02-28 21:16:18 -0800101// Defines input buffer size.
102constexpr size_t kBufferLength = 32 * 1024;
103
toyoshimd28b59c2017-02-20 11:07:37 -0800104// Global variables to identify MidiManager instance.
105constexpr int kInvalidInstanceId = -1;
106int g_active_instance_id = kInvalidInstanceId;
toyoshim63e32a52017-04-25 07:20:10 -0700107MidiManagerWin* g_manager_instance = nullptr;
toyoshimd28b59c2017-02-20 11:07:37 -0800108
109// Obtains base::Lock instance pointer to lock instance_id.
110base::Lock* GetInstanceIdLock() {
111 static base::Lock* lock = new base::Lock;
112 return lock;
113}
114
115// Issues unique MidiManager instance ID.
116int IssueNextInstanceId() {
117 static int id = kInvalidInstanceId;
118 return ++id;
119}
120
121// Use single TaskRunner for all tasks running outside the I/O thread.
122constexpr int kTaskRunner = 0;
123
124// Obtains base::Lock instance pointer to ensure tasks run safely on TaskRunner.
toyoshimc32dd892017-02-24 02:13:14 -0800125// Since all tasks on TaskRunner run behind a lock of *GetTaskLock(), we can
126// access all members even on the I/O thread if a lock of *GetTaskLock() is
127// obtained.
toyoshimd28b59c2017-02-20 11:07:37 -0800128base::Lock* GetTaskLock() {
129 static base::Lock* lock = new base::Lock;
130 return lock;
131}
132
133// Helper function to run a posted task on TaskRunner safely.
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000134void RunTask(int instance_id, base::OnceClosure task) {
toyoshimd28b59c2017-02-20 11:07:37 -0800135 // Obtains task lock to ensure that the instance should not complete
136 // Finalize() while running the |task|.
137 base::AutoLock task_lock(*GetTaskLock());
138 {
Takashi Toyoshimae8240ab2018-10-03 09:30:11 +0000139 // If destructor finished before the lock avobe, do nothing.
toyoshimd28b59c2017-02-20 11:07:37 -0800140 base::AutoLock lock(*GetInstanceIdLock());
141 if (instance_id != g_active_instance_id)
142 return;
143 }
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000144 std::move(task).Run();
toyoshimd28b59c2017-02-20 11:07:37 -0800145}
146
Takashi Toyoshimae8240ab2018-10-03 09:30:11 +0000147// TODO(toyoshim): Use midi::TaskService and deprecate its prototype
148// implementation above that is still used in this MidiManagerWin class.
toyoshimd28b59c2017-02-20 11:07:37 -0800149
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900150// Obtains base::Lock instance pointer to protect
151// |g_midi_in_get_num_devs_thread_id|.
152base::Lock* GetMidiInGetNumDevsThreadIdLock() {
153 static base::Lock* lock = new base::Lock;
154 return lock;
155}
156
157// Holds a thread id that calls midiInGetNumDevs() now. We use a platform
158// primitive to identify the thread because the following functions can be
159// called on a thread that Windows allocates internally, and Chrome or //base
160// library does not know.
161base::PlatformThreadId g_midi_in_get_num_devs_thread_id;
162
163// Prepares to call midiInGetNumDevs().
164void EnterMidiInGetNumDevs() {
165 base::AutoLock lock(*GetMidiInGetNumDevsThreadIdLock());
166 g_midi_in_get_num_devs_thread_id = base::PlatformThread::CurrentId();
167}
168
169// Finalizes to call midiInGetNumDevs().
170void LeaveMidiInGetNumDevs() {
171 base::AutoLock lock(*GetMidiInGetNumDevsThreadIdLock());
172 g_midi_in_get_num_devs_thread_id = base::PlatformThreadId();
173}
174
175// Checks if the current thread is running midiInGetNumDevs(), that means
176// current code is invoked inside midiInGetNumDevs().
177bool IsRunningInsideMidiInGetNumDevs() {
178 base::AutoLock lock(*GetMidiInGetNumDevsThreadIdLock());
179 return base::PlatformThread::CurrentId() == g_midi_in_get_num_devs_thread_id;
180}
181
toyoshim8a5ad422017-02-28 21:16:18 -0800182// Utility class to handle MIDIHDR struct safely.
183class MIDIHDRDeleter {
184 public:
185 void operator()(LPMIDIHDR header) {
186 if (!header)
187 return;
188 delete[] static_cast<char*>(header->lpData);
189 delete header;
190 }
191};
192
193using ScopedMIDIHDR = std::unique_ptr<MIDIHDR, MIDIHDRDeleter>;
194
195ScopedMIDIHDR CreateMIDIHDR(size_t size) {
196 ScopedMIDIHDR hdr(new MIDIHDR);
197 ZeroMemory(hdr.get(), sizeof(*hdr));
198 hdr->lpData = new char[size];
199 hdr->dwBufferLength = static_cast<DWORD>(size);
200 return hdr;
201}
202
toyoshim6d87aaa2017-02-28 22:36:44 -0800203ScopedMIDIHDR CreateMIDIHDR(const std::vector<uint8_t>& data) {
204 ScopedMIDIHDR hdr(CreateMIDIHDR(data.size()));
205 std::copy(data.begin(), data.end(), hdr->lpData);
206 return hdr;
207}
208
toyoshimc32dd892017-02-24 02:13:14 -0800209// Helper functions to close MIDI device handles on TaskRunner asynchronously.
toyoshim8a5ad422017-02-28 21:16:18 -0800210void FinalizeInPort(HMIDIIN handle, ScopedMIDIHDR hdr) {
211 // Resets the device. This stops receiving messages, and allows to release
212 // registered buffer headers. Otherwise, midiInUnprepareHeader() and
213 // midiInClose() will fail with MIDIERR_STILLPLAYING.
214 midiInReset(handle);
215
216 if (hdr)
217 midiInUnprepareHeader(handle, hdr.get(), sizeof(*hdr));
toyoshimc32dd892017-02-24 02:13:14 -0800218 midiInClose(handle);
219}
220
221void FinalizeOutPort(HMIDIOUT handle) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800222 // Resets inflight buffers. This will cancel sending data that system
223 // holds and were not sent yet.
224 midiOutReset(handle);
toyoshimc32dd892017-02-24 02:13:14 -0800225 midiOutClose(handle);
226}
227
toyoshim6ebf1182017-03-01 00:40:31 -0800228// Gets manufacturer name in string from identifiers.
229std::string GetManufacturerName(uint16_t id, const GUID& guid) {
230 if (IS_COMPATIBLE_USBAUDIO_MID(&guid)) {
231 const char* name =
232 device::UsbIds::GetVendorName(EXTRACT_USBAUDIO_MID(&guid));
233 if (name)
234 return std::string(name);
235 }
236 if (id == MM_MICROSOFT)
237 return "Microsoft Corporation";
238
239 // TODO(crbug.com/472341): Support other manufacture IDs.
240 return "";
241}
242
toyoshimc32dd892017-02-24 02:13:14 -0800243// All instances of Port subclasses are always accessed behind a lock of
244// *GetTaskLock(). Port and subclasses implementation do not need to
245// consider thread safety.
toyoshimd28b59c2017-02-20 11:07:37 -0800246class Port {
247 public:
248 Port(const std::string& type,
249 uint32_t device_id,
250 uint16_t manufacturer_id,
251 uint16_t product_id,
252 uint32_t driver_version,
toyoshim6ebf1182017-03-01 00:40:31 -0800253 const std::string& product_name,
254 const GUID& manufacturer_guid)
toyoshimd28b59c2017-02-20 11:07:37 -0800255 : index_(0u),
256 type_(type),
257 device_id_(device_id),
258 manufacturer_id_(manufacturer_id),
259 product_id_(product_id),
260 driver_version_(driver_version),
261 product_name_(product_name) {
toyoshim6ebf1182017-03-01 00:40:31 -0800262 info_.manufacturer =
263 GetManufacturerName(manufacturer_id, manufacturer_guid);
toyoshimd28b59c2017-02-20 11:07:37 -0800264 info_.name = product_name_;
265 info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_),
266 LOBYTE(driver_version_));
267 info_.state = mojom::PortState::DISCONNECTED;
268 }
269
270 virtual ~Port() {}
271
272 bool operator==(const Port& other) const {
273 // Should not use |device_id| for comparison because it can be changed on
274 // each enumeration.
275 // Since the GUID will be changed on each enumeration for Microsoft GS
276 // Wavetable synth and might be done for others, do not use it for device
277 // comparison.
278 return manufacturer_id_ == other.manufacturer_id_ &&
279 product_id_ == other.product_id_ &&
280 driver_version_ == other.driver_version_ &&
281 product_name_ == other.product_name_;
282 }
283
284 bool IsConnected() const {
285 return info_.state != mojom::PortState::DISCONNECTED;
286 }
287
288 void set_index(size_t index) {
289 index_ = index;
290 // TODO(toyoshim): Use hashed ID.
Bruce Dawson66ae7db2017-08-04 17:57:45 +0000291 info_.id = base::StringPrintf("%s-%zd", type_.c_str(), index_);
toyoshimd28b59c2017-02-20 11:07:37 -0800292 }
293 size_t index() { return index_; }
294 void set_device_id(uint32_t device_id) { device_id_ = device_id; }
295 uint32_t device_id() { return device_id_; }
Adithya Srinivasan33252732018-10-17 15:59:40 +0000296 const mojom::PortInfo& info() { return info_; }
toyoshimd28b59c2017-02-20 11:07:37 -0800297
298 virtual bool Connect() {
299 if (info_.state != mojom::PortState::DISCONNECTED)
300 return false;
301
302 info_.state = mojom::PortState::CONNECTED;
303 // TODO(toyoshim) Until open() / close() are supported, open each device on
304 // connected.
305 Open();
306 return true;
307 }
308
309 virtual bool Disconnect() {
310 if (info_.state == mojom::PortState::DISCONNECTED)
311 return false;
312 info_.state = mojom::PortState::DISCONNECTED;
313 return true;
314 }
315
316 virtual void Open() { info_.state = mojom::PortState::OPENED; }
317
318 protected:
319 size_t index_;
320 std::string type_;
321 uint32_t device_id_;
322 const uint16_t manufacturer_id_;
323 const uint16_t product_id_;
324 const uint32_t driver_version_;
325 const std::string product_name_;
Adithya Srinivasan33252732018-10-17 15:59:40 +0000326 mojom::PortInfo info_;
toyoshimd28b59c2017-02-20 11:07:37 -0800327}; // class Port
328
329} // namespace
330
toyoshim63e32a52017-04-25 07:20:10 -0700331class MidiManagerWin::InPort final : public Port {
toyoshimd28b59c2017-02-20 11:07:37 -0800332 public:
toyoshim63e32a52017-04-25 07:20:10 -0700333 InPort(MidiManagerWin* manager,
toyoshim8a5ad422017-02-28 21:16:18 -0800334 int instance_id,
335 UINT device_id,
336 const MIDIINCAPS2W& caps)
toyoshimd28b59c2017-02-20 11:07:37 -0800337 : Port("input",
338 device_id,
339 caps.wMid,
340 caps.wPid,
341 caps.vDriverVersion,
342 base::WideToUTF8(
toyoshim6ebf1182017-03-01 00:40:31 -0800343 base::string16(caps.szPname, wcslen(caps.szPname))),
344 caps.ManufacturerGuid),
toyoshim8a5ad422017-02-28 21:16:18 -0800345 manager_(manager),
346 in_handle_(kInvalidInHandle),
347 instance_id_(instance_id) {}
toyoshimd28b59c2017-02-20 11:07:37 -0800348
toyoshim8a5ad422017-02-28 21:16:18 -0800349 static std::vector<std::unique_ptr<InPort>> EnumerateActivePorts(
toyoshim63e32a52017-04-25 07:20:10 -0700350 MidiManagerWin* manager,
toyoshim8a5ad422017-02-28 21:16:18 -0800351 int instance_id) {
toyoshimd28b59c2017-02-20 11:07:37 -0800352 std::vector<std::unique_ptr<InPort>> ports;
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900353
354 // Allow callback invocations indie midiInGetNumDevs().
355 EnterMidiInGetNumDevs();
toyoshimd28b59c2017-02-20 11:07:37 -0800356 const UINT num_devices = midiInGetNumDevs();
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900357 LeaveMidiInGetNumDevs();
358
toyoshimd28b59c2017-02-20 11:07:37 -0800359 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
360 MIDIINCAPS2W caps;
361 MMRESULT result = midiInGetDevCaps(
362 device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps));
363 if (result != MMSYSERR_NOERROR) {
364 LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id;
365 continue;
366 }
toyoshim8a5ad422017-02-28 21:16:18 -0800367 ports.push_back(
Gyuyoung Kim34e191a2018-01-10 09:48:42 +0000368 std::make_unique<InPort>(manager, instance_id, device_id, caps));
toyoshimd28b59c2017-02-20 11:07:37 -0800369 }
370 return ports;
371 }
372
toyoshimc32dd892017-02-24 02:13:14 -0800373 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
374 if (in_handle_ != kInvalidInHandle) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000375 runner->PostTask(FROM_HERE, base::BindOnce(&FinalizeInPort, in_handle_,
376 base::Passed(&hdr_)));
toyoshim8a5ad422017-02-28 21:16:18 -0800377 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshimc32dd892017-02-24 02:13:14 -0800378 in_handle_ = kInvalidInHandle;
379 }
380 }
381
toyoshim8a5ad422017-02-28 21:16:18 -0800382 base::TimeTicks CalculateInEventTime(uint32_t elapsed_ms) const {
383 return start_time_ + base::TimeDelta::FromMilliseconds(elapsed_ms);
384 }
385
386 void RestoreBuffer() {
387 if (in_handle_ == kInvalidInHandle || !hdr_)
388 return;
389 midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
390 }
391
toyoshim63e32a52017-04-25 07:20:10 -0700392 void NotifyPortStateSet(MidiManagerWin* manager) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000393 manager->PostReplyTask(base::BindOnce(
Bruce Dawson7fd26de2017-08-01 19:33:12 +0000394 &MidiManagerWin::SetInputPortState, base::Unretained(manager),
395 static_cast<uint32_t>(index_), info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800396 }
397
toyoshim63e32a52017-04-25 07:20:10 -0700398 void NotifyPortAdded(MidiManagerWin* manager) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000399 manager->PostReplyTask(base::BindOnce(&MidiManagerWin::AddInputPort,
400 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800401 }
toyoshimc32dd892017-02-24 02:13:14 -0800402
403 // Port overrides:
404 bool Disconnect() override {
405 if (in_handle_ != kInvalidInHandle) {
406 // Following API call may fail because device was already disconnected.
407 // But just in case.
408 midiInClose(in_handle_);
toyoshim8a5ad422017-02-28 21:16:18 -0800409 manager_->port_manager()->UnregisterInHandle(in_handle_);
toyoshimc32dd892017-02-24 02:13:14 -0800410 in_handle_ = kInvalidInHandle;
411 }
412 return Port::Disconnect();
413 }
414
415 void Open() override {
toyoshim8a5ad422017-02-28 21:16:18 -0800416 MMRESULT result = midiInOpen(
417 &in_handle_, device_id_,
418 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiInCallback),
419 instance_id_, CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800420 if (result == MMSYSERR_NOERROR) {
toyoshim8a5ad422017-02-28 21:16:18 -0800421 hdr_ = CreateMIDIHDR(kBufferLength);
422 result = midiInPrepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
423 }
424 if (result != MMSYSERR_NOERROR)
425 in_handle_ = kInvalidInHandle;
426 if (result == MMSYSERR_NOERROR)
427 result = midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
428 if (result == MMSYSERR_NOERROR)
429 result = midiInStart(in_handle_);
430 if (result == MMSYSERR_NOERROR) {
431 start_time_ = base::TimeTicks::Now();
432 manager_->port_manager()->RegisterInHandle(in_handle_, index_);
toyoshimc32dd892017-02-24 02:13:14 -0800433 Port::Open();
434 } else {
toyoshim8a5ad422017-02-28 21:16:18 -0800435 if (in_handle_ != kInvalidInHandle) {
436 midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
437 hdr_.reset();
438 midiInClose(in_handle_);
439 in_handle_ = kInvalidInHandle;
440 }
toyoshimc32dd892017-02-24 02:13:14 -0800441 Disconnect();
442 }
443 }
444
445 private:
toyoshim63e32a52017-04-25 07:20:10 -0700446 MidiManagerWin* manager_;
toyoshimc32dd892017-02-24 02:13:14 -0800447 HMIDIIN in_handle_;
toyoshim8a5ad422017-02-28 21:16:18 -0800448 ScopedMIDIHDR hdr_;
449 base::TimeTicks start_time_;
450 const int instance_id_;
toyoshimd28b59c2017-02-20 11:07:37 -0800451};
452
toyoshim63e32a52017-04-25 07:20:10 -0700453class MidiManagerWin::OutPort final : public Port {
toyoshimd28b59c2017-02-20 11:07:37 -0800454 public:
455 OutPort(UINT device_id, const MIDIOUTCAPS2W& caps)
456 : Port("output",
457 device_id,
458 caps.wMid,
459 caps.wPid,
460 caps.vDriverVersion,
461 base::WideToUTF8(
toyoshim6ebf1182017-03-01 00:40:31 -0800462 base::string16(caps.szPname, wcslen(caps.szPname))),
463 caps.ManufacturerGuid),
toyoshimc32dd892017-02-24 02:13:14 -0800464 software_(caps.wTechnology == MOD_SWSYNTH),
465 out_handle_(kInvalidOutHandle) {}
toyoshimd28b59c2017-02-20 11:07:37 -0800466
467 static std::vector<std::unique_ptr<OutPort>> EnumerateActivePorts() {
468 std::vector<std::unique_ptr<OutPort>> ports;
469 const UINT num_devices = midiOutGetNumDevs();
470 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
471 MIDIOUTCAPS2W caps;
472 MMRESULT result = midiOutGetDevCaps(
473 device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps));
474 if (result != MMSYSERR_NOERROR) {
475 LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id;
476 continue;
477 }
Gyuyoung Kim34e191a2018-01-10 09:48:42 +0000478 ports.push_back(std::make_unique<OutPort>(device_id, caps));
toyoshimd28b59c2017-02-20 11:07:37 -0800479 }
480 return ports;
481 }
482
toyoshimc32dd892017-02-24 02:13:14 -0800483 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
484 if (out_handle_ != kInvalidOutHandle) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000485 runner->PostTask(FROM_HERE,
486 base::BindOnce(&FinalizeOutPort, out_handle_));
toyoshimc32dd892017-02-24 02:13:14 -0800487 out_handle_ = kInvalidOutHandle;
toyoshimd28b59c2017-02-20 11:07:37 -0800488 }
toyoshimd28b59c2017-02-20 11:07:37 -0800489 }
490
toyoshim63e32a52017-04-25 07:20:10 -0700491 void NotifyPortStateSet(MidiManagerWin* manager) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000492 manager->PostReplyTask(base::BindOnce(
Bruce Dawson7fd26de2017-08-01 19:33:12 +0000493 &MidiManagerWin::SetOutputPortState, base::Unretained(manager),
494 static_cast<uint32_t>(index_), info_.state));
toyoshimd28b59c2017-02-20 11:07:37 -0800495 }
496
toyoshim63e32a52017-04-25 07:20:10 -0700497 void NotifyPortAdded(MidiManagerWin* manager) {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000498 manager->PostReplyTask(base::BindOnce(&MidiManagerWin::AddOutputPort,
499 base::Unretained(manager), info_));
toyoshimd28b59c2017-02-20 11:07:37 -0800500 }
501
toyoshim6d87aaa2017-02-28 22:36:44 -0800502 void Send(const std::vector<uint8_t>& data) {
503 if (out_handle_ == kInvalidOutHandle)
504 return;
505
506 if (data.size() <= 3) {
507 uint32_t message = 0;
508 for (size_t i = 0; i < data.size(); ++i)
509 message |= (static_cast<uint32_t>(data[i]) << (i * 8));
510 midiOutShortMsg(out_handle_, message);
511 } else {
512 if (data.size() > kSysExSizeLimit) {
513 LOG(ERROR) << "Ignoring SysEx message due to the size limit"
514 << ", size = " << data.size();
515 // TODO(toyoshim): Consider to report metrics here.
516 return;
517 }
518 ScopedMIDIHDR hdr(CreateMIDIHDR(data));
519 MMRESULT result =
520 midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
521 if (result != MMSYSERR_NOERROR)
522 return;
523 result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr));
524 if (result != MMSYSERR_NOERROR) {
525 midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
526 } else {
527 // MIDIHDR will be released on MOM_DONE.
528 ignore_result(hdr.release());
529 }
530 }
531 }
532
toyoshimc32dd892017-02-24 02:13:14 -0800533 // Port overrides:
534 bool Connect() override {
535 // Until |software| option is supported, disable Microsoft GS Wavetable
536 // Synth that has a known security issue.
537 if (software_ && manufacturer_id_ == MM_MICROSOFT &&
538 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT ||
539 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) {
540 return false;
541 }
542 return Port::Connect();
543 }
544
545 bool Disconnect() override {
546 if (out_handle_ != kInvalidOutHandle) {
547 // Following API call may fail because device was already disconnected.
548 // But just in case.
549 midiOutClose(out_handle_);
550 out_handle_ = kInvalidOutHandle;
551 }
552 return Port::Disconnect();
553 }
554
555 void Open() override {
toyoshim6d87aaa2017-02-28 22:36:44 -0800556 MMRESULT result = midiOutOpen(
557 &out_handle_, device_id_,
558 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiOutCallback), 0,
559 CALLBACK_FUNCTION);
toyoshimc32dd892017-02-24 02:13:14 -0800560 if (result == MMSYSERR_NOERROR) {
561 Port::Open();
562 } else {
563 out_handle_ = kInvalidOutHandle;
564 Disconnect();
565 }
566 }
567
toyoshimd28b59c2017-02-20 11:07:37 -0800568 const bool software_;
toyoshimc32dd892017-02-24 02:13:14 -0800569 HMIDIOUT out_handle_;
toyoshimd28b59c2017-02-20 11:07:37 -0800570};
571
toyoshim63e32a52017-04-25 07:20:10 -0700572base::TimeTicks MidiManagerWin::PortManager::CalculateInEventTime(
toyoshim8a5ad422017-02-28 21:16:18 -0800573 size_t index,
574 uint32_t elapsed_ms) const {
575 GetTaskLock()->AssertAcquired();
576 CHECK_GT(input_ports_.size(), index);
577 return input_ports_[index]->CalculateInEventTime(elapsed_ms);
578}
579
toyoshim63e32a52017-04-25 07:20:10 -0700580void MidiManagerWin::PortManager::RegisterInHandle(HMIDIIN handle,
581 size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800582 GetTaskLock()->AssertAcquired();
583 hmidiin_to_index_map_[handle] = index;
584}
585
toyoshim63e32a52017-04-25 07:20:10 -0700586void MidiManagerWin::PortManager::UnregisterInHandle(HMIDIIN handle) {
toyoshim8a5ad422017-02-28 21:16:18 -0800587 GetTaskLock()->AssertAcquired();
588 hmidiin_to_index_map_.erase(handle);
589}
590
toyoshim63e32a52017-04-25 07:20:10 -0700591bool MidiManagerWin::PortManager::FindInHandle(HMIDIIN hmi, size_t* out_index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800592 GetTaskLock()->AssertAcquired();
593 auto found = hmidiin_to_index_map_.find(hmi);
594 if (found == hmidiin_to_index_map_.end())
595 return false;
596 *out_index = found->second;
597 return true;
598}
599
toyoshim63e32a52017-04-25 07:20:10 -0700600void MidiManagerWin::PortManager::RestoreInBuffer(size_t index) {
toyoshim8a5ad422017-02-28 21:16:18 -0800601 GetTaskLock()->AssertAcquired();
602 CHECK_GT(input_ports_.size(), index);
603 input_ports_[index]->RestoreBuffer();
604}
605
606void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700607MidiManagerWin::PortManager::HandleMidiInCallback(HMIDIIN hmi,
608 UINT msg,
609 DWORD_PTR instance,
610 DWORD_PTR param1,
611 DWORD_PTR param2) {
toyoshim8a5ad422017-02-28 21:16:18 -0800612 if (msg != MIM_DATA && msg != MIM_LONGDATA)
613 return;
614 int instance_id = static_cast<int>(instance);
toyoshim63e32a52017-04-25 07:20:10 -0700615 MidiManagerWin* manager = nullptr;
toyoshim8a5ad422017-02-28 21:16:18 -0800616
617 // Use |g_task_lock| so to ensure the instance can keep alive while running,
618 // and to access member variables that are used on TaskRunner.
Takashi Toyoshimaa09cbc72017-06-01 18:49:34 +0900619 // Exceptionally, we do not take the lock when this callback is invoked inside
620 // midiInGetNumDevs() on the caller thread because the lock is already
621 // obtained by the current caller thread.
622 std::unique_ptr<base::AutoLock> task_lock;
623 if (IsRunningInsideMidiInGetNumDevs())
624 GetTaskLock()->AssertAcquired();
625 else
626 task_lock.reset(new base::AutoLock(*GetTaskLock()));
toyoshim8a5ad422017-02-28 21:16:18 -0800627 {
628 base::AutoLock lock(*GetInstanceIdLock());
629 if (instance_id != g_active_instance_id)
630 return;
631 manager = g_manager_instance;
632 }
633
634 size_t index;
toyoshim6d87aaa2017-02-28 22:36:44 -0800635 if (!manager->port_manager()->FindInHandle(hmi, &index))
toyoshim8a5ad422017-02-28 21:16:18 -0800636 return;
637
638 DCHECK(msg == MIM_DATA || msg == MIM_LONGDATA);
639 if (msg == MIM_DATA) {
640 const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff);
641 const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff);
642 const uint8_t second_data_byte =
643 static_cast<uint8_t>((param1 >> 16) & 0xff);
644 const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte};
645 const size_t len = GetMessageLength(status_byte);
646 DCHECK_LE(len, arraysize(kData));
647 std::vector<uint8_t> data;
648 data.assign(kData, kData + len);
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000649 manager->PostReplyTask(base::BindOnce(
Yutaka Hirano138dd962017-08-01 08:14:15 +0000650 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
651 static_cast<uint32_t>(index), data,
652 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800653 } else {
654 DCHECK_EQ(static_cast<UINT>(MIM_LONGDATA), msg);
655 LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1);
656 if (hdr->dwBytesRecorded > 0) {
657 const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData);
658 std::vector<uint8_t> data;
659 data.assign(src, src + hdr->dwBytesRecorded);
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000660 manager->PostReplyTask(base::BindOnce(
Yutaka Hirano138dd962017-08-01 08:14:15 +0000661 &MidiManagerWin::ReceiveMidiData, base::Unretained(manager),
662 static_cast<uint32_t>(index), data,
663 manager->port_manager()->CalculateInEventTime(index, param2)));
toyoshim8a5ad422017-02-28 21:16:18 -0800664 }
toyoshim824deed2017-06-07 16:45:43 -0700665 manager->port_manager()->RestoreInBuffer(index);
toyoshim8a5ad422017-02-28 21:16:18 -0800666 }
667}
668
toyoshim6d87aaa2017-02-28 22:36:44 -0800669void CALLBACK
toyoshim63e32a52017-04-25 07:20:10 -0700670MidiManagerWin::PortManager::HandleMidiOutCallback(HMIDIOUT hmo,
671 UINT msg,
672 DWORD_PTR instance,
673 DWORD_PTR param1,
674 DWORD_PTR param2) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800675 if (msg == MOM_DONE) {
676 ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1));
677 if (!hdr)
678 return;
679 // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback.
680 // Since this callback may be invoked after the manager is destructed,
681 // and can not send a task to the TaskRunner in such case, we need to
682 // consider to track MIDIHDR per port, and clean it in port finalization
683 // steps, too.
684 midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr));
685 }
686}
687
toyoshim63e32a52017-04-25 07:20:10 -0700688MidiManagerWin::MidiManagerWin(MidiService* service)
toyoshim8a5ad422017-02-28 21:16:18 -0800689 : MidiManager(service),
690 instance_id_(IssueNextInstanceId()),
Gyuyoung Kim34e191a2018-01-10 09:48:42 +0000691 port_manager_(std::make_unique<PortManager>()) {
toyoshimd28b59c2017-02-20 11:07:37 -0800692 base::AutoLock lock(*GetInstanceIdLock());
693 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
694
695 // Obtains the task runner for the current thread that hosts this instnace.
696 thread_runner_ = base::ThreadTaskRunnerHandle::Get();
697}
698
toyoshim63e32a52017-04-25 07:20:10 -0700699MidiManagerWin::~MidiManagerWin() {
Takashi Toyoshimae8240ab2018-10-03 09:30:11 +0000700 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more.
toyoshimd28b59c2017-02-20 11:07:37 -0800701 CHECK(thread_runner_->BelongsToCurrentThread());
Takashi Toyoshimae8240ab2018-10-03 09:30:11 +0000702 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
703
704 // Posts tasks that finalize each device port without MidiManager instance
705 // on TaskRunner. If another MidiManager instance is created, its
706 // initialization runs on the same task runner after all tasks posted here
707 // finish.
708 for (const auto& port : *port_manager_->inputs())
709 port->Finalize(service()->GetTaskRunner(kTaskRunner));
710 for (const auto& port : *port_manager_->outputs())
711 port->Finalize(service()->GetTaskRunner(kTaskRunner));
712
713 // Invalidate instance bound tasks.
714 {
715 base::AutoLock lock(*GetInstanceIdLock());
716 CHECK_EQ(instance_id_, g_active_instance_id);
717 g_active_instance_id = kInvalidInstanceId;
718 CHECK_EQ(this, g_manager_instance);
719 g_manager_instance = nullptr;
720 }
721
722 // Ensures that no bound task runs on TaskRunner so to destruct the instance
723 // safely.
724 // Tasks that did not started yet will do nothing after invalidate the
725 // instance ID above.
726 // Behind the lock below, we can safely access all members for finalization
727 // even on the I/O thread.
728 base::AutoLock lock(*GetTaskLock());
toyoshimd28b59c2017-02-20 11:07:37 -0800729}
730
toyoshim63e32a52017-04-25 07:20:10 -0700731void MidiManagerWin::StartInitialization() {
toyoshimd28b59c2017-02-20 11:07:37 -0800732 {
733 base::AutoLock lock(*GetInstanceIdLock());
734 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
735 g_active_instance_id = instance_id_;
736 CHECK_EQ(nullptr, g_manager_instance);
737 g_manager_instance = this;
738 }
739 // Registers on the I/O thread to be notified on the I/O thread.
740 CHECK(thread_runner_->BelongsToCurrentThread());
741 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
742
743 // Starts asynchronous initialization on TaskRunner.
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000744 PostTask(base::BindOnce(&MidiManagerWin::InitializeOnTaskRunner,
745 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800746}
747
toyoshim63e32a52017-04-25 07:20:10 -0700748void MidiManagerWin::DispatchSendMidiData(MidiManagerClient* client,
749 uint32_t port_index,
750 const std::vector<uint8_t>& data,
tzik925e2c62018-02-02 07:39:45 +0000751 base::TimeTicks timestamp) {
Takashi Toyoshimaafb27d52017-09-13 11:50:41 +0000752 PostDelayedTask(
753 base::BindOnce(&MidiManagerWin::SendOnTaskRunner, base::Unretained(this),
754 client, port_index, data),
755 MidiService::TimestampToTimeDeltaDelay(timestamp));
toyoshimd28b59c2017-02-20 11:07:37 -0800756}
757
toyoshim63e32a52017-04-25 07:20:10 -0700758void MidiManagerWin::OnDevicesChanged(
toyoshimd28b59c2017-02-20 11:07:37 -0800759 base::SystemMonitor::DeviceType device_type) {
760 // Notified on the I/O thread.
761 CHECK(thread_runner_->BelongsToCurrentThread());
762
763 switch (device_type) {
764 case base::SystemMonitor::DEVTYPE_AUDIO:
765 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
766 // Add case of other unrelated device types here.
767 return;
768 case base::SystemMonitor::DEVTYPE_UNKNOWN: {
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000769 PostTask(base::BindOnce(&MidiManagerWin::UpdateDeviceListOnTaskRunner,
770 base::Unretained(this)));
toyoshimd28b59c2017-02-20 11:07:37 -0800771 break;
772 }
773 }
774}
775
toyoshim63e32a52017-04-25 07:20:10 -0700776void MidiManagerWin::ReceiveMidiData(uint32_t index,
777 const std::vector<uint8_t>& data,
778 base::TimeTicks time) {
toyoshim8a5ad422017-02-28 21:16:18 -0800779 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
780}
781
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000782void MidiManagerWin::PostTask(base::OnceClosure task) {
toyoshimd28b59c2017-02-20 11:07:37 -0800783 service()
784 ->GetTaskRunner(kTaskRunner)
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000785 ->PostTask(FROM_HERE,
786 base::BindOnce(&RunTask, instance_id_, std::move(task)));
toyoshimd28b59c2017-02-20 11:07:37 -0800787}
788
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000789void MidiManagerWin::PostDelayedTask(base::OnceClosure task,
toyoshim63e32a52017-04-25 07:20:10 -0700790 base::TimeDelta delay) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800791 service()
792 ->GetTaskRunner(kTaskRunner)
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000793 ->PostDelayedTask(FROM_HERE,
794 base::BindOnce(&RunTask, instance_id_, std::move(task)),
toyoshim6d87aaa2017-02-28 22:36:44 -0800795 delay);
796}
797
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000798void MidiManagerWin::PostReplyTask(base::OnceClosure task) {
799 thread_runner_->PostTask(
800 FROM_HERE, base::BindOnce(&RunTask, instance_id_, std::move(task)));
toyoshim8a5ad422017-02-28 21:16:18 -0800801}
802
toyoshim63e32a52017-04-25 07:20:10 -0700803void MidiManagerWin::InitializeOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800804 UpdateDeviceListOnTaskRunner();
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000805 PostReplyTask(base::BindOnce(&MidiManagerWin::CompleteInitialization,
806 base::Unretained(this), mojom::Result::OK));
toyoshimd28b59c2017-02-20 11:07:37 -0800807}
808
toyoshim63e32a52017-04-25 07:20:10 -0700809void MidiManagerWin::UpdateDeviceListOnTaskRunner() {
toyoshimd28b59c2017-02-20 11:07:37 -0800810 std::vector<std::unique_ptr<InPort>> active_input_ports =
toyoshim8a5ad422017-02-28 21:16:18 -0800811 InPort::EnumerateActivePorts(this, instance_id_);
812 ReflectActiveDeviceList(this, port_manager_->inputs(), &active_input_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800813
814 std::vector<std::unique_ptr<OutPort>> active_output_ports =
815 OutPort::EnumerateActivePorts();
toyoshim8a5ad422017-02-28 21:16:18 -0800816 ReflectActiveDeviceList(this, port_manager_->outputs(), &active_output_ports);
toyoshimd28b59c2017-02-20 11:07:37 -0800817
818 // TODO(toyoshim): This method may run before internal MIDI device lists that
819 // Windows manages were updated. This may be because MIDI driver may be loaded
820 // after the raw device list was updated. To avoid this problem, we may want
821 // to retry device check later if no changes are detected here.
822}
823
824template <typename T>
toyoshim63e32a52017-04-25 07:20:10 -0700825void MidiManagerWin::ReflectActiveDeviceList(MidiManagerWin* manager,
826 std::vector<T>* known_ports,
827 std::vector<T>* active_ports) {
toyoshimd28b59c2017-02-20 11:07:37 -0800828 // Update existing port states.
829 for (const auto& port : *known_ports) {
830 const auto& it = std::find_if(
831 active_ports->begin(), active_ports->end(),
832 [&port](const auto& candidate) { return *candidate == *port; });
833 if (it == active_ports->end()) {
834 if (port->Disconnect())
835 port->NotifyPortStateSet(this);
836 } else {
837 port->set_device_id((*it)->device_id());
838 if (port->Connect())
839 port->NotifyPortStateSet(this);
840 }
841 }
842
843 // Find new ports from active ports and append them to known ports.
844 for (auto& port : *active_ports) {
845 if (std::find_if(known_ports->begin(), known_ports->end(),
846 [&port](const auto& candidate) {
847 return *candidate == *port;
848 }) == known_ports->end()) {
849 size_t index = known_ports->size();
850 port->set_index(index);
851 known_ports->push_back(std::move(port));
852 (*known_ports)[index]->Connect();
853 (*known_ports)[index]->NotifyPortAdded(this);
854 }
855 }
856}
857
toyoshim63e32a52017-04-25 07:20:10 -0700858void MidiManagerWin::SendOnTaskRunner(MidiManagerClient* client,
859 uint32_t port_index,
860 const std::vector<uint8_t>& data) {
toyoshim6d87aaa2017-02-28 22:36:44 -0800861 CHECK_GT(port_manager_->outputs()->size(), port_index);
862 (*port_manager_->outputs())[port_index]->Send(data);
863 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
Takashi Toyoshimad2bdc592017-09-13 10:02:54 +0000864 PostReplyTask(base::BindOnce(&MidiManagerWin::AccumulateMidiBytesSent,
865 base::Unretained(this), client, data.size()));
toyoshim6d87aaa2017-02-28 22:36:44 -0800866}
867
toyoshim15385b32017-04-24 23:52:01 -0700868MidiManager* MidiManager::Create(MidiService* service) {
869 if (base::FeatureList::IsEnabled(features::kMidiManagerWinrt) &&
toyoshim63e32a52017-04-25 07:20:10 -0700870 base::win::GetVersion() >= base::win::VERSION_WIN10) {
toyoshim15385b32017-04-24 23:52:01 -0700871 return new MidiManagerWinrt(service);
toyoshim63e32a52017-04-25 07:20:10 -0700872 }
873 return new MidiManagerWin(service);
toyoshim15385b32017-04-24 23:52:01 -0700874}
875
toyoshimd28b59c2017-02-20 11:07:37 -0800876} // namespace midi