OLD | NEW |
(Empty) | |
| 1 // 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 |
| 5 #include "media/midi/dynamically_initialized_midi_manager_win.h" |
| 6 |
| 7 #include <windows.h> |
| 8 |
| 9 #include <mmreg.h> |
| 10 #include <mmsystem.h> |
| 11 |
| 12 #include <algorithm> |
| 13 #include <string> |
| 14 |
| 15 #include "base/callback.h" |
| 16 #include "base/lazy_instance.h" |
| 17 #include "base/logging.h" |
| 18 #include "base/memory/ptr_util.h" |
| 19 #include "base/strings/string16.h" |
| 20 #include "base/strings/stringprintf.h" |
| 21 #include "base/strings/utf_string_conversions.h" |
| 22 #include "base/synchronization/lock.h" |
| 23 #include "base/time/time.h" |
| 24 #include "media/midi/message_util.h" |
| 25 #include "media/midi/midi_port_info.h" |
| 26 #include "media/midi/midi_service.h" |
| 27 |
| 28 namespace midi { |
| 29 |
| 30 namespace { |
| 31 |
| 32 // Assumes that nullptr represents an invalid MIDI handle. |
| 33 constexpr HMIDIIN kInvalidInHandle = nullptr; |
| 34 constexpr HMIDIOUT kInvalidOutHandle = nullptr; |
| 35 |
| 36 // Defines SysEx message size limit. |
| 37 // TODO(crbug.com/383578): This restriction should be removed once Web MIDI |
| 38 // defines a standardized way to handle large sysex messages. |
| 39 // Note for built-in USB-MIDI driver: |
| 40 // From an observation on Windows 7/8.1 with a USB-MIDI keyboard, |
| 41 // midiOutLongMsg() will be always blocked. Sending 64 bytes or less data takes |
| 42 // roughly 300 usecs. Sending 2048 bytes or more data takes roughly |
| 43 // |message.size() / (75 * 1024)| secs in practice. Here we put 256 KB size |
| 44 // limit on SysEx message, with hoping that midiOutLongMsg will be blocked at |
| 45 // most 4 sec or so with a typical USB-MIDI device. |
| 46 // TODO(toyoshim): Consider to use linked small buffers so that midiOutReset() |
| 47 // can abort sending unhandled following buffers. |
| 48 constexpr size_t kSysExSizeLimit = 256 * 1024; |
| 49 |
| 50 // Defines input buffer size. |
| 51 constexpr size_t kBufferLength = 32 * 1024; |
| 52 |
| 53 // Global variables to identify MidiManager instance. |
| 54 constexpr int kInvalidInstanceId = -1; |
| 55 int g_active_instance_id = kInvalidInstanceId; |
| 56 int g_next_instance_id = 0; |
| 57 DynamicallyInitializedMidiManagerWin* g_manager_instance = nullptr; |
| 58 |
| 59 // Global map to resolve MIDI input port index from HMIDIIN. |
| 60 std::map<HMIDIIN, size_t> g_hmidiin_to_index_map; |
| 61 |
| 62 // Obtains base::Lock instance pointer to lock instance_id. |
| 63 base::Lock* GetInstanceIdLock() { |
| 64 static base::Lock* lock = new base::Lock; |
| 65 return lock; |
| 66 } |
| 67 |
| 68 // Use single TaskRunner for all tasks running outside the I/O thread. |
| 69 constexpr int kTaskRunner = 0; |
| 70 |
| 71 // Obtains base::Lock instance pointer to ensure tasks run safely on TaskRunner. |
| 72 base::Lock* GetTaskLock() { |
| 73 static base::Lock* lock = new base::Lock; |
| 74 return lock; |
| 75 } |
| 76 |
| 77 // Helper function to run a posted task on TaskRunner safely. |
| 78 void RunTask(int instance_id, const base::Closure& task) { |
| 79 base::AutoLock task_lock(*GetTaskLock()); |
| 80 { |
| 81 base::AutoLock lock(*GetInstanceIdLock()); |
| 82 if (instance_id != g_active_instance_id) |
| 83 return; |
| 84 } |
| 85 task.Run(); |
| 86 } |
| 87 |
| 88 // TODO(toyoshim): Factor out TaskRunner related functionaliries above, and |
| 89 // deprecate MidiScheduler. It should be available via scheduler(). |
| 90 |
| 91 // Utility class to handle MIDIHDR struct safely. |
| 92 class MIDIHDRDeleter { |
| 93 public: |
| 94 void operator()(LPMIDIHDR header) { |
| 95 if (!header) |
| 96 return; |
| 97 delete[] static_cast<char*>(header->lpData); |
| 98 delete header; |
| 99 } |
| 100 }; |
| 101 |
| 102 using ScopedMIDIHDR = std::unique_ptr<MIDIHDR, MIDIHDRDeleter>; |
| 103 |
| 104 ScopedMIDIHDR CreateMIDIHDR(size_t size) { |
| 105 ScopedMIDIHDR hdr(new MIDIHDR); |
| 106 ZeroMemory(hdr.get(), sizeof(*hdr)); |
| 107 hdr->lpData = new char[size]; |
| 108 hdr->dwBufferLength = static_cast<DWORD>(size); |
| 109 return hdr; |
| 110 } |
| 111 |
| 112 ScopedMIDIHDR CreateMIDIHDR(const std::vector<uint8_t>& data) { |
| 113 ScopedMIDIHDR hdr(CreateMIDIHDR(data.size())); |
| 114 std::copy(data.begin(), data.end(), hdr->lpData); |
| 115 return hdr; |
| 116 } |
| 117 |
| 118 // Helper functions to close MIDI device handles on TaskRunner asynchronously. |
| 119 void FinalizeInPort(HMIDIIN handle, LPMIDIHDR lphdr) { |
| 120 // Resets the device. This stops receiving messages, and allows to release |
| 121 // registered buffer headers. Otherwise, midiInUnprepareHeader() and |
| 122 // midiInClose() will fail with MIDIERR_STILLPLAYING. |
| 123 midiInReset(handle); |
| 124 |
| 125 // Obtains MIDIHDR ownership to release allocated buffers. |
| 126 ScopedMIDIHDR hdr(lphdr); |
| 127 if (hdr) |
| 128 midiInUnprepareHeader(handle, hdr.get(), sizeof(*hdr)); |
| 129 midiInClose(handle); |
| 130 } |
| 131 |
| 132 void FinalizeOutPort(HMIDIOUT handle) { |
| 133 // Resets inflight buffers. This will cancel sending data that system |
| 134 // holds and were not sent yet. |
| 135 midiOutReset(handle); |
| 136 midiOutClose(handle); |
| 137 } |
| 138 |
| 139 // Handles MIDI input port callbacks that runs on a system provided thread. |
| 140 void CALLBACK HandleMidiInCallback(HMIDIIN hmi, |
| 141 UINT msg, |
| 142 DWORD_PTR instance, |
| 143 DWORD_PTR param1, |
| 144 DWORD_PTR param2) { |
| 145 if (msg != MIM_DATA && msg != MIM_LONGDATA) |
| 146 return; |
| 147 int instance_id = static_cast<int>(instance); |
| 148 DynamicallyInitializedMidiManagerWin* manager = nullptr; |
| 149 |
| 150 // Use |g_task_lock| so to ensure the instance can keep alive while running, |
| 151 // and to access member variables that are used on TaskRunner. |
| 152 base::AutoLock task_lock(*GetTaskLock()); |
| 153 { |
| 154 base::AutoLock lock(*GetInstanceIdLock()); |
| 155 if (instance_id != g_active_instance_id) |
| 156 return; |
| 157 manager = g_manager_instance; |
| 158 } |
| 159 |
| 160 auto found = g_hmidiin_to_index_map.find(hmi); |
| 161 if (found == g_hmidiin_to_index_map.end()) |
| 162 return; |
| 163 size_t index = found->second; |
| 164 |
| 165 if (msg == MIM_DATA) { |
| 166 const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff); |
| 167 const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff); |
| 168 const uint8_t second_data_byte = |
| 169 static_cast<uint8_t>((param1 >> 16) & 0xff); |
| 170 const size_t len = GetMessageLength(status_byte); |
| 171 const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte}; |
| 172 std::vector<uint8_t> data; |
| 173 data.assign(kData, kData + len); |
| 174 manager->PostReplyTask( |
| 175 base::Bind(&DynamicallyInitializedMidiManagerWin::ReceiveMidiData, |
| 176 base::Unretained(manager), index, data, |
| 177 manager->CalculateInEventTime(index, param2))); |
| 178 } else { // msg == MIM_LONGDATA |
| 179 LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1); |
| 180 if (hdr->dwBytesRecorded > 0) { |
| 181 const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData); |
| 182 std::vector<uint8_t> data; |
| 183 data.assign(src, src + hdr->dwBytesRecorded); |
| 184 manager->PostReplyTask( |
| 185 base::Bind(&DynamicallyInitializedMidiManagerWin::ReceiveMidiData, |
| 186 base::Unretained(manager), index, data, |
| 187 manager->CalculateInEventTime(index, param2))); |
| 188 } |
| 189 // TODO(toyoshim): Call midiInAddBuffer outside the callback. |
| 190 midiInAddBuffer(hmi, hdr, sizeof(*hdr)); |
| 191 } |
| 192 } |
| 193 |
| 194 // Handles MIDI output port callbacks that runs on a system provided thread. |
| 195 void CALLBACK HandleMidiOutCallback(HMIDIOUT hmo, |
| 196 UINT msg, |
| 197 DWORD_PTR instance, |
| 198 DWORD_PTR param1, |
| 199 DWORD_PTR param2) { |
| 200 if (msg == MOM_DONE) { |
| 201 ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1)); |
| 202 if (!hdr) |
| 203 return; |
| 204 // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback. |
| 205 midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr)); |
| 206 } |
| 207 } |
| 208 |
| 209 enum class EnumerateState { Connected, Enumerating }; |
| 210 |
| 211 class Port { |
| 212 public: |
| 213 Port(const std::string& type, |
| 214 uint32_t device_id, |
| 215 uint16_t manufacturer_id, |
| 216 uint16_t product_id, |
| 217 uint32_t driver_version, |
| 218 const std::string& product_name) |
| 219 : index_(0u), |
| 220 type_(type), |
| 221 device_id_(device_id), |
| 222 manufacturer_id_(manufacturer_id), |
| 223 product_id_(product_id), |
| 224 driver_version_(driver_version), |
| 225 product_name_(product_name), |
| 226 enumerate_state_(EnumerateState::Enumerating) { |
| 227 info_.manufacturer = "unknown"; // TODO(toyoshim): Use USB information. |
| 228 info_.name = product_name_; |
| 229 info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_), |
| 230 LOBYTE(driver_version_)); |
| 231 info_.state = mojom::PortState::DISCONNECTED; |
| 232 } |
| 233 |
| 234 bool operator==(const Port& other) const { |
| 235 // Should not use |device_id| for comparison because it can be changed on |
| 236 // each enumeration. |
| 237 // Since the GUID will be changed on each enumeration for Microsoft GS |
| 238 // Wavetable synth and might be done for others, do not use it for device |
| 239 // comparison. |
| 240 return manufacturer_id_ == other.manufacturer_id_ && |
| 241 product_id_ == other.product_id_ && |
| 242 driver_version_ == other.driver_version_ && |
| 243 product_name_ == other.product_name_; |
| 244 } |
| 245 |
| 246 bool IsConnected() const { |
| 247 return info_.state != mojom::PortState::DISCONNECTED; |
| 248 } |
| 249 |
| 250 void set_index(size_t index) { |
| 251 index_ = index; |
| 252 // TODO(toyoshim): Use hashed ID. |
| 253 info_.id = base::StringPrintf("%s-%d", type_.c_str(), index_); |
| 254 } |
| 255 size_t index() { return index_; } |
| 256 void set_device_id(uint32_t device_id) { device_id_ = device_id; } |
| 257 void set_enumerate_state(EnumerateState state) { enumerate_state_ = state; } |
| 258 EnumerateState enumerate_state() { return enumerate_state_; } |
| 259 const MidiPortInfo& info() { return info_; } |
| 260 |
| 261 virtual void Connect() { |
| 262 info_.state = mojom::PortState::CONNECTED; |
| 263 // TODO(toyoshim) Until open() / close() are supported, open each device on |
| 264 // connected. |
| 265 Open(); |
| 266 } |
| 267 |
| 268 virtual void Disconnect() { info_.state = mojom::PortState::DISCONNECTED; } |
| 269 |
| 270 virtual void Open() { info_.state = mojom::PortState::OPENED; } |
| 271 |
| 272 protected: |
| 273 size_t index_; |
| 274 std::string type_; |
| 275 uint32_t device_id_; |
| 276 const uint16_t manufacturer_id_; |
| 277 const uint16_t product_id_; |
| 278 const uint32_t driver_version_; |
| 279 const std::string product_name_; |
| 280 MidiPortInfo info_; |
| 281 EnumerateState enumerate_state_; |
| 282 }; // class Port |
| 283 |
| 284 } // namespace |
| 285 |
| 286 class DynamicallyInitializedMidiManagerWin::InPort final : public Port { |
| 287 public: |
| 288 InPort(int instance_id, UINT device_id, const MIDIINCAPS2W& caps) |
| 289 : Port("input", |
| 290 device_id, |
| 291 caps.wMid, |
| 292 caps.wPid, |
| 293 caps.vDriverVersion, |
| 294 base::WideToUTF8( |
| 295 base::string16(caps.szPname, wcslen(caps.szPname)))), |
| 296 in_handle_(kInvalidInHandle), |
| 297 instance_id_(instance_id) {} |
| 298 |
| 299 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) { |
| 300 if (in_handle_ != kInvalidInHandle) |
| 301 runner->PostTask(FROM_HERE, |
| 302 base::Bind(&FinalizeInPort, in_handle_, hdr_.release())); |
| 303 } |
| 304 |
| 305 base::TimeTicks CalculateInEventTime(uint32_t elapsed_ms) const { |
| 306 return start_time_ + base::TimeDelta::FromMilliseconds(elapsed_ms); |
| 307 } |
| 308 |
| 309 // Port overrides: |
| 310 void Open() override { |
| 311 MMRESULT result = |
| 312 midiInOpen(&in_handle_, device_id_, |
| 313 reinterpret_cast<DWORD_PTR>(&HandleMidiInCallback), |
| 314 instance_id_, CALLBACK_FUNCTION); |
| 315 if (result == MMSYSERR_NOERROR) { |
| 316 hdr_ = CreateMIDIHDR(kBufferLength); |
| 317 result = midiInPrepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_)); |
| 318 } |
| 319 if (result != MMSYSERR_NOERROR) |
| 320 in_handle_ = kInvalidInHandle; |
| 321 if (result == MMSYSERR_NOERROR) |
| 322 result = midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_)); |
| 323 if (result == MMSYSERR_NOERROR) |
| 324 result = midiInStart(in_handle_); |
| 325 if (result == MMSYSERR_NOERROR) { |
| 326 start_time_ = base::TimeTicks::Now(); |
| 327 g_hmidiin_to_index_map[in_handle_] = index_; |
| 328 Port::Open(); |
| 329 } else { |
| 330 if (in_handle_ != kInvalidInHandle) { |
| 331 midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_)); |
| 332 midiInClose(in_handle_); |
| 333 in_handle_ = kInvalidInHandle; |
| 334 } |
| 335 Disconnect(); |
| 336 } |
| 337 } |
| 338 |
| 339 private: |
| 340 HMIDIIN in_handle_; |
| 341 ScopedMIDIHDR hdr_; |
| 342 base::TimeTicks start_time_; |
| 343 int instance_id_; |
| 344 }; |
| 345 |
| 346 class DynamicallyInitializedMidiManagerWin::OutPort final : public Port { |
| 347 public: |
| 348 OutPort(UINT device_id, const MIDIOUTCAPS2W& caps) |
| 349 : Port("output", |
| 350 device_id, |
| 351 caps.wMid, |
| 352 caps.wPid, |
| 353 caps.vDriverVersion, |
| 354 base::WideToUTF8( |
| 355 base::string16(caps.szPname, wcslen(caps.szPname)))), |
| 356 software_(caps.wTechnology == MOD_SWSYNTH), |
| 357 out_handle_(kInvalidOutHandle) {} |
| 358 |
| 359 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) { |
| 360 if (out_handle_ != kInvalidOutHandle) |
| 361 runner->PostTask(FROM_HERE, base::Bind(&FinalizeOutPort, out_handle_)); |
| 362 } |
| 363 |
| 364 void Send(const std::vector<uint8_t>& data) { |
| 365 if (out_handle_ == kInvalidOutHandle) |
| 366 return; |
| 367 |
| 368 if (data.size() <= 3) { |
| 369 DWORD message = 0; |
| 370 for (size_t i = 0; i < data.size(); ++i) |
| 371 message |= (static_cast<uint32_t>(data[i]) << (i * 8)); |
| 372 midiOutShortMsg(out_handle_, message); |
| 373 } else { |
| 374 if (data.size() > kSysExSizeLimit) { |
| 375 LOG(ERROR) << "Ignoring SysEx message due to the size limit" |
| 376 << ", size = " << data.size(); |
| 377 // TODO(toyoshim): Consider to report metrics here. |
| 378 return; |
| 379 } |
| 380 ScopedMIDIHDR hdr(CreateMIDIHDR(data)); |
| 381 MMRESULT result = |
| 382 midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr)); |
| 383 if (result != MMSYSERR_NOERROR) |
| 384 return; |
| 385 result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr)); |
| 386 if (result != MMSYSERR_NOERROR) |
| 387 midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr)); |
| 388 else |
| 389 ignore_result(hdr.release()); |
| 390 // MIDIHDR will be released on MOM_DONE. |
| 391 } |
| 392 } |
| 393 |
| 394 // Port overrides: |
| 395 void Connect() override { |
| 396 // Until |software| option is supported, disable Microsoft GS Wavetable |
| 397 // Synth that has a known security issue. |
| 398 if (software_ && manufacturer_id_ == MM_MICROSOFT && |
| 399 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT || |
| 400 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) { |
| 401 return; |
| 402 } |
| 403 Port::Connect(); |
| 404 } |
| 405 |
| 406 void Open() override { |
| 407 MMRESULT result = |
| 408 midiOutOpen(&out_handle_, device_id_, |
| 409 reinterpret_cast<DWORD_PTR>(&HandleMidiOutCallback), 0, |
| 410 CALLBACK_FUNCTION); |
| 411 if (result == MMSYSERR_NOERROR) { |
| 412 Port::Open(); |
| 413 } else { |
| 414 out_handle_ = kInvalidOutHandle; |
| 415 Disconnect(); |
| 416 } |
| 417 } |
| 418 |
| 419 private: |
| 420 const bool software_; |
| 421 HMIDIOUT out_handle_; |
| 422 }; |
| 423 |
| 424 DynamicallyInitializedMidiManagerWin::DynamicallyInitializedMidiManagerWin( |
| 425 MidiService* service) |
| 426 : MidiManager(service), instance_id_(kInvalidInstanceId) { |
| 427 base::AutoLock lock(*GetInstanceIdLock()); |
| 428 CHECK_EQ(kInvalidInstanceId, g_active_instance_id); |
| 429 |
| 430 // Obtains the task runner for the current thread that hosts this instnace. |
| 431 thread_runner_ = base::ThreadTaskRunnerHandle::Get(); |
| 432 } |
| 433 |
| 434 DynamicallyInitializedMidiManagerWin::~DynamicallyInitializedMidiManagerWin() { |
| 435 base::AutoLock lock(*GetInstanceIdLock()); |
| 436 CHECK_EQ(kInvalidInstanceId, g_active_instance_id); |
| 437 } |
| 438 |
| 439 base::TimeTicks DynamicallyInitializedMidiManagerWin::CalculateInEventTime( |
| 440 size_t index, |
| 441 uint32_t elapsed_ms) const { |
| 442 GetTaskLock()->AssertAcquired(); |
| 443 CHECK_GT(input_ports_.size(), index); |
| 444 return input_ports_[index]->CalculateInEventTime(elapsed_ms); |
| 445 } |
| 446 |
| 447 void DynamicallyInitializedMidiManagerWin::ReceiveMidiData( |
| 448 uint32_t index, |
| 449 const std::vector<uint8_t>& data, |
| 450 base::TimeTicks time) { |
| 451 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time); |
| 452 } |
| 453 |
| 454 void DynamicallyInitializedMidiManagerWin::PostReplyTask( |
| 455 const base::Closure& task) { |
| 456 thread_runner_->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task)); |
| 457 } |
| 458 |
| 459 void DynamicallyInitializedMidiManagerWin::StartInitialization() { |
| 460 { |
| 461 base::AutoLock lock(*GetInstanceIdLock()); |
| 462 CHECK_EQ(kInvalidInstanceId, g_active_instance_id); |
| 463 instance_id_ = g_next_instance_id++; |
| 464 g_active_instance_id = instance_id_; |
| 465 CHECK_EQ(nullptr, g_manager_instance); |
| 466 g_manager_instance = this; |
| 467 } |
| 468 // Registers on the I/O thread to be notified on the I/O thread. |
| 469 CHECK(thread_runner_->BelongsToCurrentThread()); |
| 470 base::SystemMonitor::Get()->AddDevicesChangedObserver(this); |
| 471 |
| 472 // Starts asynchronous initialization on TaskRunner. |
| 473 PostTask( |
| 474 base::Bind(&DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner, |
| 475 base::Unretained(this))); |
| 476 } |
| 477 |
| 478 void DynamicallyInitializedMidiManagerWin::Finalize() { |
| 479 // Unregisters on the I/O thread. |
| 480 CHECK(thread_runner_->BelongsToCurrentThread()); |
| 481 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this); |
| 482 { |
| 483 base::AutoLock lock(*GetInstanceIdLock()); |
| 484 CHECK_EQ(instance_id_, g_active_instance_id); |
| 485 g_active_instance_id = kInvalidInstanceId; |
| 486 CHECK_EQ(this, g_manager_instance); |
| 487 g_manager_instance = nullptr; |
| 488 } |
| 489 |
| 490 // Ensures that no task runs on TaskRunner so to destruct the instance safely. |
| 491 // Tasks that did not started yet will do nothing after invalidate the |
| 492 // instance ID above. |
| 493 base::AutoLock lock(*GetTaskLock()); |
| 494 |
| 495 // Posts tasks that finalize each device port without MidiManager instance |
| 496 // on TaskRunner. |
| 497 for (const auto& port : input_ports_) |
| 498 port->Finalize(service()->GetTaskRunner(kTaskRunner)); |
| 499 for (const auto& port : output_ports_) |
| 500 port->Finalize(service()->GetTaskRunner(kTaskRunner)); |
| 501 } |
| 502 |
| 503 void DynamicallyInitializedMidiManagerWin::DispatchSendMidiData( |
| 504 MidiManagerClient* client, |
| 505 uint32_t port_index, |
| 506 const std::vector<uint8_t>& data, |
| 507 double timestamp) { |
| 508 if (timestamp != 0.0) { |
| 509 base::TimeTicks time = |
| 510 base::TimeTicks() + base::TimeDelta::FromMicroseconds( |
| 511 timestamp * base::Time::kMicrosecondsPerSecond); |
| 512 base::TimeTicks now = base::TimeTicks::Now(); |
| 513 if (now < time) { |
| 514 PostDelayedTask( |
| 515 base::Bind(&DynamicallyInitializedMidiManagerWin::SendOnTaskRunner, |
| 516 base::Unretained(this), client, port_index, data), |
| 517 time - now); |
| 518 return; |
| 519 } |
| 520 } |
| 521 PostTask(base::Bind(&DynamicallyInitializedMidiManagerWin::SendOnTaskRunner, |
| 522 base::Unretained(this), client, port_index, data)); |
| 523 } |
| 524 |
| 525 void DynamicallyInitializedMidiManagerWin::OnDevicesChanged( |
| 526 base::SystemMonitor::DeviceType device_type) { |
| 527 // Notified on the I/O thread. |
| 528 CHECK(thread_runner_->BelongsToCurrentThread()); |
| 529 |
| 530 switch (device_type) { |
| 531 case base::SystemMonitor::DEVTYPE_AUDIO: |
| 532 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE: |
| 533 // Add case of other unrelated device types here. |
| 534 return; |
| 535 case base::SystemMonitor::DEVTYPE_UNKNOWN: { |
| 536 base::AutoLock lock(*GetInstanceIdLock()); |
| 537 if (instance_id_ != g_active_instance_id) |
| 538 return; |
| 539 PostTask(base::Bind( |
| 540 &DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner, |
| 541 base::Unretained(this))); |
| 542 break; |
| 543 } |
| 544 } |
| 545 } |
| 546 |
| 547 void DynamicallyInitializedMidiManagerWin::PostTask(const base::Closure& task) { |
| 548 service() |
| 549 ->GetTaskRunner(kTaskRunner) |
| 550 ->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task)); |
| 551 } |
| 552 |
| 553 void DynamicallyInitializedMidiManagerWin::PostDelayedTask( |
| 554 const base::Closure& task, |
| 555 base::TimeDelta delay) { |
| 556 service() |
| 557 ->GetTaskRunner(kTaskRunner) |
| 558 ->PostDelayedTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task), |
| 559 delay); |
| 560 } |
| 561 |
| 562 void DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner() { |
| 563 UpdateDeviceListOnTaskRunner(); |
| 564 PostReplyTask( |
| 565 base::Bind(&DynamicallyInitializedMidiManagerWin::CompleteInitialization, |
| 566 base::Unretained(this), mojom::Result::OK)); |
| 567 } |
| 568 |
| 569 void DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner() { |
| 570 // Update the devie list for input ports. |
| 571 // First, mark all registered input ports to |EnumerateState::Enumerating|. |
| 572 for (const auto& port : input_ports_) |
| 573 port->set_enumerate_state(EnumerateState::Enumerating); |
| 574 |
| 575 std::vector<std::unique_ptr<InPort>> new_input_ports; |
| 576 const UINT num_in_devices = midiInGetNumDevs(); |
| 577 for (UINT device_id = 0; device_id < num_in_devices; ++device_id) { |
| 578 MIDIINCAPS2W caps; |
| 579 MMRESULT result = midiInGetDevCaps( |
| 580 device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps)); |
| 581 if (result != MMSYSERR_NOERROR) { |
| 582 LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id; |
| 583 continue; |
| 584 } |
| 585 std::unique_ptr<InPort> port = |
| 586 base::MakeUnique<InPort>(instance_id_, device_id, caps); |
| 587 const auto& found = std::find_if( |
| 588 input_ports_.begin(), input_ports_.end(), |
| 589 [&port](const auto& candidate) { return *candidate == *port; }); |
| 590 if (found == input_ports_.end()) { |
| 591 new_input_ports.push_back(std::move(port)); |
| 592 } else { |
| 593 // Update device ID which may be changed when device list is updated. |
| 594 (*found)->set_device_id(device_id); |
| 595 (*found)->set_enumerate_state(EnumerateState::Connected); |
| 596 } |
| 597 } |
| 598 for (const auto& port : input_ports_) { |
| 599 if (port->enumerate_state() == EnumerateState::Enumerating) { |
| 600 // Disconnected ports have kept staying in |EnumerateState::Enumerating| |
| 601 // state as they were marked first. |
| 602 if (port->IsConnected()) { |
| 603 port->Disconnect(); |
| 604 PostReplyTask(base::Bind( |
| 605 &DynamicallyInitializedMidiManagerWin::SetInputPortState, |
| 606 base::Unretained(this), port->index(), port->info().state)); |
| 607 } |
| 608 } else if (port->enumerate_state() == EnumerateState::Connected) { |
| 609 // Ports that have been connected, and are going to be connected now are |
| 610 // in |EnumerateState::Connected| state. |
| 611 if (!port->IsConnected()) { |
| 612 port->Connect(); |
| 613 PostReplyTask(base::Bind( |
| 614 &DynamicallyInitializedMidiManagerWin::SetInputPortState, |
| 615 base::Unretained(this), port->index(), port->info().state)); |
| 616 } |
| 617 } |
| 618 } |
| 619 // Assign port index to new devices and move them to the port list. |
| 620 size_t in_index = input_ports_.size(); |
| 621 for (const auto& port : new_input_ports) { |
| 622 port->set_index(in_index++); |
| 623 port->Connect(); |
| 624 PostReplyTask( |
| 625 base::Bind(&DynamicallyInitializedMidiManagerWin::AddInputPort, |
| 626 base::Unretained(this), port->info())); |
| 627 } |
| 628 input_ports_.insert(input_ports_.end(), |
| 629 std::make_move_iterator(new_input_ports.begin()), |
| 630 std::make_move_iterator(new_input_ports.end())); |
| 631 |
| 632 // Update the devie list for output ports. |
| 633 // First, mark all registered output ports to |EnumerateState::Enumerating|. |
| 634 for (const auto& port : output_ports_) |
| 635 port->set_enumerate_state(EnumerateState::Enumerating); |
| 636 |
| 637 std::vector<std::unique_ptr<OutPort>> new_output_ports; |
| 638 const UINT num_out_devices = midiOutGetNumDevs(); |
| 639 for (UINT device_id = 0; device_id < num_out_devices; ++device_id) { |
| 640 MIDIOUTCAPS2W caps; |
| 641 MMRESULT result = midiOutGetDevCaps( |
| 642 device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps)); |
| 643 if (result != MMSYSERR_NOERROR) { |
| 644 LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id; |
| 645 continue; |
| 646 } |
| 647 std::unique_ptr<OutPort> port = base::MakeUnique<OutPort>(device_id, caps); |
| 648 const auto& found = std::find_if( |
| 649 output_ports_.begin(), output_ports_.end(), |
| 650 [&port](const auto& candidate) { return *candidate == *port; }); |
| 651 if (found == output_ports_.end()) { |
| 652 new_output_ports.push_back(std::move(port)); |
| 653 } else { |
| 654 // Update device ID which may be changed when device list is updated. |
| 655 (*found)->set_device_id(device_id); |
| 656 (*found)->set_enumerate_state(EnumerateState::Connected); |
| 657 } |
| 658 } |
| 659 for (const auto& port : output_ports_) { |
| 660 if (port->enumerate_state() == EnumerateState::Enumerating) { |
| 661 // Disconnected ports have kept staying in |EnumerateState::Enumerating| |
| 662 // state as they were marked first. |
| 663 if (port->IsConnected()) { |
| 664 port->Disconnect(); |
| 665 PostReplyTask(base::Bind( |
| 666 &DynamicallyInitializedMidiManagerWin::SetOutputPortState, |
| 667 base::Unretained(this), port->index(), port->info().state)); |
| 668 } |
| 669 } else if (port->enumerate_state() == EnumerateState::Connected) { |
| 670 // Ports that have been connected, and are going to be connected now are |
| 671 // in |EnumerateState::Connected| state. |
| 672 if (!port->IsConnected()) { |
| 673 port->Connect(); |
| 674 // Connect() won't change the state on output ports for software synth. |
| 675 if (port->IsConnected()) { |
| 676 PostReplyTask(base::Bind( |
| 677 &DynamicallyInitializedMidiManagerWin::SetOutputPortState, |
| 678 base::Unretained(this), port->index(), port->info().state)); |
| 679 } |
| 680 } |
| 681 } |
| 682 } |
| 683 // Assign port index to new devices and move them to the port list. |
| 684 size_t out_index = output_ports_.size(); |
| 685 for (const auto& port : new_output_ports) { |
| 686 port->set_index(out_index++); |
| 687 port->Connect(); |
| 688 PostReplyTask( |
| 689 base::Bind(&DynamicallyInitializedMidiManagerWin::AddOutputPort, |
| 690 base::Unretained(this), port->info())); |
| 691 } |
| 692 output_ports_.insert(output_ports_.end(), |
| 693 std::make_move_iterator(new_output_ports.begin()), |
| 694 std::make_move_iterator(new_output_ports.end())); |
| 695 |
| 696 // TODO(toyoshim): This method may run before internal MIDI device lists that |
| 697 // Windows manages were updated. This may be because MIDI driver may be loaded |
| 698 // after the raw device list was updated. To avoid this problem, we may want |
| 699 // to retry device check later if no changes are detected here. |
| 700 } |
| 701 |
| 702 void DynamicallyInitializedMidiManagerWin::SendOnTaskRunner( |
| 703 MidiManagerClient* client, |
| 704 uint32_t port_index, |
| 705 const std::vector<uint8_t>& data) { |
| 706 CHECK_GT(output_ports_.size(), port_index); |
| 707 output_ports_[port_index]->Send(data); |
| 708 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent. |
| 709 PostReplyTask( |
| 710 base::Bind(&DynamicallyInitializedMidiManagerWin::AccumulateMidiBytesSent, |
| 711 base::Unretained(this), client, data.size())); |
| 712 } |
| 713 |
| 714 } // namespace midi |
OLD | NEW |