blob: 8810a1468120fb6f9ef6aa7f58665047fd2778fe [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"
fdoray8baaff02016-08-25 08:36:37 -070024#include "base/single_thread_task_runner.h"
agoodef212b2a2015-03-19 12:53:23 -070025#include "base/strings/string_number_conversions.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000026#include "base/strings/stringprintf.h"
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +000027#include "base/time/time.h"
Takashi Toyoshima70e44ee2017-07-19 08:38:20 +000028#include "build/build_config.h"
agoodef212b2a2015-03-19 12:53:23 -070029#include "crypto/sha2.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000030#include "media/midi/midi_port_info.h"
toyoshimf4d61522017-02-10 02:03:32 -080031#include "media/midi/midi_service.h"
toyoshimefcee5e2017-06-14 07:14:39 -070032#include "media/midi/task_service.h"
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000033
toyoshime147c5e2015-05-07 21:58:31 -070034namespace midi {
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +000035
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +000036namespace {
37
toyoshimec2570a2016-10-21 02:15:27 -070038using mojom::PortState;
39using mojom::Result;
toyoshim2f3a48f2016-10-17 01:54:13 -070040
toyoshimefcee5e2017-06-14 07:14:39 -070041enum {
42 kDefaultRunnerNotUsedOnAlsa = TaskService::kDefaultRunnerId,
43 kEventTaskRunner,
44 kSendTaskRunner
45};
toyoshimf4d61522017-02-10 02:03:32 -080046
agoode@chromium.org25227512014-06-08 05:12:05 +000047// Per-output buffer. This can be smaller, but then large sysex messages
48// will be (harmlessly) split across multiple seq events. This should
49// not have any real practical effect, except perhaps to slightly reorder
50// realtime messages with respect to sysex.
toyoshimefcee5e2017-06-14 07:14:39 -070051constexpr size_t kSendBufferSize = 256;
agoode@chromium.org25227512014-06-08 05:12:05 +000052
agoodeb09423b2015-05-11 11:39:57 -070053// Minimum client id for which we will have ALSA card devices for. When we
54// are searching for card devices (used to get the path, id, and manufacturer),
55// we don't want to get confused by kernel clients that do not have a card.
56// See seq_clientmgr.c in the ALSA code for this.
57// TODO(agoode): Add proper client -> card export from the kernel to avoid
58// hardcoding.
toyoshimefcee5e2017-06-14 07:14:39 -070059constexpr int kMinimumClientIdForCards = 16;
agoodeb09423b2015-05-11 11:39:57 -070060
agoodef212b2a2015-03-19 12:53:23 -070061// ALSA constants.
62const char kAlsaHw[] = "hw";
63
agoode975043d2015-05-11 00:46:17 -070064// udev constants.
65const char kUdev[] = "udev";
66const char kUdevSubsystemSound[] = "sound";
67const char kUdevPropertySoundInitialized[] = "SOUND_INITIALIZED";
68const char kUdevActionChange[] = "change";
69const char kUdevActionRemove[] = "remove";
70
agoodeb09423b2015-05-11 11:39:57 -070071const char kUdevIdVendor[] = "ID_VENDOR";
72const char kUdevIdVendorEnc[] = "ID_VENDOR_ENC";
73const char kUdevIdVendorFromDatabase[] = "ID_VENDOR_FROM_DATABASE";
74const char kUdevIdVendorId[] = "ID_VENDOR_ID";
75const char kUdevIdModelId[] = "ID_MODEL_ID";
76const char kUdevIdBus[] = "ID_BUS";
77const char kUdevIdPath[] = "ID_PATH";
78const char kUdevIdUsbInterfaceNum[] = "ID_USB_INTERFACE_NUM";
79const char kUdevIdSerialShort[] = "ID_SERIAL_SHORT";
80
81const char kSysattrVendorName[] = "vendor_name";
82const char kSysattrVendor[] = "vendor";
83const char kSysattrModel[] = "model";
84const char kSysattrGuid[] = "guid";
85
86const char kCardSyspath[] = "/card";
87
agoode@chromium.org25227512014-06-08 05:12:05 +000088// Constants for the capabilities we search for in inputs and outputs.
89// See http://www.alsa-project.org/alsa-doc/alsa-lib/seq.html.
toyoshimefcee5e2017-06-14 07:14:39 -070090constexpr unsigned int kRequiredInputPortCaps =
agoode@chromium.org25227512014-06-08 05:12:05 +000091 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ;
toyoshimefcee5e2017-06-14 07:14:39 -070092constexpr unsigned int kRequiredOutputPortCaps =
agoode@chromium.org25227512014-06-08 05:12:05 +000093 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE;
94
toyoshimefcee5e2017-06-14 07:14:39 -070095constexpr unsigned int kCreateOutputPortCaps =
agoode99d63292015-04-13 08:39:25 -070096 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_NO_EXPORT;
toyoshimefcee5e2017-06-14 07:14:39 -070097constexpr unsigned int kCreateInputPortCaps =
agoode99d63292015-04-13 08:39:25 -070098 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_NO_EXPORT;
toyoshimefcee5e2017-06-14 07:14:39 -070099constexpr unsigned int kCreatePortType =
agoode99d63292015-04-13 08:39:25 -0700100 SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION;
agoode@chromium.org25227512014-06-08 05:12:05 +0000101
agoode99d63292015-04-13 08:39:25 -0700102int AddrToInt(int client, int port) {
103 return (client << 8) | port;
agoodef212b2a2015-03-19 12:53:23 -0700104}
agoodef212b2a2015-03-19 12:53:23 -0700105
agoodeb09423b2015-05-11 11:39:57 -0700106// Returns true if this client has an ALSA card associated with it.
107bool IsCardClient(snd_seq_client_type_t type, int client_id) {
108 return (type == SND_SEQ_KERNEL_CLIENT) &&
109 (client_id >= kMinimumClientIdForCards);
110}
111
112// TODO(agoode): Move this to device/udev_linux.
113const std::string UdevDeviceGetPropertyOrSysattr(
114 struct udev_device* udev_device,
115 const char* property_key,
116 const char* sysattr_key) {
117 // First try the property.
118 std::string value =
119 device::UdevDeviceGetPropertyValue(udev_device, property_key);
120
121 // If no property, look for sysattrs and walk up the parent devices too.
122 while (value.empty() && udev_device) {
123 value = device::UdevDeviceGetSysattrValue(udev_device, sysattr_key);
124 udev_device = device::udev_device_get_parent(udev_device);
125 }
126 return value;
127}
128
129int GetCardNumber(udev_device* dev) {
130 const char* syspath = device::udev_device_get_syspath(dev);
131 if (!syspath)
132 return -1;
133
134 std::string syspath_str(syspath);
135 size_t i = syspath_str.rfind(kCardSyspath);
136 if (i == std::string::npos)
137 return -1;
138
139 int number;
140 if (!base::StringToInt(syspath_str.substr(i + strlen(kCardSyspath)), &number))
141 return -1;
142 return number;
143}
144
agooded87fc0f2015-05-21 08:29:31 -0700145std::string GetVendor(udev_device* dev) {
146 // Try to get the vendor string. Sometimes it is encoded.
147 std::string vendor = device::UdevDecodeString(
148 device::UdevDeviceGetPropertyValue(dev, kUdevIdVendorEnc));
149 // Sometimes it is not encoded.
150 if (vendor.empty())
151 vendor =
152 UdevDeviceGetPropertyOrSysattr(dev, kUdevIdVendor, kSysattrVendorName);
153 return vendor;
154}
155
agoode8caab0b2015-03-23 18:48:02 -0700156void SetStringIfNonEmpty(base::DictionaryValue* value,
157 const std::string& path,
158 const std::string& in_value) {
159 if (!in_value.empty())
160 value->SetString(path, in_value);
161}
162
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000163} // namespace
164
toyoshimf4d61522017-02-10 02:03:32 -0800165MidiManagerAlsa::MidiManagerAlsa(MidiService* service) : MidiManager(service) {}
agoodeb2ead822016-03-11 12:14:35 -0800166
167MidiManagerAlsa::~MidiManagerAlsa() {
Takashi Toyoshima9687b7c2017-07-19 09:54:14 +0000168 base::AutoLock lock(lazy_init_member_lock_);
169
toyoshim131beb52016-07-25 00:42:41 -0700170 // Extra CHECK to verify all members are already reset.
toyoshim131beb52016-07-25 00:42:41 -0700171 CHECK(!in_client_);
172 CHECK(!out_client_);
173 CHECK(!decoder_);
174 CHECK(!udev_);
175 CHECK(!udev_monitor_);
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000176}
177
toyoshim@chromium.org51c7f532014-05-01 17:17:32 +0000178void MidiManagerAlsa::StartInitialization() {
toyoshimefcee5e2017-06-14 07:14:39 -0700179 if (!service()->task_service()->BindInstance()) {
180 NOTREACHED();
181 return CompleteInitialization(Result::INITIALIZATION_ERROR);
toyoshimf4d61522017-02-10 02:03:32 -0800182 }
183
Takashi Toyoshima9687b7c2017-07-19 09:54:14 +0000184 base::AutoLock lock(lazy_init_member_lock_);
185
agoodeb2ead822016-03-11 12:14:35 -0800186 // Create client handles.
187 snd_seq_t* tmp_seq = nullptr;
188 int err =
189 snd_seq_open(&tmp_seq, kAlsaHw, SND_SEQ_OPEN_INPUT, SND_SEQ_NONBLOCK);
agoode@chromium.org25227512014-06-08 05:12:05 +0000190 if (err != 0) {
191 VLOG(1) << "snd_seq_open fails: " << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700192 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000193 }
agoodeb2ead822016-03-11 12:14:35 -0800194 ScopedSndSeqPtr in_client(tmp_seq);
195 tmp_seq = nullptr;
196 in_client_id_ = snd_seq_client_id(in_client.get());
197
198 err = snd_seq_open(&tmp_seq, kAlsaHw, SND_SEQ_OPEN_OUTPUT, 0);
199 if (err != 0) {
200 VLOG(1) << "snd_seq_open fails: " << snd_strerror(err);
201 return CompleteInitialization(Result::INITIALIZATION_ERROR);
202 }
203 ScopedSndSeqPtr out_client(tmp_seq);
204 tmp_seq = nullptr;
205 out_client_id_ = snd_seq_client_id(out_client.get());
agoode@chromium.org25227512014-06-08 05:12:05 +0000206
207 // Name the clients.
agoodeb2ead822016-03-11 12:14:35 -0800208 err = snd_seq_set_client_name(in_client.get(), "Chrome (input)");
agoode@chromium.org25227512014-06-08 05:12:05 +0000209 if (err != 0) {
210 VLOG(1) << "snd_seq_set_client_name fails: " << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700211 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000212 }
agoodeb2ead822016-03-11 12:14:35 -0800213 err = snd_seq_set_client_name(out_client.get(), "Chrome (output)");
agoode@chromium.org25227512014-06-08 05:12:05 +0000214 if (err != 0) {
215 VLOG(1) << "snd_seq_set_client_name fails: " << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700216 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000217 }
218
219 // Create input port.
agoode99d63292015-04-13 08:39:25 -0700220 in_port_id_ = snd_seq_create_simple_port(
agoodeb2ead822016-03-11 12:14:35 -0800221 in_client.get(), NULL, kCreateInputPortCaps, kCreatePortType);
agoode99d63292015-04-13 08:39:25 -0700222 if (in_port_id_ < 0) {
223 VLOG(1) << "snd_seq_create_simple_port fails: "
224 << snd_strerror(in_port_id_);
toyoshimf1b88962015-07-09 14:14:51 -0700225 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000226 }
227
228 // Subscribe to the announce port.
229 snd_seq_port_subscribe_t* subs;
230 snd_seq_port_subscribe_alloca(&subs);
231 snd_seq_addr_t announce_sender;
232 snd_seq_addr_t announce_dest;
233 announce_sender.client = SND_SEQ_CLIENT_SYSTEM;
234 announce_sender.port = SND_SEQ_PORT_SYSTEM_ANNOUNCE;
agoode99d63292015-04-13 08:39:25 -0700235 announce_dest.client = in_client_id_;
236 announce_dest.port = in_port_id_;
agoode@chromium.org25227512014-06-08 05:12:05 +0000237 snd_seq_port_subscribe_set_sender(subs, &announce_sender);
238 snd_seq_port_subscribe_set_dest(subs, &announce_dest);
agoodeb2ead822016-03-11 12:14:35 -0800239 err = snd_seq_subscribe_port(in_client.get(), subs);
agoode@chromium.org25227512014-06-08 05:12:05 +0000240 if (err != 0) {
241 VLOG(1) << "snd_seq_subscribe_port on the announce port fails: "
242 << snd_strerror(err);
toyoshimf1b88962015-07-09 14:14:51 -0700243 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode@chromium.org25227512014-06-08 05:12:05 +0000244 }
245
agoodeb2ead822016-03-11 12:14:35 -0800246 // Initialize decoder.
Takashi Toyoshima0ae49702017-09-01 04:59:51 +0000247 ScopedSndMidiEventPtr decoder = CreateScopedSndMidiEventPtr(0);
agoodeb2ead822016-03-11 12:14:35 -0800248 snd_midi_event_no_status(decoder.get(), 1);
agoode@chromium.org25227512014-06-08 05:12:05 +0000249
agoodeb2ead822016-03-11 12:14:35 -0800250 // Initialize udev and monitor.
251 device::ScopedUdevPtr udev(device::udev_new());
252 device::ScopedUdevMonitorPtr udev_monitor(
253 device::udev_monitor_new_from_netlink(udev.get(), kUdev));
254 if (!udev_monitor.get()) {
agoode975043d2015-05-11 00:46:17 -0700255 VLOG(1) << "udev_monitor_new_from_netlink fails";
toyoshimf1b88962015-07-09 14:14:51 -0700256 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode975043d2015-05-11 00:46:17 -0700257 }
258 err = device::udev_monitor_filter_add_match_subsystem_devtype(
agoodeb2ead822016-03-11 12:14:35 -0800259 udev_monitor.get(), kUdevSubsystemSound, nullptr);
agoode975043d2015-05-11 00:46:17 -0700260 if (err != 0) {
261 VLOG(1) << "udev_monitor_add_match_subsystem fails: "
brettwf7f870f2015-06-09 11:05:24 -0700262 << base::safe_strerror(-err);
toyoshimf1b88962015-07-09 14:14:51 -0700263 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode975043d2015-05-11 00:46:17 -0700264 }
agoodeb2ead822016-03-11 12:14:35 -0800265 err = device::udev_monitor_enable_receiving(udev_monitor.get());
agoode975043d2015-05-11 00:46:17 -0700266 if (err != 0) {
brettwf7f870f2015-06-09 11:05:24 -0700267 VLOG(1) << "udev_monitor_enable_receiving fails: "
268 << base::safe_strerror(-err);
toyoshimf1b88962015-07-09 14:14:51 -0700269 return CompleteInitialization(Result::INITIALIZATION_ERROR);
agoode975043d2015-05-11 00:46:17 -0700270 }
271
agoodeb2ead822016-03-11 12:14:35 -0800272 // Success! Now, initialize members from the temporaries. Do not
273 // initialize these earlier, since they need to be destroyed by the
274 // thread that calls Finalize(), not the destructor thread (and we
275 // check this in the destructor).
276 in_client_.reset(in_client.release());
277 out_client_.reset(out_client.release());
278 decoder_.reset(decoder.release());
279 udev_.reset(udev.release());
agoode740f5222016-07-06 23:46:32 -0700280 udev_monitor_.reset(udev_monitor.release());
agoodeb2ead822016-03-11 12:14:35 -0800281
282 // Generate hotplug events for existing ports.
283 // TODO(agoode): Check the return value for failure.
284 EnumerateAlsaPorts();
285
286 // Generate hotplug events for existing udev devices. This must be done
287 // after udev_monitor_enable_receiving() is called. See the algorithm
288 // at http://www.signal11.us/oss/udev/.
agoode975043d2015-05-11 00:46:17 -0700289 EnumerateUdevCards();
290
agoodeb2ead822016-03-11 12:14:35 -0800291 // Start processing events. Don't do this before enumeration of both
292 // ALSA and udev.
toyoshimefcee5e2017-06-14 07:14:39 -0700293 service()->task_service()->PostBoundTask(
294 kEventTaskRunner,
295 base::BindOnce(&MidiManagerAlsa::EventLoop, base::Unretained(this)));
agoode@chromium.org25227512014-06-08 05:12:05 +0000296
toyoshimf1b88962015-07-09 14:14:51 -0700297 CompleteInitialization(Result::OK);
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000298}
299
toyoshim8e7d6e02015-10-06 08:47:17 -0700300void MidiManagerAlsa::Finalize() {
Takashi Toyoshima9687b7c2017-07-19 09:54:14 +0000301 {
302 base::AutoLock lock(out_client_lock_);
303 // Close the out client. This will trigger the event thread to stop,
304 // because of SND_SEQ_EVENT_CLIENT_EXIT.
305 out_client_.reset();
306 }
toyoshim8e7d6e02015-10-06 08:47:17 -0700307
toyoshimefcee5e2017-06-14 07:14:39 -0700308 // Ensure that no task is running any more.
309 bool result = service()->task_service()->UnbindInstance();
310 CHECK(result);
agoodeb2ead822016-03-11 12:14:35 -0800311
312 // Destruct the other stuff we initialized in StartInitialization().
Takashi Toyoshima9687b7c2017-07-19 09:54:14 +0000313 base::AutoLock lock(lazy_init_member_lock_);
agoodeb2ead822016-03-11 12:14:35 -0800314 udev_monitor_.reset();
315 udev_.reset();
316 decoder_.reset();
317 in_client_.reset();
toyoshim8e7d6e02015-10-06 08:47:17 -0700318}
319
toyoshim@chromium.orgc82e66e2014-02-04 07:05:47 +0000320void MidiManagerAlsa::DispatchSendMidiData(MidiManagerClient* client,
Avi Drissman3528fd02015-12-18 20:11:31 -0500321 uint32_t port_index,
322 const std::vector<uint8_t>& data,
dnicoara@chromium.org9f2a6f02014-01-03 21:25:00 +0000323 double timestamp) {
toyoshimefcee5e2017-06-14 07:14:39 -0700324 service()->task_service()->PostBoundDelayedTask(
325 kSendTaskRunner,
326 base::BindOnce(&MidiManagerAlsa::SendMidiData, base::Unretained(this),
327 client, port_index, data),
Takashi Toyoshimaafb27d52017-09-13 11:50:41 +0000328 MidiService::TimestampToTimeDeltaDelay(timestamp));
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +0000329}
330
agooded87fc0f2015-05-21 08:29:31 -0700331MidiManagerAlsa::MidiPort::Id::Id() = default;
332
333MidiManagerAlsa::MidiPort::Id::Id(const std::string& bus,
334 const std::string& vendor_id,
335 const std::string& model_id,
336 const std::string& usb_interface_num,
337 const std::string& serial)
338 : bus_(bus),
339 vendor_id_(vendor_id),
340 model_id_(model_id),
341 usb_interface_num_(usb_interface_num),
342 serial_(serial) {
343}
344
345MidiManagerAlsa::MidiPort::Id::Id(const Id&) = default;
346
347MidiManagerAlsa::MidiPort::Id::~Id() = default;
348
349bool MidiManagerAlsa::MidiPort::Id::operator==(const Id& rhs) const {
350 return (bus_ == rhs.bus_) && (vendor_id_ == rhs.vendor_id_) &&
351 (model_id_ == rhs.model_id_) &&
352 (usb_interface_num_ == rhs.usb_interface_num_) &&
353 (serial_ == rhs.serial_);
354}
355
356bool MidiManagerAlsa::MidiPort::Id::empty() const {
357 return bus_.empty() && vendor_id_.empty() && model_id_.empty() &&
358 usb_interface_num_.empty() && serial_.empty();
359}
360
agoode99d63292015-04-13 08:39:25 -0700361MidiManagerAlsa::MidiPort::MidiPort(const std::string& path,
agooded87fc0f2015-05-21 08:29:31 -0700362 const Id& id,
agoode99d63292015-04-13 08:39:25 -0700363 int client_id,
364 int port_id,
365 int midi_device,
366 const std::string& client_name,
367 const std::string& port_name,
368 const std::string& manufacturer,
369 const std::string& version,
370 Type type)
371 : id_(id),
372 midi_device_(midi_device),
373 type_(type),
374 path_(path),
375 client_id_(client_id),
376 port_id_(port_id),
377 client_name_(client_name),
378 port_name_(port_name),
379 manufacturer_(manufacturer),
agoode5a1aa112015-06-21 20:51:00 -0700380 version_(version) {
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000381}
382
agoodeb0582872015-05-20 05:22:24 -0700383MidiManagerAlsa::MidiPort::~MidiPort() = default;
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000384
agoode99d63292015-04-13 08:39:25 -0700385// Note: keep synchronized with the MidiPort::Match* methods.
danakj75afea02016-04-25 20:36:04 -0700386std::unique_ptr<base::Value> MidiManagerAlsa::MidiPort::Value() const {
387 std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue);
agoode99d63292015-04-13 08:39:25 -0700388
389 std::string type;
390 switch (type_) {
391 case Type::kInput:
392 type = "input";
393 break;
agoode99d63292015-04-13 08:39:25 -0700394 case Type::kOutput:
395 type = "output";
396 break;
397 }
398 value->SetString("type", type);
399 SetStringIfNonEmpty(value.get(), "path", path_);
agoode99d63292015-04-13 08:39:25 -0700400 SetStringIfNonEmpty(value.get(), "clientName", client_name_);
401 SetStringIfNonEmpty(value.get(), "portName", port_name_);
402 value->SetInteger("clientId", client_id_);
403 value->SetInteger("portId", port_id_);
404 value->SetInteger("midiDevice", midi_device_);
405
agooded87fc0f2015-05-21 08:29:31 -0700406 // Flatten id fields.
407 SetStringIfNonEmpty(value.get(), "bus", id_.bus());
408 SetStringIfNonEmpty(value.get(), "vendorId", id_.vendor_id());
409 SetStringIfNonEmpty(value.get(), "modelId", id_.model_id());
410 SetStringIfNonEmpty(value.get(), "usbInterfaceNum", id_.usb_interface_num());
411 SetStringIfNonEmpty(value.get(), "serial", id_.serial());
412
dchengc2aeece2015-12-27 00:54:00 -0800413 return std::move(value);
agoodebd4be9b2015-03-16 19:17:25 -0700414}
agoode@chromium.org25227512014-06-08 05:12:05 +0000415
agoode99d63292015-04-13 08:39:25 -0700416std::string MidiManagerAlsa::MidiPort::JSONValue() const {
417 std::string json;
418 JSONStringValueSerializer serializer(&json);
419 serializer.Serialize(*Value().get());
420 return json;
agoodef212b2a2015-03-19 12:53:23 -0700421}
422
agoode99d63292015-04-13 08:39:25 -0700423// TODO(agoode): Do not use SHA256 here. Instead store a persistent
424// mapping and just use a UUID or other random string.
425// http://crbug.com/465320
426std::string MidiManagerAlsa::MidiPort::OpaqueKey() const {
Avi Drissman3528fd02015-12-18 20:11:31 -0500427 uint8_t hash[crypto::kSHA256Length];
agoode99d63292015-04-13 08:39:25 -0700428 crypto::SHA256HashString(JSONValue(), &hash, sizeof(hash));
429 return base::HexEncode(&hash, sizeof(hash));
agoodebd4be9b2015-03-16 19:17:25 -0700430}
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000431
agoode99d63292015-04-13 08:39:25 -0700432bool MidiManagerAlsa::MidiPort::MatchConnected(const MidiPort& query) const {
433 // Matches on:
434 // connected == true
435 // type
436 // path
437 // id
438 // client_id
439 // port_id
440 // midi_device
441 // client_name
442 // port_name
443 return connected() && (type() == query.type()) && (path() == query.path()) &&
444 (id() == query.id()) && (client_id() == query.client_id()) &&
445 (port_id() == query.port_id()) &&
446 (midi_device() == query.midi_device()) &&
447 (client_name() == query.client_name()) &&
448 (port_name() == query.port_name());
agoodebd4be9b2015-03-16 19:17:25 -0700449}
450
agoode99d63292015-04-13 08:39:25 -0700451bool MidiManagerAlsa::MidiPort::MatchCardPass1(const MidiPort& query) const {
452 // Matches on:
453 // connected == false
454 // type
455 // path
456 // id
457 // port_id
458 // midi_device
459 return MatchCardPass2(query) && (path() == query.path());
agoodebd4be9b2015-03-16 19:17:25 -0700460}
461
agoode99d63292015-04-13 08:39:25 -0700462bool MidiManagerAlsa::MidiPort::MatchCardPass2(const MidiPort& query) const {
463 // Matches on:
464 // connected == false
465 // type
466 // id
467 // port_id
468 // midi_device
469 return !connected() && (type() == query.type()) && (id() == query.id()) &&
470 (port_id() == query.port_id()) &&
471 (midi_device() == query.midi_device());
agoodef212b2a2015-03-19 12:53:23 -0700472}
473
agoode99d63292015-04-13 08:39:25 -0700474bool MidiManagerAlsa::MidiPort::MatchNoCardPass1(const MidiPort& query) const {
475 // Matches on:
476 // connected == false
477 // type
478 // path.empty(), for both this and query
479 // id.empty(), for both this and query
480 // client_id
481 // port_id
482 // client_name
483 // port_name
484 // midi_device == -1, for both this and query
485 return MatchNoCardPass2(query) && (client_id() == query.client_id());
agoodef212b2a2015-03-19 12:53:23 -0700486}
487
agoode99d63292015-04-13 08:39:25 -0700488bool MidiManagerAlsa::MidiPort::MatchNoCardPass2(const MidiPort& query) const {
489 // Matches on:
490 // connected == false
491 // type
492 // path.empty(), for both this and query
493 // id.empty(), for both this and query
494 // port_id
495 // client_name
496 // port_name
497 // midi_device == -1, for both this and query
498 return !connected() && (type() == query.type()) && path().empty() &&
499 query.path().empty() && id().empty() && query.id().empty() &&
500 (port_id() == query.port_id()) &&
501 (client_name() == query.client_name()) &&
502 (port_name() == query.port_name()) && (midi_device() == -1) &&
503 (query.midi_device() == -1);
toyoshim@chromium.org4a8657c2014-02-06 11:23:09 +0000504}
505
agoodeb0582872015-05-20 05:22:24 -0700506MidiManagerAlsa::MidiPortStateBase::~MidiPortStateBase() = default;
agoode99d63292015-04-13 08:39:25 -0700507
508MidiManagerAlsa::MidiPortStateBase::iterator
509MidiManagerAlsa::MidiPortStateBase::Find(
510 const MidiManagerAlsa::MidiPort& port) {
511 auto result = FindConnected(port);
512 if (result == end())
513 result = FindDisconnected(port);
514 return result;
515}
516
517MidiManagerAlsa::MidiPortStateBase::iterator
518MidiManagerAlsa::MidiPortStateBase::FindConnected(
519 const MidiManagerAlsa::MidiPort& port) {
520 // Exact match required for connected ports.
danakj75afea02016-04-25 20:36:04 -0700521 auto it = std::find_if(ports_.begin(), ports_.end(),
522 [&port](std::unique_ptr<MidiPort>& p) {
523 return p->MatchConnected(port);
524 });
agoode99d63292015-04-13 08:39:25 -0700525 return it;
526}
527
528MidiManagerAlsa::MidiPortStateBase::iterator
529MidiManagerAlsa::MidiPortStateBase::FindDisconnected(
530 const MidiManagerAlsa::MidiPort& port) {
531 // Always match on:
532 // type
533 // Possible things to match on:
534 // path
535 // id
536 // client_id
537 // port_id
538 // midi_device
539 // client_name
540 // port_name
541
542 if (!port.path().empty()) {
543 // If path is present, then we have a card-based client.
544
545 // Pass 1. Match on path, id, midi_device, port_id.
546 // This is the best possible match for hardware card-based clients.
547 // This will also match the empty id correctly for devices without an id.
danakj75afea02016-04-25 20:36:04 -0700548 auto it = std::find_if(ports_.begin(), ports_.end(),
549 [&port](std::unique_ptr<MidiPort>& p) {
550 return p->MatchCardPass1(port);
551 });
agoode99d63292015-04-13 08:39:25 -0700552 if (it != ports_.end())
553 return it;
554
555 if (!port.id().empty()) {
556 // Pass 2. Match on id, midi_device, port_id.
557 // This will give us a high-confidence match when a user moves a device to
558 // another USB/Firewire/Thunderbolt/etc port, but only works if the device
559 // has a hardware id.
danakj75afea02016-04-25 20:36:04 -0700560 it = std::find_if(ports_.begin(), ports_.end(),
561 [&port](std::unique_ptr<MidiPort>& p) {
562 return p->MatchCardPass2(port);
563 });
agoode99d63292015-04-13 08:39:25 -0700564 if (it != ports_.end())
565 return it;
566 }
567 } else {
568 // Else, we have a non-card-based client.
569 // Pass 1. Match on client_id, port_id, client_name, port_name.
570 // This will give us a reasonably good match.
danakj75afea02016-04-25 20:36:04 -0700571 auto it = std::find_if(ports_.begin(), ports_.end(),
572 [&port](std::unique_ptr<MidiPort>& p) {
573 return p->MatchNoCardPass1(port);
574 });
agoode99d63292015-04-13 08:39:25 -0700575 if (it != ports_.end())
576 return it;
577
578 // Pass 2. Match on port_id, client_name, port_name.
579 // This is weaker but similar to pass 2 in the hardware card-based clients
580 // match.
danakj75afea02016-04-25 20:36:04 -0700581 it = std::find_if(ports_.begin(), ports_.end(),
582 [&port](std::unique_ptr<MidiPort>& p) {
583 return p->MatchNoCardPass2(port);
584 });
agoode99d63292015-04-13 08:39:25 -0700585 if (it != ports_.end())
586 return it;
587 }
588
589 // No match.
590 return ports_.end();
591}
592
agoodeb0582872015-05-20 05:22:24 -0700593MidiManagerAlsa::MidiPortStateBase::MidiPortStateBase() = default;
agoode99d63292015-04-13 08:39:25 -0700594
agoodedf1b9ff2015-06-25 18:14:50 -0700595MidiManagerAlsa::MidiPortState::MidiPortState() = default;
agoode99d63292015-04-13 08:39:25 -0700596
danakj75afea02016-04-25 20:36:04 -0700597uint32_t MidiManagerAlsa::MidiPortState::push_back(
598 std::unique_ptr<MidiPort> port) {
agoode99d63292015-04-13 08:39:25 -0700599 // Add the web midi index.
Avi Drissman3528fd02015-12-18 20:11:31 -0500600 uint32_t web_port_index = 0;
agoode99d63292015-04-13 08:39:25 -0700601 switch (port->type()) {
602 case MidiPort::Type::kInput:
603 web_port_index = num_input_ports_++;
604 break;
605 case MidiPort::Type::kOutput:
606 web_port_index = num_output_ports_++;
607 break;
608 }
609 port->set_web_port_index(web_port_index);
dchengc2aeece2015-12-27 00:54:00 -0800610 MidiPortStateBase::push_back(std::move(port));
agoode99d63292015-04-13 08:39:25 -0700611 return web_port_index;
612}
613
agoodedf1b9ff2015-06-25 18:14:50 -0700614MidiManagerAlsa::AlsaSeqState::AlsaSeqState() = default;
agoode99d63292015-04-13 08:39:25 -0700615
agoodeb0582872015-05-20 05:22:24 -0700616MidiManagerAlsa::AlsaSeqState::~AlsaSeqState() = default;
agoode99d63292015-04-13 08:39:25 -0700617
618void MidiManagerAlsa::AlsaSeqState::ClientStart(int client_id,
619 const std::string& client_name,
620 snd_seq_client_type_t type) {
621 ClientExit(client_id);
ricea37e45762016-08-25 02:43:39 -0700622 clients_.insert(
623 std::make_pair(client_id, base::MakeUnique<Client>(client_name, type)));
agoodeb09423b2015-05-11 11:39:57 -0700624 if (IsCardClient(type, client_id))
625 ++card_client_count_;
agoode99d63292015-04-13 08:39:25 -0700626}
627
628bool MidiManagerAlsa::AlsaSeqState::ClientStarted(int client_id) {
629 return clients_.find(client_id) != clients_.end();
630}
631
632void MidiManagerAlsa::AlsaSeqState::ClientExit(int client_id) {
633 auto it = clients_.find(client_id);
634 if (it != clients_.end()) {
agoodeb09423b2015-05-11 11:39:57 -0700635 if (IsCardClient(it->second->type(), client_id))
636 --card_client_count_;
agoode99d63292015-04-13 08:39:25 -0700637 clients_.erase(it);
638 }
639}
640
641void MidiManagerAlsa::AlsaSeqState::PortStart(
642 int client_id,
643 int port_id,
644 const std::string& port_name,
645 MidiManagerAlsa::AlsaSeqState::PortDirection direction,
646 bool midi) {
647 auto it = clients_.find(client_id);
648 if (it != clients_.end())
649 it->second->AddPort(port_id,
ricea37e45762016-08-25 02:43:39 -0700650 base::MakeUnique<Port>(port_name, direction, midi));
agoode99d63292015-04-13 08:39:25 -0700651}
652
653void MidiManagerAlsa::AlsaSeqState::PortExit(int client_id, int port_id) {
654 auto it = clients_.find(client_id);
655 if (it != clients_.end())
656 it->second->RemovePort(port_id);
657}
658
659snd_seq_client_type_t MidiManagerAlsa::AlsaSeqState::ClientType(
660 int client_id) const {
661 auto it = clients_.find(client_id);
662 if (it == clients_.end())
663 return SND_SEQ_USER_CLIENT;
664 return it->second->type();
665}
666
danakj75afea02016-04-25 20:36:04 -0700667std::unique_ptr<MidiManagerAlsa::TemporaryMidiPortState>
agoodeb09423b2015-05-11 11:39:57 -0700668MidiManagerAlsa::AlsaSeqState::ToMidiPortState(const AlsaCardMap& alsa_cards) {
danakj75afea02016-04-25 20:36:04 -0700669 std::unique_ptr<MidiManagerAlsa::TemporaryMidiPortState> midi_ports(
agoode99d63292015-04-13 08:39:25 -0700670 new TemporaryMidiPortState);
agoodeb09423b2015-05-11 11:39:57 -0700671 auto card_it = alsa_cards.begin();
agoode99d63292015-04-13 08:39:25 -0700672
agoodeb09423b2015-05-11 11:39:57 -0700673 int card_midi_device = -1;
agoode99d63292015-04-13 08:39:25 -0700674 for (const auto& client_pair : clients_) {
675 int client_id = client_pair.first;
vmpstr0205abb2016-06-28 18:50:56 -0700676 auto* client = client_pair.second.get();
agoode99d63292015-04-13 08:39:25 -0700677
678 // Get client metadata.
679 const std::string client_name = client->name();
680 std::string manufacturer;
681 std::string driver;
682 std::string path;
agooded87fc0f2015-05-21 08:29:31 -0700683 MidiPort::Id id;
agoode99d63292015-04-13 08:39:25 -0700684 std::string card_name;
685 std::string card_longname;
686 int midi_device = -1;
687
agoodeb09423b2015-05-11 11:39:57 -0700688 if (IsCardClient(client->type(), client_id)) {
689 auto& card = card_it->second;
690 if (card_midi_device == -1)
691 card_midi_device = 0;
692
693 manufacturer = card->manufacturer();
agooded87fc0f2015-05-21 08:29:31 -0700694 path = card->path();
695 id = MidiPort::Id(card->bus(), card->vendor_id(), card->model_id(),
696 card->usb_interface_num(), card->serial());
697 card_name = card->name();
698 card_longname = card->longname();
agoodeb09423b2015-05-11 11:39:57 -0700699 midi_device = card_midi_device;
700
701 ++card_midi_device;
702 if (card_midi_device >= card->midi_device_count()) {
703 card_midi_device = -1;
704 ++card_it;
705 }
706 }
707
agoode99d63292015-04-13 08:39:25 -0700708 for (const auto& port_pair : *client) {
709 int port_id = port_pair.first;
710 const auto& port = port_pair.second;
711
712 if (port->midi()) {
713 std::string version;
714 if (!driver.empty()) {
715 version = driver + " / ";
716 }
717 version +=
718 base::StringPrintf("ALSA library version %d.%d.%d", SND_LIB_MAJOR,
719 SND_LIB_MINOR, SND_LIB_SUBMINOR);
720 PortDirection direction = port->direction();
721 if (direction == PortDirection::kInput ||
722 direction == PortDirection::kDuplex) {
ricea37e45762016-08-25 02:43:39 -0700723 midi_ports->push_back(base::MakeUnique<MidiPort>(
agoode99d63292015-04-13 08:39:25 -0700724 path, id, client_id, port_id, midi_device, client->name(),
ricea37e45762016-08-25 02:43:39 -0700725 port->name(), manufacturer, version, MidiPort::Type::kInput));
agoode99d63292015-04-13 08:39:25 -0700726 }
727 if (direction == PortDirection::kOutput ||
728 direction == PortDirection::kDuplex) {
ricea37e45762016-08-25 02:43:39 -0700729 midi_ports->push_back(base::MakeUnique<MidiPort>(
agoode99d63292015-04-13 08:39:25 -0700730 path, id, client_id, port_id, midi_device, client->name(),
ricea37e45762016-08-25 02:43:39 -0700731 port->name(), manufacturer, version, MidiPort::Type::kOutput));
agoode99d63292015-04-13 08:39:25 -0700732 }
733 }
734 }
735 }
736
dchengc2aeece2015-12-27 00:54:00 -0800737 return midi_ports;
agoode99d63292015-04-13 08:39:25 -0700738}
739
740MidiManagerAlsa::AlsaSeqState::Port::Port(
741 const std::string& name,
742 MidiManagerAlsa::AlsaSeqState::PortDirection direction,
743 bool midi)
744 : name_(name), direction_(direction), midi_(midi) {
745}
746
agoodeb0582872015-05-20 05:22:24 -0700747MidiManagerAlsa::AlsaSeqState::Port::~Port() = default;
agoode99d63292015-04-13 08:39:25 -0700748
749MidiManagerAlsa::AlsaSeqState::Client::Client(const std::string& name,
750 snd_seq_client_type_t type)
mgiucad9af8452015-06-25 02:11:57 -0700751 : name_(name), type_(type) {
agoode99d63292015-04-13 08:39:25 -0700752}
753
agoodeb0582872015-05-20 05:22:24 -0700754MidiManagerAlsa::AlsaSeqState::Client::~Client() = default;
agoode99d63292015-04-13 08:39:25 -0700755
danakj75afea02016-04-25 20:36:04 -0700756void MidiManagerAlsa::AlsaSeqState::Client::AddPort(
757 int addr,
758 std::unique_ptr<Port> port) {
limasdfe59d0392015-11-19 20:28:57 -0800759 ports_[addr] = std::move(port);
agoode99d63292015-04-13 08:39:25 -0700760}
761
762void MidiManagerAlsa::AlsaSeqState::Client::RemovePort(int addr) {
mgiucad9af8452015-06-25 02:11:57 -0700763 ports_.erase(addr);
agoode99d63292015-04-13 08:39:25 -0700764}
765
766MidiManagerAlsa::AlsaSeqState::Client::PortMap::const_iterator
767MidiManagerAlsa::AlsaSeqState::Client::begin() const {
768 return ports_.begin();
769}
770
771MidiManagerAlsa::AlsaSeqState::Client::PortMap::const_iterator
772MidiManagerAlsa::AlsaSeqState::Client::end() const {
773 return ports_.end();
agoodeaf6e9f52015-03-24 10:23:49 -0700774}
775
agoodeb09423b2015-05-11 11:39:57 -0700776MidiManagerAlsa::AlsaCard::AlsaCard(udev_device* dev,
agooded87fc0f2015-05-21 08:29:31 -0700777 const std::string& name,
778 const std::string& longname,
779 const std::string& driver,
agoodeb09423b2015-05-11 11:39:57 -0700780 int midi_device_count)
agooded87fc0f2015-05-21 08:29:31 -0700781 : name_(name),
782 longname_(longname),
783 driver_(driver),
784 path_(device::UdevDeviceGetPropertyValue(dev, kUdevIdPath)),
785 bus_(device::UdevDeviceGetPropertyValue(dev, kUdevIdBus)),
786 vendor_id_(
787 UdevDeviceGetPropertyOrSysattr(dev, kUdevIdVendorId, kSysattrVendor)),
788 model_id_(
789 UdevDeviceGetPropertyOrSysattr(dev, kUdevIdModelId, kSysattrModel)),
790 usb_interface_num_(
791 device::UdevDeviceGetPropertyValue(dev, kUdevIdUsbInterfaceNum)),
792 serial_(UdevDeviceGetPropertyOrSysattr(dev,
793 kUdevIdSerialShort,
794 kSysattrGuid)),
795 midi_device_count_(midi_device_count),
796 manufacturer_(ExtractManufacturerString(
797 GetVendor(dev),
798 vendor_id_,
799 device::UdevDeviceGetPropertyValue(dev, kUdevIdVendorFromDatabase),
800 name,
801 longname)) {
agoodeb09423b2015-05-11 11:39:57 -0700802}
803
agoodeb0582872015-05-20 05:22:24 -0700804MidiManagerAlsa::AlsaCard::~AlsaCard() = default;
agoodeb09423b2015-05-11 11:39:57 -0700805
agoode55a8b522015-03-08 12:40:17 -0700806// static
agoodeb09423b2015-05-11 11:39:57 -0700807std::string MidiManagerAlsa::AlsaCard::ExtractManufacturerString(
agoode5e4e9cd2015-03-09 12:34:24 -0700808 const std::string& udev_id_vendor,
agoode55a8b522015-03-08 12:40:17 -0700809 const std::string& udev_id_vendor_id,
810 const std::string& udev_id_vendor_from_database,
811 const std::string& alsa_name,
812 const std::string& alsa_longname) {
813 // Let's try to determine the manufacturer. Here is the ordered preference
814 // in extraction:
agoodef212b2a2015-03-19 12:53:23 -0700815 // 1. Vendor name from the hardware device string, from udev properties
816 // or sysattrs.
agoode5e4e9cd2015-03-09 12:34:24 -0700817 // 2. Vendor name from the udev database (property ID_VENDOR_FROM_DATABASE).
agoode55a8b522015-03-08 12:40:17 -0700818 // 3. Heuristic from ALSA.
819
agoodee83758c2015-03-23 22:07:54 -0700820 // Is the vendor string present and not just the vendor hex id?
821 if (!udev_id_vendor.empty() && (udev_id_vendor != udev_id_vendor_id)) {
agoode55a8b522015-03-08 12:40:17 -0700822 return udev_id_vendor;
823 }
824
825 // Is there a vendor string in the hardware database?
826 if (!udev_id_vendor_from_database.empty()) {
827 return udev_id_vendor_from_database;
828 }
829
830 // Ok, udev gave us nothing useful, or was unavailable. So try a heuristic.
831 // We assume that card longname is in the format of
832 // "<manufacturer> <name> at <bus>". Otherwise, we give up to detect
833 // a manufacturer name here.
834 size_t at_index = alsa_longname.rfind(" at ");
agoodef212b2a2015-03-19 12:53:23 -0700835 if (at_index && at_index != std::string::npos) {
agoode55a8b522015-03-08 12:40:17 -0700836 size_t name_index = alsa_longname.rfind(alsa_name, at_index - 1);
agoodef212b2a2015-03-19 12:53:23 -0700837 if (name_index && name_index != std::string::npos)
agoode55a8b522015-03-08 12:40:17 -0700838 return alsa_longname.substr(0, name_index - 1);
839 }
840
841 // Failure.
842 return "";
843}
844
toyoshimefcee5e2017-06-14 07:14:39 -0700845void MidiManagerAlsa::SendMidiData(MidiManagerClient* client,
toyoshimf4d61522017-02-10 02:03:32 -0800846 uint32_t port_index,
Avi Drissman3528fd02015-12-18 20:11:31 -0500847 const std::vector<uint8_t>& data) {
Takashi Toyoshima0ae49702017-09-01 04:59:51 +0000848 ScopedSndMidiEventPtr encoder = CreateScopedSndMidiEventPtr(kSendBufferSize);
agoode5a1aa112015-06-21 20:51:00 -0700849 for (const auto datum : data) {
agoodebd4be9b2015-03-16 19:17:25 -0700850 snd_seq_event_t event;
Takashi Toyoshima0ae49702017-09-01 04:59:51 +0000851 int result = snd_midi_event_encode_byte(encoder.get(), datum, &event);
agoodebd4be9b2015-03-16 19:17:25 -0700852 if (result == 1) {
853 // Full event, send it.
agoode99d63292015-04-13 08:39:25 -0700854 base::AutoLock lock(out_ports_lock_);
855 auto it = out_ports_.find(port_index);
856 if (it != out_ports_.end()) {
Takashi Toyoshima9687b7c2017-07-19 09:54:14 +0000857 base::AutoLock lock(out_client_lock_);
858 if (!out_client_)
859 return;
agoode99d63292015-04-13 08:39:25 -0700860 snd_seq_ev_set_source(&event, it->second);
861 snd_seq_ev_set_subs(&event);
862 snd_seq_ev_set_direct(&event);
agoode5a1aa112015-06-21 20:51:00 -0700863 snd_seq_event_output_direct(out_client_.get(), &event);
agoode99d63292015-04-13 08:39:25 -0700864 }
agoodebd4be9b2015-03-16 19:17:25 -0700865 }
866 }
toyoshimf4d61522017-02-10 02:03:32 -0800867
868 // Acknowledge send.
869 AccumulateMidiBytesSent(client, data.size());
agoodebd4be9b2015-03-16 19:17:25 -0700870}
871
toyoshimefcee5e2017-06-14 07:14:39 -0700872void MidiManagerAlsa::EventLoop() {
agoode975043d2015-05-11 00:46:17 -0700873 bool loop_again = true;
agoodebd4be9b2015-03-16 19:17:25 -0700874
agoode975043d2015-05-11 00:46:17 -0700875 struct pollfd pfd[2];
agoode5a1aa112015-06-21 20:51:00 -0700876 snd_seq_poll_descriptors(in_client_.get(), &pfd[0], 1, POLLIN);
agoode975043d2015-05-11 00:46:17 -0700877 pfd[1].fd = device::udev_monitor_get_fd(udev_monitor_.get());
878 pfd[1].events = POLLIN;
agoodebd4be9b2015-03-16 19:17:25 -0700879
agoode975043d2015-05-11 00:46:17 -0700880 int err = HANDLE_EINTR(poll(pfd, arraysize(pfd), -1));
881 if (err < 0) {
brettwf7f870f2015-06-09 11:05:24 -0700882 VLOG(1) << "poll fails: " << base::safe_strerror(errno);
agoode975043d2015-05-11 00:46:17 -0700883 loop_again = false;
agoodeaf6e9f52015-03-24 10:23:49 -0700884 } else {
agoode975043d2015-05-11 00:46:17 -0700885 if (pfd[0].revents & POLLIN) {
886 // Read available incoming MIDI data.
887 int remaining;
888 double timestamp =
889 (base::TimeTicks::Now() - base::TimeTicks()).InSecondsF();
890 do {
891 snd_seq_event_t* event;
agoode5a1aa112015-06-21 20:51:00 -0700892 err = snd_seq_event_input(in_client_.get(), &event);
893 remaining = snd_seq_event_input_pending(in_client_.get(), 0);
agoode975043d2015-05-11 00:46:17 -0700894
895 if (err == -ENOSPC) {
896 // Handle out of space error.
897 VLOG(1) << "snd_seq_event_input detected buffer overrun";
898 // We've lost events: check another way to see if we need to shut
899 // down.
agoode975043d2015-05-11 00:46:17 -0700900 } else if (err == -EAGAIN) {
901 // We've read all the data.
902 } else if (err < 0) {
903 // Handle other errors.
904 VLOG(1) << "snd_seq_event_input fails: " << snd_strerror(err);
905 // TODO(agoode): Use RecordAction() or similar to log this.
906 loop_again = false;
907 } else if (event->source.client == SND_SEQ_CLIENT_SYSTEM &&
908 event->source.port == SND_SEQ_PORT_SYSTEM_ANNOUNCE) {
909 // Handle announce events.
910 switch (event->type) {
911 case SND_SEQ_EVENT_PORT_START:
912 // Don't use SND_SEQ_EVENT_CLIENT_START because the
913 // client name may not be set by the time we query
914 // it. It should be set by the time ports are made.
915 ProcessClientStartEvent(event->data.addr.client);
916 ProcessPortStartEvent(event->data.addr);
917 break;
918 case SND_SEQ_EVENT_CLIENT_EXIT:
919 // Check for disconnection of our "out" client. This means "shut
920 // down".
921 if (event->data.addr.client == out_client_id_) {
922 loop_again = false;
923 remaining = 0;
924 } else
925 ProcessClientExitEvent(event->data.addr);
926 break;
927 case SND_SEQ_EVENT_PORT_EXIT:
928 ProcessPortExitEvent(event->data.addr);
929 break;
930 }
931 } else {
932 // Normal operation.
933 ProcessSingleEvent(event, timestamp);
934 }
935 } while (remaining > 0);
936 }
937 if (pfd[1].revents & POLLIN) {
938 device::ScopedUdevDevicePtr dev(
939 device::udev_monitor_receive_device(udev_monitor_.get()));
940 if (dev.get())
941 ProcessUdevEvent(dev.get());
942 else
943 VLOG(1) << "udev_monitor_receive_device fails";
944 }
agoodebd4be9b2015-03-16 19:17:25 -0700945 }
946
agoodebd4be9b2015-03-16 19:17:25 -0700947 // Do again.
toyoshimf4d61522017-02-10 02:03:32 -0800948 if (loop_again) {
toyoshimefcee5e2017-06-14 07:14:39 -0700949 service()->task_service()->PostBoundTask(
950 kEventTaskRunner,
951 base::BindOnce(&MidiManagerAlsa::EventLoop, base::Unretained(this)));
toyoshimf4d61522017-02-10 02:03:32 -0800952 }
agoodebd4be9b2015-03-16 19:17:25 -0700953}
954
955void MidiManagerAlsa::ProcessSingleEvent(snd_seq_event_t* event,
956 double timestamp) {
agoode99d63292015-04-13 08:39:25 -0700957 auto source_it =
958 source_map_.find(AddrToInt(event->source.client, event->source.port));
agoodebd4be9b2015-03-16 19:17:25 -0700959 if (source_it != source_map_.end()) {
Avi Drissman3528fd02015-12-18 20:11:31 -0500960 uint32_t source = source_it->second;
agoodebd4be9b2015-03-16 19:17:25 -0700961 if (event->type == SND_SEQ_EVENT_SYSEX) {
962 // Special! Variable-length sysex.
Avi Drissman3528fd02015-12-18 20:11:31 -0500963 ReceiveMidiData(source, static_cast<const uint8_t*>(event->data.ext.ptr),
agoodebd4be9b2015-03-16 19:17:25 -0700964 event->data.ext.len, timestamp);
965 } else {
966 // Otherwise, decode this and send that on.
967 unsigned char buf[12];
agoode5a1aa112015-06-21 20:51:00 -0700968 long count =
969 snd_midi_event_decode(decoder_.get(), buf, sizeof(buf), event);
agoodebd4be9b2015-03-16 19:17:25 -0700970 if (count <= 0) {
971 if (count != -ENOENT) {
972 // ENOENT means that it's not a MIDI message, which is not an
973 // error, but other negative values are errors for us.
974 VLOG(1) << "snd_midi_event_decoder fails " << snd_strerror(count);
975 // TODO(agoode): Record this failure.
976 }
977 } else {
978 ReceiveMidiData(source, buf, count, timestamp);
979 }
980 }
981 }
982}
983
agoode99d63292015-04-13 08:39:25 -0700984void MidiManagerAlsa::ProcessClientStartEvent(int client_id) {
985 // Ignore if client is already started.
986 if (alsa_seq_state_.ClientStarted(client_id))
987 return;
988
989 snd_seq_client_info_t* client_info;
990 snd_seq_client_info_alloca(&client_info);
agoode5a1aa112015-06-21 20:51:00 -0700991 int err =
992 snd_seq_get_any_client_info(in_client_.get(), client_id, client_info);
agoode99d63292015-04-13 08:39:25 -0700993 if (err != 0)
994 return;
995
996 // Skip our own clients.
997 if ((client_id == in_client_id_) || (client_id == out_client_id_))
998 return;
999
1000 // Update our view of ALSA seq state.
1001 alsa_seq_state_.ClientStart(client_id,
1002 snd_seq_client_info_get_name(client_info),
1003 snd_seq_client_info_get_type(client_info));
1004
1005 // Generate Web MIDI events.
1006 UpdatePortStateAndGenerateEvents();
1007}
1008
1009void MidiManagerAlsa::ProcessPortStartEvent(const snd_seq_addr_t& addr) {
1010 snd_seq_port_info_t* port_info;
1011 snd_seq_port_info_alloca(&port_info);
agoode5a1aa112015-06-21 20:51:00 -07001012 int err = snd_seq_get_any_port_info(in_client_.get(), addr.client, addr.port,
1013 port_info);
agoode99d63292015-04-13 08:39:25 -07001014 if (err != 0)
1015 return;
1016
1017 unsigned int caps = snd_seq_port_info_get_capability(port_info);
1018 bool input = (caps & kRequiredInputPortCaps) == kRequiredInputPortCaps;
1019 bool output = (caps & kRequiredOutputPortCaps) == kRequiredOutputPortCaps;
1020 AlsaSeqState::PortDirection direction;
1021 if (input && output)
1022 direction = AlsaSeqState::PortDirection::kDuplex;
1023 else if (input)
1024 direction = AlsaSeqState::PortDirection::kInput;
1025 else if (output)
1026 direction = AlsaSeqState::PortDirection::kOutput;
1027 else
1028 return;
1029
1030 // Update our view of ALSA seq state.
1031 alsa_seq_state_.PortStart(
1032 addr.client, addr.port, snd_seq_port_info_get_name(port_info), direction,
1033 snd_seq_port_info_get_type(port_info) & SND_SEQ_PORT_TYPE_MIDI_GENERIC);
1034 // Generate Web MIDI events.
1035 UpdatePortStateAndGenerateEvents();
1036}
1037
1038void MidiManagerAlsa::ProcessClientExitEvent(const snd_seq_addr_t& addr) {
1039 // Update our view of ALSA seq state.
1040 alsa_seq_state_.ClientExit(addr.client);
1041 // Generate Web MIDI events.
1042 UpdatePortStateAndGenerateEvents();
1043}
1044
1045void MidiManagerAlsa::ProcessPortExitEvent(const snd_seq_addr_t& addr) {
1046 // Update our view of ALSA seq state.
1047 alsa_seq_state_.PortExit(addr.client, addr.port);
1048 // Generate Web MIDI events.
1049 UpdatePortStateAndGenerateEvents();
1050}
1051
agoode975043d2015-05-11 00:46:17 -07001052void MidiManagerAlsa::ProcessUdevEvent(udev_device* dev) {
1053 // Only card devices have this property set, and only when they are
1054 // fully initialized.
1055 if (!device::udev_device_get_property_value(dev,
1056 kUdevPropertySoundInitialized))
1057 return;
1058
1059 // Get the action. If no action, then we are doing first time enumeration
1060 // and the device is treated as new.
1061 const char* action = device::udev_device_get_action(dev);
1062 if (!action)
1063 action = kUdevActionChange;
1064
1065 if (strcmp(action, kUdevActionChange) == 0) {
agoodeb09423b2015-05-11 11:39:57 -07001066 AddCard(dev);
1067 // Generate Web MIDI events.
1068 UpdatePortStateAndGenerateEvents();
agoode975043d2015-05-11 00:46:17 -07001069 } else if (strcmp(action, kUdevActionRemove) == 0) {
agoodeb09423b2015-05-11 11:39:57 -07001070 RemoveCard(GetCardNumber(dev));
1071 // Generate Web MIDI events.
1072 UpdatePortStateAndGenerateEvents();
agoode975043d2015-05-11 00:46:17 -07001073 }
1074}
1075
agoodeb09423b2015-05-11 11:39:57 -07001076void MidiManagerAlsa::AddCard(udev_device* dev) {
1077 int number = GetCardNumber(dev);
1078 if (number == -1)
1079 return;
1080
1081 RemoveCard(number);
1082
1083 snd_ctl_card_info_t* card;
1084 snd_hwdep_info_t* hwdep;
1085 snd_ctl_card_info_alloca(&card);
1086 snd_hwdep_info_alloca(&hwdep);
1087 const std::string id = base::StringPrintf("hw:CARD=%i", number);
1088 snd_ctl_t* handle;
1089 int err = snd_ctl_open(&handle, id.c_str(), 0);
1090 if (err != 0) {
1091 VLOG(1) << "snd_ctl_open fails: " << snd_strerror(err);
1092 return;
1093 }
1094 err = snd_ctl_card_info(handle, card);
1095 if (err != 0) {
1096 VLOG(1) << "snd_ctl_card_info fails: " << snd_strerror(err);
1097 snd_ctl_close(handle);
1098 return;
1099 }
1100 std::string name = snd_ctl_card_info_get_name(card);
1101 std::string longname = snd_ctl_card_info_get_longname(card);
1102 std::string driver = snd_ctl_card_info_get_driver(card);
1103
1104 // Count rawmidi devices (not subdevices).
1105 int midi_count = 0;
1106 for (int device = -1;
1107 !snd_ctl_rawmidi_next_device(handle, &device) && device >= 0;)
1108 ++midi_count;
1109
1110 // Count any hwdep synths that become MIDI devices outside of rawmidi.
1111 //
1112 // Explanation:
1113 // Any kernel driver can create an ALSA client (visible to us).
1114 // With modern hardware, only rawmidi devices do this. Kernel
1115 // drivers create rawmidi devices and the rawmidi subsystem makes
1116 // the seq clients. But the OPL3 driver is special, it does not
1117 // make a rawmidi device but a seq client directly. (This is the
1118 // only one to worry about in the kernel code, as of 2015-03-23.)
1119 //
1120 // OPL3 is very old (but still possible to get in new
1121 // hardware). It is unlikely that new drivers would not use
1122 // rawmidi and defeat our heuristic.
1123 //
1124 // Longer term, support should be added in the kernel to expose a
1125 // direct link from card->client (or client->card) so that all
1126 // these heuristics will be obsolete. Once that is there, we can
1127 // assume our old heuristics will work on old kernels and the new
1128 // robust code will be used on new. Then we will not need to worry
1129 // about changes to kernel internals breaking our code.
1130 // See the TODO above at kMinimumClientIdForCards.
1131 for (int device = -1;
1132 !snd_ctl_hwdep_next_device(handle, &device) && device >= 0;) {
1133 err = snd_ctl_hwdep_info(handle, hwdep);
1134 if (err != 0) {
1135 VLOG(1) << "snd_ctl_hwdep_info fails: " << snd_strerror(err);
1136 continue;
1137 }
1138 snd_hwdep_iface_t iface = snd_hwdep_info_get_iface(hwdep);
1139 if (iface == SND_HWDEP_IFACE_OPL2 || iface == SND_HWDEP_IFACE_OPL3 ||
1140 iface == SND_HWDEP_IFACE_OPL4)
1141 ++midi_count;
1142 }
1143 snd_ctl_close(handle);
1144
mgiucad9af8452015-06-25 02:11:57 -07001145 if (midi_count > 0) {
danakj75afea02016-04-25 20:36:04 -07001146 std::unique_ptr<AlsaCard> card(
mgiucad9af8452015-06-25 02:11:57 -07001147 new AlsaCard(dev, name, longname, driver, midi_count));
limasdfe59d0392015-11-19 20:28:57 -08001148 alsa_cards_.insert(std::make_pair(number, std::move(card)));
mgiucad9af8452015-06-25 02:11:57 -07001149 alsa_card_midi_count_ += midi_count;
1150 }
agoodeb09423b2015-05-11 11:39:57 -07001151}
1152
1153void MidiManagerAlsa::RemoveCard(int number) {
1154 auto it = alsa_cards_.find(number);
1155 if (it == alsa_cards_.end())
1156 return;
1157
1158 alsa_card_midi_count_ -= it->second->midi_device_count();
agoodeb09423b2015-05-11 11:39:57 -07001159 alsa_cards_.erase(it);
1160}
1161
agoode99d63292015-04-13 08:39:25 -07001162void MidiManagerAlsa::UpdatePortStateAndGenerateEvents() {
agoodeb09423b2015-05-11 11:39:57 -07001163 // Verify that our information from ALSA and udev are in sync. If
1164 // not, we cannot generate events right now.
1165 if (alsa_card_midi_count_ != alsa_seq_state_.card_client_count())
1166 return;
1167
agoode99d63292015-04-13 08:39:25 -07001168 // Generate new port state.
agoodeb09423b2015-05-11 11:39:57 -07001169 auto new_port_state = alsa_seq_state_.ToMidiPortState(alsa_cards_);
agoode99d63292015-04-13 08:39:25 -07001170
1171 // Disconnect any connected old ports that are now missing.
agoode5ebc4932015-12-01 08:25:12 -08001172 for (auto& old_port : port_state_) {
agoode99d63292015-04-13 08:39:25 -07001173 if (old_port->connected() &&
1174 (new_port_state->FindConnected(*old_port) == new_port_state->end())) {
1175 old_port->set_connected(false);
Avi Drissman3528fd02015-12-18 20:11:31 -05001176 uint32_t web_port_index = old_port->web_port_index();
agoode99d63292015-04-13 08:39:25 -07001177 switch (old_port->type()) {
1178 case MidiPort::Type::kInput:
1179 source_map_.erase(
1180 AddrToInt(old_port->client_id(), old_port->port_id()));
toyoshimec2570a2016-10-21 02:15:27 -07001181 SetInputPortState(web_port_index, PortState::DISCONNECTED);
agoode99d63292015-04-13 08:39:25 -07001182 break;
1183 case MidiPort::Type::kOutput:
1184 DeleteAlsaOutputPort(web_port_index);
toyoshimec2570a2016-10-21 02:15:27 -07001185 SetOutputPortState(web_port_index, PortState::DISCONNECTED);
agoode99d63292015-04-13 08:39:25 -07001186 break;
1187 }
1188 }
1189 }
1190
1191 // Reconnect or add new ports.
1192 auto it = new_port_state->begin();
1193 while (it != new_port_state->end()) {
agoode5ebc4932015-12-01 08:25:12 -08001194 auto& new_port = *it;
agoode99d63292015-04-13 08:39:25 -07001195 auto old_port = port_state_.Find(*new_port);
1196 if (old_port == port_state_.end()) {
1197 // Add new port.
agoode5ebc4932015-12-01 08:25:12 -08001198 const auto& opaque_key = new_port->OpaqueKey();
1199 const auto& manufacturer = new_port->manufacturer();
1200 const auto& port_name = new_port->port_name();
1201 const auto& version = new_port->version();
1202 const auto& type = new_port->type();
1203 const auto& client_id = new_port->client_id();
1204 const auto& port_id = new_port->port_id();
1205
dchengc2aeece2015-12-27 00:54:00 -08001206 uint32_t web_port_index = port_state_.push_back(std::move(new_port));
agoode5ebc4932015-12-01 08:25:12 -08001207 it = new_port_state->erase(it);
1208
1209 MidiPortInfo info(opaque_key, manufacturer, port_name, version,
toyoshimec2570a2016-10-21 02:15:27 -07001210 PortState::OPENED);
agoode5ebc4932015-12-01 08:25:12 -08001211 switch (type) {
agoode99d63292015-04-13 08:39:25 -07001212 case MidiPort::Type::kInput:
agoode5ebc4932015-12-01 08:25:12 -08001213 if (Subscribe(web_port_index, client_id, port_id))
agoode99d63292015-04-13 08:39:25 -07001214 AddInputPort(info);
1215 break;
agoode99d63292015-04-13 08:39:25 -07001216 case MidiPort::Type::kOutput:
agoode5ebc4932015-12-01 08:25:12 -08001217 if (CreateAlsaOutputPort(web_port_index, client_id, port_id))
agoode99d63292015-04-13 08:39:25 -07001218 AddOutputPort(info);
1219 break;
1220 }
agoode99d63292015-04-13 08:39:25 -07001221 } else if (!(*old_port)->connected()) {
1222 // Reconnect.
Avi Drissman3528fd02015-12-18 20:11:31 -05001223 uint32_t web_port_index = (*old_port)->web_port_index();
agoode99d63292015-04-13 08:39:25 -07001224 (*old_port)->Update(new_port->path(), new_port->client_id(),
1225 new_port->port_id(), new_port->client_name(),
1226 new_port->port_name(), new_port->manufacturer(),
1227 new_port->version());
1228 switch ((*old_port)->type()) {
1229 case MidiPort::Type::kInput:
1230 if (Subscribe(web_port_index, (*old_port)->client_id(),
1231 (*old_port)->port_id()))
toyoshimec2570a2016-10-21 02:15:27 -07001232 SetInputPortState(web_port_index, PortState::OPENED);
agoode99d63292015-04-13 08:39:25 -07001233 break;
agoode99d63292015-04-13 08:39:25 -07001234 case MidiPort::Type::kOutput:
1235 if (CreateAlsaOutputPort(web_port_index, (*old_port)->client_id(),
1236 (*old_port)->port_id()))
toyoshimec2570a2016-10-21 02:15:27 -07001237 SetOutputPortState(web_port_index, PortState::OPENED);
agoode99d63292015-04-13 08:39:25 -07001238 break;
1239 }
1240 (*old_port)->set_connected(true);
1241 ++it;
1242 } else {
1243 ++it;
1244 }
1245 }
1246}
1247
agoode975043d2015-05-11 00:46:17 -07001248// TODO(agoode): return false on failure.
agoode99d63292015-04-13 08:39:25 -07001249void MidiManagerAlsa::EnumerateAlsaPorts() {
1250 snd_seq_client_info_t* client_info;
1251 snd_seq_client_info_alloca(&client_info);
1252 snd_seq_port_info_t* port_info;
1253 snd_seq_port_info_alloca(&port_info);
1254
1255 // Enumerate clients.
1256 snd_seq_client_info_set_client(client_info, -1);
agoode5a1aa112015-06-21 20:51:00 -07001257 while (!snd_seq_query_next_client(in_client_.get(), client_info)) {
agoode99d63292015-04-13 08:39:25 -07001258 int client_id = snd_seq_client_info_get_client(client_info);
1259 ProcessClientStartEvent(client_id);
1260
1261 // Enumerate ports.
1262 snd_seq_port_info_set_client(port_info, client_id);
1263 snd_seq_port_info_set_port(port_info, -1);
agoode5a1aa112015-06-21 20:51:00 -07001264 while (!snd_seq_query_next_port(in_client_.get(), port_info)) {
agoode99d63292015-04-13 08:39:25 -07001265 const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(port_info);
1266 ProcessPortStartEvent(*addr);
1267 }
1268 }
1269}
1270
agoode975043d2015-05-11 00:46:17 -07001271bool MidiManagerAlsa::EnumerateUdevCards() {
1272 int err;
1273
1274 device::ScopedUdevEnumeratePtr enumerate(
1275 device::udev_enumerate_new(udev_.get()));
1276 if (!enumerate.get()) {
1277 VLOG(1) << "udev_enumerate_new fails";
1278 return false;
1279 }
1280
1281 err = device::udev_enumerate_add_match_subsystem(enumerate.get(),
1282 kUdevSubsystemSound);
1283 if (err) {
1284 VLOG(1) << "udev_enumerate_add_match_subsystem fails: "
brettwf7f870f2015-06-09 11:05:24 -07001285 << base::safe_strerror(-err);
agoode975043d2015-05-11 00:46:17 -07001286 return false;
1287 }
1288
1289 err = device::udev_enumerate_scan_devices(enumerate.get());
1290 if (err) {
brettwf7f870f2015-06-09 11:05:24 -07001291 VLOG(1) << "udev_enumerate_scan_devices fails: "
1292 << base::safe_strerror(-err);
agoode975043d2015-05-11 00:46:17 -07001293 return false;
1294 }
1295
1296 udev_list_entry* list_entry;
1297 auto* devices = device::udev_enumerate_get_list_entry(enumerate.get());
1298 udev_list_entry_foreach(list_entry, devices) {
1299 const char* path = device::udev_list_entry_get_name(list_entry);
1300 device::ScopedUdevDevicePtr dev(
1301 device::udev_device_new_from_syspath(udev_.get(), path));
1302 if (dev.get())
1303 ProcessUdevEvent(dev.get());
1304 }
1305
1306 return true;
1307}
1308
Avi Drissman3528fd02015-12-18 20:11:31 -05001309bool MidiManagerAlsa::CreateAlsaOutputPort(uint32_t port_index,
agoode99d63292015-04-13 08:39:25 -07001310 int client_id,
1311 int port_id) {
1312 // Create the port.
1313 int out_port = snd_seq_create_simple_port(
agoode5a1aa112015-06-21 20:51:00 -07001314 out_client_.get(), NULL, kCreateOutputPortCaps, kCreatePortType);
agoode99d63292015-04-13 08:39:25 -07001315 if (out_port < 0) {
1316 VLOG(1) << "snd_seq_create_simple_port fails: " << snd_strerror(out_port);
1317 return false;
1318 }
1319 // Activate port subscription.
1320 snd_seq_port_subscribe_t* subs;
1321 snd_seq_port_subscribe_alloca(&subs);
1322 snd_seq_addr_t sender;
1323 sender.client = out_client_id_;
1324 sender.port = out_port;
1325 snd_seq_port_subscribe_set_sender(subs, &sender);
1326 snd_seq_addr_t dest;
1327 dest.client = client_id;
1328 dest.port = port_id;
1329 snd_seq_port_subscribe_set_dest(subs, &dest);
agoode5a1aa112015-06-21 20:51:00 -07001330 int err = snd_seq_subscribe_port(out_client_.get(), subs);
agoode99d63292015-04-13 08:39:25 -07001331 if (err != 0) {
1332 VLOG(1) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
agoode5a1aa112015-06-21 20:51:00 -07001333 snd_seq_delete_simple_port(out_client_.get(), out_port);
agoode99d63292015-04-13 08:39:25 -07001334 return false;
1335 }
1336
1337 // Update our map.
1338 base::AutoLock lock(out_ports_lock_);
1339 out_ports_[port_index] = out_port;
1340 return true;
1341}
1342
Avi Drissman3528fd02015-12-18 20:11:31 -05001343void MidiManagerAlsa::DeleteAlsaOutputPort(uint32_t port_index) {
agoode99d63292015-04-13 08:39:25 -07001344 base::AutoLock lock(out_ports_lock_);
1345 auto it = out_ports_.find(port_index);
1346 if (it == out_ports_.end())
1347 return;
1348
1349 int alsa_port = it->second;
agoode5a1aa112015-06-21 20:51:00 -07001350 snd_seq_delete_simple_port(out_client_.get(), alsa_port);
agoode99d63292015-04-13 08:39:25 -07001351 out_ports_.erase(it);
1352}
1353
Avi Drissman3528fd02015-12-18 20:11:31 -05001354bool MidiManagerAlsa::Subscribe(uint32_t port_index,
1355 int client_id,
1356 int port_id) {
agoode99d63292015-04-13 08:39:25 -07001357 // Activate port subscription.
1358 snd_seq_port_subscribe_t* subs;
1359 snd_seq_port_subscribe_alloca(&subs);
1360 snd_seq_addr_t sender;
1361 sender.client = client_id;
1362 sender.port = port_id;
1363 snd_seq_port_subscribe_set_sender(subs, &sender);
1364 snd_seq_addr_t dest;
1365 dest.client = in_client_id_;
1366 dest.port = in_port_id_;
1367 snd_seq_port_subscribe_set_dest(subs, &dest);
agoode5a1aa112015-06-21 20:51:00 -07001368 int err = snd_seq_subscribe_port(in_client_.get(), subs);
agoode99d63292015-04-13 08:39:25 -07001369 if (err != 0) {
1370 VLOG(1) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
1371 return false;
1372 }
1373
1374 // Update our map.
1375 source_map_[AddrToInt(client_id, port_id)] = port_index;
1376 return true;
1377}
1378
Takashi Toyoshima0ae49702017-09-01 04:59:51 +00001379MidiManagerAlsa::ScopedSndMidiEventPtr
1380MidiManagerAlsa::CreateScopedSndMidiEventPtr(size_t size) {
1381 snd_midi_event_t* coder;
1382 snd_midi_event_new(size, &coder);
1383 return ScopedSndMidiEventPtr(coder);
1384}
1385
Takashi Toyoshima70e44ee2017-07-19 08:38:20 +00001386#if !defined(OS_CHROMEOS)
toyoshimf4d61522017-02-10 02:03:32 -08001387MidiManager* MidiManager::Create(MidiService* service) {
1388 return new MidiManagerAlsa(service);
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +00001389}
Takashi Toyoshima70e44ee2017-07-19 08:38:20 +00001390#endif
toyoshim@chromium.orga97eebf2014-01-03 07:52:39 +00001391
toyoshime147c5e2015-05-07 21:58:31 -07001392} // namespace midi