blob: 19af8fa5816b3581b9c10e2d63d341f74aa6ecde [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>
11
12#include <base/bind.h>
Prashant Malanifd1e2002017-08-09 13:22:59 -070013#include <poll.h>
14
Prashant Malani3c540362017-09-28 13:35:14 -070015#include "midis/constants.h"
16
Prashant Malanifd1e2002017-08-09 13:22:59 -070017namespace {
18
19const unsigned int kCreateInputPortCaps =
20 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_NO_EXPORT;
21const unsigned int kCreateOutputPortCaps =
22 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_NO_EXPORT;
23const unsigned int kCreatePortType =
24 SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION;
25const char kSndSeqName[] = "hw";
26
27} // namespace
28
29namespace midis {
30
Prashant Malani3c540362017-09-28 13:35:14 -070031SeqHandler::SeqHandler() : weak_factory_(this) {}
32
Prashant Malanifd1e2002017-08-09 13:22:59 -070033SeqHandler::SeqHandler(AddDeviceCallback add_device_cb,
34 RemoveDeviceCallback remove_device_cb,
35 HandleReceiveDataCallback handle_rx_data_cb,
36 IsDevicePresentCallback is_device_present_cb,
37 IsPortPresentCallback is_port_present_cb)
38 : add_device_cb_(add_device_cb),
39 remove_device_cb_(remove_device_cb),
40 handle_rx_data_cb_(handle_rx_data_cb),
41 is_device_present_cb_(is_device_present_cb),
42 is_port_present_cb_(is_port_present_cb),
43 weak_factory_(this) {}
44
45bool SeqHandler::InitSeq() {
46 // Create client handles.
47 snd_seq_t* tmp_seq = nullptr;
48 int err =
49 snd_seq_open(&tmp_seq, kSndSeqName, SND_SEQ_OPEN_INPUT, SND_SEQ_NONBLOCK);
50 if (err != 0) {
51 LOG(ERROR) << "snd_seq_open fails: " << snd_strerror(err);
52 return false;
53 }
54 ScopedSeqPtr in_client(tmp_seq);
55 tmp_seq = nullptr;
56 in_client_id_ = snd_seq_client_id(in_client.get());
57
58 err = snd_seq_open(&tmp_seq, kSndSeqName, SND_SEQ_OPEN_OUTPUT, 0);
59 if (err != 0) {
60 LOG(ERROR) << "snd_seq_open fails: " << snd_strerror(err);
61 return false;
62 }
63
64 ScopedSeqPtr out_client(tmp_seq);
65 tmp_seq = nullptr;
66 out_client_id_ = snd_seq_client_id(out_client.get());
67
68 // Name the clients.
69 err = snd_seq_set_client_name(in_client.get(), "midis (input)");
70 if (err != 0) {
71 LOG(ERROR) << "snd_seq_set_client_name fails: " << snd_strerror(err);
72 return false;
73 }
74 err = snd_seq_set_client_name(out_client.get(), "midis (output)");
75 if (err != 0) {
76 LOG(ERROR) << "snd_seq_set_client_name fails: " << snd_strerror(err);
77 return false;
78 }
79
80 // Create input port.
81 in_port_id_ = snd_seq_create_simple_port(
82 in_client.get(), NULL, kCreateInputPortCaps, kCreatePortType);
83 if (in_port_id_ < 0) {
84 LOG(ERROR) << "snd_seq_create_simple_port fails: "
85 << snd_strerror(in_port_id_);
86 return false;
87 }
88
89 // Subscribe to the announce port.
90 snd_seq_port_subscribe_t* subs;
91 snd_seq_port_subscribe_alloca(&subs);
92 snd_seq_addr_t announce_sender;
93 snd_seq_addr_t announce_dest;
94 announce_sender.client = SND_SEQ_CLIENT_SYSTEM;
95 announce_sender.port = SND_SEQ_PORT_SYSTEM_ANNOUNCE;
96 announce_dest.client = in_client_id_;
97 announce_dest.port = in_port_id_;
98 snd_seq_port_subscribe_set_sender(subs, &announce_sender);
99 snd_seq_port_subscribe_set_dest(subs, &announce_dest);
100 err = snd_seq_subscribe_port(in_client.get(), subs);
101 if (err != 0) {
102 LOG(ERROR) << "snd_seq_subscribe_port on the announce port fails: "
103 << snd_strerror(err);
104 return false;
105 }
106
107 // Initialize decoder.
108 snd_midi_event_t* tmp_decoder = nullptr;
109 snd_midi_event_new(0, &tmp_decoder);
110 ScopedMidiEventPtr decoder(tmp_decoder);
111 tmp_decoder = nullptr;
112 snd_midi_event_no_status(decoder.get(), 1);
113
114 in_client_.reset(in_client.release());
115 out_client_.reset(out_client.release());
116 decoder_.reset(decoder.release());
117
Prashant Malani8ca4ab32017-10-03 15:12:49 -0700118 EnumerateExistingDevices();
119
Prashant Malanifd1e2002017-08-09 13:22:59 -0700120 // Obtain the poll file descriptor to watch.
Ben Chand496e612017-09-29 00:20:50 -0700121 pfd_ = std::make_unique<pollfd>();
Prashant Malanifd1e2002017-08-09 13:22:59 -0700122 snd_seq_poll_descriptors(in_client_.get(), pfd_.get(), 1, POLLIN);
123
124 taskid_ = brillo::MessageLoop::current()->WatchFileDescriptor(
Prashant Malani3c540362017-09-28 13:35:14 -0700125 FROM_HERE, pfd_.get()->fd, brillo::MessageLoop::kWatchRead, true,
Prashant Malanifd1e2002017-08-09 13:22:59 -0700126 base::Bind(&SeqHandler::ProcessAlsaClientFd, weak_factory_.GetWeakPtr()));
127
128 if (taskid_ == brillo::MessageLoop::kTaskIdNull) {
129 in_client_.reset();
130 out_client_.reset();
131 decoder_.reset();
132 pfd_.reset();
133 return false;
134 }
135
136 return true;
137}
138
139void SeqHandler::ProcessAlsaClientFd() {
140 int remaining;
141 do {
142 snd_seq_event_t* event;
Prashant Malania9bbf542017-10-19 18:27:18 -0700143 int err = SndSeqEventInput(in_client_.get(), &event);
144 remaining = SndSeqEventInputPending(in_client_.get(), 0);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700145
146 if (err == -ENOSPC) {
147 // Handle out of space error.
148 LOG(ERROR) << "snd_seq_event_input detected buffer overrun";
149 // We've lost events: check another way to see if we need to shut
150 // down.
151 } else if (err == -EAGAIN) {
152 // We've read all the data.
153 } else if (err < 0) {
154 // Handle other errors.
155 LOG(ERROR) << "snd_seq_event_input fails: " << snd_strerror(err);
156 // TODO(pmalani): Stop the message loop here then.
157 } else if (event->source.client == SND_SEQ_CLIENT_SYSTEM &&
158 event->source.port == SND_SEQ_PORT_SYSTEM_ANNOUNCE) {
159 // Handle announce events.
160 switch (event->type) {
161 case SND_SEQ_EVENT_PORT_START:
162 // Don't use SND_SEQ_EVENT_CLIENT_START because the
163 // client name may not be set by the time we query
164 // it. It should be set by the time ports are made.
165 AddSeqDevice(event->data.addr.client);
166 AddSeqPort(event->data.addr.client, event->data.addr.port);
167 break;
168 case SND_SEQ_EVENT_CLIENT_EXIT:
169 // Check for disconnection of our "out" client. This means "shut
170 // down".
171 if (event->data.addr.client == out_client_id_) {
172 // TODO(pmalani): Stop the message loop here then.
173 remaining = 0;
174 } else {
175 RemoveSeqDevice(event->data.addr.client);
176 }
177 break;
178 case SND_SEQ_EVENT_PORT_EXIT:
179 RemoveSeqPort(event->data.addr.client, event->data.addr.port);
180 break;
181 }
182 } else {
183 // Normal operation.
184 ProcessMidiEvent(event);
185 }
186 } while (remaining > 0);
187}
188
189void SeqHandler::AddSeqDevice(uint32_t device_id) {
Prashant Malani3c540362017-09-28 13:35:14 -0700190 if (is_device_present_cb_.Run(0 /* TODO(pmalani): Remove card number */,
191 device_id)) {
Prashant Malanifd1e2002017-08-09 13:22:59 -0700192 LOG(INFO) << "Device: " << device_id << " already exists.";
193 return;
194 }
195
196 // Check that the device isn't our own in/our client.
197 if (device_id == in_client_id_ || device_id == out_client_id_) {
198 return;
199 }
200
201 snd_seq_client_info_t* client_info;
202 snd_seq_client_info_alloca(&client_info);
203 int err =
204 snd_seq_get_any_client_info(in_client_.get(), device_id, client_info);
205 if (err != 0) {
206 LOG(ERROR) << "Failed to get client info.";
207 return;
208 }
209
210 std::string name(snd_seq_client_info_get_name(client_info));
211 uint32_t num_subdevices = snd_seq_client_info_get_num_ports(client_info);
212
213 // Store the list of MIDI ports and corresponding capabilities in a map.
214 std::map<uint32_t, unsigned int> port_caps;
215 snd_seq_port_info_t* port_info;
216 snd_seq_port_info_alloca(&port_info);
217 snd_seq_port_info_set_client(port_info, device_id);
218 snd_seq_port_info_set_port(port_info, -1);
219 while (!snd_seq_query_next_port(in_client_.get(), port_info)) {
220 if (!(snd_seq_port_info_get_type(port_info) &
221 SND_SEQ_PORT_TYPE_MIDI_GENERIC)) {
222 LOG(INFO) << "Skipping non-MIDI port.";
223 continue;
224 }
225 port_caps.emplace(snd_seq_port_info_get_port(port_info),
226 snd_seq_port_info_get_capability(port_info));
227 }
228
Ben Chan2a3a8e32017-10-05 11:15:11 -0700229 auto dev = std::make_unique<Device>(
Prashant Malani3c540362017-09-28 13:35:14 -0700230 name, std::string(),
231 0 /* card number; TODO(pmalani) remove card number */, device_id,
232 num_subdevices, 0 /* device flags TODO(pmalani): flags not needed. */,
Prashant Malanifd1e2002017-08-09 13:22:59 -0700233 base::Bind(&SeqHandler::SubscribeInPort, base::Unretained(this)),
234 base::Bind(&SeqHandler::SubscribeOutPort, base::Unretained(this)),
235 base::Bind(&SeqHandler::UnsubscribeInPort, weak_factory_.GetWeakPtr()),
236 base::Bind(&SeqHandler::UnsubscribeOutPort, weak_factory_.GetWeakPtr()),
237 base::Bind(&SeqHandler::SendMidiData, weak_factory_.GetWeakPtr()),
238 std::move(port_caps));
239 add_device_cb_.Run(std::move(dev));
240}
241
242void SeqHandler::AddSeqPort(uint32_t device_id, uint32_t port_id) {
243 if (!is_port_present_cb_.Run(0, device_id, port_id)) {
244 LOG(WARNING) << "Received port start event for new port: " << port_id
245 << " on device: " << device_id << "; ignoring";
246 }
247}
248
249void SeqHandler::RemoveSeqDevice(uint32_t device_id) {
250 remove_device_cb_.Run(0 /* FIXME remove card number */, device_id);
251}
252
253void SeqHandler::RemoveSeqPort(uint32_t device_id, uint32_t port_id) {
254 if (!is_port_present_cb_.Run(0, device_id, port_id)) {
255 LOG(WARNING) << "Received port start event for new port: " << port_id
256 << " on device: " << device_id << "; ignoring";
257 }
258}
259
260bool SeqHandler::SubscribeInPort(uint32_t device_id, uint32_t port_id) {
261 snd_seq_port_subscribe_t* subs;
262 snd_seq_port_subscribe_alloca(&subs);
263 snd_seq_addr_t sender;
264 sender.client = device_id;
265 sender.port = port_id;
266 snd_seq_port_subscribe_set_sender(subs, &sender);
267
268 snd_seq_addr_t dest;
269 dest.client = in_client_id_;
270 dest.port = in_port_id_;
271 snd_seq_port_subscribe_set_dest(subs, &dest);
272
273 int err = snd_seq_subscribe_port(in_client_.get(), subs);
274 if (err != 0) {
275 LOG(ERROR) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
276 return false;
277 }
278
279 return true;
280}
281
282int SeqHandler::SubscribeOutPort(uint32_t device_id, uint32_t port_id) {
283 int out_port;
Prashant Malani3c540362017-09-28 13:35:14 -0700284 out_port = snd_seq_create_simple_port(out_client_.get(), NULL,
285 kCreateOutputPortCaps, kCreatePortType);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700286 if (out_port < 0) {
287 LOG(INFO) << "snd_seq_creat_simple_port (output) failed: "
288 << snd_strerror(out_port);
289 return -1;
290 }
291
292 snd_seq_port_subscribe_t* subs;
293 snd_seq_port_subscribe_alloca(&subs);
294 snd_seq_addr_t sender;
295 sender.client = out_client_id_;
296 sender.port = out_port;
297 snd_seq_port_subscribe_set_sender(subs, &sender);
298
299 snd_seq_addr_t dest;
300 dest.client = device_id;
301 dest.port = port_id;
302 snd_seq_port_subscribe_set_dest(subs, &dest);
303
304 int err = snd_seq_subscribe_port(out_client_.get(), subs);
305 if (err != 0) {
306 snd_seq_delete_simple_port(out_client_.get(), out_port);
307 LOG(ERROR) << "snd_seq_subscribe_port fails: " << snd_strerror(err);
308 return -1;
309 }
310
311 return out_port;
312}
313
314void SeqHandler::UnsubscribeInPort(uint32_t device_id, uint32_t port_id) {
315 snd_seq_port_subscribe_t* subs;
316 snd_seq_port_subscribe_alloca(&subs);
317 snd_seq_addr_t sender;
318 sender.client = device_id;
319 sender.port = port_id;
320 snd_seq_port_subscribe_set_sender(subs, &sender);
321 snd_seq_addr_t dest;
322 dest.client = in_client_id_;
323 dest.port = in_port_id_;
324 snd_seq_port_subscribe_set_dest(subs, &dest);
325
326 int err = snd_seq_unsubscribe_port(in_client_.get(), subs);
327 if (err != 0) {
328 LOG(WARNING) << "snd_seq_unsubscribe_port fails: " << snd_strerror(err);
329 return;
330 }
331}
332
333void SeqHandler::UnsubscribeOutPort(int out_port_id) {
334 snd_seq_delete_simple_port(out_client_.get(), out_port_id);
335}
336
Prashant Malani3c540362017-09-28 13:35:14 -0700337bool SeqHandler::EncodeMidiBytes(int out_port_id,
338 snd_seq_t* out_client,
339 const uint8_t* buffer,
340 size_t buf_len,
341 snd_midi_event_t* encoder) {
342 if (buf_len == 0 || buf_len > kMaxBufSize) {
343 return false;
344 }
345
Prashant Malanifd1e2002017-08-09 13:22:59 -0700346 for (int i = 0; i < buf_len; i++) {
347 snd_seq_event_t event;
348 int result = snd_midi_event_encode_byte(encoder, buffer[i], &event);
Prashant Malani3c540362017-09-28 13:35:14 -0700349 if (result < 0) {
350 LOG(ERROR) << "Error snd_midi_event_encode_byte(): " << result;
351 return false;
352 }
Prashant Malanifd1e2002017-08-09 13:22:59 -0700353 if (result == 1) {
354 // Send the message.
355 snd_seq_ev_set_source(&event, out_port_id);
356 snd_seq_ev_set_subs(&event);
357 snd_seq_ev_set_direct(&event);
Prashant Malani3c540362017-09-28 13:35:14 -0700358 int expected_length = snd_seq_event_length(&event);
359 result = SndSeqEventOutputDirect(out_client, &event);
360 if (result != expected_length) {
361 LOG(ERROR) << "Error in snd_seq_event_output_direct(): " << result;
362 return false;
363 }
364 return true;
Prashant Malanifd1e2002017-08-09 13:22:59 -0700365 }
366 }
Prashant Malani3c540362017-09-28 13:35:14 -0700367
368 // If we reached here, something went wrong.
369 return false;
370}
371
372void SeqHandler::SendMidiData(int out_port_id,
373 const uint8_t* buffer,
374 size_t buf_len) {
375 snd_midi_event_t* encoder;
376 int ret = snd_midi_event_new(buf_len, &encoder);
377 if (ret != 0) {
378 LOG(ERROR) << "Error snd_midi_event_new(): " << ret;
379 return;
380 }
381 bool success =
382 EncodeMidiBytes(out_port_id, out_client_.get(), buffer, buf_len, encoder);
383 if (!success) {
384 LOG(ERROR) << "Failed to send MIDI data to output port: " << out_port_id;
385 }
Prashant Malanifd1e2002017-08-09 13:22:59 -0700386 snd_midi_event_free(encoder);
387}
388
389void SeqHandler::ProcessMidiEvent(snd_seq_event_t* event) {
390 uint32_t device_id = event->source.client;
391 uint32_t subdevice_num = event->source.port;
392
393 if (event->type == SND_SEQ_EVENT_SYSEX) {
394 // SysEX, so pass it through without decoding.
Prashant Malani3c540362017-09-28 13:35:14 -0700395 handle_rx_data_cb_.Run(0, device_id, subdevice_num,
Prashant Malanifd1e2002017-08-09 13:22:59 -0700396 static_cast<char*>(event->data.ext.ptr),
397 event->data.ext.len);
398 } else {
399 // Normal message, so decode and send.
400 unsigned char buf[12];
401 int64_t count =
402 snd_midi_event_decode(decoder_.get(), buf, sizeof(buf), event);
403 if (count <= 0) {
404 if (count != -ENOENT) {
405 LOG(ERROR) << "snd_midi_event_decoder failed: " << snd_strerror(count);
406 }
407 } else {
Prashant Malani3c540362017-09-28 13:35:14 -0700408 handle_rx_data_cb_.Run(0, device_id, subdevice_num,
409 reinterpret_cast<char*>(buf), count);
Prashant Malanifd1e2002017-08-09 13:22:59 -0700410 }
411 }
412}
413
Prashant Malani3c540362017-09-28 13:35:14 -0700414int SeqHandler::SndSeqEventOutputDirect(snd_seq_t* out_client,
415 snd_seq_event_t* event) {
416 return snd_seq_event_output_direct(out_client, event);
417}
418
Prashant Malania9bbf542017-10-19 18:27:18 -0700419int SeqHandler::SndSeqEventInput(snd_seq_t* in_client, snd_seq_event_t** ev) {
420 return snd_seq_event_input(in_client, ev);
421}
422
423int SeqHandler::SndSeqEventInputPending(snd_seq_t* in_client,
424 int fetch_sequencer) {
425 return snd_seq_event_input_pending(in_client, fetch_sequencer);
426}
427
Prashant Malani8ca4ab32017-10-03 15:12:49 -0700428void SeqHandler::EnumerateExistingDevices() {
429 snd_seq_client_info_t* client_info;
430 snd_seq_client_info_alloca(&client_info);
431 snd_seq_port_info_t* port_info;
432 snd_seq_port_info_alloca(&port_info);
433
434 snd_seq_client_info_set_client(client_info, -1);
435 while (!snd_seq_query_next_client(in_client_.get(), client_info)) {
436 int device_id = snd_seq_client_info_get_client(client_info);
437 AddSeqDevice(device_id);
438
439 // Call AddSeqPort to make sure we "process" all the ports of a client.
440 // Note that currently we don't support the dynamic addition / deletion
441 // of ports.
442 snd_seq_port_info_set_client(port_info, device_id);
443 snd_seq_port_info_set_port(port_info, -1);
444 while (!snd_seq_query_next_port(in_client_.get(), port_info)) {
445 int port_id = snd_seq_port_info_get_port(port_info);
446 AddSeqPort(device_id, port_id);
447 }
448 }
449}
450
Prashant Malanifd1e2002017-08-09 13:22:59 -0700451} // namespace midis