blob: 751b736324794c09ff327484c6ef8fd7e1bf21d2 [file] [log] [blame]
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +00001// Copyright 2014 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
dnicoara@chromium.org9f2a6f02014-01-03 21:25:00 +00005#include "media/midi/midi_manager_alsa.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +00006
mostynbbd693172015-11-17 19:06:54 -08007#include <errno.h>
agoode975043d2015-05-11 00:46:17 -07008#include <poll.h>
avi793390d2015-12-22 22:22:36 -08009#include <stddef.h>
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +000010#include <stdlib.h>
danakj75afea02016-04-25 20:36:04 -070011
yhirano@chromium.orgcfa642c2014-05-01 08:54:41 +000012#include <algorithm>
13#include <string>
limasdfe59d0392015-11-19 20:28:57 -080014#include <utility>
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000015
16#include "base/bind.h"
agoodef212b2a2015-03-19 12:53:23 -070017#include "base/json/json_string_value_serializer.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000018#include "base/logging.h"
avi793390d2015-12-22 22:22:36 -080019#include "base/macros.h"
danakj75afea02016-04-25 20:36:04 -070020#include "base/memory/ptr_util.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000021#include "base/message_loop/message_loop.h"
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +000022#include "base/posix/eintr_wrapper.h"
brettwf7f870f2015-06-09 11:05:24 -070023#include "base/posix/safe_strerror.h"
agoodef212b2a2015-03-19 12:53:23 -070024#include "base/strings/string_number_conversions.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000025#include "base/strings/stringprintf.h"
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +000026#include "base/time/time.h"
agoodef212b2a2015-03-19 12:53:23 -070027#include "crypto/sha2.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000028#include "media/midi/midi_port_info.h"
29
30namespace media {
toyoshime147c5e2015-05-07 21:58:31 -070031namespace midi {
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000032
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +000033namespace {
34
agoode@chromium.org25227512014-06-08 05:12:05 +000035// Per-output buffer. This can be smaller, but then large sysex messages
36// will be (harmlessly) split across multiple seq events. This should
37// not have any real practical effect, except perhaps to slightly reorder
38// realtime messages with respect to sysex.
39const size_t kSendBufferSize = 256;
40
agoodeb09423b2015-05-11 11:39:57 -070041// Minimum client id for which we will have ALSA card devices for. When we
42// are searching for card devices (used to get the path, id, and manufacturer),
43// we don't want to get confused by kernel clients that do not have a card.
44// See seq_clientmgr.c in the ALSA code for this.
45// TODO(agoode): Add proper client -> card export from the kernel to avoid
46// hardcoding.
47const int kMinimumClientIdForCards = 16;
48
agoodef212b2a2015-03-19 12:53:23 -070049// ALSA constants.
50const char kAlsaHw[] = "hw";
51
agoode975043d2015-05-11 00:46:17 -070052// udev constants.
53const char kUdev[] = "udev";
54const char kUdevSubsystemSound[] = "sound";
55const char kUdevPropertySoundInitialized[] = "SOUND_INITIALIZED";
56const char kUdevActionChange[] = "change";
57const char kUdevActionRemove[] = "remove";
58
agoodeb09423b2015-05-11 11:39:57 -070059const char kUdevIdVendor[] = "ID_VENDOR";
60const char kUdevIdVendorEnc[] = "ID_VENDOR_ENC";
61const char kUdevIdVendorFromDatabase[] = "ID_VENDOR_FROM_DATABASE";
62const char kUdevIdVendorId[] = "ID_VENDOR_ID";
63const char kUdevIdModelId[] = "ID_MODEL_ID";
64const char kUdevIdBus[] = "ID_BUS";
65const char kUdevIdPath[] = "ID_PATH";
66const char kUdevIdUsbInterfaceNum[] = "ID_USB_INTERFACE_NUM";
67const char kUdevIdSerialShort[] = "ID_SERIAL_SHORT";
68
69const char kSysattrVendorName[] = "vendor_name";
70const char kSysattrVendor[] = "vendor";
71const char kSysattrModel[] = "model";
72const char kSysattrGuid[] = "guid";
73
74const char kCardSyspath[] = "/card";
75
agoode@chromium.org25227512014-06-08 05:12:05 +000076// Constants for the capabilities we search for in inputs and outputs.
77// See http://www.alsa-project.org/alsa-doc/alsa-lib/seq.html.
78const unsigned int kRequiredInputPortCaps =
79 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ;
80const unsigned int kRequiredOutputPortCaps =
81 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE;
82
agoode99d63292015-04-13 08:39:25 -070083const unsigned int kCreateOutputPortCaps =
84 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_NO_EXPORT;
85const unsigned int kCreateInputPortCaps =
86 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_NO_EXPORT;
87const unsigned int kCreatePortType =
88 SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION;
agoode@chromium.org25227512014-06-08 05:12:05 +000089
agoode99d63292015-04-13 08:39:25 -070090int AddrToInt(int client, int port) {
91 return (client << 8) | port;
agoodef212b2a2015-03-19 12:53:23 -070092}
agoodef212b2a2015-03-19 12:53:23 -070093
agoodeb09423b2015-05-11 11:39:57 -070094// Returns true if this client has an ALSA card associated with it.
95bool IsCardClient(snd_seq_client_type_t type, int client_id) {
96 return (type == SND_SEQ_KERNEL_CLIENT) &&
97 (client_id >= kMinimumClientIdForCards);
98}
99
100// TODO(agoode): Move this to device/udev_linux.
101const std::string UdevDeviceGetPropertyOrSysattr(
102 struct udev_device* udev_device,
103 const char* property_key,
104 const char* sysattr_key) {
105 // First try the property.
106 std::string value =
107 device::UdevDeviceGetPropertyValue(udev_device, property_key);
108
109 // If no property, look for sysattrs and walk up the parent devices too.
110 while (value.empty() && udev_device) {
111 value = device::UdevDeviceGetSysattrValue(udev_device, sysattr_key);
112 udev_device = device::udev_device_get_parent(udev_device);
113 }
114 return value;
115}
116
117int GetCardNumber(udev_device* dev) {
118 const char* syspath = device::udev_device_get_syspath(dev);
119 if (!syspath)
120 return -1;
121
122 std::string syspath_str(syspath);
123 size_t i = syspath_str.rfind(kCardSyspath);
124 if (i == std::string::npos)
125 return -1;
126
127 int number;
128 if (!base::StringToInt(syspath_str.substr(i + strlen(kCardSyspath)), &number))
129 return -1;
130 return number;
131}
132
agooded87fc0f2015-05-21 08:29:31 -0700133std::string GetVendor(udev_device* dev) {
134 // Try to get the vendor string. Sometimes it is encoded.
135 std::string vendor = device::UdevDecodeString(
136 device::UdevDeviceGetPropertyValue(dev, kUdevIdVendorEnc));
137 // Sometimes it is not encoded.
138 if (vendor.empty())
139 vendor =
140 UdevDeviceGetPropertyOrSysattr(dev, kUdevIdVendor, kSysattrVendorName);
141 return vendor;
142}
143
agoode8caab0b2015-03-23 18:48:02 -0700144void SetStringIfNonEmpty(base::DictionaryValue* value,
145 const std::string& path,
146 const std::string& in_value) {
147 if (!in_value.empty())
148 value->SetString(path, in_value);
149}
150
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000151} // namespace
152
toyoshim@chromium.orgc82e66e2014-02-04 07:05:47 +0000153MidiManagerAlsa::MidiManagerAlsa()
agoodeb2ead822016-03-11 12:14:35 -0800154 : event_thread_("MidiEventThread"), send_thread_("MidiSendThread") {}
155
156MidiManagerAlsa::~MidiManagerAlsa() {
157 // Take lock to ensure that the members initialized on the IO thread
158 // are not destructed here.
159 base::AutoLock lock(lazy_init_member_lock_);
160
161 // Extra DCHECK to verify all members are already reset.
162 DCHECK(!initialization_thread_checker_);
163 DCHECK(!in_client_);
164 DCHECK(!out_client_);
165 DCHECK(!decoder_);
166 DCHECK(!udev_);
167 DCHECK(!udev_monitor_);
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000168}
169
toyoshim@chromium.org51c7f532014-05-01 17:17:32 +0000170void MidiManagerAlsa::StartInitialization() {
agoodeb2ead822016-03-11 12:14:35 -0800171 base::AutoLock lock(lazy_init_member_lock_);
agoode5a1aa112015-06-21 20:51:00 -0700172
agoodeb2ead822016-03-11 12:14:35 -0800173 initialization_thread_checker_.reset(new base::ThreadChecker());
174
175 // Create client handles.
176 snd_seq_t* tmp_seq = nullptr;
177 int err =
178 snd_seq_open(&tmp_seq, kAlsaHw, SND_SEQ_OPEN_INPUT, SND_SEQ_NONBLOCK);
agoode@chromium.org25227512014-06-08 05:12:05 +0000179 if (err != 0) {
180 VLOG(1) << "snd_seq_open fails: " << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700181 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000182 }
agoodeb2ead822016-03-11 12:14:35 -0800183 ScopedSndSeqPtr in_client(tmp_seq);
184 tmp_seq = nullptr;
185 in_client_id_ = snd_seq_client_id(in_client.get());
186
187 err = snd_seq_open(&tmp_seq, kAlsaHw, SND_SEQ_OPEN_OUTPUT, 0);
188 if (err != 0) {
189 VLOG(1) << "snd_seq_open fails: " << snd_strerror(err);
190 return CompleteInitialization(Result::INITIALIZATION_ERROR);
191 }
192 ScopedSndSeqPtr out_client(tmp_seq);
193 tmp_seq = nullptr;
194 out_client_id_ = snd_seq_client_id(out_client.get());
agoode@chromium.org25227512014-06-08 05:12:05 +0000195
196 // Name the clients.
agoodeb2ead822016-03-11 12:14:35 -0800197 err = snd_seq_set_client_name(in_client.get(), "Chrome (input)");
agoode@chromium.org25227512014-06-08 05:12:05 +0000198 if (err != 0) {
199 VLOG(1) << "snd_seq_set_client_name fails: " << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700200 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000201 }
agoodeb2ead822016-03-11 12:14:35 -0800202 err = snd_seq_set_client_name(out_client.get(), "Chrome (output)");
agoode@chromium.org25227512014-06-08 05:12:05 +0000203 if (err != 0) {
204 VLOG(1) << "snd_seq_set_client_name fails: " << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700205 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000206 }
207
208 // Create input port.
agoode99d63292015-04-13 08:39:25 -0700209 in_port_id_ = snd_seq_create_simple_port(
agoodeb2ead822016-03-11 12:14:35 -0800210 in_client.get(), NULL, kCreateInputPortCaps, kCreatePortType);
agoode99d63292015-04-13 08:39:25 -0700211 if (in_port_id_ < 0) {
212 VLOG(1) << "snd_seq_create_simple_port fails: "
213 << snd_strerror(in_port_id_);
toyoshimf1b88962015-07-09 14:14:51 -0700214 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000215 }
216
217 // Subscribe to the announce port.
218 snd_seq_port_subscribe_t* subs;
219 snd_seq_port_subscribe_alloca(&subs);
220 snd_seq_addr_t announce_sender;
221 snd_seq_addr_t announce_dest;
222 announce_sender.client = SND_SEQ_CLIENT_SYSTEM;
223 announce_sender.port = SND_SEQ_PORT_SYSTEM_ANNOUNCE;
agoode99d63292015-04-13 08:39:25 -0700224 announce_dest.client = in_client_id_;
225 announce_dest.port = in_port_id_;
agoode@chromium.org25227512014-06-08 05:12:05 +0000226 snd_seq_port_subscribe_set_sender(subs, &announce_sender);
227 snd_seq_port_subscribe_set_dest(subs, &announce_dest);
agoodeb2ead822016-03-11 12:14:35 -0800228 err = snd_seq_subscribe_port(in_client.get(), subs);
agoode@chromium.org25227512014-06-08 05:12:05 +0000229 if (err != 0) {
230 VLOG(1) << "snd_seq_subscribe_port on the announce port fails: "
231 << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700232 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000233 }
234
agoodeb2ead822016-03-11 12:14:35 -0800235 // Initialize decoder.
236 snd_midi_event_t* tmp_decoder = nullptr;
237 snd_midi_event_new(0, &tmp_decoder);
238 ScopedSndMidiEventPtr decoder(tmp_decoder);
239 tmp_decoder = nullptr;
240 snd_midi_event_no_status(decoder.get(), 1);
agoode@chromium.org25227512014-06-08 05:12:05 +0000241
agoodeb2ead822016-03-11 12:14:35 -0800242 // Initialize udev and monitor.
243 device::ScopedUdevPtr udev(device::udev_new());
244 device::ScopedUdevMonitorPtr udev_monitor(
245 device::udev_monitor_new_from_netlink(udev.get(), kUdev));
246 if (!udev_monitor.get()) {
agoode975043d2015-05-11 00:46:17 -0700247 VLOG(1) << "udev_monitor_new_from_netlink fails";
toyoshimf1b88962015-07-09 14:14:51 -0700248 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode975043d2015-05-11 00:46:17 -0700249 }
250 err = device::udev_monitor_filter_add_match_subsystem_devtype(
agoodeb2ead822016-03-11 12:14:35 -0800251 udev_monitor.get(), kUdevSubsystemSound, nullptr);
agoode975043d2015-05-11 00:46:17 -0700252 if (err != 0) {
253 VLOG(1) << "udev_monitor_add_match_subsystem fails: "
brettwf7f870f2015-06-09 11:05:24 -0700254 << base::safe_strerror(-err);
toyoshimf1b88962015-07-09 14:14:51 -0700255 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode975043d2015-05-11 00:46:17 -0700256 }
agoodeb2ead822016-03-11 12:14:35 -0800257 err = device::udev_monitor_enable_receiving(udev_monitor.get());
agoode975043d2015-05-11 00:46:17 -0700258 if (err != 0) {
brettwf7f870f2015-06-09 11:05:24 -0700259 VLOG(1) << "udev_monitor_enable_receiving fails: "
260 << base::safe_strerror(-err);
toyoshimf1b88962015-07-09 14:14:51 -0700261 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode975043d2015-05-11 00:46:17 -0700262 }
263
agoodeb2ead822016-03-11 12:14:35 -0800264 // Success! Now, initialize members from the temporaries. Do not
265 // initialize these earlier, since they need to be destroyed by the
266 // thread that calls Finalize(), not the destructor thread (and we
267 // check this in the destructor).
268 in_client_.reset(in_client.release());
269 out_client_.reset(out_client.release());
270 decoder_.reset(decoder.release());
271 udev_.reset(udev.release());
272 udev_monitor_.reset(udev_monitor_.release());
273
274 // Generate hotplug events for existing ports.
275 // TODO(agoode): Check the return value for failure.
276 EnumerateAlsaPorts();
277
278 // Generate hotplug events for existing udev devices. This must be done
279 // after udev_monitor_enable_receiving() is called. See the algorithm
280 // at http://www.signal11.us/oss/udev/.
agoode975043d2015-05-11 00:46:17 -0700281 EnumerateUdevCards();
282
agoodeb2ead822016-03-11 12:14:35 -0800283 // Start processing events. Don't do this before enumeration of both
284 // ALSA and udev.
agoode@chromium.org25227512014-06-08 05:12:05 +0000285 event_thread_.Start();
286 event_thread_.message_loop()->PostTask(
287 FROM_HERE,
agoodebd4be9b2015-03-16 19:17:25 -0700288 base::Bind(&MidiManagerAlsa::ScheduleEventLoop, base::Unretained(this)));
agoodeb2ead822016-03-11 12:14:35 -0800289 send_thread_.Start();
agoode@chromium.org25227512014-06-08 05:12:05 +0000290
toyoshimf1b88962015-07-09 14:14:51 -0700291 CompleteInitialization(Result::OK);
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000292}
293
toyoshim8e7d6e02015-10-06 08:47:17 -0700294void MidiManagerAlsa::Finalize() {
agoodeb2ead822016-03-11 12:14:35 -0800295 base::AutoLock lock(lazy_init_member_lock_);
296 DCHECK(initialization_thread_checker_->CalledOnValidThread());
297
toyoshim8e7d6e02015-10-06 08:47:17 -0700298 // Tell the event thread it will soon be time to shut down. This gives
299 // us assurance the thread will stop in case the SND_SEQ_EVENT_CLIENT_EXIT
300 // message is lost.
301 {
302 base::AutoLock lock(shutdown_lock_);
303 event_thread_shutdown_ = true;
304 }
305
306 // Stop the send thread.
307 send_thread_.Stop();
308
309 // Close the out client. This will trigger the event thread to stop,
310 // because of SND_SEQ_EVENT_CLIENT_EXIT.
agoodeb2ead822016-03-11 12:14:35 -0800311 out_client_.reset();
toyoshim8e7d6e02015-10-06 08:47:17 -0700312
313 // Wait for the event thread to stop.
314 event_thread_.Stop();
agoodeb2ead822016-03-11 12:14:35 -0800315
316 // Destruct the other stuff we initialized in StartInitialization().
317 udev_monitor_.reset();
318 udev_.reset();
319 decoder_.reset();
320 in_client_.reset();
321 initialization_thread_checker_.reset();
toyoshim8e7d6e02015-10-06 08:47:17 -0700322}
323
toyoshim@chromium.orgc82e66e2014-02-04 07:05:47 +0000324void MidiManagerAlsa::DispatchSendMidiData(MidiManagerClient* client,
Avi Drissman3528fd02015-12-18 20:11:31 -0500325 uint32_t port_index,
326 const std::vector<uint8_t>& data,
dnicoara@chromium.org9f2a6f02014-01-03 21:25:00 +0000327 double timestamp) {
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000328 base::TimeDelta delay;
329 if (timestamp != 0.0) {
330 base::TimeTicks time_to_send =
331 base::TimeTicks() + base::TimeDelta::FromMicroseconds(
agoodebd4be9b2015-03-16 19:17:25 -0700332 timestamp * base::Time::kMicrosecondsPerSecond);
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000333 delay = std::max(time_to_send - base::TimeTicks::Now(), base::TimeDelta());
334 }
335
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000336 send_thread_.message_loop()->PostDelayedTask(
agoodebd4be9b2015-03-16 19:17:25 -0700337 FROM_HERE, base::Bind(&MidiManagerAlsa::SendMidiData,
338 base::Unretained(this), port_index, data),
339 delay);
agoode@chromium.org25227512014-06-08 05:12:05 +0000340
341 // Acknowledge send.
342 send_thread_.message_loop()->PostTask(
agoodead116b22015-12-07 00:00:35 -0800343 FROM_HERE, base::Bind(&MidiManagerAlsa::AccumulateMidiBytesSent,
344 base::Unretained(this), client, data.size()));
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000345}
346
agooded87fc0f2015-05-21 08:29:31 -0700347MidiManagerAlsa::MidiPort::Id::Id() = default;
348
349MidiManagerAlsa::MidiPort::Id::Id(const std::string& bus,
350 const std::string& vendor_id,
351 const std::string& model_id,
352 const std::string& usb_interface_num,
353 const std::string& serial)
354 : bus_(bus),
355 vendor_id_(vendor_id),
356 model_id_(model_id),
357 usb_interface_num_(usb_interface_num),
358 serial_(serial) {
359}
360
361MidiManagerAlsa::MidiPort::Id::Id(const Id&) = default;
362
363MidiManagerAlsa::MidiPort::Id::~Id() = default;
364
365bool MidiManagerAlsa::MidiPort::Id::operator==(const Id& rhs) const {
366 return (bus_ == rhs.bus_) && (vendor_id_ == rhs.vendor_id_) &&
367 (model_id_ == rhs.model_id_) &&
368 (usb_interface_num_ == rhs.usb_interface_num_) &&
369 (serial_ == rhs.serial_);
370}
371
372bool MidiManagerAlsa::MidiPort::Id::empty() const {
373 return bus_.empty() && vendor_id_.empty() && model_id_.empty() &&
374 usb_interface_num_.empty() && serial_.empty();
375}
376
agoode99d63292015-04-13 08:39:25 -0700377MidiManagerAlsa::MidiPort::MidiPort(const std::string& path,
agooded87fc0f2015-05-21 08:29:31 -0700378 const Id& id,
agoode99d63292015-04-13 08:39:25 -0700379 int client_id,
380 int port_id,
381 int midi_device,
382 const std::string& client_name,
383 const std::string& port_name,
384 const std::string& manufacturer,
385 const std::string& version,
386 Type type)
387 : id_(id),
388 midi_device_(midi_device),
389 type_(type),
390 path_(path),
391 client_id_(client_id),
392 port_id_(port_id),
393 client_name_(client_name),
394 port_name_(port_name),
395 manufacturer_(manufacturer),
agoode5a1aa112015-06-21 20:51:00 -0700396 version_(version) {
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000397}
398
agoodeb0582872015-05-20 05:22:24 -0700399MidiManagerAlsa::MidiPort::~MidiPort() = default;
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000400
agoode99d63292015-04-13 08:39:25 -0700401// Note: keep synchronized with the MidiPort::Match* methods.
danakj75afea02016-04-25 20:36:04 -0700402std::unique_ptr<base::Value> MidiManagerAlsa::MidiPort::Value() const {
403 std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
agoode99d63292015-04-13 08:39:25 -0700404
405 std::string type;
406 switch (type_) {
407 case Type::kInput:
408 type = "input";
409 break;
agoode99d63292015-04-13 08:39:25 -0700410 case Type::kOutput:
411 type = "output";
412 break;
413 }
414 value->SetString("type", type);
415 SetStringIfNonEmpty(value.get(), "path", path_);
agoode99d63292015-04-13 08:39:25 -0700416 SetStringIfNonEmpty(value.get(), "clientName", client_name_);
417 SetStringIfNonEmpty(value.get(), "portName", port_name_);
418 value->SetInteger("clientId", client_id_);
419 value->SetInteger("portId", port_id_);
420 value->SetInteger("midiDevice", midi_device_);
421
agooded87fc0f2015-05-21 08:29:31 -0700422 // Flatten id fields.
423 SetStringIfNonEmpty(value.get(), "bus", id_.bus());
424 SetStringIfNonEmpty(value.get(), "vendorId", id_.vendor_id());
425 SetStringIfNonEmpty(value.get(), "modelId", id_.model_id());
426 SetStringIfNonEmpty(value.get(), "usbInterfaceNum", id_.usb_interface_num());
427 SetStringIfNonEmpty(value.get(), "serial", id_.serial());
428
dchengc2aeece2015-12-27 00:54:00 -0800429 return std::move(value);
agoodebd4be9b2015-03-16 19:17:25 -0700430}
agoode@chromium.org25227512014-06-08 05:12:05 +0000431
agoode99d63292015-04-13 08:39:25 -0700432std::string MidiManagerAlsa::MidiPort::JSONValue() const {
433 std::string json;
434 JSONStringValueSerializer serializer(&json);
435 serializer.Serialize(*Value().get());
436 return json;
agoodef212b2a2015-03-19 12:53:23 -0700437}
438
agoode99d63292015-04-13 08:39:25 -0700439// TODO(agoode): Do not use SHA256 here. Instead store a persistent
440// mapping and just use a UUID or other random string.
441// http://crbug.com/465320
442std::string MidiManagerAlsa::MidiPort::OpaqueKey() const {
Avi Drissman3528fd02015-12-18 20:11:31 -0500443 uint8_t hash[crypto::kSHA256Length];
agoode99d63292015-04-13 08:39:25 -0700444 crypto::SHA256HashString(JSONValue(), &hash, sizeof(hash));
445 return base::HexEncode(&hash, sizeof(hash));
agoodebd4be9b2015-03-16 19:17:25 -0700446}
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000447
agoode99d63292015-04-13 08:39:25 -0700448bool MidiManagerAlsa::MidiPort::MatchConnected(const MidiPort& query) const {
449 // Matches on:
450 // connected == true
451 // type
452 // path
453 // id
454 // client_id
455 // port_id
456 // midi_device
457 // client_name
458 // port_name
459 return connected() && (type() == query.type()) && (path() == query.path()) &&
460 (id() == query.id()) && (client_id() == query.client_id()) &&
461 (port_id() == query.port_id()) &&
462 (midi_device() == query.midi_device()) &&
463 (client_name() == query.client_name()) &&
464 (port_name() == query.port_name());
agoodebd4be9b2015-03-16 19:17:25 -0700465}
466
agoode99d63292015-04-13 08:39:25 -0700467bool MidiManagerAlsa::MidiPort::MatchCardPass1(const MidiPort& query) const {
468 // Matches on:
469 // connected == false
470 // type
471 // path
472 // id
473 // port_id
474 // midi_device
475 return MatchCardPass2(query) && (path() == query.path());
agoodebd4be9b2015-03-16 19:17:25 -0700476}
477
agoode99d63292015-04-13 08:39:25 -0700478bool MidiManagerAlsa::MidiPort::MatchCardPass2(const MidiPort& query) const {
479 // Matches on:
480 // connected == false
481 // type
482 // id
483 // port_id
484 // midi_device
485 return !connected() && (type() == query.type()) && (id() == query.id()) &&
486 (port_id() == query.port_id()) &&
487 (midi_device() == query.midi_device());
agoodef212b2a2015-03-19 12:53:23 -0700488}
489
agoode99d63292015-04-13 08:39:25 -0700490bool MidiManagerAlsa::MidiPort::MatchNoCardPass1(const MidiPort& query) const {
491 // Matches on:
492 // connected == false
493 // type
494 // path.empty(), for both this and query
495 // id.empty(), for both this and query
496 // client_id
497 // port_id
498 // client_name
499 // port_name
500 // midi_device == -1, for both this and query
501 return MatchNoCardPass2(query) && (client_id() == query.client_id());
agoodef212b2a2015-03-19 12:53:23 -0700502}
503
agoode99d63292015-04-13 08:39:25 -0700504bool MidiManagerAlsa::MidiPort::MatchNoCardPass2(const MidiPort& query) const {
505 // Matches on:
506 // connected == false
507 // type
508 // path.empty(), for both this and query
509 // id.empty(), for both this and query
510 // port_id
511 // client_name
512 // port_name
513 // midi_device == -1, for both this and query
514 return !connected() && (type() == query.type()) && path().empty() &&
515 query.path().empty() && id().empty() && query.id().empty() &&
516 (port_id() == query.port_id()) &&
517 (client_name() == query.client_name()) &&
518 (port_name() == query.port_name()) && (midi_device() == -1) &&
519 (query.midi_device() == -1);
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000520}
521
agoodeb0582872015-05-20 05:22:24 -0700522MidiManagerAlsa::MidiPortStateBase::~MidiPortStateBase() = default;
agoode99d63292015-04-13 08:39:25 -0700523
524MidiManagerAlsa::MidiPortStateBase::iterator
525MidiManagerAlsa::MidiPortStateBase::Find(
526 const MidiManagerAlsa::MidiPort& port) {
527 auto result = FindConnected(port);
528 if (result == end())
529 result = FindDisconnected(port);
530 return result;
531}
532
533MidiManagerAlsa::MidiPortStateBase::iterator
534MidiManagerAlsa::MidiPortStateBase::FindConnected(
535 const MidiManagerAlsa::MidiPort& port) {
536 // Exact match required for connected ports.
danakj75afea02016-04-25 20:36:04 -0700537 auto it = std::find_if(ports_.begin(), ports_.end(),
538 [&port](std::unique_ptr<MidiPort>& p) {
539 return p->MatchConnected(port);
540 });
agoode99d63292015-04-13 08:39:25 -0700541 return it;
542}
543
544MidiManagerAlsa::MidiPortStateBase::iterator
545MidiManagerAlsa::MidiPortStateBase::FindDisconnected(
546 const MidiManagerAlsa::MidiPort& port) {
547 // Always match on:
548 // type
549 // Possible things to match on:
550 // path
551 // id
552 // client_id
553 // port_id
554 // midi_device
555 // client_name
556 // port_name
557
558 if (!port.path().empty()) {
559 // If path is present, then we have a card-based client.
560
561 // Pass 1. Match on path, id, midi_device, port_id.
562 // This is the best possible match for hardware card-based clients.
563 // This will also match the empty id correctly for devices without an id.
danakj75afea02016-04-25 20:36:04 -0700564 auto it = std::find_if(ports_.begin(), ports_.end(),
565 [&port](std::unique_ptr<MidiPort>& p) {
566 return p->MatchCardPass1(port);
567 });
agoode99d63292015-04-13 08:39:25 -0700568 if (it != ports_.end())
569 return it;
570
571 if (!port.id().empty()) {
572 // Pass 2. Match on id, midi_device, port_id.
573 // This will give us a high-confidence match when a user moves a device to
574 // another USB/Firewire/Thunderbolt/etc port, but only works if the device
575 // has a hardware id.
danakj75afea02016-04-25 20:36:04 -0700576 it = std::find_if(ports_.begin(), ports_.end(),
577 [&port](std::unique_ptr<MidiPort>& p) {
578 return p->MatchCardPass2(port);
579 });
agoode99d63292015-04-13 08:39:25 -0700580 if (it != ports_.end())
581 return it;
582 }
583 } else {
584 // Else, we have a non-card-based client.
585 // Pass 1. Match on client_id, port_id, client_name, port_name.
586 // This will give us a reasonably good match.
danakj75afea02016-04-25 20:36:04 -0700587 auto it = std::find_if(ports_.begin(), ports_.end(),
588 [&port](std::unique_ptr<MidiPort>& p) {
589 return p->MatchNoCardPass1(port);
590 });
agoode99d63292015-04-13 08:39:25 -0700591 if (it != ports_.end())
592 return it;
593
594 // Pass 2. Match on port_id, client_name, port_name.
595 // This is weaker but similar to pass 2 in the hardware card-based clients
596 // match.
danakj75afea02016-04-25 20:36:04 -0700597 it = std::find_if(ports_.begin(), ports_.end(),
598 [&port](std::unique_ptr<MidiPort>& p) {
599 return p->MatchNoCardPass2(port);
600 });
agoode99d63292015-04-13 08:39:25 -0700601 if (it != ports_.end())
602 return it;
603 }
604
605 // No match.
606 return ports_.end();
607}
608
agoodeb0582872015-05-20 05:22:24 -0700609MidiManagerAlsa::MidiPortStateBase::MidiPortStateBase() = default;
agoode99d63292015-04-13 08:39:25 -0700610
agoodedf1b9ff2015-06-25 18:14:50 -0700611MidiManagerAlsa::MidiPortState::MidiPortState() = default;
agoode99d63292015-04-13 08:39:25 -0700612
danakj75afea02016-04-25 20:36:04 -0700613uint32_t MidiManagerAlsa::MidiPortState::push_back(
614 std::unique_ptr<MidiPort> port) {
agoode99d63292015-04-13 08:39:25 -0700615 // Add the web midi index.
Avi Drissman3528fd02015-12-18 20:11:31 -0500616 uint32_t web_port_index = 0;
agoode99d63292015-04-13 08:39:25 -0700617 switch (port->type()) {
618 case MidiPort::Type::kInput:
619 web_port_index = num_input_ports_++;
620 break;
621 case MidiPort::Type::kOutput:
622 web_port_index = num_output_ports_++;
623 break;
624 }
625 port->set_web_port_index(web_port_index);
dchengc2aeece2015-12-27 00:54:00 -0800626 MidiPortStateBase::push_back(std::move(port));
agoode99d63292015-04-13 08:39:25 -0700627 return web_port_index;
628}
629
agoodedf1b9ff2015-06-25 18:14:50 -0700630MidiManagerAlsa::AlsaSeqState::AlsaSeqState() = default;
agoode99d63292015-04-13 08:39:25 -0700631
agoodeb0582872015-05-20 05:22:24 -0700632MidiManagerAlsa::AlsaSeqState::~AlsaSeqState() = default;
agoode99d63292015-04-13 08:39:25 -0700633
634void MidiManagerAlsa::AlsaSeqState::ClientStart(int client_id,
635 const std::string& client_name,
636 snd_seq_client_type_t type) {
637 ClientExit(client_id);
limasdfe59d0392015-11-19 20:28:57 -0800638 clients_.insert(std::make_pair(
danakj75afea02016-04-25 20:36:04 -0700639 client_id, base::WrapUnique(new Client(client_name, type))));
agoodeb09423b2015-05-11 11:39:57 -0700640 if (IsCardClient(type, client_id))
641 ++card_client_count_;
agoode99d63292015-04-13 08:39:25 -0700642}
643
644bool MidiManagerAlsa::AlsaSeqState::ClientStarted(int client_id) {
645 return clients_.find(client_id) != clients_.end();
646}
647
648void MidiManagerAlsa::AlsaSeqState::ClientExit(int client_id) {
649 auto it = clients_.find(client_id);
650 if (it != clients_.end()) {
agoodeb09423b2015-05-11 11:39:57 -0700651 if (IsCardClient(it->second->type(), client_id))
652 --card_client_count_;
agoode99d63292015-04-13 08:39:25 -0700653 clients_.erase(it);
654 }
655}
656
657void MidiManagerAlsa::AlsaSeqState::PortStart(
658 int client_id,
659 int port_id,
660 const std::string& port_name,
661 MidiManagerAlsa::AlsaSeqState::PortDirection direction,
662 bool midi) {
663 auto it = clients_.find(client_id);
664 if (it != clients_.end())
665 it->second->AddPort(port_id,
danakj75afea02016-04-25 20:36:04 -0700666 base::WrapUnique(new Port(port_name, direction, midi)));
agoode99d63292015-04-13 08:39:25 -0700667}
668
669void MidiManagerAlsa::AlsaSeqState::PortExit(int client_id, int port_id) {
670 auto it = clients_.find(client_id);
671 if (it != clients_.end())
672 it->second->RemovePort(port_id);
673}
674
675snd_seq_client_type_t MidiManagerAlsa::AlsaSeqState::ClientType(
676 int client_id) const {
677 auto it = clients_.find(client_id);
678 if (it == clients_.end())
679 return SND_SEQ_USER_CLIENT;
680 return it->second->type();
681}
682
danakj75afea02016-04-25 20:36:04 -0700683std::unique_ptr<MidiManagerAlsa::TemporaryMidiPortState>
agoodeb09423b2015-05-11 11:39:57 -0700684MidiManagerAlsa::AlsaSeqState::ToMidiPortState(const AlsaCardMap& alsa_cards) {
danakj75afea02016-04-25 20:36:04 -0700685 std::unique_ptr<MidiManagerAlsa::TemporaryMidiPortState> midi_ports(
agoode99d63292015-04-13 08:39:25 -0700686 new TemporaryMidiPortState);
agoodeb09423b2015-05-11 11:39:57 -0700687 auto card_it = alsa_cards.begin();
agoode99d63292015-04-13 08:39:25 -0700688
agoodeb09423b2015-05-11 11:39:57 -0700689 int card_midi_device = -1;
agoode99d63292015-04-13 08:39:25 -0700690 for (const auto& client_pair : clients_) {
691 int client_id = client_pair.first;
vmpstr0205abb2016-06-28 18:50:56 -0700692 auto* client = client_pair.second.get();
agoode99d63292015-04-13 08:39:25 -0700693
694 // Get client metadata.
695 const std::string client_name = client->name();
696 std::string manufacturer;
697 std::string driver;
698 std::string path;
agooded87fc0f2015-05-21 08:29:31 -0700699 MidiPort::Id id;
agoode99d63292015-04-13 08:39:25 -0700700 std::string card_name;
701 std::string card_longname;
702 int midi_device = -1;
703
agoodeb09423b2015-05-11 11:39:57 -0700704 if (IsCardClient(client->type(), client_id)) {
705 auto& card = card_it->second;
706 if (card_midi_device == -1)
707 card_midi_device = 0;
708
709 manufacturer = card->manufacturer();
agooded87fc0f2015-05-21 08:29:31 -0700710 path = card->path();
711 id = MidiPort::Id(card->bus(), card->vendor_id(), card->model_id(),
712 card->usb_interface_num(), card->serial());
713 card_name = card->name();
714 card_longname = card->longname();
agoodeb09423b2015-05-11 11:39:57 -0700715 midi_device = card_midi_device;
716
717 ++card_midi_device;
718 if (card_midi_device >= card->midi_device_count()) {
719 card_midi_device = -1;
720 ++card_it;
721 }
722 }
723
agoode99d63292015-04-13 08:39:25 -0700724 for (const auto& port_pair : *client) {
725 int port_id = port_pair.first;
726 const auto& port = port_pair.second;
727
728 if (port->midi()) {
729 std::string version;
730 if (!driver.empty()) {
731 version = driver + " / ";
732 }
733 version +=
734 base::StringPrintf("ALSA library version %d.%d.%d", SND_LIB_MAJOR,
735 SND_LIB_MINOR, SND_LIB_SUBMINOR);
736 PortDirection direction = port->direction();
737 if (direction == PortDirection::kInput ||
738 direction == PortDirection::kDuplex) {
danakj75afea02016-04-25 20:36:04 -0700739 midi_ports->push_back(base::WrapUnique(new MidiPort(
agoode99d63292015-04-13 08:39:25 -0700740 path, id, client_id, port_id, midi_device, client->name(),
741 port->name(), manufacturer, version, MidiPort::Type::kInput)));
742 }
743 if (direction == PortDirection::kOutput ||
744 direction == PortDirection::kDuplex) {
danakj75afea02016-04-25 20:36:04 -0700745 midi_ports->push_back(base::WrapUnique(new MidiPort(
agoode99d63292015-04-13 08:39:25 -0700746 path, id, client_id, port_id, midi_device, client->name(),
747 port->name(), manufacturer, version, MidiPort::Type::kOutput)));
748 }
749 }
750 }
751 }
752
dchengc2aeece2015-12-27 00:54:00 -0800753 return midi_ports;
agoode99d63292015-04-13 08:39:25 -0700754}
755
756MidiManagerAlsa::AlsaSeqState::Port::Port(
757 const std::string& name,
758 MidiManagerAlsa::AlsaSeqState::PortDirection direction,
759 bool midi)
760 : name_(name), direction_(direction), midi_(midi) {
761}
762
agoodeb0582872015-05-20 05:22:24 -0700763MidiManagerAlsa::AlsaSeqState::Port::~Port() = default;
agoode99d63292015-04-13 08:39:25 -0700764
765MidiManagerAlsa::AlsaSeqState::Client::Client(const std::string& name,
766 snd_seq_client_type_t type)
mgiucad9af8452015-06-25 02:11:57 -0700767 : name_(name), type_(type) {
agoode99d63292015-04-13 08:39:25 -0700768}
769
agoodeb0582872015-05-20 05:22:24 -0700770MidiManagerAlsa::AlsaSeqState::Client::~Client() = default;
agoode99d63292015-04-13 08:39:25 -0700771
danakj75afea02016-04-25 20:36:04 -0700772void MidiManagerAlsa::AlsaSeqState::Client::AddPort(
773 int addr,
774 std::unique_ptr<Port> port) {
limasdfe59d0392015-11-19 20:28:57 -0800775 ports_[addr] = std::move(port);
agoode99d63292015-04-13 08:39:25 -0700776}
777
778void MidiManagerAlsa::AlsaSeqState::Client::RemovePort(int addr) {
mgiucad9af8452015-06-25 02:11:57 -0700779 ports_.erase(addr);
agoode99d63292015-04-13 08:39:25 -0700780}
781
782MidiManagerAlsa::AlsaSeqState::Client::PortMap::const_iterator
783MidiManagerAlsa::AlsaSeqState::Client::begin() const {
784 return ports_.begin();
785}
786
787MidiManagerAlsa::AlsaSeqState::Client::PortMap::const_iterator
788MidiManagerAlsa::AlsaSeqState::Client::end() const {
789 return ports_.end();
agoodeaf6e9f52015-03-24 10:23:49 -0700790}
791
agoodeb09423b2015-05-11 11:39:57 -0700792MidiManagerAlsa::AlsaCard::AlsaCard(udev_device* dev,
agooded87fc0f2015-05-21 08:29:31 -0700793 const std::string& name,
794 const std::string& longname,
795 const std::string& driver,
agoodeb09423b2015-05-11 11:39:57 -0700796 int midi_device_count)
agooded87fc0f2015-05-21 08:29:31 -0700797 : name_(name),
798 longname_(longname),
799 driver_(driver),
800 path_(device::UdevDeviceGetPropertyValue(dev, kUdevIdPath)),
801 bus_(device::UdevDeviceGetPropertyValue(dev, kUdevIdBus)),
802 vendor_id_(
803 UdevDeviceGetPropertyOrSysattr(dev, kUdevIdVendorId, kSysattrVendor)),
804 model_id_(
805 UdevDeviceGetPropertyOrSysattr(dev, kUdevIdModelId, kSysattrModel)),
806 usb_interface_num_(
807 device::UdevDeviceGetPropertyValue(dev, kUdevIdUsbInterfaceNum)),
808 serial_(UdevDeviceGetPropertyOrSysattr(dev,
809 kUdevIdSerialShort,
810 kSysattrGuid)),
811 midi_device_count_(midi_device_count),
812 manufacturer_(ExtractManufacturerString(
813 GetVendor(dev),
814 vendor_id_,
815 device::UdevDeviceGetPropertyValue(dev, kUdevIdVendorFromDatabase),
816 name,
817 longname)) {
agoodeb09423b2015-05-11 11:39:57 -0700818}
819
agoodeb0582872015-05-20 05:22:24 -0700820MidiManagerAlsa::AlsaCard::~AlsaCard() = default;
agoodeb09423b2015-05-11 11:39:57 -0700821
agoode55a8b522015-03-08 12:40:17 -0700822// static
agoodeb09423b2015-05-11 11:39:57 -0700823std::string MidiManagerAlsa::AlsaCard::ExtractManufacturerString(
agoode5e4e9cd2015-03-09 12:34:24 -0700824 const std::string& udev_id_vendor,
agoode55a8b522015-03-08 12:40:17 -0700825 const std::string& udev_id_vendor_id,
826 const std::string& udev_id_vendor_from_database,
827 const std::string& alsa_name,
828 const std::string& alsa_longname) {
829 // Let's try to determine the manufacturer. Here is the ordered preference
830 // in extraction:
agoodef212b2a2015-03-19 12:53:23 -0700831 // 1. Vendor name from the hardware device string, from udev properties
832 // or sysattrs.
agoode5e4e9cd2015-03-09 12:34:24 -0700833 // 2. Vendor name from the udev database (property ID_VENDOR_FROM_DATABASE).
agoode55a8b522015-03-08 12:40:17 -0700834 // 3. Heuristic from ALSA.
835
agoodee83758c2015-03-23 22:07:54 -0700836 // Is the vendor string present and not just the vendor hex id?
837 if (!udev_id_vendor.empty() && (udev_id_vendor != udev_id_vendor_id)) {
agoode55a8b522015-03-08 12:40:17 -0700838 return udev_id_vendor;
839 }
840
841 // Is there a vendor string in the hardware database?
842 if (!udev_id_vendor_from_database.empty()) {
843 return udev_id_vendor_from_database;
844 }
845
846 // Ok, udev gave us nothing useful, or was unavailable. So try a heuristic.
847 // We assume that card longname is in the format of
848 // "<manufacturer> <name> at <bus>". Otherwise, we give up to detect
849 // a manufacturer name here.
850 size_t at_index = alsa_longname.rfind(" at ");
agoodef212b2a2015-03-19 12:53:23 -0700851 if (at_index && at_index != std::string::npos) {
agoode55a8b522015-03-08 12:40:17 -0700852 size_t name_index = alsa_longname.rfind(alsa_name, at_index - 1);
agoodef212b2a2015-03-19 12:53:23 -0700853 if (name_index && name_index != std::string::npos)
agoode55a8b522015-03-08 12:40:17 -0700854 return alsa_longname.substr(0, name_index - 1);
855 }
856
857 // Failure.
858 return "";
859}
860
Avi Drissman3528fd02015-12-18 20:11:31 -0500861void MidiManagerAlsa::SendMidiData(uint32_t port_index,
862 const std::vector<uint8_t>& data) {
skyostil93e2ec22015-06-17 08:49:09 -0700863 DCHECK(send_thread_.task_runner()->BelongsToCurrentThread());
agoodebd4be9b2015-03-16 19:17:25 -0700864
agoodef212b2a2015-03-19 12:53:23 -0700865 snd_midi_event_t* encoder;
866 snd_midi_event_new(kSendBufferSize, &encoder);
agoode5a1aa112015-06-21 20:51:00 -0700867 for (const auto datum : data) {
agoodebd4be9b2015-03-16 19:17:25 -0700868 snd_seq_event_t event;
agoode5a1aa112015-06-21 20:51:00 -0700869 int result = snd_midi_event_encode_byte(encoder, datum, &event);
agoodebd4be9b2015-03-16 19:17:25 -0700870 if (result == 1) {
871 // Full event, send it.
agoode99d63292015-04-13 08:39:25 -0700872 base::AutoLock lock(out_ports_lock_);
873 auto it = out_ports_.find(port_index);
874 if (it != out_ports_.end()) {
875 snd_seq_ev_set_source(&event, it->second);
876 snd_seq_ev_set_subs(&event);
877 snd_seq_ev_set_direct(&event);
agoode5a1aa112015-06-21 20:51:00 -0700878 snd_seq_event_output_direct(out_client_.get(), &event);
agoode99d63292015-04-13 08:39:25 -0700879 }
agoodebd4be9b2015-03-16 19:17:25 -0700880 }
881 }
agoodef212b2a2015-03-19 12:53:23 -0700882 snd_midi_event_free(encoder);
agoodebd4be9b2015-03-16 19:17:25 -0700883}
884
885void MidiManagerAlsa::ScheduleEventLoop() {
886 event_thread_.message_loop()->PostTask(
887 FROM_HERE,
888 base::Bind(&MidiManagerAlsa::EventLoop, base::Unretained(this)));
889}
890
891void MidiManagerAlsa::EventLoop() {
agoode975043d2015-05-11 00:46:17 -0700892 bool loop_again = true;
agoodebd4be9b2015-03-16 19:17:25 -0700893
agoode975043d2015-05-11 00:46:17 -0700894 struct pollfd pfd[2];
agoode5a1aa112015-06-21 20:51:00 -0700895 snd_seq_poll_descriptors(in_client_.get(), &pfd[0], 1, POLLIN);
agoode975043d2015-05-11 00:46:17 -0700896 pfd[1].fd = device::udev_monitor_get_fd(udev_monitor_.get());
897 pfd[1].events = POLLIN;
agoodebd4be9b2015-03-16 19:17:25 -0700898
agoode975043d2015-05-11 00:46:17 -0700899 int err = HANDLE_EINTR(poll(pfd, arraysize(pfd), -1));
900 if (err < 0) {
brettwf7f870f2015-06-09 11:05:24 -0700901 VLOG(1) << "poll fails: " << base::safe_strerror(errno);
agoode975043d2015-05-11 00:46:17 -0700902 loop_again = false;
agoodeaf6e9f52015-03-24 10:23:49 -0700903 } else {
agoode975043d2015-05-11 00:46:17 -0700904 if (pfd[0].revents & POLLIN) {
905 // Read available incoming MIDI data.
906 int remaining;
907 double timestamp =
908 (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
909 do {
910 snd_seq_event_t* event;
agoode5a1aa112015-06-21 20:51:00 -0700911 err = snd_seq_event_input(in_client_.get(), &event);
912 remaining = snd_seq_event_input_pending(in_client_.get(), 0);
agoode975043d2015-05-11 00:46:17 -0700913
914 if (err == -ENOSPC) {
915 // Handle out of space error.
916 VLOG(1) << "snd_seq_event_input detected buffer overrun";
917 // We've lost events: check another way to see if we need to shut
918 // down.
919 base::AutoLock lock(shutdown_lock_);
920 if (event_thread_shutdown_)
921 loop_again = false;
922 } else if (err == -EAGAIN) {
923 // We've read all the data.
924 } else if (err < 0) {
925 // Handle other errors.
926 VLOG(1) << "snd_seq_event_input fails: " << snd_strerror(err);
927 // TODO(agoode): Use RecordAction() or similar to log this.
928 loop_again = false;
929 } else if (event->source.client == SND_SEQ_CLIENT_SYSTEM &&
930 event->source.port == SND_SEQ_PORT_SYSTEM_ANNOUNCE) {
931 // Handle announce events.
932 switch (event->type) {
933 case SND_SEQ_EVENT_PORT_START:
934 // Don't use SND_SEQ_EVENT_CLIENT_START because the
935 // client name may not be set by the time we query
936 // it. It should be set by the time ports are made.
937 ProcessClientStartEvent(event->data.addr.client);
938 ProcessPortStartEvent(event->data.addr);
939 break;
940 case SND_SEQ_EVENT_CLIENT_EXIT:
941 // Check for disconnection of our "out" client. This means "shut
942 // down".
943 if (event->data.addr.client == out_client_id_) {
944 loop_again = false;
945 remaining = 0;
946 } else
947 ProcessClientExitEvent(event->data.addr);
948 break;
949 case SND_SEQ_EVENT_PORT_EXIT:
950 ProcessPortExitEvent(event->data.addr);
951 break;
952 }
953 } else {
954 // Normal operation.
955 ProcessSingleEvent(event, timestamp);
956 }
957 } while (remaining > 0);
958 }
959 if (pfd[1].revents & POLLIN) {
960 device::ScopedUdevDevicePtr dev(
961 device::udev_monitor_receive_device(udev_monitor_.get()));
962 if (dev.get())
963 ProcessUdevEvent(dev.get());
964 else
965 VLOG(1) << "udev_monitor_receive_device fails";
966 }
agoodebd4be9b2015-03-16 19:17:25 -0700967 }
968
agoodebd4be9b2015-03-16 19:17:25 -0700969 // Do again.
agoode975043d2015-05-11 00:46:17 -0700970 if (loop_again)
971 ScheduleEventLoop();
agoodebd4be9b2015-03-16 19:17:25 -0700972}
973
974void MidiManagerAlsa::ProcessSingleEvent(snd_seq_event_t* event,
975 double timestamp) {
agoode99d63292015-04-13 08:39:25 -0700976 auto source_it =
977 source_map_.find(AddrToInt(event->source.client, event->source.port));
agoodebd4be9b2015-03-16 19:17:25 -0700978 if (source_it != source_map_.end()) {
Avi Drissman3528fd02015-12-18 20:11:31 -0500979 uint32_t source = source_it->second;
agoodebd4be9b2015-03-16 19:17:25 -0700980 if (event->type == SND_SEQ_EVENT_SYSEX) {
981 // Special! Variable-length sysex.
Avi Drissman3528fd02015-12-18 20:11:31 -0500982 ReceiveMidiData(source, static_cast<const uint8_t*>(event->data.ext.ptr),
agoodebd4be9b2015-03-16 19:17:25 -0700983 event->data.ext.len, timestamp);
984 } else {
985 // Otherwise, decode this and send that on.
986 unsigned char buf[12];
agoode5a1aa112015-06-21 20:51:00 -0700987 long count =
988 snd_midi_event_decode(decoder_.get(), buf, sizeof(buf), event);
agoodebd4be9b2015-03-16 19:17:25 -0700989 if (count <= 0) {
990 if (count != -ENOENT) {
991 // ENOENT means that it's not a MIDI message, which is not an
992 // error, but other negative values are errors for us.
993 VLOG(1) << "snd_midi_event_decoder fails " << snd_strerror(count);
994 // TODO(agoode): Record this failure.
995 }
996 } else {
997 ReceiveMidiData(source, buf, count, timestamp);
998 }
999 }
1000 }
1001}
1002
agoode99d63292015-04-13 08:39:25 -07001003void MidiManagerAlsa::ProcessClientStartEvent(int client_id) {
1004 // Ignore if client is already started.
1005 if (alsa_seq_state_.ClientStarted(client_id))
1006 return;
1007
1008 snd_seq_client_info_t* client_info;
1009 snd_seq_client_info_alloca(&client_info);
agoode5a1aa112015-06-21 20:51:00 -07001010 int err =
1011 snd_seq_get_any_client_info(in_client_.get(), client_id, client_info);
agoode99d63292015-04-13 08:39:25 -07001012 if (err != 0)
1013 return;
1014
1015 // Skip our own clients.
1016 if ((client_id == in_client_id_) || (client_id == out_client_id_))
1017 return;
1018
1019 // Update our view of ALSA seq state.
1020 alsa_seq_state_.ClientStart(client_id,
1021 snd_seq_client_info_get_name(client_info),
1022 snd_seq_client_info_get_type(client_info));
1023
1024 // Generate Web MIDI events.
1025 UpdatePortStateAndGenerateEvents();
1026}
1027
1028void MidiManagerAlsa::ProcessPortStartEvent(const snd_seq_addr_t& addr) {
1029 snd_seq_port_info_t* port_info;
1030 snd_seq_port_info_alloca(&port_info);
agoode5a1aa112015-06-21 20:51:00 -07001031 int err = snd_seq_get_any_port_info(in_client_.get(), addr.client, addr.port,
1032 port_info);
agoode99d63292015-04-13 08:39:25 -07001033 if (err != 0)
1034 return;
1035
1036 unsigned int caps = snd_seq_port_info_get_capability(port_info);
1037 bool input = (caps & kRequiredInputPortCaps) == kRequiredInputPortCaps;
1038 bool output = (caps & kRequiredOutputPortCaps) == kRequiredOutputPortCaps;
1039 AlsaSeqState::PortDirection direction;
1040 if (input && output)
1041 direction = AlsaSeqState::PortDirection::kDuplex;
1042 else if (input)
1043 direction = AlsaSeqState::PortDirection::kInput;
1044 else if (output)
1045 direction = AlsaSeqState::PortDirection::kOutput;
1046 else
1047 return;
1048
1049 // Update our view of ALSA seq state.
1050 alsa_seq_state_.PortStart(
1051 addr.client, addr.port, snd_seq_port_info_get_name(port_info), direction,
1052 snd_seq_port_info_get_type(port_info) & SND_SEQ_PORT_TYPE_MIDI_GENERIC);
1053 // Generate Web MIDI events.
1054 UpdatePortStateAndGenerateEvents();
1055}
1056
1057void MidiManagerAlsa::ProcessClientExitEvent(const snd_seq_addr_t& addr) {
1058 // Update our view of ALSA seq state.
1059 alsa_seq_state_.ClientExit(addr.client);
1060 // Generate Web MIDI events.
1061 UpdatePortStateAndGenerateEvents();
1062}
1063
1064void MidiManagerAlsa::ProcessPortExitEvent(const snd_seq_addr_t& addr) {
1065 // Update our view of ALSA seq state.
1066 alsa_seq_state_.PortExit(addr.client, addr.port);
1067 // Generate Web MIDI events.
1068 UpdatePortStateAndGenerateEvents();
1069}
1070
agoode975043d2015-05-11 00:46:17 -07001071void MidiManagerAlsa::ProcessUdevEvent(udev_device* dev) {
1072 // Only card devices have this property set, and only when they are
1073 // fully initialized.
1074 if (!device::udev_device_get_property_value(dev,
1075 kUdevPropertySoundInitialized))
1076 return;
1077
1078 // Get the action. If no action, then we are doing first time enumeration
1079 // and the device is treated as new.
1080 const char* action = device::udev_device_get_action(dev);
1081 if (!action)
1082 action = kUdevActionChange;
1083
1084 if (strcmp(action, kUdevActionChange) == 0) {
agoodeb09423b2015-05-11 11:39:57 -07001085 AddCard(dev);
1086 // Generate Web MIDI events.
1087 UpdatePortStateAndGenerateEvents();
agoode975043d2015-05-11 00:46:17 -07001088 } else if (strcmp(action, kUdevActionRemove) == 0) {
agoodeb09423b2015-05-11 11:39:57 -07001089 RemoveCard(GetCardNumber(dev));
1090 // Generate Web MIDI events.
1091 UpdatePortStateAndGenerateEvents();
agoode975043d2015-05-11 00:46:17 -07001092 }
1093}
1094
agoodeb09423b2015-05-11 11:39:57 -07001095void MidiManagerAlsa::AddCard(udev_device* dev) {
1096 int number = GetCardNumber(dev);
1097 if (number == -1)
1098 return;
1099
1100 RemoveCard(number);
1101
1102 snd_ctl_card_info_t* card;
1103 snd_hwdep_info_t* hwdep;
1104 snd_ctl_card_info_alloca(&card);
1105 snd_hwdep_info_alloca(&hwdep);
1106 const std::string id = base::StringPrintf("hw:CARD=%i", number);
1107 snd_ctl_t* handle;
1108 int err = snd_ctl_open(&handle, id.c_str(), 0);
1109 if (err != 0) {
1110 VLOG(1) << "snd_ctl_open fails: " << snd_strerror(err);
1111 return;
1112 }
1113 err = snd_ctl_card_info(handle, card);
1114 if (err != 0) {
1115 VLOG(1) << "snd_ctl_card_info fails: " << snd_strerror(err);
1116 snd_ctl_close(handle);
1117 return;
1118 }
1119 std::string name = snd_ctl_card_info_get_name(card);
1120 std::string longname = snd_ctl_card_info_get_longname(card);
1121 std::string driver = snd_ctl_card_info_get_driver(card);
1122
1123 // Count rawmidi devices (not subdevices).
1124 int midi_count = 0;
1125 for (int device = -1;
1126 !snd_ctl_rawmidi_next_device(handle, &device) && device >= 0;)
1127 ++midi_count;
1128
1129 // Count any hwdep synths that become MIDI devices outside of rawmidi.
1130 //
1131 // Explanation:
1132 // Any kernel driver can create an ALSA client (visible to us).
1133 // With modern hardware, only rawmidi devices do this. Kernel
1134 // drivers create rawmidi devices and the rawmidi subsystem makes
1135 // the seq clients. But the OPL3 driver is special, it does not
1136 // make a rawmidi device but a seq client directly. (This is the
1137 // only one to worry about in the kernel code, as of 2015-03-23.)
1138 //
1139 // OPL3 is very old (but still possible to get in new
1140 // hardware). It is unlikely that new drivers would not use
1141 // rawmidi and defeat our heuristic.
1142 //
1143 // Longer term, support should be added in the kernel to expose a
1144 // direct link from card->client (or client->card) so that all
1145 // these heuristics will be obsolete. Once that is there, we can
1146 // assume our old heuristics will work on old kernels and the new
1147 // robust code will be used on new. Then we will not need to worry
1148 // about changes to kernel internals breaking our code.
1149 // See the TODO above at kMinimumClientIdForCards.
1150 for (int device = -1;
1151 !snd_ctl_hwdep_next_device(handle, &device) && device >= 0;) {
1152 err = snd_ctl_hwdep_info(handle, hwdep);
1153 if (err != 0) {
1154 VLOG(1) << "snd_ctl_hwdep_info fails: " << snd_strerror(err);
1155 continue;
1156 }
1157 snd_hwdep_iface_t iface = snd_hwdep_info_get_iface(hwdep);
1158 if (iface == SND_HWDEP_IFACE_OPL2 || iface == SND_HWDEP_IFACE_OPL3 ||
1159 iface == SND_HWDEP_IFACE_OPL4)
1160 ++midi_count;
1161 }
1162 snd_ctl_close(handle);
1163
mgiucad9af8452015-06-25 02:11:57 -07001164 if (midi_count > 0) {
danakj75afea02016-04-25 20:36:04 -07001165 std::unique_ptr<AlsaCard> card(
mgiucad9af8452015-06-25 02:11:57 -07001166 new AlsaCard(dev, name, longname, driver, midi_count));
limasdfe59d0392015-11-19 20:28:57 -08001167 alsa_cards_.insert(std::make_pair(number, std::move(card)));
mgiucad9af8452015-06-25 02:11:57 -07001168 alsa_card_midi_count_ += midi_count;
1169 }
agoodeb09423b2015-05-11 11:39:57 -07001170}
1171
1172void MidiManagerAlsa::RemoveCard(int number) {
1173 auto it = alsa_cards_.find(number);
1174 if (it == alsa_cards_.end())
1175 return;
1176
1177 alsa_card_midi_count_ -= it->second->midi_device_count();
agoodeb09423b2015-05-11 11:39:57 -07001178 alsa_cards_.erase(it);
1179}
1180
agoode99d63292015-04-13 08:39:25 -07001181void MidiManagerAlsa::UpdatePortStateAndGenerateEvents() {
agoodeb09423b2015-05-11 11:39:57 -07001182 // Verify that our information from ALSA and udev are in sync. If
1183 // not, we cannot generate events right now.
1184 if (alsa_card_midi_count_ != alsa_seq_state_.card_client_count())
1185 return;
1186
agoode99d63292015-04-13 08:39:25 -07001187 // Generate new port state.
agoodeb09423b2015-05-11 11:39:57 -07001188 auto new_port_state = alsa_seq_state_.ToMidiPortState(alsa_cards_);
agoode99d63292015-04-13 08:39:25 -07001189
1190 // Disconnect any connected old ports that are now missing.
agoode5ebc4932015-12-01 08:25:12 -08001191 for (auto& old_port : port_state_) {
agoode99d63292015-04-13 08:39:25 -07001192 if (old_port->connected() &&
1193 (new_port_state->FindConnected(*old_port) == new_port_state->end())) {
1194 old_port->set_connected(false);
Avi Drissman3528fd02015-12-18 20:11:31 -05001195 uint32_t web_port_index = old_port->web_port_index();
agoode99d63292015-04-13 08:39:25 -07001196 switch (old_port->type()) {
1197 case MidiPort::Type::kInput:
1198 source_map_.erase(
1199 AddrToInt(old_port->client_id(), old_port->port_id()));
1200 SetInputPortState(web_port_index, MIDI_PORT_DISCONNECTED);
1201 break;
1202 case MidiPort::Type::kOutput:
1203 DeleteAlsaOutputPort(web_port_index);
1204 SetOutputPortState(web_port_index, MIDI_PORT_DISCONNECTED);
1205 break;
1206 }
1207 }
1208 }
1209
1210 // Reconnect or add new ports.
1211 auto it = new_port_state->begin();
1212 while (it != new_port_state->end()) {
agoode5ebc4932015-12-01 08:25:12 -08001213 auto& new_port = *it;
agoode99d63292015-04-13 08:39:25 -07001214 auto old_port = port_state_.Find(*new_port);
1215 if (old_port == port_state_.end()) {
1216 // Add new port.
agoode5ebc4932015-12-01 08:25:12 -08001217 const auto& opaque_key = new_port->OpaqueKey();
1218 const auto& manufacturer = new_port->manufacturer();
1219 const auto& port_name = new_port->port_name();
1220 const auto& version = new_port->version();
1221 const auto& type = new_port->type();
1222 const auto& client_id = new_port->client_id();
1223 const auto& port_id = new_port->port_id();
1224
dchengc2aeece2015-12-27 00:54:00 -08001225 uint32_t web_port_index = port_state_.push_back(std::move(new_port));
agoode5ebc4932015-12-01 08:25:12 -08001226 it = new_port_state->erase(it);
1227
1228 MidiPortInfo info(opaque_key, manufacturer, port_name, version,
agoode99d63292015-04-13 08:39:25 -07001229 MIDI_PORT_OPENED);
agoode5ebc4932015-12-01 08:25:12 -08001230 switch (type) {
agoode99d63292015-04-13 08:39:25 -07001231 case MidiPort::Type::kInput:
agoode5ebc4932015-12-01 08:25:12 -08001232 if (Subscribe(web_port_index, client_id, port_id))
agoode99d63292015-04-13 08:39:25 -07001233 AddInputPort(info);
1234 break;
agoode99d63292015-04-13 08:39:25 -07001235 case MidiPort::Type::kOutput:
agoode5ebc4932015-12-01 08:25:12 -08001236 if (CreateAlsaOutputPort(web_port_index, client_id, port_id))
agoode99d63292015-04-13 08:39:25 -07001237 AddOutputPort(info);
1238 break;
1239 }
agoode99d63292015-04-13 08:39:25 -07001240 } else if (!(*old_port)->connected()) {
1241 // Reconnect.
Avi Drissman3528fd02015-12-18 20:11:31 -05001242 uint32_t web_port_index = (*old_port)->web_port_index();
agoode99d63292015-04-13 08:39:25 -07001243 (*old_port)->Update(new_port->path(), new_port->client_id(),
1244 new_port->port_id(), new_port->client_name(),
1245 new_port->port_name(), new_port->manufacturer(),
1246 new_port->version());
1247 switch ((*old_port)->type()) {
1248 case MidiPort::Type::kInput:
1249 if (Subscribe(web_port_index, (*old_port)->client_id(),
1250 (*old_port)->port_id()))
1251 SetInputPortState(web_port_index, MIDI_PORT_OPENED);
1252 break;
agoode99d63292015-04-13 08:39:25 -07001253 case MidiPort::Type::kOutput:
1254 if (CreateAlsaOutputPort(web_port_index, (*old_port)->client_id(),
1255 (*old_port)->port_id()))
1256 SetOutputPortState(web_port_index, MIDI_PORT_OPENED);
1257 break;
1258 }
1259 (*old_port)->set_connected(true);
1260 ++it;
1261 } else {
1262 ++it;
1263 }
1264 }
1265}
1266
agoode975043d2015-05-11 00:46:17 -07001267// TODO(agoode): return false on failure.
agoode99d63292015-04-13 08:39:25 -07001268void MidiManagerAlsa::EnumerateAlsaPorts() {
1269 snd_seq_client_info_t* client_info;
1270 snd_seq_client_info_alloca(&client_info);
1271 snd_seq_port_info_t* port_info;
1272 snd_seq_port_info_alloca(&port_info);
1273
1274 // Enumerate clients.
1275 snd_seq_client_info_set_client(client_info, -1);
agoode5a1aa112015-06-21 20:51:00 -07001276 while (!snd_seq_query_next_client(in_client_.get(), client_info)) {
agoode99d63292015-04-13 08:39:25 -07001277 int client_id = snd_seq_client_info_get_client(client_info);
1278 ProcessClientStartEvent(client_id);
1279
1280 // Enumerate ports.
1281 snd_seq_port_info_set_client(port_info, client_id);
1282 snd_seq_port_info_set_port(port_info, -1);
agoode5a1aa112015-06-21 20:51:00 -07001283 while (!snd_seq_query_next_port(in_client_.get(), port_info)) {
agoode99d63292015-04-13 08:39:25 -07001284 const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(port_info);
1285 ProcessPortStartEvent(*addr);
1286 }
1287 }
1288}
1289
agoode975043d2015-05-11 00:46:17 -07001290bool MidiManagerAlsa::EnumerateUdevCards() {
1291 int err;
1292
1293 device::ScopedUdevEnumeratePtr enumerate(
1294 device::udev_enumerate_new(udev_.get()));
1295 if (!enumerate.get()) {
1296 VLOG(1) << "udev_enumerate_new fails";
1297 return false;
1298 }
1299
1300 err = device::udev_enumerate_add_match_subsystem(enumerate.get(),
1301 kUdevSubsystemSound);
1302 if (err) {
1303 VLOG(1) << "udev_enumerate_add_match_subsystem fails: "
brettwf7f870f2015-06-09 11:05:24 -07001304 << base::safe_strerror(-err);
agoode975043d2015-05-11 00:46:17 -07001305 return false;
1306 }
1307
1308 err = device::udev_enumerate_scan_devices(enumerate.get());
1309 if (err) {
brettwf7f870f2015-06-09 11:05:24 -07001310 VLOG(1) << "udev_enumerate_scan_devices fails: "
1311 << base::safe_strerror(-err);
agoode975043d2015-05-11 00:46:17 -07001312 return false;
1313 }
1314
1315 udev_list_entry* list_entry;
1316 auto* devices = device::udev_enumerate_get_list_entry(enumerate.get());
1317 udev_list_entry_foreach(list_entry, devices) {
1318 const char* path = device::udev_list_entry_get_name(list_entry);
1319 device::ScopedUdevDevicePtr dev(
1320 device::udev_device_new_from_syspath(udev_.get(), path));
1321 if (dev.get())
1322 ProcessUdevEvent(dev.get());
1323 }
1324
1325 return true;
1326}
1327
Avi Drissman3528fd02015-12-18 20:11:31 -05001328bool MidiManagerAlsa::CreateAlsaOutputPort(uint32_t port_index,
agoode99d63292015-04-13 08:39:25 -07001329 int client_id,
1330 int port_id) {
1331 // Create the port.
1332 int out_port = snd_seq_create_simple_port(
agoode5a1aa112015-06-21 20:51:00 -07001333 out_client_.get(), NULL, kCreateOutputPortCaps, kCreatePortType);
agoode99d63292015-04-13 08:39:25 -07001334 if (out_port < 0) {
1335 VLOG(1) << "snd_seq_create_simple_port fails: " << snd_strerror(out_port);
1336 return false;
1337 }
1338 // Activate port subscription.
1339 snd_seq_port_subscribe_t* subs;
1340 snd_seq_port_subscribe_alloca(&subs);
1341 snd_seq_addr_t sender;
1342 sender.client = out_client_id_;
1343 sender.port = out_port;
1344 snd_seq_port_subscribe_set_sender(subs, &sender);
1345 snd_seq_addr_t dest;
1346 dest.client = client_id;
1347 dest.port = port_id;
1348 snd_seq_port_subscribe_set_dest(subs, &dest);
agoode5a1aa112015-06-21 20:51:00 -07001349 int err = snd_seq_subscribe_port(out_client_.get(), subs);
agoode99d63292015-04-13 08:39:25 -07001350 if (err != 0) {
1351 VLOG(1) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
agoode5a1aa112015-06-21 20:51:00 -07001352 snd_seq_delete_simple_port(out_client_.get(), out_port);
agoode99d63292015-04-13 08:39:25 -07001353 return false;
1354 }
1355
1356 // Update our map.
1357 base::AutoLock lock(out_ports_lock_);
1358 out_ports_[port_index] = out_port;
1359 return true;
1360}
1361
Avi Drissman3528fd02015-12-18 20:11:31 -05001362void MidiManagerAlsa::DeleteAlsaOutputPort(uint32_t port_index) {
agoode99d63292015-04-13 08:39:25 -07001363 base::AutoLock lock(out_ports_lock_);
1364 auto it = out_ports_.find(port_index);
1365 if (it == out_ports_.end())
1366 return;
1367
1368 int alsa_port = it->second;
agoode5a1aa112015-06-21 20:51:00 -07001369 snd_seq_delete_simple_port(out_client_.get(), alsa_port);
agoode99d63292015-04-13 08:39:25 -07001370 out_ports_.erase(it);
1371}
1372
Avi Drissman3528fd02015-12-18 20:11:31 -05001373bool MidiManagerAlsa::Subscribe(uint32_t port_index,
1374 int client_id,
1375 int port_id) {
agoode99d63292015-04-13 08:39:25 -07001376 // Activate port subscription.
1377 snd_seq_port_subscribe_t* subs;
1378 snd_seq_port_subscribe_alloca(&subs);
1379 snd_seq_addr_t sender;
1380 sender.client = client_id;
1381 sender.port = port_id;
1382 snd_seq_port_subscribe_set_sender(subs, &sender);
1383 snd_seq_addr_t dest;
1384 dest.client = in_client_id_;
1385 dest.port = in_port_id_;
1386 snd_seq_port_subscribe_set_dest(subs, &dest);
agoode5a1aa112015-06-21 20:51:00 -07001387 int err = snd_seq_subscribe_port(in_client_.get(), subs);
agoode99d63292015-04-13 08:39:25 -07001388 if (err != 0) {
1389 VLOG(1) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
1390 return false;
1391 }
1392
1393 // Update our map.
1394 source_map_[AddrToInt(client_id, port_id)] = port_index;
1395 return true;
1396}
1397
toyoshim@chromium.orgc82e66e2014-02-04 07:05:47 +00001398MidiManager* MidiManager::Create() {
1399 return new MidiManagerAlsa();
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +00001400}
1401
toyoshime147c5e2015-05-07 21:58:31 -07001402} // namespace midi
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +00001403} // namespace media