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/logging.h" | |
17 #include "base/memory/ptr_util.h" | |
18 #include "base/strings/string16.h" | |
19 #include "base/strings/stringprintf.h" | |
20 #include "base/strings/utf_string_conversions.h" | |
21 #include "base/synchronization/lock.h" | |
22 #include "media/midi/midi_port_info.h" | |
23 #include "media/midi/midi_service.h" | |
24 | |
25 namespace midi { | |
26 | |
27 namespace { | |
28 | |
29 // Global variables to identify MidiManager instance. | |
Takashi Toyoshima
2017/02/17 09:34:27
Concept is same with ALSA's dynamic instantiation
| |
30 constexpr int kInvalidInstanceId = -1; | |
31 int g_active_instance_id = kInvalidInstanceId; | |
32 int g_next_instance_id = 0; | |
33 DynamicallyInitializedMidiManagerWin* g_manager_instance = nullptr; | |
34 | |
35 // Obtains base::Lock instance pointer to lock instance_id. | |
36 base::Lock* GetInstanceIdLock() { | |
37 static base::Lock* lock = new base::Lock; | |
yhirano
2017/02/17 10:27:49
Looks racy; If there is a guarantee that the first
Takashi Toyoshima
2017/02/17 11:46:36
This looks a quite new idiom that is replacing Laz
| |
38 return lock; | |
39 } | |
40 | |
41 // Use single TaskRunner for all tasks running outside the I/O thread. | |
42 constexpr int kTaskRunner = 0; | |
43 | |
44 // Obtains base::Lock instance pointer to ensure tasks run safely on TaskRunner. | |
45 base::Lock* GetTaskLock() { | |
46 static base::Lock* lock = new base::Lock; | |
47 return lock; | |
48 } | |
49 | |
50 // Helper function to run a posted task on TaskRunner safely. | |
51 void RunTask(int instance_id, const base::Closure& task) { | |
52 // Obtains task lock to ensure that the instance should not complete | |
53 // Finalize() while running the |task|. | |
54 base::AutoLock task_lock(*GetTaskLock()); | |
55 { | |
56 // If Finalize() finished before the lock avobe, do nothing. | |
57 base::AutoLock lock(*GetInstanceIdLock()); | |
58 if (instance_id != g_active_instance_id) | |
59 return; | |
60 } | |
61 task.Run(); | |
62 } | |
63 | |
64 // TODO(toyoshim): Factor out TaskRunner related functionaliries above, and | |
65 // deprecate MidiScheduler. It should be available via MidiManager::scheduler(). | |
66 | |
67 enum class EnumerateState { Connected, Enumerating }; | |
68 | |
69 class Port { | |
70 public: | |
71 Port(const std::string& type, | |
72 uint32_t device_id, | |
73 uint16_t manufacturer_id, | |
74 uint16_t product_id, | |
75 uint32_t driver_version, | |
76 const std::string& product_name) | |
77 : index_(0u), | |
78 type_(type), | |
79 device_id_(device_id), | |
80 manufacturer_id_(manufacturer_id), | |
81 product_id_(product_id), | |
82 driver_version_(driver_version), | |
83 product_name_(product_name), | |
84 enumerate_state_(EnumerateState::Enumerating) { | |
85 info_.manufacturer = "unknown"; // TODO(toyoshim): Use USB information. | |
86 info_.name = product_name_; | |
87 info_.version = base::StringPrintf("%d.%d", HIBYTE(driver_version_), | |
88 LOBYTE(driver_version_)); | |
89 info_.state = mojom::PortState::DISCONNECTED; | |
90 } | |
91 | |
yhirano
2017/02/17 10:27:49
+virtual ~Port() {}
Takashi Toyoshima
2017/02/17 11:46:36
Done.
| |
92 bool operator==(const Port& other) const { | |
93 // Should not use |device_id| for comparison because it can be changed on | |
94 // each enumeration. | |
95 // Since the GUID will be changed on each enumeration for Microsoft GS | |
96 // Wavetable synth and might be done for others, do not use it for device | |
97 // comparison. | |
98 return manufacturer_id_ == other.manufacturer_id_ && | |
99 product_id_ == other.product_id_ && | |
100 driver_version_ == other.driver_version_ && | |
101 product_name_ == other.product_name_; | |
102 } | |
103 | |
104 bool IsConnected() const { | |
105 return info_.state != mojom::PortState::DISCONNECTED; | |
106 } | |
107 | |
108 void set_index(size_t index) { | |
109 index_ = index; | |
110 // TODO(toyoshim): Use hashed ID. | |
111 info_.id = base::StringPrintf("%s-%d", type_.c_str(), index_); | |
112 } | |
113 size_t index() { return index_; } | |
114 void set_device_id(uint32_t device_id) { device_id_ = device_id; } | |
115 void set_enumerate_state(EnumerateState state) { enumerate_state_ = state; } | |
116 EnumerateState enumerate_state() { return enumerate_state_; } | |
117 const MidiPortInfo& info() { return info_; } | |
118 | |
119 virtual void Connect() { | |
120 info_.state = mojom::PortState::CONNECTED; | |
121 // TODO(toyoshim) Until open() / close() are supported, open each device on | |
122 // connected. | |
123 Open(); | |
124 } | |
125 | |
126 virtual void Disconnect() { info_.state = mojom::PortState::DISCONNECTED; } | |
127 | |
128 virtual void Open() { info_.state = mojom::PortState::OPENED; } | |
129 | |
130 protected: | |
131 size_t index_; | |
132 std::string type_; | |
133 uint32_t device_id_; | |
134 const uint16_t manufacturer_id_; | |
135 const uint16_t product_id_; | |
136 const uint32_t driver_version_; | |
137 const std::string product_name_; | |
138 MidiPortInfo info_; | |
139 EnumerateState enumerate_state_; | |
140 }; // class Port | |
141 | |
142 } // namespace | |
143 | |
144 // TODO(toyoshim): Following patches will implement actual functions. | |
145 class DynamicallyInitializedMidiManagerWin::InPort final : public Port { | |
146 public: | |
147 InPort(int instance_id, UINT device_id, const MIDIINCAPS2W& caps) | |
Takashi Toyoshima
2017/02/17 17:42:29
this first argument wasn't used yet in this first
| |
148 : Port("input", | |
149 device_id, | |
150 caps.wMid, | |
151 caps.wPid, | |
152 caps.vDriverVersion, | |
153 base::WideToUTF8( | |
154 base::string16(caps.szPname, wcslen(caps.szPname)))) {} | |
155 }; | |
156 | |
157 // TODO(toyoshim): Following patches will implement actual functions. | |
158 class DynamicallyInitializedMidiManagerWin::OutPort final : public Port { | |
159 public: | |
160 OutPort(UINT device_id, const MIDIOUTCAPS2W& caps) | |
161 : Port("output", | |
162 device_id, | |
163 caps.wMid, | |
164 caps.wPid, | |
165 caps.vDriverVersion, | |
166 base::WideToUTF8( | |
167 base::string16(caps.szPname, wcslen(caps.szPname)))), | |
168 software_(caps.wTechnology == MOD_SWSYNTH) {} | |
169 | |
170 // Port overrides: | |
171 void Connect() override { | |
172 // Until |software| option is supported, disable Microsoft GS Wavetable | |
173 // Synth that has a known security issue. | |
174 if (software_ && manufacturer_id_ == MM_MICROSOFT && | |
175 (product_id_ == MM_MSFT_WDMAUDIO_MIDIOUT || | |
176 product_id_ == MM_MSFT_GENERIC_MIDISYNTH)) { | |
177 return; | |
178 } | |
179 Port::Connect(); | |
180 } | |
181 | |
182 private: | |
183 const bool software_; | |
184 }; | |
185 | |
186 DynamicallyInitializedMidiManagerWin::DynamicallyInitializedMidiManagerWin( | |
187 MidiService* service) | |
188 : MidiManager(service), instance_id_(kInvalidInstanceId) { | |
189 base::AutoLock lock(*GetInstanceIdLock()); | |
190 CHECK_EQ(kInvalidInstanceId, g_active_instance_id); | |
191 | |
192 // Obtains the task runner for the current thread that hosts this instnace. | |
193 thread_runner_ = base::ThreadTaskRunnerHandle::Get(); | |
194 } | |
195 | |
196 DynamicallyInitializedMidiManagerWin::~DynamicallyInitializedMidiManagerWin() { | |
197 base::AutoLock lock(*GetInstanceIdLock()); | |
198 CHECK_EQ(kInvalidInstanceId, g_active_instance_id); | |
199 CHECK(thread_runner_->BelongsToCurrentThread()); | |
200 } | |
201 | |
202 void DynamicallyInitializedMidiManagerWin::PostReplyTask( | |
203 const base::Closure& task) { | |
yhirano
2017/02/17 10:27:49
base::AutoLock lock(*GetInstanceIdLock());
Takashi Toyoshima
2017/02/17 11:46:36
instance id lock is used only for global variables
yhirano
2017/02/17 11:51:43
Thank you! I overlooked that.
Is it possible to in
| |
204 thread_runner_->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task)); | |
205 } | |
206 | |
207 void DynamicallyInitializedMidiManagerWin::StartInitialization() { | |
208 { | |
209 base::AutoLock lock(*GetInstanceIdLock()); | |
210 CHECK_EQ(kInvalidInstanceId, g_active_instance_id); | |
211 instance_id_ = g_next_instance_id++; | |
212 g_active_instance_id = instance_id_; | |
213 CHECK_EQ(nullptr, g_manager_instance); | |
214 g_manager_instance = this; | |
215 } | |
216 // Registers on the I/O thread to be notified on the I/O thread. | |
217 CHECK(thread_runner_->BelongsToCurrentThread()); | |
218 base::SystemMonitor::Get()->AddDevicesChangedObserver(this); | |
219 | |
220 // Starts asynchronous initialization on TaskRunner. | |
221 PostTask( | |
222 base::Bind(&DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner, | |
223 base::Unretained(this))); | |
224 } | |
225 | |
226 void DynamicallyInitializedMidiManagerWin::Finalize() { | |
227 // Unregisters on the I/O thread. OnDevicesChanged() won't be called any more. | |
228 CHECK(thread_runner_->BelongsToCurrentThread()); | |
229 base::SystemMonitor::Get()->RemoveDevicesChangedObserver(this); | |
230 { | |
231 base::AutoLock lock(*GetInstanceIdLock()); | |
232 CHECK_EQ(instance_id_, g_active_instance_id); | |
233 g_active_instance_id = kInvalidInstanceId; | |
234 CHECK_EQ(this, g_manager_instance); | |
235 g_manager_instance = nullptr; | |
236 } | |
237 | |
238 // Ensures that no task runs on TaskRunner so to destruct the instance safely. | |
239 // Tasks that did not started yet will do nothing after invalidate the | |
240 // instance ID above. | |
241 base::AutoLock lock(*GetTaskLock()); | |
242 } | |
243 | |
244 void DynamicallyInitializedMidiManagerWin::DispatchSendMidiData( | |
245 MidiManagerClient* client, | |
246 uint32_t port_index, | |
247 const std::vector<uint8_t>& data, | |
248 double timestamp) { | |
249 // TODO(toyoshim): Following patches will implement. | |
250 } | |
251 | |
252 void DynamicallyInitializedMidiManagerWin::OnDevicesChanged( | |
253 base::SystemMonitor::DeviceType device_type) { | |
254 // Notified on the I/O thread. | |
255 CHECK(thread_runner_->BelongsToCurrentThread()); | |
256 | |
257 switch (device_type) { | |
258 case base::SystemMonitor::DEVTYPE_AUDIO: | |
259 case base::SystemMonitor::DEVTYPE_VIDEO_CAPTURE: | |
260 // Add case of other unrelated device types here. | |
261 return; | |
262 case base::SystemMonitor::DEVTYPE_UNKNOWN: { | |
263 base::AutoLock lock(*GetInstanceIdLock()); | |
yhirano
2017/02/17 10:27:49
I believe these two lines should be in PostTask. P
Takashi Toyoshima
2017/02/17 11:46:36
For missing lock for instance_id_, see my previous
| |
264 CHECK_EQ(instance_id_, g_active_instance_id); | |
265 PostTask(base::Bind( | |
266 &DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner, | |
267 base::Unretained(this))); | |
268 break; | |
269 } | |
270 } | |
271 } | |
272 | |
273 void DynamicallyInitializedMidiManagerWin::PostTask(const base::Closure& task) { | |
yhirano
2017/02/17 10:27:49
DCHECK(thread_runner_->BelongsToCurrentThread());
Takashi Toyoshima
2017/02/17 11:46:36
I will use this even from task runner.
I expect th
| |
274 service() | |
275 ->GetTaskRunner(kTaskRunner) | |
276 ->PostTask(FROM_HERE, base::Bind(&RunTask, instance_id_, task)); | |
277 } | |
278 | |
279 void DynamicallyInitializedMidiManagerWin::InitializeOnTaskRunner() { | |
280 UpdateDeviceListOnTaskRunner(); | |
281 PostReplyTask( | |
282 base::Bind(&DynamicallyInitializedMidiManagerWin::CompleteInitialization, | |
283 base::Unretained(this), mojom::Result::OK)); | |
284 } | |
285 | |
286 void DynamicallyInitializedMidiManagerWin::UpdateDeviceListOnTaskRunner() { | |
Takashi Toyoshima
2017/02/17 09:34:27
main logic of this patch.
100+ lines, but latter p
yhirano
2017/02/17 10:27:49
Splitting this method into two (one for input and
Takashi Toyoshima
2017/02/17 11:46:36
will try rewriting this as we discussed
| |
287 // Update the devie list for input ports. | |
288 // First, mark all registered input ports to |EnumerateState::Enumerating|. | |
289 for (const auto& port : input_ports_) | |
290 port->set_enumerate_state(EnumerateState::Enumerating); | |
291 | |
292 std::vector<std::unique_ptr<InPort>> new_input_ports; | |
293 const UINT num_in_devices = midiInGetNumDevs(); | |
294 for (UINT device_id = 0; device_id < num_in_devices; ++device_id) { | |
295 MIDIINCAPS2W caps; | |
296 MMRESULT result = midiInGetDevCaps( | |
297 device_id, reinterpret_cast<LPMIDIINCAPSW>(&caps), sizeof(caps)); | |
298 if (result != MMSYSERR_NOERROR) { | |
299 LOG(ERROR) << "midiInGetDevCaps fails on device " << device_id; | |
300 continue; | |
301 } | |
302 std::unique_ptr<InPort> port = | |
303 base::MakeUnique<InPort>(instance_id_, device_id, caps); | |
304 const auto& found = std::find_if( | |
305 input_ports_.begin(), input_ports_.end(), | |
306 [&port](const auto& candidate) { return *candidate == *port; }); | |
307 if (found == input_ports_.end()) { | |
308 new_input_ports.push_back(std::move(port)); | |
309 } else { | |
310 // Update device ID which may be changed when device list is updated. | |
311 (*found)->set_device_id(device_id); | |
312 // Found devices in the list are marked to |EnumerateState::Connected|. | |
313 (*found)->set_enumerate_state(EnumerateState::Connected); | |
314 } | |
315 } | |
316 for (const auto& port : input_ports_) { | |
317 if (port->enumerate_state() == EnumerateState::Enumerating) { | |
318 // Disconnected ports have kept staying in |EnumerateState::Enumerating| | |
319 // state as they were marked first. | |
320 if (port->IsConnected()) { | |
321 // Change state and notify it. | |
322 port->Disconnect(); | |
323 PostReplyTask(base::Bind( | |
324 &DynamicallyInitializedMidiManagerWin::SetInputPortState, | |
325 base::Unretained(this), port->index(), port->info().state)); | |
326 } | |
327 } else if (port->enumerate_state() == EnumerateState::Connected) { | |
328 // Ports that have been connected, and are going to be connected now are | |
329 // in |EnumerateState::Connected| state. | |
330 if (!port->IsConnected()) { | |
331 // Change state and notify it. | |
332 port->Connect(); | |
333 PostReplyTask(base::Bind( | |
334 &DynamicallyInitializedMidiManagerWin::SetInputPortState, | |
335 base::Unretained(this), port->index(), port->info().state)); | |
336 } | |
337 } | |
338 } | |
339 // Assign port index to new devices and move them to the port list. | |
340 size_t in_index = input_ports_.size(); | |
341 for (const auto& port : new_input_ports) { | |
342 port->set_index(in_index++); | |
343 port->Connect(); | |
344 PostReplyTask( | |
345 base::Bind(&DynamicallyInitializedMidiManagerWin::AddInputPort, | |
346 base::Unretained(this), port->info())); | |
347 } | |
348 input_ports_.insert(input_ports_.end(), | |
349 std::make_move_iterator(new_input_ports.begin()), | |
350 std::make_move_iterator(new_input_ports.end())); | |
351 | |
352 // Update the devie list for output ports. | |
353 // First, mark all registered output ports to |EnumerateState::Enumerating|. | |
354 for (const auto& port : output_ports_) | |
355 port->set_enumerate_state(EnumerateState::Enumerating); | |
356 | |
357 std::vector<std::unique_ptr<OutPort>> new_output_ports; | |
358 const UINT num_out_devices = midiOutGetNumDevs(); | |
359 for (UINT device_id = 0; device_id < num_out_devices; ++device_id) { | |
360 MIDIOUTCAPS2W caps; | |
361 MMRESULT result = midiOutGetDevCaps( | |
362 device_id, reinterpret_cast<LPMIDIOUTCAPSW>(&caps), sizeof(caps)); | |
363 if (result != MMSYSERR_NOERROR) { | |
364 LOG(ERROR) << "midiOutGetDevCaps fails on device " << device_id; | |
365 continue; | |
366 } | |
367 std::unique_ptr<OutPort> port = base::MakeUnique<OutPort>(device_id, caps); | |
368 const auto& found = std::find_if( | |
369 output_ports_.begin(), output_ports_.end(), | |
370 [&port](const auto& candidate) { return *candidate == *port; }); | |
371 if (found == output_ports_.end()) { | |
372 new_output_ports.push_back(std::move(port)); | |
373 } else { | |
374 // Update device ID which may be changed when device list is updated. | |
375 (*found)->set_device_id(device_id); | |
376 // Found devices in the list are marked to |EnumerateState::Connected|. | |
377 (*found)->set_enumerate_state(EnumerateState::Connected); | |
378 } | |
379 } | |
380 for (const auto& port : output_ports_) { | |
381 if (port->enumerate_state() == EnumerateState::Enumerating) { | |
382 // Disconnected ports have kept staying in |EnumerateState::Enumerating| | |
383 // state as they were marked first. | |
384 if (port->IsConnected()) { | |
385 // Change state and notify it. | |
386 port->Disconnect(); | |
387 PostReplyTask(base::Bind( | |
388 &DynamicallyInitializedMidiManagerWin::SetOutputPortState, | |
389 base::Unretained(this), port->index(), port->info().state)); | |
390 } | |
391 } else if (port->enumerate_state() == EnumerateState::Connected) { | |
392 // Ports that have been connected, and are going to be connected now are | |
393 // in |EnumerateState::Connected| state. | |
394 if (!port->IsConnected()) { | |
395 // Try changing state and notify it if it was changed. Note that | |
396 // Connect() won't change the state on output ports for software synth. | |
397 port->Connect(); | |
398 if (port->IsConnected()) { | |
399 PostReplyTask(base::Bind( | |
400 &DynamicallyInitializedMidiManagerWin::SetOutputPortState, | |
401 base::Unretained(this), port->index(), port->info().state)); | |
402 } | |
403 } | |
404 } | |
405 } | |
406 // Assign port index to new devices and move them to the port list. | |
407 size_t out_index = output_ports_.size(); | |
408 for (const auto& port : new_output_ports) { | |
409 port->set_index(out_index++); | |
410 port->Connect(); | |
411 PostReplyTask( | |
412 base::Bind(&DynamicallyInitializedMidiManagerWin::AddOutputPort, | |
413 base::Unretained(this), port->info())); | |
414 } | |
415 output_ports_.insert(output_ports_.end(), | |
416 std::make_move_iterator(new_output_ports.begin()), | |
417 std::make_move_iterator(new_output_ports.end())); | |
418 | |
419 // TODO(toyoshim): This method may run before internal MIDI device lists that | |
420 // Windows manages were updated. This may be because MIDI driver may be loaded | |
421 // after the raw device list was updated. To avoid this problem, we may want | |
422 // to retry device check later if no changes are detected here. | |
423 } | |
424 | |
425 } // namespace midi | |
OLD | NEW |