Debian Codegraph @

CorsixTH/Src/midi_player.cpp

raw
1 /*
2 Copyright (c) 2025 Stephen Baker
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "midi_player.h"
24
25 #include "config.h"
26
27 #include <SDL_events.h>
28
29 #include <algorithm>
30 #include <chrono>
31 #include <cstdio>
32 #include <queue>
33
34 #include "lua_sdl.h"
35 #include "xmi2mid.h"
36
37 #ifdef WITH_MIDI_DEVICE
38
39 namespace {
40
41 /**
42 * The MIDI application name. On some APIs this along with the port name is used
43 * to identify the source.
44 */
45 const std::string midi_application_name("corsixth");
46
47 /**
48 * The friendly name to use for the Virtual Port option in CorsixTH. This name
49 * is not passed to the MIDI APIs.
50 */
51 const char* const midi_virtual_port_name = "Virtual Port";
52
53 /**
54 * Number of MIDI channels. The MIDI 1.0 specification specifies 16.
55 */
56 constexpr unsigned int midi_channels = 16;
57
58 /**
59 * The maximum volume that can be set on in a MIDI channel message. The
60 * MIDI specification defines the channel volume ranges as 0-127.
61 */
62 constexpr uint8_t midi_max_channel_volume = 127;
63
64 /**
65 * Convert a string representation of a MIDI api to the matching RtMidi::Api
66 */
67 RtMidi::Api midi_api_from_string(std::string_view apiName) {
68 if (apiName.empty() || apiName == "Native") {
69 return RtMidi::UNSPECIFIED;
70 }
71 if (apiName == "ALSA") {
72 return RtMidi::LINUX_ALSA;
73 }
74 if (apiName == "JACK") {
75 return RtMidi::UNIX_JACK;
76 }
77 if (apiName == "CoreMIDI") {
78 return RtMidi::MACOSX_CORE;
79 }
80 if (apiName == "Windows MM") {
81 return RtMidi::WINDOWS_MM;
82 }
83 if (apiName == "Web MIDI API") {
84 return RtMidi::WEB_MIDI_API;
85 }
86 #if RTMIDI_MAJOR_VERSION > 5
87 if (apiName == "Windows UWP") {
88 return RtMidi::WINDOWS_UWP;
89 }
90 if (apiName == "Android AMidi") {
91 return RtMidi::ANDROID_AMIDI;
92 }
93 #endif
94 throw std::invalid_argument("Unknown API name");
95 }
96
97 /**
98 * Return whether the given RtMidi API supports the openVirtualPort method.
99 *
100 *\see https://caml.music.mcgill.ca/~gary/rtmidi/index.html#virtual
101 */
102 bool api_supports_virtual_port(RtMidi::Api api) {
103 switch (api) {
104 case RtMidi::MACOSX_CORE:
105 case RtMidi::LINUX_ALSA:
106 case RtMidi::UNIX_JACK:
107 return true;
108 default:
109 return false;
110 }
111 }
112
113 /**
114 * Send MIDI events to stop the currently playing audio.
115 *
116 * Sends three channel codes on all MIDI channels: all notes off, all sound off,
117 * and reset controllers. The song cannot be resumed from its current state
118 * because of the reset.
119 *
120 * \param midi_out The midi library
121 */
122 void send_stop_playback(RtMidiOut& midi_out) {
123 std::vector<uint8_t> buffer(3);
124 for (unsigned int channel = 0; channel < midi_channels; ++channel) {
125 buffer[0] = static_cast<unsigned char>(midi_event_control_change | channel);
126 buffer[2] = 0x00;
127
128 buffer[1] = midi_channel_code_all_notes_off;
129 midi_out.sendMessage(&buffer);
130
131 buffer[1] = midi_channel_code_all_sound_off;
132 midi_out.sendMessage(&buffer);
133
134 buffer[1] = midi_channel_code_reset_controllers;
135 midi_out.sendMessage(&buffer);
136 }
137 }
138
139 /**
140 * Send MIDI event to temporarily stop the currently playing audio.
141 *
142 * Uses a MIDI all note off control event on each channel to stop the currently
143 * playing note.
144 *
145 * \param midi_out The midi library
146 */
147 void send_all_notes_off(RtMidiOut& midi_out) {
148 std::vector<uint8_t> buffer(3);
149 for (unsigned int channel = 0; channel < midi_channels; ++channel) {
150 buffer[0] = static_cast<unsigned char>(midi_event_control_change | channel);
151 buffer[1] = midi_channel_code_all_notes_off;
152 buffer[2] = 0x00;
153
154 midi_out.sendMessage(&buffer);
155 }
156 }
157
158 /**
159 * Sends a message to enable GM mode.
160 *
161 * From the MIDI 1.0 Detailed Specification: General MIDI System Messages
162 */
163 void send_gsm_enable(RtMidiOut& midi_out) {
164 std::vector<unsigned char> buffer;
165 buffer.push_back(midi_event_sysex);
166 buffer.push_back(0x7E); // Non-realtime
167 buffer.push_back(0x7F); // All devices
168 buffer.push_back(0x09); // General MIDI
169 buffer.push_back(0x01); // Enable
170 buffer.push_back(midi_event_end_of_sysex);
171 midi_out.sendMessage(&buffer);
172 }
173
174 /**
175 * Sends the master volume level.
176 *
177 * From the MIDI 1.0 Detailed Specification: Device Control
178 * \param midi_out The MIDI output library
179 * \param volume The volume level, in the range 0.0 (silent) to 1.0 (maximum)
180 */
181 void send_master_volume(RtMidiOut& midi_out, double volume) {
182 // unsigned 14-bit max
183 constexpr int midi_max_master_volume = 16383;
184
185 uint16_t vol14bit =
186 std::clamp(static_cast<int>(volume * midi_max_master_volume), 0,
187 midi_max_master_volume);
188
189 std::vector<unsigned char> buffer;
190 buffer.push_back(midi_event_sysex);
191 buffer.push_back(0x7F); // Realtime
192 buffer.push_back(0x7F); // All devices
193 buffer.push_back(0x04); // Device Control
194 buffer.push_back(0x01); // Master Volume
195 buffer.push_back(vol14bit & 0x7F); // Volume (7 least significant bits)
196 buffer.push_back((vol14bit >> 7) & 0x7F); // Volume (7 most significant bits)
197 buffer.push_back(midi_event_end_of_sysex);
198
199 midi_out.sendMessage(&buffer);
200 }
201
202 /**
203 * Adjust all channel volumes relative to a given master sound volume level
204 *
205 * Calculates a channel control volume relative to the passed in channel volume
206 * using the provided master volume and sends a control message to the MIDI
207 * channels adjusting the volume.
208 *
209 * \param midi_out The midi output library
210 * \param channel_volumes The currently set unadjusted channel volumes from the
211 * midi track (between 0 and 127 per the MIDI spec).
212 * \param volume The target volume level between 0 and 1.
213 */
214 void send_control_change_volume(RtMidiOut& midi_out,
215 std::vector<uint8_t> channel_volumes,
216 double volume) {
217 if (channel_volumes.size() != midi_channels) {
218 throw std::invalid_argument("channel_volumes must have 16 elements");
219 }
220
221 std::vector<uint8_t> buffer(3);
222 for (unsigned int channel = 0; channel < midi_channels; ++channel) {
223 uint8_t vol7bit =
224 std::clamp(static_cast<int>(volume * channel_volumes[channel]), 0,
225 static_cast<int>(midi_max_channel_volume));
226 buffer[0] = static_cast<unsigned char>(midi_event_control_change | channel);
227 buffer[1] = midi_control_code_volume;
228 buffer[2] = vol7bit;
229
230 midi_out.sendMessage(&buffer);
231 }
232 }
233
234 /**
235 * Set the channel volume to a level proportional to the given master volume.
236 *
237 * This function is intended to be called before playback, during playback the
238 * song may have adjusted the volume of one or more channels which would sound
239 * off if reset to the master volume.
240 *
241 * \param midi_out The midi output library
242 * \param volume The master volume between 0 and 1
243 */
244 void send_control_change_volume(RtMidiOut& midi_out, double volume) {
245 send_control_change_volume(
246 midi_out, std::vector(midi_channels, midi_max_channel_volume), volume);
247 }
248
249 /**
250 * Send an SDL event indicating that the track is over
251 */
252 void midi_music_over_callback() {
253 SDL_Event e;
254 e.type = SDL_USEREVENT_MUSIC_OVER;
255 SDL_PushEvent(&e);
256 }
257
258 } // namespace
259
260 void player_command_queue::push(player_command cmd) {
261 std::unique_lock lock(mut);
262 queue.push(cmd);
263 cv.notify_one();
264 }
265
266 player_command player_command_queue::pop(bool blocking) {
267 std::unique_lock lock(mut);
268 while (blocking && queue.empty()) {
269 cv.wait(lock);
270 }
271 if (queue.empty()) {
272 return player_command::noop;
273 }
274 player_command cmd = queue.front();
275 queue.pop();
276 return cmd;
277 }
278
279 void player_command_queue::clear() {
280 std::unique_lock lock(mut);
281 while (!queue.empty()) {
282 queue.pop();
283 }
284 }
285
286 struct playback_state {
287 midi_player& player;
288 player_command_queue& command_queue;
289 midi_token_list events;
290
291 size_t current_event_index{0};
292
293 //! Start time, adjusted for any pauses
294 std::chrono::time_point<std::chrono::steady_clock> adjusted_start_time{
295 std::chrono::steady_clock::now()};
296
297 explicit playback_state(midi_player& player,
298 player_command_queue& command_queue,
299 midi_token_list&& events)
300 : player{player},
301 command_queue{command_queue},
302 events{std::move(events)} {}
303 };
304
305 midi_player::midi_player(std::string_view api, std::string_view device_name,
306 bool use_sysex_master_volume)
307 : midi_out{std::make_unique<RtMidiOut>(midi_api_from_string(api),
308 midi_application_name)},
309 use_master_volume_sysex{use_sysex_master_volume} {
310 set_port(device_name);
311 }
312
313 midi_player::~midi_player() { stop(); }
314
315 std::vector<std::string> midi_player::api_list() {
316 std::vector<RtMidi::Api> apis;
317 RtMidi::getCompiledApi(apis);
318
319 std::vector<std::string> apiStrings;
320 for (RtMidi::Api api : apis) {
321 switch (api) {
322 case RtMidi::LINUX_ALSA:
323 apiStrings.emplace_back("ALSA");
324 break;
325 case RtMidi::UNIX_JACK:
326 apiStrings.emplace_back("JACK");
327 break;
328 case RtMidi::MACOSX_CORE:
329 apiStrings.emplace_back("CoreMIDI");
330 break;
331 case RtMidi::WINDOWS_MM:
332 apiStrings.emplace_back("Windows MM");
333 break;
334 case RtMidi::WEB_MIDI_API:
335 apiStrings.emplace_back("Web MIDI API");
336 break;
337 #if RTMIDI_VERSION_MAJOR > 5
338 case RtMidi::WINDOWS_UWP:
339 apiStrings.emplace_back("Windows UWP");
340 break;
341 case RtMidi::ANDROID_AMIDI:
342 apiStrings.emplace_back("Android AMidi");
343 break;
344 #endif
345 case RtMidi::RTMIDI_DUMMY:
346 case RtMidi::UNSPECIFIED:
347 case RtMidi::NUM_APIS:
348 // These should not be selectable
349 break;
350 }
351 }
352
353 return apiStrings;
354 }
355
356 std::vector<std::string> midi_player::port_list() const {
357 unsigned int pc = midi_out->getPortCount();
358 std::vector<std::string> devices;
359 devices.reserve(pc);
360 for (unsigned int i = 0; i < pc; i++) {
361 devices.push_back(midi_out->getPortName(i));
362 }
363
364 // A few APIs support virtual ports, add those too
365 if (api_supports_virtual_port(midi_out->getCurrentApi())) {
366 devices.emplace_back(midi_virtual_port_name);
367 }
368
369 return devices;
370 }
371
372 void midi_player::set_port(std::string_view device_name) {
373 std::unique_lock lock(midi_out_mutex);
374 if (device_name.empty()) {
375 open_default_port();
376 return;
377 }
378 for (unsigned int i = 0; i < midi_out->getPortCount(); i++) {
379 if (midi_out->getPortName(i) == device_name) {
380 port.emplace(*midi_out, i);
381 return;
382 }
383 }
384 if (device_name == midi_virtual_port_name) {
385 port.emplace(*midi_out, midi_virtual_port_index);
386 return;
387 }
388 std::fprintf(stderr, "MIDI device not found: %s\n",
389 std::string(device_name).c_str());
390 }
391
392 void midi_player::play_xmi(const unsigned char* xmi_data, size_t xmi_length) {
393 if (!is_port_open()) {
394 std::fprintf(stderr, "No MIDI port is open for playback\n");
395 return;
396 }
397
398 uint32_t tempo;
399 midi_token_list events = xmi_to_midi_token_list(xmi_data, xmi_length, tempo);
400
401 playback_state song(*this, command_queue, std::move(events));
402 stop();
403 playback_thread = std::thread(playback_loop, std::move(song));
404 }
405
406 void midi_player::set_volume(double v) {
407 volume.store(v);
408 command_queue.push(player_command::set_volume);
409 }
410
411 void midi_player::stop() {
412 if (playback_thread.joinable()) {
413 command_queue.push(player_command::stop);
414 playback_thread.join();
415 }
416 command_queue.clear();
417
418 std::unique_lock lock(midi_out_mutex);
419 if (is_port_open()) {
420 send_stop_playback(*midi_out);
421 }
422 }
423
424 void midi_player::pause() { command_queue.push(player_command::pause); }
425
426 void midi_player::resume() { command_queue.push(player_command::resume); }
427
428 void midi_player::open_default_port() {
429 for (unsigned int i = 0; i < midi_out->getPortCount(); i++) {
430 try {
431 port.emplace(*midi_out, i);
432 return;
433 } catch (RtMidiError& err) {
434 // Ignore errors finding a port
435 std::fprintf(stderr, "Failed to open MIDI port %u: %s\n", i,
436 err.getMessage().c_str());
437 }
438 }
439 if (api_supports_virtual_port(midi_out->getCurrentApi())) {
440 try {
441 port.emplace(*midi_out, midi_virtual_port_index);
442 } catch (RtMidiError& err) {
443 std::fprintf(stderr, "Failed to open Virtual MIDI port: %s\n",
444 err.getMessage().c_str());
445 }
446 }
447 std::fprintf(stderr, "No suitable MIDI output port found\n");
448 }
449
450 bool midi_player::is_port_open() const {
451 return port.has_value() && (port->is_virtual() || midi_out->isPortOpen());
452 }
453
454 void midi_player::init_playback(playback_state& state) {
455 std::unique_lock lock(state.player.midi_out_mutex);
456
457 if (!state.player.is_port_open()) {
458 // Should not be possible due to checks before starting playback
459 throw std::runtime_error("MIDI port is not open for playback");
460 }
461
462 send_gsm_enable(*state.player.midi_out);
463
464 if (state.player.use_master_volume_sysex) {
465 send_master_volume(*state.player.midi_out, state.player.volume.load());
466 } else {
467 send_control_change_volume(*state.player.midi_out,
468 state.player.volume.load());
469 }
470
471 state.adjusted_start_time = std::chrono::steady_clock::now();
472 }
473
474 void midi_player::playback_loop(playback_state&& state) {
475 try {
476 init_playback(state);
477 } catch (std::exception& e) {
478 fprintf(stderr, "Aborting MIDI playback: %s", e.what());
479 return;
480 }
481
482 bool paused = false;
483 std::chrono::time_point<std::chrono::steady_clock> pause_time;
484 std::vector<unsigned char> msg_buffer;
485 std::vector channel_volumes(midi_channels, midi_max_channel_volume);
486 while (state.current_event_index < state.events.size()) {
487 // Block for commands if paused, otherwise just check for them
488 const player_command cmd = state.command_queue.pop(paused);
489
490 switch (cmd) {
491 case player_command::stop:
492 return;
493 case player_command::pause: {
494 paused = true;
495 pause_time = std::chrono::steady_clock::now();
496 std::unique_lock lock(state.player.midi_out_mutex);
497 send_all_notes_off(*state.player.midi_out);
498 } break;
499 case player_command::resume:
500 if (paused) {
501 paused = false;
502 auto pause_duration = std::chrono::steady_clock::now() - pause_time;
503 state.adjusted_start_time += pause_duration;
504 }
505 break;
506 case player_command::set_volume:
507 if (state.player.use_master_volume_sysex) {
508 send_master_volume(*state.player.midi_out,
509 state.player.volume.load());
510 } else {
511 send_control_change_volume(*state.player.midi_out, channel_volumes,
512 state.player.volume.load());
513 }
514 break;
515 case player_command::noop:
516 // No operation
517 break;
518 }
519
520 if (paused) {
521 continue;
522 }
523
524 const midi_token& event = state.events[state.current_event_index];
525 if (event.type == midi_event_meta &&
526 event.data == midi_meta_event_end_of_track) {
527 break;
528 }
529
530 std::chrono::microseconds event_time_microseconds{
531 static_cast<int64_t>(event.time * xmi_microseconds_per_tick)};
532
533 std::chrono::duration event_wait = state.adjusted_start_time -
534 std::chrono::steady_clock::now() +
535 event_time_microseconds;
536 if (event_wait.count() > 0) {
537 std::this_thread::sleep_for(event_wait);
538 }
539
540 if (event.type == midi_event_meta) {
541 // Skip meta events except end of track
542 state.current_event_index++;
543 continue;
544 }
545
546 msg_buffer.clear();
547 msg_buffer.push_back(event.type);
548 msg_buffer.push_back(event.data);
549 if (!event.buffer.empty()) {
550 msg_buffer.insert(msg_buffer.end(), event.buffer.begin(),
551 event.buffer.end());
552 }
553
554 // Adjust the volume defined in the MIDI track for the channel by the
555 // currently set player volume if not using sysex mode.
556 if ((event.type & 0xF0) == midi_event_control_change &&
557 event.data == midi_control_code_volume && msg_buffer.size() == 3 &&
558 !state.player.use_master_volume_sysex) {
559 // Store the raw channel volume in case the user changes the volume level
560 // while playing.
561 channel_volumes[event.type & 0x0F] = msg_buffer[2];
562 msg_buffer[2] = static_cast<uint8_t>(std::clamp(
563 static_cast<int>(msg_buffer[2] * state.player.volume.load()), 0,
564 static_cast<int>(midi_max_channel_volume)));
565 }
566
567 #ifdef MIDI_DEVICE_DEBUG
568 if ((event.type & 0xF0) != midi_event_note_on) {
569 std::printf("Midi event:");
570 for (auto b : msg_buffer) {
571 std::printf(" %02x", b);
572 }
573 std::printf("\n");
574 }
575 #endif
576
577 std::unique_lock lock(state.player.midi_out_mutex);
578 state.player.midi_out->sendMessage(&msg_buffer);
579 state.current_event_index++;
580 }
581
582 midi_music_over_callback();
583 }
584
585 #endif // WITH_MIDI_DEVICE