Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(59)

Side by Side Diff: media/midi/dynamically_initialized_midi_manager_win.cc

Issue 2841493003: Web MIDI: remove old Windows backend (Closed)
Patch Set: owners update Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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 <ks.h>
10 #include <ksmedia.h>
11 #include <mmreg.h>
12 #include <mmsystem.h>
13
14 #include <algorithm>
15 #include <string>
16
17 #include "base/bind_helpers.h"
18 #include "base/callback.h"
19 #include "base/logging.h"
20 #include "base/memory/ptr_util.h"
21 #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"
25 #include "device/usb/usb_ids.h"
26 #include "media/midi/message_util.h"
27 #include "media/midi/midi_port_info.h"
28 #include "media/midi/midi_service.h"
29
30 namespace midi {
31
32 // Forward declaration of PortManager for anonymous functions and internal
33 // classes to use it.
34 class DynamicallyInitializedMidiManagerWin::PortManager {
35 public:
36 // Calculates event time from elapsed time that system provides.
37 base::TimeTicks CalculateInEventTime(size_t index, uint32_t elapsed_ms) const;
38
39 // Registers HMIDIIN handle to resolve port index.
40 void RegisterInHandle(HMIDIIN handle, size_t index);
41
42 // Unregisters HMIDIIN handle.
43 void UnregisterInHandle(HMIDIIN handle);
44
45 // Finds HMIDIIN handle and fullfil |out_index| with the port index.
46 bool FindInHandle(HMIDIIN hmi, size_t* out_index);
47
48 // Restores used input buffer for the next data receive.
49 void RestoreInBuffer(size_t index);
50
51 // Ports accessors.
52 std::vector<std::unique_ptr<InPort>>* inputs() { return &input_ports_; }
53 std::vector<std::unique_ptr<OutPort>>* outputs() { return &output_ports_; }
54
55 // Handles MIDI input port callbacks that runs on a system provided thread.
56 static void CALLBACK HandleMidiInCallback(HMIDIIN hmi,
57 UINT msg,
58 DWORD_PTR instance,
59 DWORD_PTR param1,
60 DWORD_PTR param2);
61
62 // Handles MIDI output port callbacks that runs on a system provided thread.
63 static void CALLBACK HandleMidiOutCallback(HMIDIOUT hmo,
64 UINT msg,
65 DWORD_PTR instance,
66 DWORD_PTR param1,
67 DWORD_PTR param2);
68
69 private:
70 // Holds all MIDI input or output ports connected once.
71 std::vector<std::unique_ptr<InPort>> input_ports_;
72 std::vector<std::unique_ptr<OutPort>> output_ports_;
73
74 // Map to resolve MIDI input port index from HMIDIIN.
75 std::map<HMIDIIN, size_t> hmidiin_to_index_map_;
76 };
77
78 namespace {
79
80 // Assumes that nullptr represents an invalid MIDI handle.
81 constexpr HMIDIIN kInvalidInHandle = nullptr;
82 constexpr HMIDIOUT kInvalidOutHandle = nullptr;
83
84 // Defines SysEx message size limit.
85 // TODO(crbug.com/383578): This restriction should be removed once Web MIDI
86 // defines a standardized way to handle large sysex messages.
87 // Note for built-in USB-MIDI driver:
88 // From an observation on Windows 7/8.1 with a USB-MIDI keyboard,
89 // midiOutLongMsg() will be always blocked. Sending 64 bytes or less data takes
90 // roughly 300 usecs. Sending 2048 bytes or more data takes roughly
91 // |message.size() / (75 * 1024)| secs in practice. Here we put 256 KB size
92 // limit on SysEx message, with hoping that midiOutLongMsg will be blocked at
93 // most 4 sec or so with a typical USB-MIDI device.
94 // TODO(toyoshim): Consider to use linked small buffers so that midiOutReset()
95 // can abort sending unhandled following buffers.
96 constexpr size_t kSysExSizeLimit = 256 * 1024;
97
98 // Defines input buffer size.
99 constexpr size_t kBufferLength = 32 * 1024;
100
101 // Global variables to identify MidiManager instance.
102 constexpr int kInvalidInstanceId = -1;
103 int g_active_instance_id = kInvalidInstanceId;
104 DynamicallyInitializedMidiManagerWin* g_manager_instance = nullptr;
105
106 // Obtains base::Lock instance pointer to lock instance_id.
107 base::Lock* GetInstanceIdLock() {
108 static base::Lock* lock = new base::Lock;
109 return lock;
110 }
111
112 // Issues unique MidiManager instance ID.
113 int IssueNextInstanceId() {
114 static int id = kInvalidInstanceId;
115 return ++id;
116 }
117
118 // Use single TaskRunner for all tasks running outside the I/O thread.
119 constexpr int kTaskRunner = 0;
120
121 // Obtains base::Lock instance pointer to ensure tasks run safely on TaskRunner.
122 // Since all tasks on TaskRunner run behind a lock of *GetTaskLock(), we can
123 // access all members even on the I/O thread if a lock of *GetTaskLock() is
124 // obtained.
125 base::Lock* GetTaskLock() {
126 static base::Lock* lock = new base::Lock;
127 return lock;
128 }
129
130 // Helper function to run a posted task on TaskRunner safely.
131 void RunTask(int instance_id, const base::Closure& task) {
132 // Obtains task lock to ensure that the instance should not complete
133 // Finalize() while running the |task|.
134 base::AutoLock task_lock(*GetTaskLock());
135 {
136 // If Finalize() finished before the lock avobe, do nothing.
137 base::AutoLock lock(*GetInstanceIdLock());
138 if (instance_id != g_active_instance_id)
139 return;
140 }
141 task.Run();
142 }
143
144 // TODO(toyoshim): Factor out TaskRunner related functionaliries above, and
145 // deprecate MidiScheduler. It should be available via MidiManager::scheduler().
146
147 // Utility class to handle MIDIHDR struct safely.
148 class MIDIHDRDeleter {
149 public:
150 void operator()(LPMIDIHDR header) {
151 if (!header)
152 return;
153 delete[] static_cast<char*>(header->lpData);
154 delete header;
155 }
156 };
157
158 using ScopedMIDIHDR = std::unique_ptr<MIDIHDR, MIDIHDRDeleter>;
159
160 ScopedMIDIHDR CreateMIDIHDR(size_t size) {
161 ScopedMIDIHDR hdr(new MIDIHDR);
162 ZeroMemory(hdr.get(), sizeof(*hdr));
163 hdr->lpData = new char[size];
164 hdr->dwBufferLength = static_cast<DWORD>(size);
165 return hdr;
166 }
167
168 ScopedMIDIHDR CreateMIDIHDR(const std::vector<uint8_t>& data) {
169 ScopedMIDIHDR hdr(CreateMIDIHDR(data.size()));
170 std::copy(data.begin(), data.end(), hdr->lpData);
171 return hdr;
172 }
173
174 // Helper functions to close MIDI device handles on TaskRunner asynchronously.
175 void FinalizeInPort(HMIDIIN handle, ScopedMIDIHDR hdr) {
176 // Resets the device. This stops receiving messages, and allows to release
177 // registered buffer headers. Otherwise, midiInUnprepareHeader() and
178 // midiInClose() will fail with MIDIERR_STILLPLAYING.
179 midiInReset(handle);
180
181 if (hdr)
182 midiInUnprepareHeader(handle, hdr.get(), sizeof(*hdr));
183 midiInClose(handle);
184 }
185
186 void FinalizeOutPort(HMIDIOUT handle) {
187 // Resets inflight buffers. This will cancel sending data that system
188 // holds and were not sent yet.
189 midiOutReset(handle);
190 midiOutClose(handle);
191 }
192
193 // Gets manufacturer name in string from identifiers.
194 std::string GetManufacturerName(uint16_t id, const GUID& guid) {
195 if (IS_COMPATIBLE_USBAUDIO_MID(&guid)) {
196 const char* name =
197 device::UsbIds::GetVendorName(EXTRACT_USBAUDIO_MID(&guid));
198 if (name)
199 return std::string(name);
200 }
201 if (id == MM_MICROSOFT)
202 return "Microsoft Corporation";
203
204 // TODO(crbug.com/472341): Support other manufacture IDs.
205 return "";
206 }
207
208 // All instances of Port subclasses are always accessed behind a lock of
209 // *GetTaskLock(). Port and subclasses implementation do not need to
210 // consider thread safety.
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 const GUID& manufacturer_guid)
220 : index_(0u),
221 type_(type),
222 device_id_(device_id),
223 manufacturer_id_(manufacturer_id),
224 product_id_(product_id),
225 driver_version_(driver_version),
226 product_name_(product_name) {
227 info_.manufacturer =
228 GetManufacturerName(manufacturer_id, manufacturer_guid);
229 info_.name = product_name_;
230 info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_),
231 LOBYTE(driver_version_));
232 info_.state = mojom::PortState::DISCONNECTED;
233 }
234
235 virtual ~Port() {}
236
237 bool operator==(const Port& other) const {
238 // Should not use |device_id| for comparison because it can be changed on
239 // each enumeration.
240 // Since the GUID will be changed on each enumeration for Microsoft GS
241 // Wavetable synth and might be done for others, do not use it for device
242 // comparison.
243 return manufacturer_id_ == other.manufacturer_id_ &&
244 product_id_ == other.product_id_ &&
245 driver_version_ == other.driver_version_ &&
246 product_name_ == other.product_name_;
247 }
248
249 bool IsConnected() const {
250 return info_.state != mojom::PortState::DISCONNECTED;
251 }
252
253 void set_index(size_t index) {
254 index_ = index;
255 // TODO(toyoshim): Use hashed ID.
256 info_.id = base::StringPrintf("%s-%d", type_.c_str(), index_);
257 }
258 size_t index() { return index_; }
259 void set_device_id(uint32_t device_id) { device_id_ = device_id; }
260 uint32_t device_id() { return device_id_; }
261 const MidiPortInfo& info() { return info_; }
262
263 virtual bool Connect() {
264 if (info_.state != mojom::PortState::DISCONNECTED)
265 return false;
266
267 info_.state = mojom::PortState::CONNECTED;
268 // TODO(toyoshim) Until open() / close() are supported, open each device on
269 // connected.
270 Open();
271 return true;
272 }
273
274 virtual bool Disconnect() {
275 if (info_.state == mojom::PortState::DISCONNECTED)
276 return false;
277 info_.state = mojom::PortState::DISCONNECTED;
278 return true;
279 }
280
281 virtual void Open() { info_.state = mojom::PortState::OPENED; }
282
283 protected:
284 size_t index_;
285 std::string type_;
286 uint32_t device_id_;
287 const uint16_t manufacturer_id_;
288 const uint16_t product_id_;
289 const uint32_t driver_version_;
290 const std::string product_name_;
291 MidiPortInfo info_;
292 }; // class Port
293
294 } // namespace
295
296 class DynamicallyInitializedMidiManagerWin::InPort final : public Port {
297 public:
298 InPort(DynamicallyInitializedMidiManagerWin* manager,
299 int instance_id,
300 UINT device_id,
301 const MIDIINCAPS2W& caps)
302 : Port("input",
303 device_id,
304 caps.wMid,
305 caps.wPid,
306 caps.vDriverVersion,
307 base::WideToUTF8(
308 base::string16(caps.szPname, wcslen(caps.szPname))),
309 caps.ManufacturerGuid),
310 manager_(manager),
311 in_handle_(kInvalidInHandle),
312 instance_id_(instance_id) {}
313
314 static std::vector<std::unique_ptr<InPort>> EnumerateActivePorts(
315 DynamicallyInitializedMidiManagerWin* manager,
316 int instance_id) {
317 std::vector<std::unique_ptr<InPort>> ports;
318 const UINT num_devices = midiInGetNumDevs();
319 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
320 MIDIINCAPS2W caps;
321 MMRESULT result = midiInGetDevCaps(
322 device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps));
323 if (result != MMSYSERR_NOERROR) {
324 LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id;
325 continue;
326 }
327 ports.push_back(
328 base::MakeUnique<InPort>(manager, instance_id, device_id, caps));
329 }
330 return ports;
331 }
332
333 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
334 if (in_handle_ != kInvalidInHandle) {
335 runner->PostTask(
336 FROM_HERE,
337 base::Bind(&FinalizeInPort, in_handle_, base::Passed(&hdr_)));
338 manager_->port_manager()->UnregisterInHandle(in_handle_);
339 in_handle_ = kInvalidInHandle;
340 }
341 }
342
343 base::TimeTicks CalculateInEventTime(uint32_t elapsed_ms) const {
344 return start_time_ + base::TimeDelta::FromMilliseconds(elapsed_ms);
345 }
346
347 void RestoreBuffer() {
348 if (in_handle_ == kInvalidInHandle || !hdr_)
349 return;
350 midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
351 }
352
353 void NotifyPortStateSet(DynamicallyInitializedMidiManagerWin* manager) {
354 manager->PostReplyTask(
355 base::Bind(&DynamicallyInitializedMidiManagerWin::SetInputPortState,
356 base::Unretained(manager), index_, info_.state));
357 }
358
359 void NotifyPortAdded(DynamicallyInitializedMidiManagerWin* manager) {
360 manager->PostReplyTask(
361 base::Bind(&DynamicallyInitializedMidiManagerWin::AddInputPort,
362 base::Unretained(manager), info_));
363 }
364
365 // Port overrides:
366 bool Disconnect() override {
367 if (in_handle_ != kInvalidInHandle) {
368 // Following API call may fail because device was already disconnected.
369 // But just in case.
370 midiInClose(in_handle_);
371 manager_->port_manager()->UnregisterInHandle(in_handle_);
372 in_handle_ = kInvalidInHandle;
373 }
374 return Port::Disconnect();
375 }
376
377 void Open() override {
378 MMRESULT result = midiInOpen(
379 &in_handle_, device_id_,
380 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiInCallback),
381 instance_id_, CALLBACK_FUNCTION);
382 if (result == MMSYSERR_NOERROR) {
383 hdr_ = CreateMIDIHDR(kBufferLength);
384 result = midiInPrepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
385 }
386 if (result != MMSYSERR_NOERROR)
387 in_handle_ = kInvalidInHandle;
388 if (result == MMSYSERR_NOERROR)
389 result = midiInAddBuffer(in_handle_, hdr_.get(), sizeof(*hdr_));
390 if (result == MMSYSERR_NOERROR)
391 result = midiInStart(in_handle_);
392 if (result == MMSYSERR_NOERROR) {
393 start_time_ = base::TimeTicks::Now();
394 manager_->port_manager()->RegisterInHandle(in_handle_, index_);
395 Port::Open();
396 } else {
397 if (in_handle_ != kInvalidInHandle) {
398 midiInUnprepareHeader(in_handle_, hdr_.get(), sizeof(*hdr_));
399 hdr_.reset();
400 midiInClose(in_handle_);
401 in_handle_ = kInvalidInHandle;
402 }
403 Disconnect();
404 }
405 }
406
407 private:
408 DynamicallyInitializedMidiManagerWin* manager_;
409 HMIDIIN in_handle_;
410 ScopedMIDIHDR hdr_;
411 base::TimeTicks start_time_;
412 const int instance_id_;
413 };
414
415 class DynamicallyInitializedMidiManagerWin::OutPort final : public Port {
416 public:
417 OutPort(UINT device_id, const MIDIOUTCAPS2W& caps)
418 : Port("output",
419 device_id,
420 caps.wMid,
421 caps.wPid,
422 caps.vDriverVersion,
423 base::WideToUTF8(
424 base::string16(caps.szPname, wcslen(caps.szPname))),
425 caps.ManufacturerGuid),
426 software_(caps.wTechnology == MOD_SWSYNTH),
427 out_handle_(kInvalidOutHandle) {}
428
429 static std::vector<std::unique_ptr<OutPort>> EnumerateActivePorts() {
430 std::vector<std::unique_ptr<OutPort>> ports;
431 const UINT num_devices = midiOutGetNumDevs();
432 for (UINT device_id = 0; device_id < num_devices; ++device_id) {
433 MIDIOUTCAPS2W caps;
434 MMRESULT result = midiOutGetDevCaps(
435 device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps));
436 if (result != MMSYSERR_NOERROR) {
437 LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id;
438 continue;
439 }
440 ports.push_back(base::MakeUnique<OutPort>(device_id, caps));
441 }
442 return ports;
443 }
444
445 void Finalize(scoped_refptr<base::SingleThreadTaskRunner> runner) {
446 if (out_handle_ != kInvalidOutHandle) {
447 runner->PostTask(FROM_HERE, base::Bind(&FinalizeOutPort, out_handle_));
448 out_handle_ = kInvalidOutHandle;
449 }
450 }
451
452 void NotifyPortStateSet(DynamicallyInitializedMidiManagerWin* manager) {
453 manager->PostReplyTask(
454 base::Bind(&DynamicallyInitializedMidiManagerWin::SetOutputPortState,
455 base::Unretained(manager), index_, info_.state));
456 }
457
458 void NotifyPortAdded(DynamicallyInitializedMidiManagerWin* manager) {
459 manager->PostReplyTask(
460 base::Bind(&DynamicallyInitializedMidiManagerWin::AddOutputPort,
461 base::Unretained(manager), info_));
462 }
463
464 void Send(const std::vector<uint8_t>& data) {
465 if (out_handle_ == kInvalidOutHandle)
466 return;
467
468 if (data.size() <= 3) {
469 uint32_t message = 0;
470 for (size_t i = 0; i < data.size(); ++i)
471 message |= (static_cast<uint32_t>(data[i]) << (i * 8));
472 midiOutShortMsg(out_handle_, message);
473 } else {
474 if (data.size() > kSysExSizeLimit) {
475 LOG(ERROR) << "Ignoring SysEx message due to the size limit"
476 << ", size = " << data.size();
477 // TODO(toyoshim): Consider to report metrics here.
478 return;
479 }
480 ScopedMIDIHDR hdr(CreateMIDIHDR(data));
481 MMRESULT result =
482 midiOutPrepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
483 if (result != MMSYSERR_NOERROR)
484 return;
485 result = midiOutLongMsg(out_handle_, hdr.get(), sizeof(*hdr));
486 if (result != MMSYSERR_NOERROR) {
487 midiOutUnprepareHeader(out_handle_, hdr.get(), sizeof(*hdr));
488 } else {
489 // MIDIHDR will be released on MOM_DONE.
490 ignore_result(hdr.release());
491 }
492 }
493 }
494
495 // Port overrides:
496 bool Connect() override {
497 // Until |software| option is supported, disable Microsoft GS Wavetable
498 // Synth that has a known security issue.
499 if (software_ && manufacturer_id_ == MM_MICROSOFT &&
500 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT ||
501 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) {
502 return false;
503 }
504 return Port::Connect();
505 }
506
507 bool Disconnect() override {
508 if (out_handle_ != kInvalidOutHandle) {
509 // Following API call may fail because device was already disconnected.
510 // But just in case.
511 midiOutClose(out_handle_);
512 out_handle_ = kInvalidOutHandle;
513 }
514 return Port::Disconnect();
515 }
516
517 void Open() override {
518 MMRESULT result = midiOutOpen(
519 &out_handle_, device_id_,
520 reinterpret_cast<DWORD_PTR>(&PortManager::HandleMidiOutCallback), 0,
521 CALLBACK_FUNCTION);
522 if (result == MMSYSERR_NOERROR) {
523 Port::Open();
524 } else {
525 out_handle_ = kInvalidOutHandle;
526 Disconnect();
527 }
528 }
529
530 const bool software_;
531 HMIDIOUT out_handle_;
532 };
533
534 base::TimeTicks
535 DynamicallyInitializedMidiManagerWin::PortManager::CalculateInEventTime(
536 size_t index,
537 uint32_t elapsed_ms) const {
538 GetTaskLock()->AssertAcquired();
539 CHECK_GT(input_ports_.size(), index);
540 return input_ports_[index]->CalculateInEventTime(elapsed_ms);
541 }
542
543 void DynamicallyInitializedMidiManagerWin::PortManager::RegisterInHandle(
544 HMIDIIN handle,
545 size_t index) {
546 GetTaskLock()->AssertAcquired();
547 hmidiin_to_index_map_[handle] = index;
548 }
549
550 void DynamicallyInitializedMidiManagerWin::PortManager::UnregisterInHandle(
551 HMIDIIN handle) {
552 GetTaskLock()->AssertAcquired();
553 hmidiin_to_index_map_.erase(handle);
554 }
555
556 bool DynamicallyInitializedMidiManagerWin::PortManager::FindInHandle(
557 HMIDIIN hmi,
558 size_t* out_index) {
559 GetTaskLock()->AssertAcquired();
560 auto found = hmidiin_to_index_map_.find(hmi);
561 if (found == hmidiin_to_index_map_.end())
562 return false;
563 *out_index = found->second;
564 return true;
565 }
566
567 void DynamicallyInitializedMidiManagerWin::PortManager::RestoreInBuffer(
568 size_t index) {
569 GetTaskLock()->AssertAcquired();
570 CHECK_GT(input_ports_.size(), index);
571 input_ports_[index]->RestoreBuffer();
572 }
573
574 void CALLBACK
575 DynamicallyInitializedMidiManagerWin::PortManager::HandleMidiInCallback(
576 HMIDIIN hmi,
577 UINT msg,
578 DWORD_PTR instance,
579 DWORD_PTR param1,
580 DWORD_PTR param2) {
581 if (msg != MIM_DATA && msg != MIM_LONGDATA)
582 return;
583 int instance_id = static_cast<int>(instance);
584 DynamicallyInitializedMidiManagerWin* manager = nullptr;
585
586 // Use |g_task_lock| so to ensure the instance can keep alive while running,
587 // and to access member variables that are used on TaskRunner.
588 base::AutoLock task_lock(*GetTaskLock());
589 {
590 base::AutoLock lock(*GetInstanceIdLock());
591 if (instance_id != g_active_instance_id)
592 return;
593 manager = g_manager_instance;
594 }
595
596 size_t index;
597 if (!manager->port_manager()->FindInHandle(hmi, &index))
598 return;
599
600 DCHECK(msg == MIM_DATA || msg == MIM_LONGDATA);
601 if (msg == MIM_DATA) {
602 const uint8_t status_byte = static_cast<uint8_t>(param1 & 0xff);
603 const uint8_t first_data_byte = static_cast<uint8_t>((param1 >> 8) & 0xff);
604 const uint8_t second_data_byte =
605 static_cast<uint8_t>((param1 >> 16) & 0xff);
606 const uint8_t kData[] = {status_byte, first_data_byte, second_data_byte};
607 const size_t len = GetMessageLength(status_byte);
608 DCHECK_LE(len, arraysize(kData));
609 std::vector<uint8_t> data;
610 data.assign(kData, kData + len);
611 manager->PostReplyTask(base::Bind(
612 &DynamicallyInitializedMidiManagerWin::ReceiveMidiData,
613 base::Unretained(manager), index, data,
614 manager->port_manager()->CalculateInEventTime(index, param2)));
615 } else {
616 DCHECK_EQ(static_cast<UINT>(MIM_LONGDATA), msg);
617 LPMIDIHDR hdr = reinterpret_cast<LPMIDIHDR>(param1);
618 if (hdr->dwBytesRecorded > 0) {
619 const uint8_t* src = reinterpret_cast<const uint8_t*>(hdr->lpData);
620 std::vector<uint8_t> data;
621 data.assign(src, src + hdr->dwBytesRecorded);
622 manager->PostReplyTask(base::Bind(
623 &DynamicallyInitializedMidiManagerWin::ReceiveMidiData,
624 base::Unretained(manager), index, data,
625 manager->port_manager()->CalculateInEventTime(index, param2)));
626 }
627 manager->PostTask(base::Bind(
628 &DynamicallyInitializedMidiManagerWin::PortManager::RestoreInBuffer,
629 base::Unretained(manager->port_manager()), index));
630 }
631 }
632
633 void CALLBACK
634 DynamicallyInitializedMidiManagerWin::PortManager::HandleMidiOutCallback(
635 HMIDIOUT hmo,
636 UINT msg,
637 DWORD_PTR instance,
638 DWORD_PTR param1,
639 DWORD_PTR param2) {
640 if (msg == MOM_DONE) {
641 ScopedMIDIHDR hdr(reinterpret_cast<LPMIDIHDR>(param1));
642 if (!hdr)
643 return;
644 // TODO(toyoshim): Call midiOutUnprepareHeader outside the callback.
645 // Since this callback may be invoked after the manager is destructed,
646 // and can not send a task to the TaskRunner in such case, we need to
647 // consider to track MIDIHDR per port, and clean it in port finalization
648 // steps, too.
649 midiOutUnprepareHeader(hmo, hdr.get(), sizeof(*hdr));
650 }
651 }
652
653 DynamicallyInitializedMidiManagerWin::DynamicallyInitializedMidiManagerWin(
654 MidiService* service)
655 : MidiManager(service),
656 instance_id_(IssueNextInstanceId()),
657 port_manager_(base::MakeUnique<PortManager>()) {
658 base::AutoLock lock(*GetInstanceIdLock());
659 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
660
661 // Obtains the task runner for the current thread that hosts this instnace.
662 thread_runner_ = base::ThreadTaskRunnerHandle::Get();
663 }
664
665 DynamicallyInitializedMidiManagerWin::~DynamicallyInitializedMidiManagerWin() {
666 base::AutoLock lock(*GetInstanceIdLock());
667 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
668 CHECK(thread_runner_->BelongsToCurrentThread());
669 }
670
671 void DynamicallyInitializedMidiManagerWin::StartInitialization() {
672 {
673 base::AutoLock lock(*GetInstanceIdLock());
674 CHECK_EQ(kInvalidInstanceId, g_active_instance_id);
675 g_active_instance_id = instance_id_;
676 CHECK_EQ(nullptr, g_manager_instance);
677 g_manager_instance = this;
678 }
679 // Registers on the I/O thread to be notified on the I/O thread.
680 CHECK(thread_runner_->BelongsToCurrentThread());
681 base::SystemMonitor::Get()->AddDevicesChangedObserver(this);
682
683 // Starts asynchronous initialization on TaskRunner.
684 PostTask(
685 base::Bind(&DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner,
686 base::Unretained(this)));
687 }
688
689 void DynamicallyInitializedMidiManagerWin::Finalize() {
690 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more.
691 CHECK(thread_runner_->BelongsToCurrentThread());
692 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this);
693 {
694 base::AutoLock lock(*GetInstanceIdLock());
695 CHECK_EQ(instance_id_, g_active_instance_id);
696 g_active_instance_id = kInvalidInstanceId;
697 CHECK_EQ(this, g_manager_instance);
698 g_manager_instance = nullptr;
699 }
700
701 // Ensures that no task runs on TaskRunner so to destruct the instance safely.
702 // Tasks that did not started yet will do nothing after invalidate the
703 // instance ID above.
704 // Behind the lock below, we can safely access all members for finalization
705 // even on the I/O thread.
706 base::AutoLock lock(*GetTaskLock());
707
708 // Posts tasks that finalize each device port without MidiManager instance
709 // on TaskRunner. If another MidiManager instance is created, its
710 // initialization runs on the same task runner after all tasks posted here
711 // finish.
712 for (const auto& port : *port_manager_->inputs())
713 port->Finalize(service()->GetTaskRunner(kTaskRunner));
714 for (const auto& port : *port_manager_->outputs())
715 port->Finalize(service()->GetTaskRunner(kTaskRunner));
716 }
717
718 void DynamicallyInitializedMidiManagerWin::DispatchSendMidiData(
719 MidiManagerClient* client,
720 uint32_t port_index,
721 const std::vector<uint8_t>& data,
722 double timestamp) {
723 if (timestamp != 0.0) {
724 base::TimeTicks time = base::TimeTicks() +
725 base::TimeDelta::FromMicroseconds(
726 timestamp * base::Time::kMicrosecondsPerSecond);
727 base::TimeTicks now = base::TimeTicks::Now();
728 if (now < time) {
729 PostDelayedTask(
730 base::Bind(&DynamicallyInitializedMidiManagerWin::SendOnTaskRunner,
731 base::Unretained(this), client, port_index, data),
732 time - now);
733 return;
734 }
735 }
736 PostTask(base::Bind(&DynamicallyInitializedMidiManagerWin::SendOnTaskRunner,
737 base::Unretained(this), client, port_index, data));
738 }
739
740 void DynamicallyInitializedMidiManagerWin::OnDevicesChanged(
741 base::SystemMonitor::DeviceType device_type) {
742 // Notified on the I/O thread.
743 CHECK(thread_runner_->BelongsToCurrentThread());
744
745 switch (device_type) {
746 case base::SystemMonitor::DEVTYPE_AUDIO:
747 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE:
748 // Add case of other unrelated device types here.
749 return;
750 case base::SystemMonitor::DEVTYPE_UNKNOWN: {
751 PostTask(base::Bind(
752 &DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner,
753 base::Unretained(this)));
754 break;
755 }
756 }
757 }
758
759 void DynamicallyInitializedMidiManagerWin::ReceiveMidiData(
760 uint32_t index,
761 const std::vector<uint8_t>& data,
762 base::TimeTicks time) {
763 MidiManager::ReceiveMidiData(index, data.data(), data.size(), time);
764 }
765
766 void DynamicallyInitializedMidiManagerWin::PostTask(const base::Closure& task) {
767 service()
768 ->GetTaskRunner(kTaskRunner)
769 ->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
770 }
771
772 void DynamicallyInitializedMidiManagerWin::PostDelayedTask(
773 const base::Closure& task,
774 base::TimeDelta delay) {
775 service()
776 ->GetTaskRunner(kTaskRunner)
777 ->PostDelayedTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task),
778 delay);
779 }
780
781 void DynamicallyInitializedMidiManagerWin::PostReplyTask(
782 const base::Closure& task) {
783 thread_runner_->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task));
784 }
785
786 void DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner() {
787 UpdateDeviceListOnTaskRunner();
788 PostReplyTask(
789 base::Bind(&DynamicallyInitializedMidiManagerWin::CompleteInitialization,
790 base::Unretained(this), mojom::Result::OK));
791 }
792
793 void DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner() {
794 std::vector<std::unique_ptr<InPort>> active_input_ports =
795 InPort::EnumerateActivePorts(this, instance_id_);
796 ReflectActiveDeviceList(this, port_manager_->inputs(), &active_input_ports);
797
798 std::vector<std::unique_ptr<OutPort>> active_output_ports =
799 OutPort::EnumerateActivePorts();
800 ReflectActiveDeviceList(this, port_manager_->outputs(), &active_output_ports);
801
802 // TODO(toyoshim): This method may run before internal MIDI device lists that
803 // Windows manages were updated. This may be because MIDI driver may be loaded
804 // after the raw device list was updated. To avoid this problem, we may want
805 // to retry device check later if no changes are detected here.
806 }
807
808 template <typename T>
809 void DynamicallyInitializedMidiManagerWin::ReflectActiveDeviceList(
810 DynamicallyInitializedMidiManagerWin* manager,
811 std::vector<T>* known_ports,
812 std::vector<T>* active_ports) {
813 // Update existing port states.
814 for (const auto& port : *known_ports) {
815 const auto& it = std::find_if(
816 active_ports->begin(), active_ports->end(),
817 [&port](const auto& candidate) { return *candidate == *port; });
818 if (it == active_ports->end()) {
819 if (port->Disconnect())
820 port->NotifyPortStateSet(this);
821 } else {
822 port->set_device_id((*it)->device_id());
823 if (port->Connect())
824 port->NotifyPortStateSet(this);
825 }
826 }
827
828 // Find new ports from active ports and append them to known ports.
829 for (auto& port : *active_ports) {
830 if (std::find_if(known_ports->begin(), known_ports->end(),
831 [&port](const auto& candidate) {
832 return *candidate == *port;
833 }) == known_ports->end()) {
834 size_t index = known_ports->size();
835 port->set_index(index);
836 known_ports->push_back(std::move(port));
837 (*known_ports)[index]->Connect();
838 (*known_ports)[index]->NotifyPortAdded(this);
839 }
840 }
841 }
842
843 void DynamicallyInitializedMidiManagerWin::SendOnTaskRunner(
844 MidiManagerClient* client,
845 uint32_t port_index,
846 const std::vector<uint8_t>& data) {
847 CHECK_GT(port_manager_->outputs()->size(), port_index);
848 (*port_manager_->outputs())[port_index]->Send(data);
849 // |client| will be checked inside MidiManager::AccumulateMidiBytesSent.
850 PostReplyTask(
851 base::Bind(&DynamicallyInitializedMidiManagerWin::AccumulateMidiBytesSent,
852 base::Unretained(this), client, data.size()));
853 }
854
855 } // namespace midi
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698