OpenTTD Source: src/music/fluidsynth.cpp Source File

OpenTTD Source 15.3

fluidsynth.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "../stdafx.h"
11
12#include "fluidsynth.h"
13
14#include <filesystem>
15#include <fluidsynth.h>
16#include <mutex>
17
18#include "../debug.h"
19#include "../mixer.h"
20#include "midifile.hpp"
21
22#include "../safeguards.h"
23
24static struct {
25 fluid_settings_t *settings;
26 fluid_synth_t *synth;
27 fluid_player_t *player;
28 std::mutex synth_mutex;
29} _midi;
30
32 static FMusicDriver_FluidSynth iFMusicDriver_FluidSynth;
33
35 static const char *_default_soundfonts[] = {
36 /* FluidSynth preferred */
37 /* See: https://www.fluidsynth.org/api/settings_synth.html#settings_synth_default-soundfont */
38 "/usr/share/soundfonts/default.sf2",
39
40 /* Debian/Ubuntu preferred */
41 /* See: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=929185 */
42 "/usr/share/sounds/sf3/default-GM.sf3",
43
44 /* OpenSUSE preferred */
45 "/usr/share/sounds/sf2/FluidR3_GM.sf2",
46
47 /* RedHat/Fedora/Arch preferred */
48 "/usr/share/soundfonts/FluidR3_GM.sf2",
49
50 /* Debian/Ubuntu/OpenSUSE alternatives */
51 "/usr/share/sounds/sf2/TimGM6mb.sf2",
52 "/usr/share/sounds/sf2/FluidR3_GS.sf2",
53};
54
55static void RenderMusicStream(int16_t *buffer, size_t samples)
56{
57 std::unique_lock<std::mutex> lock{_midi.synth_mutex, std::try_to_lock};
58
59 if (!lock.owns_lock() || _midi.synth == nullptr || _midi.player == nullptr) return;
60 fluid_synth_write_s16(_midi.synth, samples, buffer, 0, 2, buffer, 1, 2);
61}
62
63static void load_and_execute_config_file(fluid_cmd_handler_t *cmd_handler, const char *config_file)
64{
65 if (std::filesystem::exists(config_file)) {
66 Debug(driver, 2, "Fluidsynth: Attempting to load config file '{}'", config_file);
67 if (fluid_source(cmd_handler, config_file) < 0) {
68 Debug(driver, 0, "Fluidsynth: Failed to execute command configuration file '{}'", config_file);
69 }
70 } else {
71 Debug(driver, 1, "Fluidsynth: Failed to load config file '{}' - file doesn't exist", config_file);
72 }
73}
74
75std::optional<std::string_view> MusicDriver_FluidSynth::Start(const StringList &param)
76{
77 std::lock_guard<std::mutex> lock{_midi.synth_mutex};
78
79 auto sfont_name = GetDriverParam(param, "soundfont");
80 int sfont_id;
81
82 Debug(driver, 1, "Fluidsynth: sf {}", sfont_name.has_value() ? *sfont_name : "(null)");
83
84 /* Create the settings. */
85 _midi.settings = new_fluid_settings();
86 if (_midi.settings == nullptr) return "Could not create midi settings";
87
88 /* Read config file(s) */
89 fluid_cmd_handler_t *cmd_handler = new_fluid_cmd_handler2(_midi.settings, nullptr, nullptr, nullptr);
90 if (cmd_handler == NULL) return "Failed to create the early command handler";
91
92 char buf[MAX_PATH] = {};
93 const char *config_file = fluid_get_sysconf(buf, sizeof(buf)); // system-wide config file
94 load_and_execute_config_file(cmd_handler, config_file);
95 config_file = fluid_get_userconf(buf, sizeof(buf)); // user config file (potentially overrides system)
96 load_and_execute_config_file(cmd_handler, config_file);
97
98 delete_fluid_cmd_handler(cmd_handler);
99
100 /* Don't try to lock sample data in memory, OTTD usually does not run with privileges allowing that */
101 fluid_settings_setint(_midi.settings, "synth.lock-memory", 0);
102
103 /* Install the music render routine and set up the samplerate */
104 uint32_t samplerate = MxSetMusicSource(RenderMusicStream);
105 fluid_settings_setnum(_midi.settings, "synth.sample-rate", samplerate);
106 Debug(driver, 1, "Fluidsynth: samplerate {:.0f}", (float)samplerate);
107
108 /* Create the synthesizer. */
109 _midi.synth = new_fluid_synth(_midi.settings);
110 if (_midi.synth == nullptr) return "Could not open synth";
111
112 /* Load a SoundFont and reset presets (so that new instruments
113 * get used from the SoundFont) */
114 if (!sfont_name.has_value()) {
115 sfont_id = FLUID_FAILED;
116
117 /* Try loading the default soundfont registered with FluidSynth. */
118 char *default_soundfont = nullptr;
119 fluid_settings_dupstr(_midi.settings, "synth.default-soundfont", &default_soundfont);
120 if (default_soundfont != nullptr && std::filesystem::exists(default_soundfont) && fluid_is_soundfont(default_soundfont)) {
121 sfont_id = fluid_synth_sfload(_midi.synth, default_soundfont, 1);
122 }
123 fluid_free(default_soundfont);
124
125 /* If no default soundfont found, try our own list. */
126 if (sfont_id == FLUID_FAILED) {
127 for (const char *soundfont : _default_soundfonts) {
128 if (!std::filesystem::exists(soundfont) || !fluid_is_soundfont(soundfont)) continue;
129 sfont_id = fluid_synth_sfload(_midi.synth, soundfont, 1);
130 if (sfont_id != FLUID_FAILED) break;
131 }
132 }
133 if (sfont_id == FLUID_FAILED) return "Could not open any sound font";
134 } else {
135 std::string name{sfont_name.value()};
136 sfont_id = fluid_synth_sfload(_midi.synth, name.c_str(), 1);
137 if (sfont_id == FLUID_FAILED) return "Could not open sound font";
138 }
139
140 _midi.player = nullptr;
141
142 return std::nullopt;
143}
144
145 void MusicDriver_FluidSynth::Stop()
146{
147 MxSetMusicSource(nullptr);
148
149 std::lock_guard<std::mutex> lock{_midi.synth_mutex};
150
151 if (_midi.player != nullptr) delete_fluid_player(_midi.player);
152 _midi.player = nullptr;
153
154 if (_midi.synth != nullptr) delete_fluid_synth(_midi.synth);
155 _midi.synth = nullptr;
156
157 if (_midi.settings != nullptr) delete_fluid_settings(_midi.settings);
158 _midi.settings = nullptr;
159}
160
161 void MusicDriver_FluidSynth::PlaySong(const MusicSongInfo &song)
162{
163 std::string filename = MidiFile::GetSMFFile(song);
164
165 this->StopSong();
166
167 if (filename.empty()) {
168 return;
169 }
170
171 std::lock_guard<std::mutex> lock{_midi.synth_mutex};
172
173 _midi.player = new_fluid_player(_midi.synth);
174 if (_midi.player == nullptr) {
175 Debug(driver, 0, "Could not create midi player");
176 return;
177 }
178
179 if (fluid_player_add(_midi.player, filename.c_str()) != FLUID_OK) {
180 Debug(driver, 0, "Could not open music file");
181 delete_fluid_player(_midi.player);
182 _midi.player = nullptr;
183 return;
184 }
185 if (fluid_player_play(_midi.player) != FLUID_OK) {
186 Debug(driver, 0, "Could not start midi player");
187 delete_fluid_player(_midi.player);
188 _midi.player = nullptr;
189 return;
190 }
191}
192
193 void MusicDriver_FluidSynth::StopSong()
194{
195 std::lock_guard<std::mutex> lock{_midi.synth_mutex};
196
197 if (_midi.player == nullptr) return;
198
199 fluid_player_stop(_midi.player);
200 /* No fluid_player_join needed */
201 delete_fluid_player(_midi.player);
202 fluid_synth_system_reset(_midi.synth);
203 fluid_synth_all_sounds_off(_midi.synth, -1);
204 _midi.player = nullptr;
205}
206
207 bool MusicDriver_FluidSynth::IsSongPlaying()
208{
209 std::lock_guard<std::mutex> lock{_midi.synth_mutex};
210 if (_midi.player == nullptr) return false;
211
212 return fluid_player_get_status(_midi.player) == FLUID_PLAYER_PLAYING;
213}
214
215 void MusicDriver_FluidSynth::SetVolume(uint8_t vol)
216{
217 std::lock_guard<std::mutex> lock{_midi.synth_mutex};
218 if (_midi.settings == nullptr) return;
219
220 /* Allowed range of synth.gain is 0.0 to 10.0 */
221 /* fluidsynth's default gain is 0.2, so use this as "full
222 * volume". Set gain using OpenTTD's volume, as a number between 0
223 * and 0.2. */
224 double gain = (1.0 * vol) / (128.0 * 5.0);
225 if (fluid_settings_setnum(_midi.settings, "synth.gain", gain) != FLUID_OK) {
226 Debug(driver, 0, "Could not set volume");
227 }
228}
FMusicDriver_FluidSynth
Factory for the fluidsynth driver.
Definition fluidsynth.h:33
MusicDriver_FluidSynth::Start
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition fluidsynth.cpp:75
MusicDriver_FluidSynth::PlaySong
void PlaySong(const MusicSongInfo &song) override
Play a particular song.
Definition fluidsynth.cpp:161
MusicDriver_FluidSynth::IsSongPlaying
bool IsSongPlaying() override
Are we currently playing a song?
Definition fluidsynth.cpp:207
MusicDriver_FluidSynth::StopSong
void StopSong() override
Stop playing the current song.
Definition fluidsynth.cpp:193
MusicDriver_FluidSynth::SetVolume
void SetVolume(uint8_t vol) override
Set the volume, if possible.
Definition fluidsynth.cpp:215
MusicDriver_FluidSynth::Stop
void Stop() override
Stop this driver.
Definition fluidsynth.cpp:145
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
GetDriverParam
std::optional< std::string_view > GetDriverParam(const StringList &parm, std::string_view name)
Get a string parameter the list of parameters.
Definition driver.cpp:47
_midi
static struct @13 _midi
Metadata about the midi we're playing.
synth_mutex
std::mutex synth_mutex
Guard mutex for synth access.
Definition fluidsynth.cpp:28
iFMusicDriver_FluidSynth
static FMusicDriver_FluidSynth iFMusicDriver_FluidSynth
Factory for the FluidSynth driver.
Definition fluidsynth.cpp:32
_default_soundfonts
static const char * _default_soundfonts[]
List of sound fonts to try by default.
Definition fluidsynth.cpp:35
player
fluid_player_t * player
FluidSynth MIDI player handle.
Definition fluidsynth.cpp:27
synth
fluid_synth_t * synth
FluidSynth synthesizer handle.
Definition fluidsynth.cpp:26
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition fluidsynth.cpp:25
fluidsynth.h
Base for FluidSynth music playback.
MxSetMusicSource
uint32_t MxSetMusicSource(MxStreamCallback music_callback)
Set source of PCM music.
Definition mixer.cpp:234
StringList
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
MidiFile::GetSMFFile
static std::string GetSMFFile(const MusicSongInfo &song)
Get the name of a Standard MIDI File for a given song.
Definition midifile.cpp:1033
MusicSongInfo
Metadata about a music track.
Definition base_media_music.h:35
lock
std::mutex lock
synchronization for playback status fields
Definition win32_m.cpp:35