OLD | NEW |
1 // Copyright 2014 The Chromium Authors. All rights reserved. | 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "media/midi/midi_manager_alsa.h" | 5 #include "media/midi/midi_manager_alsa.h" |
6 | 6 |
7 #include <errno.h> | 7 #include <errno.h> |
8 #include <poll.h> | 8 #include <poll.h> |
9 #include <stddef.h> | 9 #include <stddef.h> |
10 #include <stdlib.h> | 10 #include <stdlib.h> |
11 | 11 |
12 #include <algorithm> | 12 #include <algorithm> |
13 #include <string> | 13 #include <string> |
14 #include <utility> | 14 #include <utility> |
15 | 15 |
16 #include "base/bind.h" | 16 #include "base/bind.h" |
17 #include "base/json/json_string_value_serializer.h" | 17 #include "base/json/json_string_value_serializer.h" |
| 18 #include "base/lazy_instance.h" |
18 #include "base/logging.h" | 19 #include "base/logging.h" |
19 #include "base/macros.h" | 20 #include "base/macros.h" |
20 #include "base/memory/ptr_util.h" | 21 #include "base/memory/ptr_util.h" |
21 #include "base/message_loop/message_loop.h" | 22 #include "base/message_loop/message_loop.h" |
22 #include "base/posix/eintr_wrapper.h" | 23 #include "base/posix/eintr_wrapper.h" |
23 #include "base/posix/safe_strerror.h" | 24 #include "base/posix/safe_strerror.h" |
24 #include "base/single_thread_task_runner.h" | 25 #include "base/single_thread_task_runner.h" |
25 #include "base/strings/string_number_conversions.h" | 26 #include "base/strings/string_number_conversions.h" |
26 #include "base/strings/stringprintf.h" | 27 #include "base/strings/stringprintf.h" |
27 #include "base/time/time.h" | 28 #include "base/time/time.h" |
28 #include "crypto/sha2.h" | 29 #include "crypto/sha2.h" |
29 #include "media/midi/midi_port_info.h" | 30 #include "media/midi/midi_port_info.h" |
| 31 #include "media/midi/midi_service.h" |
30 | 32 |
31 namespace midi { | 33 namespace midi { |
32 | 34 |
33 namespace { | 35 namespace { |
34 | 36 |
35 using mojom::PortState; | 37 using mojom::PortState; |
36 using mojom::Result; | 38 using mojom::Result; |
37 | 39 |
| 40 // TODO(toyoshim): use constexpr for following const values. |
| 41 const int kEventTaskRunner = 0; |
| 42 const int kSendTaskRunner = 1; |
| 43 |
38 // Per-output buffer. This can be smaller, but then large sysex messages | 44 // Per-output buffer. This can be smaller, but then large sysex messages |
39 // will be (harmlessly) split across multiple seq events. This should | 45 // will be (harmlessly) split across multiple seq events. This should |
40 // not have any real practical effect, except perhaps to slightly reorder | 46 // not have any real practical effect, except perhaps to slightly reorder |
41 // realtime messages with respect to sysex. | 47 // realtime messages with respect to sysex. |
42 const size_t kSendBufferSize = 256; | 48 const size_t kSendBufferSize = 256; |
43 | 49 |
44 // Minimum client id for which we will have ALSA card devices for. When we | 50 // Minimum client id for which we will have ALSA card devices for. When we |
45 // are searching for card devices (used to get the path, id, and manufacturer), | 51 // are searching for card devices (used to get the path, id, and manufacturer), |
46 // we don't want to get confused by kernel clients that do not have a card. | 52 // we don't want to get confused by kernel clients that do not have a card. |
47 // See seq_clientmgr.c in the ALSA code for this. | 53 // See seq_clientmgr.c in the ALSA code for this. |
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
83 const unsigned int kRequiredOutputPortCaps = | 89 const unsigned int kRequiredOutputPortCaps = |
84 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE; | 90 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE; |
85 | 91 |
86 const unsigned int kCreateOutputPortCaps = | 92 const unsigned int kCreateOutputPortCaps = |
87 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_NO_EXPORT; | 93 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_NO_EXPORT; |
88 const unsigned int kCreateInputPortCaps = | 94 const unsigned int kCreateInputPortCaps = |
89 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_NO_EXPORT; | 95 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_NO_EXPORT; |
90 const unsigned int kCreatePortType = | 96 const unsigned int kCreatePortType = |
91 SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION; | 97 SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION; |
92 | 98 |
| 99 // Global variables to protect tasks running on external TaskRunners from |
| 100 // running with another MidiManagerAlsa instance. These IDs can be read |
| 101 // under one of following task_runner_lock, and can be written under both |
| 102 // task_runner_lock. |
| 103 const int kInvalidManagerId = -1; |
| 104 int g_active_manager_id = kInvalidManagerId; |
| 105 int g_next_manager_id = 0; |
| 106 |
| 107 // Protects tasks that run on external TaskRunners. |
| 108 base::LazyInstance<base::Lock> g_event_task_runner_lock = |
| 109 LAZY_INSTANCE_INITIALIZER; |
| 110 base::LazyInstance<base::Lock> g_send_task_runner_lock = |
| 111 LAZY_INSTANCE_INITIALIZER; |
| 112 |
93 int AddrToInt(int client, int port) { | 113 int AddrToInt(int client, int port) { |
94 return (client << 8) | port; | 114 return (client << 8) | port; |
95 } | 115 } |
96 | 116 |
97 // Returns true if this client has an ALSA card associated with it. | 117 // Returns true if this client has an ALSA card associated with it. |
98 bool IsCardClient(snd_seq_client_type_t type, int client_id) { | 118 bool IsCardClient(snd_seq_client_type_t type, int client_id) { |
99 return (type == SND_SEQ_KERNEL_CLIENT) && | 119 return (type == SND_SEQ_KERNEL_CLIENT) && |
100 (client_id >= kMinimumClientIdForCards); | 120 (client_id >= kMinimumClientIdForCards); |
101 } | 121 } |
102 | 122 |
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
146 | 166 |
147 void SetStringIfNonEmpty(base::DictionaryValue* value, | 167 void SetStringIfNonEmpty(base::DictionaryValue* value, |
148 const std::string& path, | 168 const std::string& path, |
149 const std::string& in_value) { | 169 const std::string& in_value) { |
150 if (!in_value.empty()) | 170 if (!in_value.empty()) |
151 value->SetString(path, in_value); | 171 value->SetString(path, in_value); |
152 } | 172 } |
153 | 173 |
154 } // namespace | 174 } // namespace |
155 | 175 |
156 MidiManagerAlsa::MidiManagerAlsa() | 176 MidiManagerAlsa::MidiManagerAlsa() { |
157 : event_thread_("MidiEventThread"), send_thread_("MidiSendThread") {} | 177 base::AutoLock event_runner_lock(g_event_task_runner_lock.Get()); |
| 178 base::AutoLock send_runner_lock(g_send_task_runner_lock.Get()); |
| 179 instance_id_ = g_next_manager_id++; |
| 180 g_active_manager_id = instance_id_; |
| 181 } |
158 | 182 |
159 MidiManagerAlsa::~MidiManagerAlsa() { | 183 MidiManagerAlsa::~MidiManagerAlsa() { |
160 // Take lock to ensure that the members initialized on the IO thread | 184 // Take lock to ensure that the members initialized on the IO thread |
161 // are not destructed here. | 185 // are not destructed here. |
162 base::AutoLock lock(lazy_init_member_lock_); | 186 base::AutoLock lock(lazy_init_member_lock_); |
163 | 187 |
164 // Extra CHECK to verify all members are already reset. | 188 // Extra CHECK to verify all members are already reset. |
165 CHECK(!initialization_thread_checker_); | 189 CHECK(!initialization_thread_checker_); |
166 CHECK(!in_client_); | 190 CHECK(!in_client_); |
167 CHECK(!out_client_); | 191 CHECK(!out_client_); |
168 CHECK(!decoder_); | 192 CHECK(!decoder_); |
169 CHECK(!udev_); | 193 CHECK(!udev_); |
170 CHECK(!udev_monitor_); | 194 CHECK(!udev_monitor_); |
171 | |
172 CHECK(!send_thread_.IsRunning()); | |
173 CHECK(!event_thread_.IsRunning()); | |
174 } | 195 } |
175 | 196 |
176 void MidiManagerAlsa::StartInitialization() { | 197 void MidiManagerAlsa::StartInitialization() { |
177 base::AutoLock lock(lazy_init_member_lock_); | 198 base::AutoLock lock(lazy_init_member_lock_); |
178 | 199 |
179 initialization_thread_checker_.reset(new base::ThreadChecker()); | 200 initialization_thread_checker_.reset(new base::ThreadChecker()); |
180 | 201 |
181 // Create client handles. | 202 // Create client handles. |
182 snd_seq_t* tmp_seq = nullptr; | 203 snd_seq_t* tmp_seq = nullptr; |
183 int err = | 204 int err = |
(...skipping 97 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
281 // TODO(agoode): Check the return value for failure. | 302 // TODO(agoode): Check the return value for failure. |
282 EnumerateAlsaPorts(); | 303 EnumerateAlsaPorts(); |
283 | 304 |
284 // Generate hotplug events for existing udev devices. This must be done | 305 // Generate hotplug events for existing udev devices. This must be done |
285 // after udev_monitor_enable_receiving() is called. See the algorithm | 306 // after udev_monitor_enable_receiving() is called. See the algorithm |
286 // at http://www.signal11.us/oss/udev/. | 307 // at http://www.signal11.us/oss/udev/. |
287 EnumerateUdevCards(); | 308 EnumerateUdevCards(); |
288 | 309 |
289 // Start processing events. Don't do this before enumeration of both | 310 // Start processing events. Don't do this before enumeration of both |
290 // ALSA and udev. | 311 // ALSA and udev. |
291 event_thread_.Start(); | 312 MidiService::GetTaskRunner(kEventTaskRunner) |
292 event_thread_.task_runner()->PostTask( | 313 ->PostTask(FROM_HERE, base::Bind(&MidiManagerAlsa::EventLoop, |
293 FROM_HERE, | 314 base::Unretained(this), instance_id_)); |
294 base::Bind(&MidiManagerAlsa::ScheduleEventLoop, base::Unretained(this))); | |
295 send_thread_.Start(); | |
296 | 315 |
297 CompleteInitialization(Result::OK); | 316 CompleteInitialization(Result::OK); |
298 } | 317 } |
299 | 318 |
300 void MidiManagerAlsa::Finalize() { | 319 void MidiManagerAlsa::Finalize() { |
301 base::AutoLock lock(lazy_init_member_lock_); | 320 base::AutoLock lock(lazy_init_member_lock_); |
302 DCHECK(initialization_thread_checker_->CalledOnValidThread()); | 321 DCHECK(initialization_thread_checker_->CalledOnValidThread()); |
303 | 322 |
304 // Tell the event thread it will soon be time to shut down. This gives | 323 // Tell the event thread it will soon be time to shut down. This gives |
305 // us assurance the thread will stop in case the SND_SEQ_EVENT_CLIENT_EXIT | 324 // us assurance the thread will stop in case the SND_SEQ_EVENT_CLIENT_EXIT |
306 // message is lost. | 325 // message is lost. |
307 { | 326 { |
308 base::AutoLock lock(shutdown_lock_); | 327 base::AutoLock lock(shutdown_lock_); |
309 event_thread_shutdown_ = true; | 328 event_thread_shutdown_ = true; |
310 } | 329 } |
311 | 330 |
312 // Stop the send thread. | 331 // Ensure that no tasks run on kSendTaskRunner. |
313 send_thread_.Stop(); | 332 base::AutoLock send_runner_lock(g_send_task_runner_lock.Get()); |
314 | 333 |
315 // Close the out client. This will trigger the event thread to stop, | 334 // Close the out client. This will trigger the event thread to stop, |
316 // because of SND_SEQ_EVENT_CLIENT_EXIT. | 335 // because of SND_SEQ_EVENT_CLIENT_EXIT. |
317 out_client_.reset(); | 336 out_client_.reset(); |
318 | 337 |
319 // Wait for the event thread to stop. | 338 // Ensure that no tasks run on kEventTaskRunner. |
320 event_thread_.Stop(); | 339 base::AutoLock event_runner_lock(g_event_task_runner_lock.Get()); |
| 340 |
| 341 // All pending tasks including one blocked on a lock do nothing from now on. |
| 342 g_active_manager_id = kInvalidManagerId; |
321 | 343 |
322 // Destruct the other stuff we initialized in StartInitialization(). | 344 // Destruct the other stuff we initialized in StartInitialization(). |
323 udev_monitor_.reset(); | 345 udev_monitor_.reset(); |
324 udev_.reset(); | 346 udev_.reset(); |
325 decoder_.reset(); | 347 decoder_.reset(); |
326 in_client_.reset(); | 348 in_client_.reset(); |
327 initialization_thread_checker_.reset(); | 349 initialization_thread_checker_.reset(); |
328 } | 350 } |
329 | 351 |
330 void MidiManagerAlsa::DispatchSendMidiData(MidiManagerClient* client, | 352 void MidiManagerAlsa::DispatchSendMidiData(MidiManagerClient* client, |
331 uint32_t port_index, | 353 uint32_t port_index, |
332 const std::vector<uint8_t>& data, | 354 const std::vector<uint8_t>& data, |
333 double timestamp) { | 355 double timestamp) { |
334 base::TimeDelta delay; | 356 base::TimeDelta delay; |
335 if (timestamp != 0.0) { | 357 if (timestamp != 0.0) { |
336 base::TimeTicks time_to_send = | 358 base::TimeTicks time_to_send = |
337 base::TimeTicks() + base::TimeDelta::FromMicroseconds( | 359 base::TimeTicks() + base::TimeDelta::FromMicroseconds( |
338 timestamp * base::Time::kMicrosecondsPerSecond); | 360 timestamp * base::Time::kMicrosecondsPerSecond); |
339 delay = std::max(time_to_send - base::TimeTicks::Now(), base::TimeDelta()); | 361 delay = std::max(time_to_send - base::TimeTicks::Now(), base::TimeDelta()); |
340 } | 362 } |
341 | 363 |
342 send_thread_.task_runner()->PostDelayedTask( | 364 MidiService::GetTaskRunner(kSendTaskRunner) |
343 FROM_HERE, base::Bind(&MidiManagerAlsa::SendMidiData, | 365 ->PostDelayedTask( |
344 base::Unretained(this), port_index, data), | 366 FROM_HERE, |
345 delay); | 367 base::Bind(&MidiManagerAlsa::SendMidiData, base::Unretained(this), |
346 | 368 instance_id_, client, port_index, data), |
347 // Acknowledge send. | 369 delay); |
348 send_thread_.task_runner()->PostTask( | |
349 FROM_HERE, base::Bind(&MidiManagerAlsa::AccumulateMidiBytesSent, | |
350 base::Unretained(this), client, data.size())); | |
351 } | 370 } |
352 | 371 |
353 MidiManagerAlsa::MidiPort::Id::Id() = default; | 372 MidiManagerAlsa::MidiPort::Id::Id() = default; |
354 | 373 |
355 MidiManagerAlsa::MidiPort::Id::Id(const std::string& bus, | 374 MidiManagerAlsa::MidiPort::Id::Id(const std::string& bus, |
356 const std::string& vendor_id, | 375 const std::string& vendor_id, |
357 const std::string& model_id, | 376 const std::string& model_id, |
358 const std::string& usb_interface_num, | 377 const std::string& usb_interface_num, |
359 const std::string& serial) | 378 const std::string& serial) |
360 : bus_(bus), | 379 : bus_(bus), |
(...skipping 496 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
857 if (at_index && at_index != std::string::npos) { | 876 if (at_index && at_index != std::string::npos) { |
858 size_t name_index = alsa_longname.rfind(alsa_name, at_index - 1); | 877 size_t name_index = alsa_longname.rfind(alsa_name, at_index - 1); |
859 if (name_index && name_index != std::string::npos) | 878 if (name_index && name_index != std::string::npos) |
860 return alsa_longname.substr(0, name_index - 1); | 879 return alsa_longname.substr(0, name_index - 1); |
861 } | 880 } |
862 | 881 |
863 // Failure. | 882 // Failure. |
864 return ""; | 883 return ""; |
865 } | 884 } |
866 | 885 |
867 void MidiManagerAlsa::SendMidiData(uint32_t port_index, | 886 void MidiManagerAlsa::SendMidiData(int instance_id, |
| 887 MidiManagerClient* client, |
| 888 uint32_t port_index, |
868 const std::vector<uint8_t>& data) { | 889 const std::vector<uint8_t>& data) { |
869 DCHECK(send_thread_.task_runner()->BelongsToCurrentThread()); | 890 DCHECK(MidiService::GetTaskRunner(kSendTaskRunner)->BelongsToCurrentThread()); |
| 891 base::AutoLock lock(g_send_task_runner_lock.Get()); |
| 892 if (instance_id != g_active_manager_id) |
| 893 return; |
870 | 894 |
871 snd_midi_event_t* encoder; | 895 snd_midi_event_t* encoder; |
872 snd_midi_event_new(kSendBufferSize, &encoder); | 896 snd_midi_event_new(kSendBufferSize, &encoder); |
873 for (const auto datum : data) { | 897 for (const auto datum : data) { |
874 snd_seq_event_t event; | 898 snd_seq_event_t event; |
875 int result = snd_midi_event_encode_byte(encoder, datum, &event); | 899 int result = snd_midi_event_encode_byte(encoder, datum, &event); |
876 if (result == 1) { | 900 if (result == 1) { |
877 // Full event, send it. | 901 // Full event, send it. |
878 base::AutoLock lock(out_ports_lock_); | 902 base::AutoLock lock(out_ports_lock_); |
879 auto it = out_ports_.find(port_index); | 903 auto it = out_ports_.find(port_index); |
880 if (it != out_ports_.end()) { | 904 if (it != out_ports_.end()) { |
881 snd_seq_ev_set_source(&event, it->second); | 905 snd_seq_ev_set_source(&event, it->second); |
882 snd_seq_ev_set_subs(&event); | 906 snd_seq_ev_set_subs(&event); |
883 snd_seq_ev_set_direct(&event); | 907 snd_seq_ev_set_direct(&event); |
884 snd_seq_event_output_direct(out_client_.get(), &event); | 908 snd_seq_event_output_direct(out_client_.get(), &event); |
885 } | 909 } |
886 } | 910 } |
887 } | 911 } |
888 snd_midi_event_free(encoder); | 912 snd_midi_event_free(encoder); |
| 913 |
| 914 // Acknowledge send. |
| 915 AccumulateMidiBytesSent(client, data.size()); |
889 } | 916 } |
890 | 917 |
891 void MidiManagerAlsa::ScheduleEventLoop() { | 918 void MidiManagerAlsa::EventLoop(int instance_id) { |
892 event_thread_.task_runner()->PostTask( | 919 base::AutoLock lock(g_event_task_runner_lock.Get()); |
893 FROM_HERE, | 920 if (instance_id != g_active_manager_id) |
894 base::Bind(&MidiManagerAlsa::EventLoop, base::Unretained(this))); | 921 return; |
895 } | |
896 | 922 |
897 void MidiManagerAlsa::EventLoop() { | |
898 bool loop_again = true; | 923 bool loop_again = true; |
899 | 924 |
900 struct pollfd pfd[2]; | 925 struct pollfd pfd[2]; |
901 snd_seq_poll_descriptors(in_client_.get(), &pfd[0], 1, POLLIN); | 926 snd_seq_poll_descriptors(in_client_.get(), &pfd[0], 1, POLLIN); |
902 pfd[1].fd = device::udev_monitor_get_fd(udev_monitor_.get()); | 927 pfd[1].fd = device::udev_monitor_get_fd(udev_monitor_.get()); |
903 pfd[1].events = POLLIN; | 928 pfd[1].events = POLLIN; |
904 | 929 |
905 int err = HANDLE_EINTR(poll(pfd, arraysize(pfd), -1)); | 930 int err = HANDLE_EINTR(poll(pfd, arraysize(pfd), -1)); |
906 if (err < 0) { | 931 if (err < 0) { |
907 VLOG(1) << "poll fails: " << base::safe_strerror(errno); | 932 VLOG(1) << "poll fails: " << base::safe_strerror(errno); |
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
966 device::ScopedUdevDevicePtr dev( | 991 device::ScopedUdevDevicePtr dev( |
967 device::udev_monitor_receive_device(udev_monitor_.get())); | 992 device::udev_monitor_receive_device(udev_monitor_.get())); |
968 if (dev.get()) | 993 if (dev.get()) |
969 ProcessUdevEvent(dev.get()); | 994 ProcessUdevEvent(dev.get()); |
970 else | 995 else |
971 VLOG(1) << "udev_monitor_receive_device fails"; | 996 VLOG(1) << "udev_monitor_receive_device fails"; |
972 } | 997 } |
973 } | 998 } |
974 | 999 |
975 // Do again. | 1000 // Do again. |
976 if (loop_again) | 1001 if (loop_again) { |
977 ScheduleEventLoop(); | 1002 MidiService::GetTaskRunner(kEventTaskRunner) |
| 1003 ->PostTask(FROM_HERE, base::Bind(&MidiManagerAlsa::EventLoop, |
| 1004 base::Unretained(this), instance_id)); |
| 1005 } |
978 } | 1006 } |
979 | 1007 |
980 void MidiManagerAlsa::ProcessSingleEvent(snd_seq_event_t* event, | 1008 void MidiManagerAlsa::ProcessSingleEvent(snd_seq_event_t* event, |
981 double timestamp) { | 1009 double timestamp) { |
982 auto source_it = | 1010 auto source_it = |
983 source_map_.find(AddrToInt(event->source.client, event->source.port)); | 1011 source_map_.find(AddrToInt(event->source.client, event->source.port)); |
984 if (source_it != source_map_.end()) { | 1012 if (source_it != source_map_.end()) { |
985 uint32_t source = source_it->second; | 1013 uint32_t source = source_it->second; |
986 if (event->type == SND_SEQ_EVENT_SYSEX) { | 1014 if (event->type == SND_SEQ_EVENT_SYSEX) { |
987 // Special! Variable-length sysex. | 1015 // Special! Variable-length sysex. |
(...skipping 411 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1399 // Update our map. | 1427 // Update our map. |
1400 source_map_[AddrToInt(client_id, port_id)] = port_index; | 1428 source_map_[AddrToInt(client_id, port_id)] = port_index; |
1401 return true; | 1429 return true; |
1402 } | 1430 } |
1403 | 1431 |
1404 MidiManager* MidiManager::Create() { | 1432 MidiManager* MidiManager::Create() { |
1405 return new MidiManagerAlsa(); | 1433 return new MidiManagerAlsa(); |
1406 } | 1434 } |
1407 | 1435 |
1408 } // namespace midi | 1436 } // namespace midi |
OLD | NEW |