Debian Codegraph @

CorsixTH/Src/midi_player.h

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 #ifndef CORSIX_TH_MIDI_PLAYER_H
24 #define CORSIX_TH_MIDI_PLAYER_H
25
26 #include "config.h"
27
28 #ifdef WITH_MIDI_DEVICE
29 #include <rtmidi/RtMidi.h>
30
31 #include <atomic>
32 #include <climits>
33 #include <condition_variable>
34 #include <memory>
35 #include <optional>
36 #include <queue>
37 #include <string>
38 #include <thread>
39 #include <vector>
40
41 struct playback_state;
42
43 /**
44 * An index representing the virtual port
45 */
46 constexpr unsigned int midi_virtual_port_index = UINT_MAX;
47
48 /**
49 * The port name for the corsixth source
50 */
51 const char* const midi_external_port_name = "midi_out";
52
53 /**
54 * Holds a MIDI port open for the lifetime of the object and releases it after.
55 *
56 * Instances of this class must not out-live the midi_out they reference.
57 */
58 class open_midi_port {
59 public:
60 /**
61 * Open the given port on midi_out
62 * @param midi_out The midi library
63 * @param port The RtMidiOut port index, or midi_virtual_port_index for a
64 * virtual port.
65 */
66 open_midi_port(RtMidiOut& midi_out, unsigned int port)
67 : midi_out(midi_out), port(port) {
68 if (port == midi_virtual_port_index) {
69 midi_out.openVirtualPort(midi_external_port_name);
70 } else {
71 midi_out.openPort(port, midi_external_port_name);
72 }
73 }
74 open_midi_port(const open_midi_port&) = delete;
75 open_midi_port& operator=(const open_midi_port&) = delete;
76 open_midi_port(const open_midi_port&&) = delete;
77 open_midi_port& operator=(const open_midi_port&&) = delete;
78
79 /**
80 * Release the open port
81 */
82 ~open_midi_port() { midi_out.closePort(); }
83
84 /**
85 * True if the port is virtual (midi_virtual_port_index)
86 */
87 bool is_virtual() const { return port == midi_virtual_port_index; }
88
89 /**
90 * The owned port index
91 */
92 unsigned int get_port() const { return port; }
93
94 private:
95 /// Reference to MIDI API
96 RtMidiOut& midi_out;
97
98 /// Owned/opened port index
99 unsigned int port;
100 };
101
102 /**
103 * Commands between the midi_player and the playback thread
104 */
105 enum class player_command {
106 /// Stop MIDI playback
107 stop,
108
109 /// Pause MIDI playback with the intention to resume from the same point
110 pause,
111
112 /// Resume MIDI playback after pause
113 resume,
114
115 /// Adjust the master volume level, based on the currently set value in
116 /// midi_player
117 set_volume,
118
119 /// Continue processing as if there was no command
120 noop
121 };
122
123 /**
124 * A thread safe queue of player_command with optional blocking on pop
125 *
126 * For sharing commands between the playback thread and the main thread.
127 */
128 class player_command_queue {
129 public:
130 /**
131 * Push a command to the back of the queue
132 * @param command The command to push
133 */
134 void push(player_command command);
135
136 /**
137 * Pop a command off the queue
138 *
139 * Waits if the queue is empty and blocking is set to true.
140 * @param blocking Whether to block and wait for a command if the queue is
141 * empty
142 * @return The command at the front of the queue, or noop if the queue is
143 * empty.
144 */
145 player_command pop(bool blocking);
146
147 /**
148 * Empty the queue
149 */
150 void clear();
151
152 private:
153 /// Mutex to guard the queue
154 std::mutex mut{};
155
156 /// The queue
157 std::queue<player_command> queue{};
158
159 /// Condition to wait on when empty and notify when populated
160 std::condition_variable cv{};
161 };
162
163 /**
164 * Control class for playing MIDI
165 */
166 class midi_player {
167 public:
168 /**
169 * Initialize a connection on a given MIDI API and port for playing CorsixTH
170 * XMI files
171 *
172 * @param api The MIDI API to use, one of:
173 * \li <empty string> or "Native" - Any available API
174 * \li "ALSA" - Linux ALSA
175 * \li "JACK" - JACK on Linux and Unix where available
176 * \li "CoreMIDI" - MacOS CoreMIDI
177 * \li "Windows MM" - Windows MIDI Api
178 * \li "Web MIDI API" - Web MIDI API
179 * \li "Windows UWP" - Universal Windows Platform MIDI API (RtMidi 6+)
180 * \li "Android AMIDI" - Android MIDI API (AMIDI) (RtMidi 6+)
181 *
182 * Use media_player::api_list() to find the list available for the target
183 * device
184 *
185 * @param port_name The MIDI port name to connect to. Empty string will
186 * connect to any available port. A list can be obtained from
187 * midi_player::port_list(). The list depends on the selected api.
188 *
189 * @param use_master_volume_sysex If true volume is assigned using the master
190 * volume sysex sequence. If false then the volume is set by relatively
191 * adjusting the control volumes of each channel during playback. Many
192 * synthesizers do not support the master volume sysex.
193 */
194 midi_player(std::string_view api, std::string_view port_name,
195 bool use_master_volume_sysex);
196 midi_player(const midi_player&) = delete;
197 midi_player& operator=(const midi_player&) = delete;
198 ~midi_player();
199
200 /**
201 * List of available APIs on the target
202 */
203 static std::vector<std::string> api_list();
204
205 /**
206 * List of available port names for the current API
207 */
208 std::vector<std::string> port_list() const;
209
210 /**
211 * Change the currently connected port
212 *
213 * \see midi_player:port_list()
214 */
215 void set_port(std::string_view port_name);
216
217 /**
218 * Set the relative playback volume
219 * @param volume volume between 0 and 1
220 */
221 void set_volume(double volume);
222
223 /**
224 * Play the given XMI file
225 * @param xmi_data The raw bytes of the uncompressed XMI file
226 * @param xmi_length The length of the data
227 */
228 void play_xmi(const unsigned char* xmi_data, size_t xmi_length);
229
230 /**
231 * Stop the currently playing MIDI track
232 *
233 * Resets the MIDI device and stops the playback thread.
234 */
235 void stop();
236
237 /**
238 * Pause the currently playing MIDI track
239 */
240 void pause();
241
242 /**
243 * Resume the current MIDI track if paused
244 */
245 void resume();
246
247 private:
248 /**
249 * Open the first successful MIDI output port, or a virtual port if supported.
250 *
251 * It is assumed that midi_out_mutex is held by the caller.
252 */
253 void open_default_port();
254
255 /**
256 * Return true if the MIDI port is open both according to our code and the
257 * RtMidi library.
258 *
259 * \remark RtMidi isPortOpen always returns false on virtual ports. This
260 * method returns true if we expect a virtual port to be open.
261 */
262 bool is_port_open() const;
263
264 /**
265 * Setup the MIDI device for playback
266 *
267 * \remark Intended to be called from the playback thread
268 * @param state Playback data for the current song
269 */
270 static void init_playback(playback_state& state);
271
272 /**
273 * Play a MIDI song until completion or interruption by a stop command
274 *
275 * \remark Intended to be the target of the playback thread
276 * @param state Playback data for the current song
277 */
278 static void playback_loop(playback_state&& state);
279
280 /// The MIDI library
281 std::unique_ptr<RtMidiOut> midi_out;
282
283 /// Port currently in use if any
284 std::optional<open_midi_port> port;
285
286 /// The thread that runs the playback_loop while the MIDI is playing or paused
287 std::thread playback_thread{};
288
289 /// Queue for communicating between the main thread and the playback thread
290 player_command_queue command_queue{};
291
292 /// The currently assigned music volume
293 std::atomic<double> volume{1.0};
294
295 /// Whether to use sysex master volume, if true or control volume (CC 7), if
296 /// false
297 bool use_master_volume_sysex{false};
298
299 /// Mutex to prevent race conditions on access to midi_out
300 std::mutex midi_out_mutex{};
301 };
302
303 #else // WITH_MIDI_DEVICE
304
305 class midi_player {};
306
307 #endif // WITH_MIDI_DEVICE
308
309 #endif // CORSIX_TH_MIDI_PLAYER_H