blob: 729f4743e610a5c48e9f85f9f4b0cdf62999067c [file] [log] [blame]
Prashant Malanifd1e2002017-08-09 13:22:59 -07001// Copyright 2017 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "midis/seq_handler.h"
6
7#include <map>
Ben Chand496e612017-09-29 00:20:50 -07008#include <memory>
Prashant Malanifd1e2002017-08-09 13:22:59 -07009#include <string>
10#include <utility>
Prashant Malanie6e6b272018-05-02 10:16:30 -070011#include <vector>
Prashant Malanifd1e2002017-08-09 13:22:59 -070012
13#include <base/bind.h>
Prashant Malanifd1e2002017-08-09 13:22:59 -070014#include <poll.h>
15
Prashant Malanie6e6b272018-05-02 10:16:30 -070016#include "media/midi/message_util.h"
Prashant Malani3c540362017-09-28 13:35:14 -070017#include "midis/constants.h"
18
Prashant Malanifd1e2002017-08-09 13:22:59 -070019namespace {
20
21const unsigned int kCreateInputPortCaps =
22 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_NO_EXPORT;
23const unsigned int kCreateOutputPortCaps =
24 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_NO_EXPORT;
25const unsigned int kCreatePortType =
26 SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION;
27const char kSndSeqName[] = "hw";
28
29} // namespace
30
31namespace midis {
32
Prashant Malani3c540362017-09-28 13:35:14 -070033SeqHandler::SeqHandler() : weak_factory_(this) {}
34
Prashant Malanifd1e2002017-08-09 13:22:59 -070035SeqHandler::SeqHandler(AddDeviceCallback add_device_cb,
36 RemoveDeviceCallback remove_device_cb,
37 HandleReceiveDataCallback handle_rx_data_cb,
38 IsDevicePresentCallback is_device_present_cb,
39 IsPortPresentCallback is_port_present_cb)
40 : add_device_cb_(add_device_cb),
41 remove_device_cb_(remove_device_cb),
42 handle_rx_data_cb_(handle_rx_data_cb),
43 is_device_present_cb_(is_device_present_cb),
44 is_port_present_cb_(is_port_present_cb),
45 weak_factory_(this) {}
46
47bool SeqHandler::InitSeq() {
48 // Create client handles.
49 snd_seq_t* tmp_seq = nullptr;
50 int err =
51 snd_seq_open(&tmp_seq, kSndSeqName, SND_SEQ_OPEN_INPUT, SND_SEQ_NONBLOCK);
52 if (err != 0) {
53 LOG(ERROR) << "snd_seq_open fails: " << snd_strerror(err);
54 return false;
55 }
56 ScopedSeqPtr in_client(tmp_seq);
57 tmp_seq = nullptr;
58 in_client_id_ = snd_seq_client_id(in_client.get());
59
60 err = snd_seq_open(&tmp_seq, kSndSeqName, SND_SEQ_OPEN_OUTPUT, 0);
61 if (err != 0) {
62 LOG(ERROR) << "snd_seq_open fails: " << snd_strerror(err);
63 return false;
64 }
65
66 ScopedSeqPtr out_client(tmp_seq);
67 tmp_seq = nullptr;
68 out_client_id_ = snd_seq_client_id(out_client.get());
69
70 // Name the clients.
71 err = snd_seq_set_client_name(in_client.get(), "midis (input)");
72 if (err != 0) {
73 LOG(ERROR) << "snd_seq_set_client_name fails: " << snd_strerror(err);
74 return false;
75 }
76 err = snd_seq_set_client_name(out_client.get(), "midis (output)");
77 if (err != 0) {
78 LOG(ERROR) << "snd_seq_set_client_name fails: " << snd_strerror(err);
79 return false;
80 }
81
82 // Create input port.
83 in_port_id_ = snd_seq_create_simple_port(
84 in_client.get(), NULL, kCreateInputPortCaps, kCreatePortType);
85 if (in_port_id_ < 0) {
86 LOG(ERROR) << "snd_seq_create_simple_port fails: "
87 << snd_strerror(in_port_id_);
88 return false;
89 }
90
91 // Subscribe to the announce port.
92 snd_seq_port_subscribe_t* subs;
93 snd_seq_port_subscribe_alloca(&subs);
94 snd_seq_addr_t announce_sender;
95 snd_seq_addr_t announce_dest;
96 announce_sender.client = SND_SEQ_CLIENT_SYSTEM;
97 announce_sender.port = SND_SEQ_PORT_SYSTEM_ANNOUNCE;
98 announce_dest.client = in_client_id_;
99 announce_dest.port = in_port_id_;
100 snd_seq_port_subscribe_set_sender(subs, &announce_sender);
101 snd_seq_port_subscribe_set_dest(subs, &announce_dest);
102 err = snd_seq_subscribe_port(in_client.get(), subs);
103 if (err != 0) {
104 LOG(ERROR) << "snd_seq_subscribe_port on the announce port fails: "
105 << snd_strerror(err);
106 return false;
107 }
108
Prashant Malani78b59c32017-10-24 22:54:51 -0700109 in_client_ = std::move(in_client);
110 out_client_ = std::move(out_client);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700111
Prashant Malani78b59c32017-10-24 22:54:51 -0700112 // Initialize decoder.
113 decoder_ = CreateMidiEvent(0);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700114
Prashant Malani8ca4ab32017-10-03 15:12:49 -0700115 EnumerateExistingDevices();
116
Prashant Malanifd1e2002017-08-09 13:22:59 -0700117 // Obtain the poll file descriptor to watch.
Ben Chand496e612017-09-29 00:20:50 -0700118 pfd_ = std::make_unique<pollfd>();
Prashant Malanifd1e2002017-08-09 13:22:59 -0700119 snd_seq_poll_descriptors(in_client_.get(), pfd_.get(), 1, POLLIN);
120
121 taskid_ = brillo::MessageLoop::current()->WatchFileDescriptor(
Prashant Malani3c540362017-09-28 13:35:14 -0700122 FROM_HERE, pfd_.get()->fd, brillo::MessageLoop::kWatchRead, true,
Prashant Malanifd1e2002017-08-09 13:22:59 -0700123 base::Bind(&SeqHandler::ProcessAlsaClientFd, weak_factory_.GetWeakPtr()));
124
125 if (taskid_ == brillo::MessageLoop::kTaskIdNull) {
126 in_client_.reset();
127 out_client_.reset();
128 decoder_.reset();
129 pfd_.reset();
130 return false;
131 }
132
133 return true;
134}
135
136void SeqHandler::ProcessAlsaClientFd() {
137 int remaining;
138 do {
139 snd_seq_event_t* event;
Prashant Malania9bbf542017-10-19 18:27:18 -0700140 int err = SndSeqEventInput(in_client_.get(), &event);
141 remaining = SndSeqEventInputPending(in_client_.get(), 0);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700142
143 if (err == -ENOSPC) {
144 // Handle out of space error.
145 LOG(ERROR) << "snd_seq_event_input detected buffer overrun";
146 // We've lost events: check another way to see if we need to shut
147 // down.
148 } else if (err == -EAGAIN) {
149 // We've read all the data.
150 } else if (err < 0) {
151 // Handle other errors.
152 LOG(ERROR) << "snd_seq_event_input fails: " << snd_strerror(err);
153 // TODO(pmalani): Stop the message loop here then.
154 } else if (event->source.client == SND_SEQ_CLIENT_SYSTEM &&
155 event->source.port == SND_SEQ_PORT_SYSTEM_ANNOUNCE) {
156 // Handle announce events.
157 switch (event->type) {
158 case SND_SEQ_EVENT_PORT_START:
159 // Don't use SND_SEQ_EVENT_CLIENT_START because the
160 // client name may not be set by the time we query
161 // it. It should be set by the time ports are made.
162 AddSeqDevice(event->data.addr.client);
163 AddSeqPort(event->data.addr.client, event->data.addr.port);
164 break;
165 case SND_SEQ_EVENT_CLIENT_EXIT:
166 // Check for disconnection of our "out" client. This means "shut
167 // down".
168 if (event->data.addr.client == out_client_id_) {
169 // TODO(pmalani): Stop the message loop here then.
170 remaining = 0;
171 } else {
172 RemoveSeqDevice(event->data.addr.client);
173 }
174 break;
175 case SND_SEQ_EVENT_PORT_EXIT:
176 RemoveSeqPort(event->data.addr.client, event->data.addr.port);
177 break;
178 }
179 } else {
180 // Normal operation.
181 ProcessMidiEvent(event);
182 }
183 } while (remaining > 0);
184}
185
186void SeqHandler::AddSeqDevice(uint32_t device_id) {
Prashant Malani3c540362017-09-28 13:35:14 -0700187 if (is_device_present_cb_.Run(0 /* TODO(pmalani): Remove card number */,
188 device_id)) {
Prashant Malanifd1e2002017-08-09 13:22:59 -0700189 LOG(INFO) << "Device: " << device_id << " already exists.";
190 return;
191 }
192
193 // Check that the device isn't our own in/our client.
194 if (device_id == in_client_id_ || device_id == out_client_id_) {
195 return;
196 }
197
198 snd_seq_client_info_t* client_info;
199 snd_seq_client_info_alloca(&client_info);
200 int err =
201 snd_seq_get_any_client_info(in_client_.get(), device_id, client_info);
202 if (err != 0) {
203 LOG(ERROR) << "Failed to get client info.";
204 return;
205 }
206
207 std::string name(snd_seq_client_info_get_name(client_info));
Prashant Malanifd1e2002017-08-09 13:22:59 -0700208
209 // Store the list of MIDI ports and corresponding capabilities in a map.
210 std::map<uint32_t, unsigned int> port_caps;
211 snd_seq_port_info_t* port_info;
212 snd_seq_port_info_alloca(&port_info);
213 snd_seq_port_info_set_client(port_info, device_id);
214 snd_seq_port_info_set_port(port_info, -1);
215 while (!snd_seq_query_next_port(in_client_.get(), port_info)) {
216 if (!(snd_seq_port_info_get_type(port_info) &
217 SND_SEQ_PORT_TYPE_MIDI_GENERIC)) {
218 LOG(INFO) << "Skipping non-MIDI port.";
219 continue;
220 }
221 port_caps.emplace(snd_seq_port_info_get_port(port_info),
222 snd_seq_port_info_get_capability(port_info));
223 }
224
Prashant Malani06d54652018-03-08 18:58:15 -0800225 // If the number of MIDI ports is 0, there is no use in creating
226 // a device.
227 if (port_caps.size() == 0) {
228 LOG(INFO) << "Connected device: " << name << " has no MIDI ports.";
229 return;
230 }
231
Ben Chan2a3a8e32017-10-05 11:15:11 -0700232 auto dev = std::make_unique<Device>(
Prashant Malani3c540362017-09-28 13:35:14 -0700233 name, std::string(),
234 0 /* card number; TODO(pmalani) remove card number */, device_id,
Prashant Malani06d54652018-03-08 18:58:15 -0800235 port_caps.size(), 0 /* device flags TODO(pmalani): flags not needed. */,
Prashant Malanifd1e2002017-08-09 13:22:59 -0700236 base::Bind(&SeqHandler::SubscribeInPort, base::Unretained(this)),
237 base::Bind(&SeqHandler::SubscribeOutPort, base::Unretained(this)),
238 base::Bind(&SeqHandler::UnsubscribeInPort, weak_factory_.GetWeakPtr()),
239 base::Bind(&SeqHandler::UnsubscribeOutPort, weak_factory_.GetWeakPtr()),
240 base::Bind(&SeqHandler::SendMidiData, weak_factory_.GetWeakPtr()),
241 std::move(port_caps));
242 add_device_cb_.Run(std::move(dev));
243}
244
245void SeqHandler::AddSeqPort(uint32_t device_id, uint32_t port_id) {
246 if (!is_port_present_cb_.Run(0, device_id, port_id)) {
247 LOG(WARNING) << "Received port start event for new port: " << port_id
248 << " on device: " << device_id << "; ignoring";
249 }
250}
251
252void SeqHandler::RemoveSeqDevice(uint32_t device_id) {
253 remove_device_cb_.Run(0 /* FIXME remove card number */, device_id);
254}
255
256void SeqHandler::RemoveSeqPort(uint32_t device_id, uint32_t port_id) {
257 if (!is_port_present_cb_.Run(0, device_id, port_id)) {
258 LOG(WARNING) << "Received port start event for new port: " << port_id
259 << " on device: " << device_id << "; ignoring";
260 }
261}
262
263bool SeqHandler::SubscribeInPort(uint32_t device_id, uint32_t port_id) {
264 snd_seq_port_subscribe_t* subs;
265 snd_seq_port_subscribe_alloca(&subs);
266 snd_seq_addr_t sender;
267 sender.client = device_id;
268 sender.port = port_id;
269 snd_seq_port_subscribe_set_sender(subs, &sender);
270
271 snd_seq_addr_t dest;
272 dest.client = in_client_id_;
273 dest.port = in_port_id_;
274 snd_seq_port_subscribe_set_dest(subs, &dest);
275
276 int err = snd_seq_subscribe_port(in_client_.get(), subs);
277 if (err != 0) {
278 LOG(ERROR) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
279 return false;
280 }
281
282 return true;
283}
284
285int SeqHandler::SubscribeOutPort(uint32_t device_id, uint32_t port_id) {
286 int out_port;
Prashant Malani3c540362017-09-28 13:35:14 -0700287 out_port = snd_seq_create_simple_port(out_client_.get(), NULL,
288 kCreateOutputPortCaps, kCreatePortType);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700289 if (out_port < 0) {
290 LOG(INFO) << "snd_seq_creat_simple_port (output) failed: "
291 << snd_strerror(out_port);
292 return -1;
293 }
294
295 snd_seq_port_subscribe_t* subs;
296 snd_seq_port_subscribe_alloca(&subs);
297 snd_seq_addr_t sender;
298 sender.client = out_client_id_;
299 sender.port = out_port;
300 snd_seq_port_subscribe_set_sender(subs, &sender);
301
302 snd_seq_addr_t dest;
303 dest.client = device_id;
304 dest.port = port_id;
305 snd_seq_port_subscribe_set_dest(subs, &dest);
306
307 int err = snd_seq_subscribe_port(out_client_.get(), subs);
308 if (err != 0) {
309 snd_seq_delete_simple_port(out_client_.get(), out_port);
310 LOG(ERROR) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
311 return -1;
312 }
313
314 return out_port;
315}
316
317void SeqHandler::UnsubscribeInPort(uint32_t device_id, uint32_t port_id) {
318 snd_seq_port_subscribe_t* subs;
319 snd_seq_port_subscribe_alloca(&subs);
320 snd_seq_addr_t sender;
321 sender.client = device_id;
322 sender.port = port_id;
323 snd_seq_port_subscribe_set_sender(subs, &sender);
324 snd_seq_addr_t dest;
325 dest.client = in_client_id_;
326 dest.port = in_port_id_;
327 snd_seq_port_subscribe_set_dest(subs, &dest);
328
329 int err = snd_seq_unsubscribe_port(in_client_.get(), subs);
330 if (err != 0) {
331 LOG(WARNING) << "snd_seq_unsubscribe_port fails: " << snd_strerror(err);
332 return;
333 }
334}
335
336void SeqHandler::UnsubscribeOutPort(int out_port_id) {
337 snd_seq_delete_simple_port(out_client_.get(), out_port_id);
338}
339
Prashant Malani3c540362017-09-28 13:35:14 -0700340bool SeqHandler::EncodeMidiBytes(int out_port_id,
341 snd_seq_t* out_client,
342 const uint8_t* buffer,
343 size_t buf_len,
344 snd_midi_event_t* encoder) {
345 if (buf_len == 0 || buf_len > kMaxBufSize) {
346 return false;
347 }
348
Prashant Malanifd1e2002017-08-09 13:22:59 -0700349 for (int i = 0; i < buf_len; i++) {
350 snd_seq_event_t event;
351 int result = snd_midi_event_encode_byte(encoder, buffer[i], &event);
Prashant Malani3c540362017-09-28 13:35:14 -0700352 if (result < 0) {
353 LOG(ERROR) << "Error snd_midi_event_encode_byte(): " << result;
354 return false;
355 }
Prashant Malanifd1e2002017-08-09 13:22:59 -0700356 if (result == 1) {
357 // Send the message.
358 snd_seq_ev_set_source(&event, out_port_id);
359 snd_seq_ev_set_subs(&event);
360 snd_seq_ev_set_direct(&event);
Prashant Malani3c540362017-09-28 13:35:14 -0700361 int expected_length = snd_seq_event_length(&event);
362 result = SndSeqEventOutputDirect(out_client, &event);
363 if (result != expected_length) {
Prashant Malanie6e6b272018-05-02 10:16:30 -0700364 LOG(WARNING) << "Error in snd_seq_event_output_direct(): " << result;
Prashant Malani3c540362017-09-28 13:35:14 -0700365 return false;
366 }
367 return true;
Prashant Malanifd1e2002017-08-09 13:22:59 -0700368 }
369 }
Prashant Malani3c540362017-09-28 13:35:14 -0700370
371 // If we reached here, something went wrong.
372 return false;
373}
374
375void SeqHandler::SendMidiData(int out_port_id,
376 const uint8_t* buffer,
377 size_t buf_len) {
Prashant Malanie6e6b272018-05-02 10:16:30 -0700378 std::vector<uint8_t> v(buffer, buffer + buf_len);
379 if (!midi::IsValidWebMIDIData(v)) {
380 LOG(WARNING) << "Received invalid MIDI Data.";
381 return;
382 }
383
Prashant Malani3c540362017-09-28 13:35:14 -0700384 snd_midi_event_t* encoder;
385 int ret = snd_midi_event_new(buf_len, &encoder);
386 if (ret != 0) {
387 LOG(ERROR) << "Error snd_midi_event_new(): " << ret;
388 return;
389 }
390 bool success =
391 EncodeMidiBytes(out_port_id, out_client_.get(), buffer, buf_len, encoder);
392 if (!success) {
Prashant Malanie6e6b272018-05-02 10:16:30 -0700393 LOG(WARNING) << "Failed to send MIDI data to output port: " << out_port_id;
Prashant Malani3c540362017-09-28 13:35:14 -0700394 }
Prashant Malanifd1e2002017-08-09 13:22:59 -0700395 snd_midi_event_free(encoder);
396}
397
398void SeqHandler::ProcessMidiEvent(snd_seq_event_t* event) {
399 uint32_t device_id = event->source.client;
400 uint32_t subdevice_num = event->source.port;
401
402 if (event->type == SND_SEQ_EVENT_SYSEX) {
403 // SysEX, so pass it through without decoding.
Prashant Malani3c540362017-09-28 13:35:14 -0700404 handle_rx_data_cb_.Run(0, device_id, subdevice_num,
Prashant Malanifd1e2002017-08-09 13:22:59 -0700405 static_cast<char*>(event->data.ext.ptr),
406 event->data.ext.len);
407 } else {
408 // Normal message, so decode and send.
409 unsigned char buf[12];
410 int64_t count =
411 snd_midi_event_decode(decoder_.get(), buf, sizeof(buf), event);
412 if (count <= 0) {
413 if (count != -ENOENT) {
414 LOG(ERROR) << "snd_midi_event_decoder failed: " << snd_strerror(count);
415 }
416 } else {
Prashant Malani3c540362017-09-28 13:35:14 -0700417 handle_rx_data_cb_.Run(0, device_id, subdevice_num,
418 reinterpret_cast<char*>(buf), count);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700419 }
420 }
421}
422
Prashant Malani3c540362017-09-28 13:35:14 -0700423int SeqHandler::SndSeqEventOutputDirect(snd_seq_t* out_client,
424 snd_seq_event_t* event) {
425 return snd_seq_event_output_direct(out_client, event);
426}
427
Prashant Malania9bbf542017-10-19 18:27:18 -0700428int SeqHandler::SndSeqEventInput(snd_seq_t* in_client, snd_seq_event_t** ev) {
429 return snd_seq_event_input(in_client, ev);
430}
431
432int SeqHandler::SndSeqEventInputPending(snd_seq_t* in_client,
433 int fetch_sequencer) {
434 return snd_seq_event_input_pending(in_client, fetch_sequencer);
435}
436
Prashant Malani8ca4ab32017-10-03 15:12:49 -0700437void SeqHandler::EnumerateExistingDevices() {
438 snd_seq_client_info_t* client_info;
439 snd_seq_client_info_alloca(&client_info);
440 snd_seq_port_info_t* port_info;
441 snd_seq_port_info_alloca(&port_info);
442
443 snd_seq_client_info_set_client(client_info, -1);
444 while (!snd_seq_query_next_client(in_client_.get(), client_info)) {
445 int device_id = snd_seq_client_info_get_client(client_info);
446 AddSeqDevice(device_id);
447
448 // Call AddSeqPort to make sure we "process" all the ports of a client.
449 // Note that currently we don't support the dynamic addition / deletion
450 // of ports.
451 snd_seq_port_info_set_client(port_info, device_id);
452 snd_seq_port_info_set_port(port_info, -1);
453 while (!snd_seq_query_next_port(in_client_.get(), port_info)) {
454 int port_id = snd_seq_port_info_get_port(port_info);
455 AddSeqPort(device_id, port_id);
456 }
457 }
458}
459
Prashant Malani78b59c32017-10-24 22:54:51 -0700460SeqHandler::ScopedMidiEventPtr SeqHandler::CreateMidiEvent(size_t buf_size) {
461 snd_midi_event_t* tmp = nullptr;
462 snd_midi_event_new(buf_size, &tmp);
463 ScopedMidiEventPtr ev(tmp);
464 tmp = nullptr;
465 snd_midi_event_no_status(ev.get(), 1);
466
467 return ev;
468}
469
Prashant Malanifd1e2002017-08-09 13:22:59 -0700470} // namespace midis