openMSX
MidiSessionALSA.cc
Go to the documentation of this file.
1#include "MidiSessionALSA.hh"
2#include "CliComm.hh"
3#include "MidiOutDevice.hh"
4#include "MidiInDevice.hh"
5#include "MidiInConnector.hh"
6#include "EventListener.hh"
7#include "EventDistributor.hh"
8#include "PlugException.hh"
10#include "Scheduler.hh"
11#include "narrow.hh"
12#include "serialize.hh"
13#include "circular_buffer.hh"
14#include "checked_cast.hh"
15#include <iostream>
16#include <memory>
17#include <thread>
18
19
20namespace openmsx {
21
22// MidiOutALSA ==============================================================
23
24class MidiOutALSA final : public MidiOutDevice {
25public:
27 snd_seq_t& seq,
28 snd_seq_client_info_t& cinfo, snd_seq_port_info_t& pinfo);
29 ~MidiOutALSA() override;
30 MidiOutALSA(const MidiOutALSA&) = delete;
32
33 // Pluggable
34 void plugHelper(Connector& connector, EmuTime::param time) override;
35 void unplugHelper(EmuTime::param time) override;
36 [[nodiscard]] std::string_view getName() const override;
37 [[nodiscard]] std::string_view getDescription() const override;
38
39 // MidiOutDevice
40 void recvMessage(
41 const std::vector<uint8_t>& message, EmuTime::param time) override;
42
43 template<typename Archive>
44 void serialize(Archive& ar, unsigned version);
45
46private:
47 void connect();
48 void disconnect();
49
50private:
51 snd_seq_t& seq;
52 snd_midi_event_t* event_parser;
53 int sourcePort = -1;
54 int destClient;
55 int destPort;
56 std::string name;
57 std::string desc;
58 bool connected = false;
59};
60
62 snd_seq_t& seq_,
63 snd_seq_client_info_t& cinfo, snd_seq_port_info_t& pinfo)
64 : seq(seq_)
65 , destClient(snd_seq_port_info_get_client(&pinfo))
66 , destPort(snd_seq_port_info_get_port(&pinfo))
67 , name(snd_seq_client_info_get_name(&cinfo))
68 , desc(snd_seq_port_info_get_name(&pinfo))
69{
70}
71
73{
74 if (connected) {
75 disconnect();
76 }
77}
78
79void MidiOutALSA::plugHelper(Connector& /*connector_*/, EmuTime::param /*time*/)
80{
81 connect();
82}
83
84void MidiOutALSA::unplugHelper(EmuTime::param /*time*/)
85{
86 disconnect();
87}
88
89void MidiOutALSA::connect()
90{
91 sourcePort = snd_seq_create_simple_port(
92 &seq, "MIDI out pluggable",
93 0, SND_SEQ_PORT_TYPE_MIDI_GENERIC);
94 if (sourcePort < 0) {
95 throw PlugException(
96 "Failed to create ALSA port: ", snd_strerror(sourcePort));
97 }
98
99 int err = snd_seq_connect_to(&seq, sourcePort, destClient, destPort);
100 if (err) {
101 snd_seq_delete_simple_port(&seq, sourcePort);
102 throw PlugException(
103 "Failed to connect to ALSA port "
104 "(", destClient, ':', destPort, ")"
105 ": ", snd_strerror(err));
106 }
107
108 snd_midi_event_new(MAX_MESSAGE_SIZE, &event_parser);
109
110 connected = true;
111}
112
113void MidiOutALSA::disconnect()
114{
115 snd_midi_event_free(event_parser);
116 snd_seq_disconnect_to(&seq, sourcePort, destClient, destPort);
117 snd_seq_delete_simple_port(&seq, sourcePort);
118
119 connected = false;
120}
121
122std::string_view MidiOutALSA::getName() const
123{
124 return name;
125}
126
127std::string_view MidiOutALSA::getDescription() const
128{
129 return desc;
130}
131
133 const std::vector<uint8_t>& message, EmuTime::param /*time*/)
134{
135 snd_seq_event_t ev;
136 snd_seq_ev_clear(&ev);
137
138 // Set routing.
139 snd_seq_ev_set_source(&ev, narrow_cast<uint8_t>(sourcePort));
140 snd_seq_ev_set_subs(&ev);
141
142 // Set message.
143 long encodeLen = snd_midi_event_encode(
144 event_parser, message.data(), narrow<long>(message.size()), &ev);
145 if (encodeLen < 0) {
146 std::cerr << "Error encoding MIDI message of type "
147 << std::hex << int(message[0]) << std::dec
148 << ": " << snd_strerror(narrow<int>(encodeLen)) << '\n';
149 return;
150 }
151 if (ev.type == SND_SEQ_EVENT_NONE) {
152 std::cerr << "Incomplete MIDI message of type "
153 << std::hex << int(message[0]) << std::dec << '\n';
154 return;
155 }
156
157 // Send event.
158 snd_seq_ev_set_direct(&ev);
159 int err = snd_seq_event_output(&seq, &ev);
160 if (err < 0) {
161 std::cerr << "Error sending MIDI event: "
162 << snd_strerror(err) << '\n';
163 }
164 snd_seq_drain_output(&seq);
165}
166
167template<typename Archive>
168void MidiOutALSA::serialize(Archive& /*ar*/, unsigned /*version*/)
169{
170 if constexpr (Archive::IS_LOADER) {
171 connect();
172 }
173}
176
177// MidiInALSA ==============================================================
178class MidiInALSA final : public MidiInDevice, private EventListener
179{
180public:
182 EventDistributor& eventDistributor, Scheduler& scheduler, snd_seq_t& seq,
183 snd_seq_client_info_t& cinfo, snd_seq_port_info_t& pinfo);
184 ~MidiInALSA() override;
185
186 // Pluggable
187 void plugHelper(Connector& connector, EmuTime::param time) override;
188 void unplugHelper(EmuTime::param time) override;
189 [[nodiscard]] std::string_view getName() const override;
190 [[nodiscard]] std::string_view getDescription() const override;
191
192 // MidiInDevice
193 void signal(EmuTime::param time) override;
194
195 template<typename Archive>
196 void serialize(Archive& ar, unsigned version);
197
198private:
199 void run();
200 void connect();
201 void disconnect();
202
203 // EventListener
204 int signalEvent(const Event& event) override;
205
206private:
207 EventDistributor& eventDistributor;
208 Scheduler& scheduler;
209 std::thread thread;
210 snd_seq_t& seq;
211 snd_midi_event_t* event_parser;
212 int destinationPort = -1;
213 int srcClient;
214 int srcPort;
215 std::string name;
216 std::string desc;
217 bool connected = false;
218 bool stop = false;
219 cb_queue<uint8_t> queue;
220 std::mutex mutex; // to protect queue
221};
222
224 EventDistributor& eventDistributor_,
225 Scheduler& scheduler_,
226 snd_seq_t& seq_,
227 snd_seq_client_info_t& cinfo, snd_seq_port_info_t& pinfo)
228 : eventDistributor(eventDistributor_)
229 , scheduler(scheduler_)
230 , seq(seq_)
231 , srcClient(snd_seq_port_info_get_client(&pinfo))
232 , srcPort(snd_seq_port_info_get_port(&pinfo))
233 , name(snd_seq_client_info_get_name(&cinfo))
234 , desc(snd_seq_port_info_get_name(&pinfo))
235{
236 eventDistributor.registerEventListener(EventType::MIDI_IN_ALSA, *this);
237 if ((snd_seq_port_info_get_capability(&pinfo) & (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE))) {
238 name.append(" (input)");
239 }
240}
241
243{
244 if (connected) {
245 disconnect();
246 }
247 eventDistributor.unregisterEventListener(EventType::MIDI_IN_ALSA, *this);
248}
249
250void MidiInALSA::plugHelper(Connector& connector_, EmuTime::param /*time*/)
251{
252 auto& midiConnector = checked_cast<MidiInConnector&>(connector_);
253 midiConnector.setDataBits(SerialDataInterface::DATA_8); // 8 data bits
254 midiConnector.setStopBits(SerialDataInterface::STOP_1); // 1 stop bit
255 midiConnector.setParityBit(false, SerialDataInterface::EVEN); // no parity
256
257 setConnector(&midiConnector); // base class will do this in a moment,
258 // but thread already needs it
259 connect();
260}
261
262void MidiInALSA::unplugHelper(EmuTime::param /*time*/)
263{
264 if (connected) {
265 disconnect();
266 }
267}
268
269void MidiInALSA::connect()
270{
271 destinationPort = snd_seq_create_simple_port(
272 &seq, "MIDI in pluggable",
273 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE, SND_SEQ_PORT_TYPE_MIDI_GENERIC);
274 if (destinationPort < 0) {
275 throw PlugException(
276 "Failed to create ALSA port: ", snd_strerror(destinationPort));
277 }
278
279 int err = snd_seq_connect_from(&seq, destinationPort, srcClient, srcPort);
280 if (err) {
281 snd_seq_delete_simple_port(&seq, destinationPort);
282 throw PlugException(
283 "Failed to connect to ALSA port "
284 "(", srcClient, ':', srcPort, ")"
285 ": ", snd_strerror(err));
286 }
287
288 snd_midi_event_new(MidiOutDevice::MAX_MESSAGE_SIZE, &event_parser);
289 snd_midi_event_no_status(event_parser, 1);
290
291 connected = true;
292 stop = false;
293
294 thread = std::thread([this]() { run(); });
295}
296
297void MidiInALSA::disconnect()
298{
299 stop = true;
300 thread.join();
301
302 snd_midi_event_free(event_parser);
303 snd_seq_disconnect_from(&seq, destinationPort, srcClient, srcPort);
304 snd_seq_delete_simple_port(&seq, destinationPort);
305
306 connected = false;
307}
308
309void MidiInALSA::run()
310{
311 assert(isPluggedIn());
312
313 auto npfd = snd_seq_poll_descriptors_count(&seq, POLLIN);
314 std::vector<struct pollfd> pfd(npfd);
315 snd_seq_poll_descriptors(&seq, pfd.data(), npfd, POLLIN);
316
317 while (!stop) {
318 if (poll(pfd.data(), npfd, 1000) > 0) {
319 snd_seq_event_t *ev = nullptr;
320 if (auto err = snd_seq_event_input(&seq, &ev); err < 0) {
321 std::cerr << "Error receiving MIDI event: "
322 << snd_strerror(err) << '\n';
323 continue;
324 }
325 if (!ev) continue;
326
327 if (ev->type == SND_SEQ_EVENT_SYSEX) {
328 std::lock_guard<std::mutex> lock(mutex);
329 for (auto i : xrange(ev->data.ext.len)) {
330 queue.push_back(static_cast<uint8_t*>(ev->data.ext.ptr)[i]);
331 }
332
333 } else {
334 std::array<uint8_t, 12> bytes = {};
335 auto size = snd_midi_event_decode(event_parser, bytes.data(), bytes.size(), ev);
336 if (size < 0) {
337 std::cerr << "Error decoding MIDI event: "
338 << snd_strerror(int(size)) << '\n';
339 snd_seq_free_event(ev);
340 continue;
341 }
342
343 std::lock_guard<std::mutex> lock(mutex);
344 for (auto i : xrange(size)) {
345 queue.push_back(bytes[i]);
346 }
347 }
348 snd_seq_free_event(ev);
349 eventDistributor.distributeEvent(MidiInALSAEvent());
350 }
351 }
352}
353
354void MidiInALSA::signal(EmuTime::param time)
355{
356 auto* conn = checked_cast<MidiInConnector*>(getConnector());
357 if (!conn->acceptsData()) {
358 std::lock_guard<std::mutex> lock(mutex);
359 queue.clear();
360 return;
361 }
362 if (!conn->ready()) return;
363
364 uint8_t data;
365 {
366 std::lock_guard<std::mutex> lock(mutex);
367 if (queue.empty()) return;
368 data = queue.pop_front();
369 }
370 conn->recvByte(data, time);
371}
372
373// EventListener
374int MidiInALSA::signalEvent(const Event& /*event*/)
375{
376 if (isPluggedIn()) {
377 signal(scheduler.getCurrentTime());
378 } else {
379 std::lock_guard<std::mutex> lock(mutex);
380 queue.clear();
381 }
382 return 0;
383}
384
385std::string_view MidiInALSA::getName() const
386{
387 return name;
388}
389
390std::string_view MidiInALSA::getDescription() const
391{
392 return desc;
393}
394
395template<typename Archive>
396void MidiInALSA::serialize(Archive& /*ar*/, unsigned /*version*/)
397{
398 if constexpr (Archive::IS_LOADER) {
399 connect();
400 }
401}
404
405
406// MidiSessionALSA ==========================================================
407
408std::unique_ptr<MidiSessionALSA> MidiSessionALSA::instance;
409
411 PluggingController& controller, CliComm& cliComm,
412 EventDistributor& eventDistributor, Scheduler& scheduler)
413{
414 if (!instance) {
415 // Open the sequencer.
416 snd_seq_t* seq;
417 int err = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0);
418 if (err < 0) {
419 cliComm.printError(
420 "Could not open sequencer: ", snd_strerror(err));
421 return;
422 }
423 snd_seq_set_client_name(seq, "openMSX");
424 instance.reset(new MidiSessionALSA(*seq));
425 }
426 instance->scanClients(controller, eventDistributor, scheduler);
427}
428
429MidiSessionALSA::MidiSessionALSA(snd_seq_t& seq_)
430 : seq(seq_)
431{
432}
433
435{
436 // While the Pluggables still have a copy of this pointer, they won't
437 // be accessing it anymore when openMSX is exiting.
438 snd_seq_close(&seq);
439}
440
441void MidiSessionALSA::scanClients(
442 PluggingController& controller,
443 EventDistributor& eventDistributor,
444 Scheduler& scheduler)
445{
446 // Iterate through all clients.
447 snd_seq_client_info_t* cInfo;
448 snd_seq_client_info_alloca(&cInfo);
449 snd_seq_client_info_set_client(cInfo, -1);
450 while (snd_seq_query_next_client(&seq, cInfo) >= 0) {
451 int client = snd_seq_client_info_get_client(cInfo);
452 if (client == SND_SEQ_CLIENT_SYSTEM) {
453 continue;
454 }
455
456 // TODO: When there is more than one usable port per client,
457 // register them as separate pluggables.
458 snd_seq_port_info_t* pInfo;
459 snd_seq_port_info_alloca(&pInfo);
460 snd_seq_port_info_set_client(pInfo, client);
461 snd_seq_port_info_set_port(pInfo, -1);
462 while (snd_seq_query_next_port(&seq, pInfo) >= 0) {
463 unsigned int type = snd_seq_port_info_get_type(pInfo);
464 if (!(type & SND_SEQ_PORT_TYPE_MIDI_GENERIC)) {
465 continue;
466 }
467 constexpr unsigned int wrCaps =
468 SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE;
469 constexpr unsigned int rdCaps =
470 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ;
471 if ((snd_seq_port_info_get_capability(pInfo) & wrCaps) == wrCaps) {
472 controller.registerPluggable(std::make_unique<MidiOutALSA>(
473 seq, *cInfo, *pInfo));
474 }
475 if ((snd_seq_port_info_get_capability(pInfo) & rdCaps) == rdCaps) {
476 controller.registerPluggable(std::make_unique<MidiInALSA>(
477 eventDistributor, scheduler, seq, *cInfo, *pInfo));
478 }
479 }
480 }
481}
482
483} // namespace openmsx
This implements a queue on top of circular_buffer (not part of boost).
bool empty() const
void push_back(U &&u)
void printError(std::string_view message)
Definition CliComm.cc:15
Represents something you can plug devices into.
Definition Connector.hh:21
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void distributeEvent(Event &&event)
Schedule the given event for delivery.
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
std::string_view getDescription() const override
Description for this pluggable.
void serialize(Archive &ar, unsigned version)
std::string_view getName() const override
Name used to identify this pluggable.
void plugHelper(Connector &connector, EmuTime::param time) override
MidiInALSA(EventDistributor &eventDistributor, Scheduler &scheduler, snd_seq_t &seq, snd_seq_client_info_t &cinfo, snd_seq_port_info_t &pinfo)
void unplugHelper(EmuTime::param time) override
void signal(EmuTime::param time) override
MidiOutALSA & operator=(const MidiOutALSA &)=delete
void serialize(Archive &ar, unsigned version)
MidiOutALSA(snd_seq_t &seq, snd_seq_client_info_t &cinfo, snd_seq_port_info_t &pinfo)
MidiOutALSA(const MidiOutALSA &)=delete
void plugHelper(Connector &connector, EmuTime::param time) override
std::string_view getName() const override
Name used to identify this pluggable.
void recvMessage(const std::vector< uint8_t > &message, EmuTime::param time) override
Called when a full MIDI message is ready to be sent.
void unplugHelper(EmuTime::param time) override
std::string_view getDescription() const override
Description for this pluggable.
Pluggable that connects an MSX MIDI out port to a host MIDI device.
static constexpr size_t MAX_MESSAGE_SIZE
The limit for the amount of data we'll put into one MIDI message.
Lists ALSA MIDI ports we can connect to.
static void registerAll(PluggingController &controller, CliComm &cliComm, EventDistributor &eventDistributor, Scheduler &scheduler)
Thrown when a plug action fails.
bool isPluggedIn() const
Returns true if this pluggable is currently plugged into a connector.
Definition Pluggable.hh:49
void setConnector(Connector *conn)
Definition Pluggable.hh:58
Connector * getConnector() const
Get the connector this Pluggable is plugged into.
Definition Pluggable.hh:43
Central administration of Connectors and Pluggables.
void registerPluggable(std::unique_ptr< Pluggable > pluggable)
Add a Pluggable to the registry.
EmuTime::param getCurrentTime() const
Get the current scheduler time.
Definition Scheduler.cc:84
This file implemented 3 utility functions:
Definition Autofire.cc:9
std::variant< KeyUpEvent, KeyDownEvent, MouseMotionEvent, MouseButtonUpEvent, MouseButtonDownEvent, MouseWheelEvent, JoystickAxisMotionEvent, JoystickHatEvent, JoystickButtonUpEvent, JoystickButtonDownEvent, OsdControlReleaseEvent, OsdControlPressEvent, WindowEvent, TextEvent, FileDropEvent, QuitEvent, FinishFrameEvent, CliCommandEvent, GroupEvent, BootEvent, FrameDrawnEvent, BreakEvent, SwitchRendererEvent, TakeReverseSnapshotEvent, AfterTimedEvent, MachineLoadedEvent, MachineActivatedEvent, MachineDeactivatedEvent, MidiInReaderEvent, MidiInWindowsEvent, MidiInCoreMidiEvent, MidiInCoreMidiVirtualEvent, MidiInALSAEvent, Rs232TesterEvent, Rs232NetEvent, ImGuiDelayedActionEvent, ImGuiActiveEvent > Event
Definition Event.hh:454
size_t size(std::string_view utf8)
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
#define REGISTER_POLYMORPHIC_INITIALIZER(BASE, CLASS, NAME)
constexpr auto xrange(T e)
Definition xrange.hh:132