| Index: media/midi/dynamically_initialized_midi_manager_win.cc
|
| diff --git a/media/midi/dynamically_initialized_midi_manager_win.cc b/media/midi/dynamically_initialized_midi_manager_win.cc
|
| new file mode 100644
|
| index 0000000000000000000000000000000000000000..619991e6b32c89beb8389e6d1e06e3bbd2e61545
|
| --- /dev/null
|
| +++ b/media/midi/dynamically_initialized_midi_manager_win.cc
|
| @@ -0,0 +1,714 @@
|
| +// Copyright 2017 The Chromium Authors. All rights reserved.
|
| +// Use of this source code is governed by a BSD-style license that can be
|
| +// found in the LICENSE file.
|
| +
|
| +#include "media/midi/dynamically_initialized_midi_manager_win.h"
|
| +
|
| +#include <windows.h>
|
| +
|
| +#include <mmreg.h>
|
| +#include <mmsystem.h>
|
| +
|
| +#include <algorithm>
|
| +#include <string>
|
| +
|
| +#include "base/callback.h"
|
| +#include "base/lazy_instance.h"
|
| +#include "base/logging.h"
|
| +#include "base/memory/ptr_util.h"
|
| +#include "base/strings/string16.h"
|
| +#include "base/strings/stringprintf.h"
|
| +#include "base/strings/utf_string_conversions.h"
|
| +#include "base/synchronization/lock.h"
|
| +#include "base/time/time.h"
|
| +#include "media/midi/message_util.h"
|
| +#include "media/midi/midi_port_info.h"
|
| +#include "media/midi/midi_service.h"
|
| +
|
| +namespace midi {
|
| +
|
| +namespace {
|
| +
|
| +// Assumes that nullptr represents an invalid MIDI handle.
|
| +constexpr HMIDIIN kInvalidInHandle = nullptr;
|
| +constexpr HMIDIOUT kInvalidOutHandle = nullptr;
|
| +
|
| +// Defines SysEx message size limit.
|
| +// TODO(crbug.com/383578): This restriction should be removed once Web MIDI
|
| +// defines a standardized way to handle large sysex messages.
|
| +// Note for built-in USB-MIDI driver:
|
| +// From an observation on Windows 7/8.1 with a USB-MIDI keyboard,
|
| +// midiOutLongMsg() will be always blocked. Sending 64 bytes or less data takes
|
| +// roughly 300 usecs. Sending 2048 bytes or more data takes roughly
|
| +// |message.size() / (75 * 1024)| secs in practice. Here we put 256 KB size
|
| +// limit on SysEx message, with hoping that midiOutLongMsg will be blocked at
|
| +// most 4 sec or so with a typical USB-MIDI device.
|
| +// TODO(toyoshim): Consider to use linked small buffers so that midiOutReset()
|
| +// can abort sending unhandled following buffers.
|
| +constexpr size_t kSysExSizeLimit = 256 * 1024;
|
| +
|
| +// Defines input buffer size.
|
| +constexpr size_t kBufferLength = 32 * 1024;
|
| +
|
| +// Global variables to identify MidiManager instance.
|
| +constexpr int kInvalidInstanceId = -1;
|
| +int g_active_instance_id = kInvalidInstanceId;
|
| +int g_next_instance_id = 0;
|
| +DynamicallyInitializedMidiManagerWin* g_manager_instance = nullptr;
|
| +
|
| +// Global map to resolve MIDI input port index from HMIDIIN.
|
| +std::map<HMIDIIN, size_t> g_hmidiin_to_index_map;
|
| +
|
| +// Obtains base::Lock instance pointer to lock instance_id.
|
| +base::Lock* GetInstanceIdLock() {
|
| + static base::Lock* lock = new base::Lock;
|
| + return lock;
|
| +}
|
| +
|
| +// Use single TaskRunner for all tasks running outside the I/O thread.
|
| +constexpr int kTaskRunner = 0;
|
| +
|
| +// Obtains base::Lock instance pointer to ensure tasks run safely on TaskRunner.
|
| +base::Lock* GetTaskLock() {
|
| + static base::Lock* lock = new base::Lock;
|
| + return lock;
|
| +}
|
| +
|
| +// Helper function to run a posted task on TaskRunner safely.
|
| +void RunTask(int instance_id, const base::Closure& task) {
|
| + base::AutoLock task_lock(*GetTaskLock());
|
| + {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + if (instance_id != g_active_instance_id)
|
| + return;
|
| + }
|
| + task.Run();
|
| +}
|
| +
|
| +// TODO(toyoshim): Factor out TaskRunner related functionaliries above, and
|
| +// deprecate MidiScheduler. It should be available via scheduler().
|
| +
|
| +// Utility class to handle MIDIHDR struct safely.
|
| +class MIDIHDRDeleter {
|
| + public:
|
| + void operator()(LPMIDIHDR header) {
|
| + if (!header)
|
| + return;
|
| + delete[] static_cast<char*>(header->lpData);
|
| + delete header;
|
| + }
|
| +};
|
| +
|
| +using ScopedMIDIHDR = std::unique_ptr<MIDIHDR, MIDIHDRDeleter>;
|
| +
|
| +ScopedMIDIHDR CreateMIDIHDR(size_t size) {
|
| + ScopedMIDIHDR hdr(new MIDIHDR);
|
| + ZeroMemory(hdr.get(), sizeof(*hdr));
|
| + hdr->lpData = new char[size];
|
| + hdr->dwBufferLength = static_cast<DWORD>(size);
|
| + return hdr;
|
| +}
|
| +
|
| +ScopedMIDIHDR CreateMIDIHDR(const std::vector<uint8_t>& data) {
|
| + ScopedMIDIHDR hdr(CreateMIDIHDR(data.size()));
|
| + std::copy(data.begin(), data.end(), hdr->lpData);
|
| + return hdr;
|
| +}
|
| +
|
| +// Helper functions to close MIDI device handles on TaskRunner asynchronously.
|
| +void FinalizeInPort(HMIDIIN handle, LPMIDIHDR lphdr) {
|
| + // Resets the device. This stops receiving messages, and allows to release
|
| + // registered buffer headers. Otherwise, midiInUnprepareHeader() and
|
| + // midiInClose() will fail with MIDIERR_STILLPLAYING.
|
| + midiInReset(handle);
|
| +
|
| + // Obtains MIDIHDR ownership to release allocated buffers.
|
| + ScopedMIDIHDR hdr(lphdr);
|
| + if (hdr)
|
| + midiInUnprepareHeader(handle, hdr.get(), sizeof(*hdr));
|
| + midiInClose(handle);
|
| +}
|
| +
|
| +void FinalizeOutPort(HMIDIOUT handle) {
|
| + // Resets inflight buffers. This will cancel sending data that system
|
| + // holds and were not sent yet.
|
| + midiOutReset(handle);
|
| + midiOutClose(handle);
|
| +}
|
| +
|
| +// Handles MIDI input port callbacks that runs on a system provided thread.
|
| +void CALLBACK HandleMidiInCallback(HMIDIIN hmi,
|
| + UINT msg,
|
| + DWORD_PTR instance,
|
| + DWORD_PTR param1,
|
| + DWORD_PTR param2) {
|
| + if (msg != MIM_DATA && msg != MIM_LONGDATA)
|
| + return;
|
| + int instance_id = static_cast<int>(instance);
|
| + DynamicallyInitializedMidiManagerWin* manager = nullptr;
|
| +
|
| + // Use |g_task_lock| so to ensure the instance can keep alive while running,
|
| + // and to access member variables that are used on TaskRunner.
|
| + base::AutoLock task_lock(*GetTaskLock());
|
| + {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + if (instance_id != g_active_instance_id)
|
| + return;
|
| + manager = g_manager_instance;
|
| + }
|
| +
|
| + auto found = g_hmidiin_to_index_map.find(hmi);
|
| + if (found == g_hmidiin_to_index_map.end())
|
| + return;
|
| + size_t index = found->second;
|
| +
|
| + if (msg == MIM_DATA) {
|
| + const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff);
|
| + const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff);
|
| + const uint8_t second_data_byte =
|
| + static_cast<uint8_t>((param1 >> 16) & 0xff);
|
| + const size_t len = GetMessageLength(status_byte);
|
| + const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte};
|
| + std::vector<uint8_t> data;
|
| + data.assign(kData, kData + len);
|
| + manager->PostReplyTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::ReceiveMidiData,
|
| + base::Unretained(manager), index, data,
|
| + manager->CalculateInEventTime(index, param2)));
|
| + } else { // msg == MIM_LONGDATA
|
| + LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1);
|
| + if (hdr->dwBytesRecorded > 0) {
|
| + const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData);
|
| + std::vector<uint8_t> data;
|
| + data.assign(src, src + hdr->dwBytesRecorded);
|
| + manager->PostReplyTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::ReceiveMidiData,
|
| + base::Unretained(manager), index, data,
|
| + manager->CalculateInEventTime(index, param2)));
|
| + }
|
| + // TODO(toyoshim): Call midiInAddBuffer outside the callback.
|
| + midiInAddBuffer(hmi, hdr, sizeof(*hdr));
|
| + }
|
| +}
|
| +
|
| +// Handles MIDI output port callbacks that runs on a system provided thread.
|
| +void CALLBACK HandleMidiOutCallback(HMIDIOUT hmo,
|
| + UINT msg,
|
| + DWORD_PTR instance,
|
| + DWORD_PTR param1,
|
| + DWORD_PTR param2) {
|
| + if (msg == MOM_DONE) {
|
| + ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1));
|
| + if (!hdr)
|
| + return;
|
| + // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback.
|
| + midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr));
|
| + }
|
| +}
|
| +
|
| +enum class EnumerateState { Connected, Enumerating };
|
| +
|
| +class Port {
|
| + public:
|
| + Port(const std::string& type,
|
| + uint32_t device_id,
|
| + uint16_t manufacturer_id,
|
| + uint16_t product_id,
|
| + uint32_t driver_version,
|
| + const std::string& product_name)
|
| + : index_(0u),
|
| + type_(type),
|
| + device_id_(device_id),
|
| + manufacturer_id_(manufacturer_id),
|
| + product_id_(product_id),
|
| + driver_version_(driver_version),
|
| + product_name_(product_name),
|
| + enumerate_state_(EnumerateState::Enumerating) {
|
| + info_.manufacturer = "unknown"; // TODO(toyoshim): Use USB information.
|
| + info_.name = product_name_;
|
| + info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_),
|
| + LOBYTE(driver_version_));
|
| + info_.state = mojom::PortState::DISCONNECTED;
|
| + }
|
| +
|
| + bool operator==(const Port& other) const {
|
| + // Should not use |device_id| for comparison because it can be changed on
|
| + // each enumeration.
|
| + // Since the GUID will be changed on each enumeration for Microsoft GS
|
| + // Wavetable synth and might be done for others, do not use it for device
|
| + // comparison.
|
| + return manufacturer_id_ == other.manufacturer_id_ &&
|
| + product_id_ == other.product_id_ &&
|
| + driver_version_ == other.driver_version_ &&
|
| + product_name_ == other.product_name_;
|
| + }
|
| +
|
| + bool IsConnected() const {
|
| + return info_.state != mojom::PortState::DISCONNECTED;
|
| + }
|
| +
|
| + void set_index(size_t index) {
|
| + index_ = index;
|
| + // TODO(toyoshim): Use hashed ID.
|
| + info_.id = base::StringPrintf("%s-%d", type_.c_str(), index_);
|
| + }
|
| + size_t index() { return index_; }
|
| + void set_device_id(uint32_t device_id) { device_id_ = device_id; }
|
| + void set_enumerate_state(EnumerateState state) { enumerate_state_ = state; }
|
| + EnumerateState enumerate_state() { return enumerate_state_; }
|
| + const MidiPortInfo& info() { return info_; }
|
| +
|
| + virtual void Connect() {
|
| + info_.state = mojom::PortState::CONNECTED;
|
| + // TODO(toyoshim) Until open() / close() are supported, open each device on
|
| + // connected.
|
| + Open();
|
| + }
|
| +
|
| + virtual void Disconnect() { info_.state = mojom::PortState::DISCONNECTED; }
|
| +
|
| + virtual void Open() { info_.state = mojom::PortState::OPENED; }
|
| +
|
| + protected:
|
| + size_t index_;
|
| + std::string type_;
|
| + uint32_t device_id_;
|
| + const uint16_t manufacturer_id_;
|
| + const uint16_t product_id_;
|
| + const uint32_t driver_version_;
|
| + const std::string product_name_;
|
| + MidiPortInfo info_;
|
| + EnumerateState enumerate_state_;
|
| +}; // class Port
|
| +
|
| +} // namespace
|
| +
|
| +class DynamicallyInitializedMidiManagerWin::InPort final : public Port {
|
| + public:
|
| + InPort(int instance_id, UINT device_id, const MIDIINCAPS2W& caps)
|
| + : Port("input",
|
| + device_id,
|
| + caps.wMid,
|
| + caps.wPid,
|
| + caps.vDriverVersion,
|
| + base::WideToUTF8(
|
| + base::string16(caps.szPname, wcslen(caps.szPname)))),
|
| + in_handle_(kInvalidInHandle),
|
| + instance_id_(instance_id) {}
|
| +
|
| + void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
|
| + if (in_handle_ != kInvalidInHandle)
|
| + runner->PostTask(FROM_HERE,
|
| + base::Bind(&FinalizeInPort, in_handle_, hdr_.release()));
|
| + }
|
| +
|
| + base::TimeTicks CalculateInEventTime(uint32_t elapsed_ms) const {
|
| + return start_time_ + base::TimeDelta::FromMilliseconds(elapsed_ms);
|
| + }
|
| +
|
| + // Port overrides:
|
| + void Open() override {
|
| + MMRESULT result =
|
| + midiInOpen(&in_handle_, device_id_,
|
| + reinterpret_cast<DWORD_PTR>(&HandleMidiInCallback),
|
| + instance_id_, CALLBACK_FUNCTION);
|
| + if (result == MMSYSERR_NOERROR) {
|
| + hdr_ = CreateMIDIHDR(kBufferLength);
|
| + result = midiInPrepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
|
| + }
|
| + if (result != MMSYSERR_NOERROR)
|
| + in_handle_ = kInvalidInHandle;
|
| + if (result == MMSYSERR_NOERROR)
|
| + result = midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
|
| + if (result == MMSYSERR_NOERROR)
|
| + result = midiInStart(in_handle_);
|
| + if (result == MMSYSERR_NOERROR) {
|
| + start_time_ = base::TimeTicks::Now();
|
| + g_hmidiin_to_index_map[in_handle_] = index_;
|
| + Port::Open();
|
| + } else {
|
| + if (in_handle_ != kInvalidInHandle) {
|
| + midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
|
| + midiInClose(in_handle_);
|
| + in_handle_ = kInvalidInHandle;
|
| + }
|
| + Disconnect();
|
| + }
|
| + }
|
| +
|
| + private:
|
| + HMIDIIN in_handle_;
|
| + ScopedMIDIHDR hdr_;
|
| + base::TimeTicks start_time_;
|
| + int instance_id_;
|
| +};
|
| +
|
| +class DynamicallyInitializedMidiManagerWin::OutPort final : public Port {
|
| + public:
|
| + OutPort(UINT device_id, const MIDIOUTCAPS2W& caps)
|
| + : Port("output",
|
| + device_id,
|
| + caps.wMid,
|
| + caps.wPid,
|
| + caps.vDriverVersion,
|
| + base::WideToUTF8(
|
| + base::string16(caps.szPname, wcslen(caps.szPname)))),
|
| + software_(caps.wTechnology == MOD_SWSYNTH),
|
| + out_handle_(kInvalidOutHandle) {}
|
| +
|
| + void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
|
| + if (out_handle_ != kInvalidOutHandle)
|
| + runner->PostTask(FROM_HERE, base::Bind(&FinalizeOutPort, out_handle_));
|
| + }
|
| +
|
| + void Send(const std::vector<uint8_t>& data) {
|
| + if (out_handle_ == kInvalidOutHandle)
|
| + return;
|
| +
|
| + if (data.size() <= 3) {
|
| + DWORD message = 0;
|
| + for (size_t i = 0; i < data.size(); ++i)
|
| + message |= (static_cast<uint32_t>(data[i]) << (i * 8));
|
| + midiOutShortMsg(out_handle_, message);
|
| + } else {
|
| + if (data.size() > kSysExSizeLimit) {
|
| + LOG(ERROR) << "Ignoring SysEx message due to the size limit"
|
| + << ", size = " << data.size();
|
| + // TODO(toyoshim): Consider to report metrics here.
|
| + return;
|
| + }
|
| + ScopedMIDIHDR hdr(CreateMIDIHDR(data));
|
| + MMRESULT result =
|
| + midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
|
| + if (result != MMSYSERR_NOERROR)
|
| + return;
|
| + result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr));
|
| + if (result != MMSYSERR_NOERROR)
|
| + midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
|
| + else
|
| + ignore_result(hdr.release());
|
| + // MIDIHDR will be released on MOM_DONE.
|
| + }
|
| + }
|
| +
|
| + // Port overrides:
|
| + void Connect() override {
|
| + // Until |software| option is supported, disable Microsoft GS Wavetable
|
| + // Synth that has a known security issue.
|
| + if (software_ && manufacturer_id_ == MM_MICROSOFT &&
|
| + (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT ||
|
| + product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) {
|
| + return;
|
| + }
|
| + Port::Connect();
|
| + }
|
| +
|
| + void Open() override {
|
| + MMRESULT result =
|
| + midiOutOpen(&out_handle_, device_id_,
|
| + reinterpret_cast<DWORD_PTR>(&HandleMidiOutCallback), 0,
|
| + CALLBACK_FUNCTION);
|
| + if (result == MMSYSERR_NOERROR) {
|
| + Port::Open();
|
| + } else {
|
| + out_handle_ = kInvalidOutHandle;
|
| + Disconnect();
|
| + }
|
| + }
|
| +
|
| + private:
|
| + const bool software_;
|
| + HMIDIOUT out_handle_;
|
| +};
|
| +
|
| +DynamicallyInitializedMidiManagerWin::DynamicallyInitializedMidiManagerWin(
|
| + MidiService* service)
|
| + : MidiManager(service), instance_id_(kInvalidInstanceId) {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
|
| +
|
| + // Obtains the task runner for the current thread that hosts this instnace.
|
| + thread_runner_ = base::ThreadTaskRunnerHandle::Get();
|
| +}
|
| +
|
| +DynamicallyInitializedMidiManagerWin::~DynamicallyInitializedMidiManagerWin() {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
|
| +}
|
| +
|
| +base::TimeTicks DynamicallyInitializedMidiManagerWin::CalculateInEventTime(
|
| + size_t index,
|
| + uint32_t elapsed_ms) const {
|
| + GetTaskLock()->AssertAcquired();
|
| + CHECK_GT(input_ports_.size(), index);
|
| + return input_ports_[index]->CalculateInEventTime(elapsed_ms);
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::ReceiveMidiData(
|
| + uint32_t index,
|
| + const std::vector<uint8_t>& data,
|
| + base::TimeTicks time) {
|
| + MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::PostReplyTask(
|
| + const base::Closure& task) {
|
| + thread_runner_->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::StartInitialization() {
|
| + {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
|
| + instance_id_ = g_next_instance_id++;
|
| + g_active_instance_id = instance_id_;
|
| + CHECK_EQ(nullptr, g_manager_instance);
|
| + g_manager_instance = this;
|
| + }
|
| + // Registers on the I/O thread to be notified on the I/O thread.
|
| + CHECK(thread_runner_->BelongsToCurrentThread());
|
| + base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
|
| +
|
| + // Starts asynchronous initialization on TaskRunner.
|
| + PostTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner,
|
| + base::Unretained(this)));
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::Finalize() {
|
| + // Unregisters on the I/O thread.
|
| + CHECK(thread_runner_->BelongsToCurrentThread());
|
| + base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
|
| + {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + CHECK_EQ(instance_id_, g_active_instance_id);
|
| + g_active_instance_id = kInvalidInstanceId;
|
| + CHECK_EQ(this, g_manager_instance);
|
| + g_manager_instance = nullptr;
|
| + }
|
| +
|
| + // Ensures that no task runs on TaskRunner so to destruct the instance safely.
|
| + // Tasks that did not started yet will do nothing after invalidate the
|
| + // instance ID above.
|
| + base::AutoLock lock(*GetTaskLock());
|
| +
|
| + // Posts tasks that finalize each device port without MidiManager instance
|
| + // on TaskRunner.
|
| + for (const auto& port : input_ports_)
|
| + port->Finalize(service()->GetTaskRunner(kTaskRunner));
|
| + for (const auto& port : output_ports_)
|
| + port->Finalize(service()->GetTaskRunner(kTaskRunner));
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::DispatchSendMidiData(
|
| + MidiManagerClient* client,
|
| + uint32_t port_index,
|
| + const std::vector<uint8_t>& data,
|
| + double timestamp) {
|
| + if (timestamp != 0.0) {
|
| + base::TimeTicks time =
|
| + base::TimeTicks() + base::TimeDelta::FromMicroseconds(
|
| + timestamp * base::Time::kMicrosecondsPerSecond);
|
| + base::TimeTicks now = base::TimeTicks::Now();
|
| + if (now < time) {
|
| + PostDelayedTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::SendOnTaskRunner,
|
| + base::Unretained(this), client, port_index, data),
|
| + time - now);
|
| + return;
|
| + }
|
| + }
|
| + PostTask(base::Bind(&DynamicallyInitializedMidiManagerWin::SendOnTaskRunner,
|
| + base::Unretained(this), client, port_index, data));
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::OnDevicesChanged(
|
| + base::SystemMonitor::DeviceType device_type) {
|
| + // Notified on the I/O thread.
|
| + CHECK(thread_runner_->BelongsToCurrentThread());
|
| +
|
| + switch (device_type) {
|
| + case base::SystemMonitor::DEVTYPE_AUDIO:
|
| + case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
|
| + // Add case of other unrelated device types here.
|
| + return;
|
| + case base::SystemMonitor::DEVTYPE_UNKNOWN: {
|
| + base::AutoLock lock(*GetInstanceIdLock());
|
| + if (instance_id_ != g_active_instance_id)
|
| + return;
|
| + PostTask(base::Bind(
|
| + &DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner,
|
| + base::Unretained(this)));
|
| + break;
|
| + }
|
| + }
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::PostTask(const base::Closure& task) {
|
| + service()
|
| + ->GetTaskRunner(kTaskRunner)
|
| + ->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::PostDelayedTask(
|
| + const base::Closure& task,
|
| + base::TimeDelta delay) {
|
| + service()
|
| + ->GetTaskRunner(kTaskRunner)
|
| + ->PostDelayedTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task),
|
| + delay);
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner() {
|
| + UpdateDeviceListOnTaskRunner();
|
| + PostReplyTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::CompleteInitialization,
|
| + base::Unretained(this), mojom::Result::OK));
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner() {
|
| + // Update the devie list for input ports.
|
| + // First, mark all registered input ports to |EnumerateState::Enumerating|.
|
| + for (const auto& port : input_ports_)
|
| + port->set_enumerate_state(EnumerateState::Enumerating);
|
| +
|
| + std::vector<std::unique_ptr<InPort>> new_input_ports;
|
| + const UINT num_in_devices = midiInGetNumDevs();
|
| + for (UINT device_id = 0; device_id < num_in_devices; ++device_id) {
|
| + MIDIINCAPS2W caps;
|
| + MMRESULT result = midiInGetDevCaps(
|
| + device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps));
|
| + if (result != MMSYSERR_NOERROR) {
|
| + LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id;
|
| + continue;
|
| + }
|
| + std::unique_ptr<InPort> port =
|
| + base::MakeUnique<InPort>(instance_id_, device_id, caps);
|
| + const auto& found = std::find_if(
|
| + input_ports_.begin(), input_ports_.end(),
|
| + [&port](const auto& candidate) { return *candidate == *port; });
|
| + if (found == input_ports_.end()) {
|
| + new_input_ports.push_back(std::move(port));
|
| + } else {
|
| + // Update device ID which may be changed when device list is updated.
|
| + (*found)->set_device_id(device_id);
|
| + (*found)->set_enumerate_state(EnumerateState::Connected);
|
| + }
|
| + }
|
| + for (const auto& port : input_ports_) {
|
| + if (port->enumerate_state() == EnumerateState::Enumerating) {
|
| + // Disconnected ports have kept staying in |EnumerateState::Enumerating|
|
| + // state as they were marked first.
|
| + if (port->IsConnected()) {
|
| + port->Disconnect();
|
| + PostReplyTask(base::Bind(
|
| + &DynamicallyInitializedMidiManagerWin::SetInputPortState,
|
| + base::Unretained(this), port->index(), port->info().state));
|
| + }
|
| + } else if (port->enumerate_state() == EnumerateState::Connected) {
|
| + // Ports that have been connected, and are going to be connected now are
|
| + // in |EnumerateState::Connected| state.
|
| + if (!port->IsConnected()) {
|
| + port->Connect();
|
| + PostReplyTask(base::Bind(
|
| + &DynamicallyInitializedMidiManagerWin::SetInputPortState,
|
| + base::Unretained(this), port->index(), port->info().state));
|
| + }
|
| + }
|
| + }
|
| + // Assign port index to new devices and move them to the port list.
|
| + size_t in_index = input_ports_.size();
|
| + for (const auto& port : new_input_ports) {
|
| + port->set_index(in_index++);
|
| + port->Connect();
|
| + PostReplyTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::AddInputPort,
|
| + base::Unretained(this), port->info()));
|
| + }
|
| + input_ports_.insert(input_ports_.end(),
|
| + std::make_move_iterator(new_input_ports.begin()),
|
| + std::make_move_iterator(new_input_ports.end()));
|
| +
|
| + // Update the devie list for output ports.
|
| + // First, mark all registered output ports to |EnumerateState::Enumerating|.
|
| + for (const auto& port : output_ports_)
|
| + port->set_enumerate_state(EnumerateState::Enumerating);
|
| +
|
| + std::vector<std::unique_ptr<OutPort>> new_output_ports;
|
| + const UINT num_out_devices = midiOutGetNumDevs();
|
| + for (UINT device_id = 0; device_id < num_out_devices; ++device_id) {
|
| + MIDIOUTCAPS2W caps;
|
| + MMRESULT result = midiOutGetDevCaps(
|
| + device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps));
|
| + if (result != MMSYSERR_NOERROR) {
|
| + LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id;
|
| + continue;
|
| + }
|
| + std::unique_ptr<OutPort> port = base::MakeUnique<OutPort>(device_id, caps);
|
| + const auto& found = std::find_if(
|
| + output_ports_.begin(), output_ports_.end(),
|
| + [&port](const auto& candidate) { return *candidate == *port; });
|
| + if (found == output_ports_.end()) {
|
| + new_output_ports.push_back(std::move(port));
|
| + } else {
|
| + // Update device ID which may be changed when device list is updated.
|
| + (*found)->set_device_id(device_id);
|
| + (*found)->set_enumerate_state(EnumerateState::Connected);
|
| + }
|
| + }
|
| + for (const auto& port : output_ports_) {
|
| + if (port->enumerate_state() == EnumerateState::Enumerating) {
|
| + // Disconnected ports have kept staying in |EnumerateState::Enumerating|
|
| + // state as they were marked first.
|
| + if (port->IsConnected()) {
|
| + port->Disconnect();
|
| + PostReplyTask(base::Bind(
|
| + &DynamicallyInitializedMidiManagerWin::SetOutputPortState,
|
| + base::Unretained(this), port->index(), port->info().state));
|
| + }
|
| + } else if (port->enumerate_state() == EnumerateState::Connected) {
|
| + // Ports that have been connected, and are going to be connected now are
|
| + // in |EnumerateState::Connected| state.
|
| + if (!port->IsConnected()) {
|
| + port->Connect();
|
| + // Connect() won't change the state on output ports for software synth.
|
| + if (port->IsConnected()) {
|
| + PostReplyTask(base::Bind(
|
| + &DynamicallyInitializedMidiManagerWin::SetOutputPortState,
|
| + base::Unretained(this), port->index(), port->info().state));
|
| + }
|
| + }
|
| + }
|
| + }
|
| + // Assign port index to new devices and move them to the port list.
|
| + size_t out_index = output_ports_.size();
|
| + for (const auto& port : new_output_ports) {
|
| + port->set_index(out_index++);
|
| + port->Connect();
|
| + PostReplyTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::AddOutputPort,
|
| + base::Unretained(this), port->info()));
|
| + }
|
| + output_ports_.insert(output_ports_.end(),
|
| + std::make_move_iterator(new_output_ports.begin()),
|
| + std::make_move_iterator(new_output_ports.end()));
|
| +
|
| + // TODO(toyoshim): This method may run before internal MIDI device lists that
|
| + // Windows manages were updated. This may be because MIDI driver may be loaded
|
| + // after the raw device list was updated. To avoid this problem, we may want
|
| + // to retry device check later if no changes are detected here.
|
| +}
|
| +
|
| +void DynamicallyInitializedMidiManagerWin::SendOnTaskRunner(
|
| + MidiManagerClient* client,
|
| + uint32_t port_index,
|
| + const std::vector<uint8_t>& data) {
|
| + CHECK_GT(output_ports_.size(), port_index);
|
| + output_ports_[port_index]->Send(data);
|
| + // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
|
| + PostReplyTask(
|
| + base::Bind(&DynamicallyInitializedMidiManagerWin::AccumulateMidiBytesSent,
|
| + base::Unretained(this), client, data.size()));
|
| +}
|
| +
|
| +} // namespace midi
|
|
|