aboutsummaryrefslogtreecommitdiffstats
path: root/Alc/midi/fluidsynth.c
blob: 7461cc4e707f423bb0afa1046b8a8b9500a73265 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include "midi/base.h"

#include "alMain.h"
#include "alError.h"
#include "evtqueue.h"
#include "rwlock.h"
#include "alu.h"

#ifdef HAVE_FLUIDSYNTH

#include <fluidsynth.h>


/* MIDI events */
#define SYSEX_EVENT  (0xF0)

/* MIDI controllers */
#define CTRL_BANKSELECT_MSB  (0)
#define CTRL_BANKSELECT_LSB  (32)
#define CTRL_ALLNOTESOFF     (123)


typedef struct FSynth {
    DERIVE_FROM_TYPE(MidiSynth);

    fluid_settings_t *Settings;
    fluid_synth_t *Synth;
    int FontID;

    ALboolean ForceGM2BankSelect;
} FSynth;

static void FSynth_Construct(FSynth *self, ALCdevice *device);
static void FSynth_Destruct(FSynth *self);
static ALboolean FSynth_init(FSynth *self, ALCdevice *device);
static ALboolean FSynth_isSoundfont(FSynth *self, const char *filename);
static ALenum FSynth_loadSoundfont(FSynth *self, const char *filename);
static void FSynth_setGain(FSynth *self, ALfloat gain);
static void FSynth_setState(FSynth *self, ALenum state);
static void FSynth_stop(FSynth *self);
static void FSynth_reset(FSynth *self);
static void FSynth_update(FSynth *self, ALCdevice *device);
static void FSynth_processQueue(FSynth *self, ALuint64 time);
static void FSynth_process(FSynth *self, ALuint SamplesToDo, ALfloat (*restrict DryBuffer)[BUFFERSIZE]);
static void FSynth_Delete(FSynth *self);
DEFINE_MIDISYNTH_VTABLE(FSynth);


static void FSynth_Construct(FSynth *self, ALCdevice *device)
{
    MidiSynth_Construct(STATIC_CAST(MidiSynth, self), device);
    SET_VTABLE2(FSynth, MidiSynth, self);

    self->Settings = NULL;
    self->Synth = NULL;
    self->FontID = FLUID_FAILED;
    self->ForceGM2BankSelect = AL_FALSE;
}

static void FSynth_Destruct(FSynth *self)
{
    if(self->FontID != FLUID_FAILED)
        fluid_synth_sfunload(self->Synth, self->FontID, 0);
    self->FontID = FLUID_FAILED;

    if(self->Synth != NULL)
        delete_fluid_synth(self->Synth);
    self->Synth = NULL;

    if(self->Settings != NULL)
        delete_fluid_settings(self->Settings);
    self->Settings = NULL;

    MidiSynth_Destruct(STATIC_CAST(MidiSynth, self));
}

static ALboolean FSynth_init(FSynth *self, ALCdevice *device)
{
    self->Settings = new_fluid_settings();
    if(!self->Settings)
    {
        ERR("Failed to create FluidSettings\n");
        return AL_FALSE;
    }

    fluid_settings_setint(self->Settings, "synth.polyphony", 256);
    fluid_settings_setnum(self->Settings, "synth.sample-rate", device->Frequency);

    self->Synth = new_fluid_synth(self->Settings);
    if(!self->Synth)
    {
        ERR("Failed to create FluidSynth\n");
        return AL_FALSE;
    }

    return AL_TRUE;
}


static ALboolean FSynth_isSoundfont(FSynth *self, const char *filename)
{
    filename = MidiSynth_getFontName(STATIC_CAST(MidiSynth, self), filename);
    if(!filename[0]) return AL_FALSE;

    if(!fluid_is_soundfont(filename))
        return AL_FALSE;
    return AL_TRUE;
}

static ALenum FSynth_loadSoundfont(FSynth *self, const char *filename)
{
    int fontid;

    filename = MidiSynth_getFontName(STATIC_CAST(MidiSynth, self), filename);
    if(!filename[0]) return AL_INVALID_VALUE;

    fontid = fluid_synth_sfload(self->Synth, filename, 1);
    if(fontid == FLUID_FAILED)
    {
        ERR("Failed to load soundfont '%s'\n", filename);
        return AL_INVALID_VALUE;
    }

    if(self->FontID != FLUID_FAILED)
        fluid_synth_sfunload(self->Synth, self->FontID, 1);
    self->FontID = fontid;

    return AL_NO_ERROR;
}


static void FSynth_setGain(FSynth *self, ALfloat gain)
{
    /* Scale gain by an additional 0.2 (-14dB), to help keep the mix from clipping. */
    fluid_settings_setnum(self->Settings, "synth.gain", 0.2 * gain);
    fluid_synth_set_gain(self->Synth, 0.2f * gain);
    MidiSynth_setGain(STATIC_CAST(MidiSynth, self), gain);
}


static void FSynth_setState(FSynth *self, ALenum state)
{
    if(state == AL_PLAYING && self->FontID == FLUID_FAILED)
        FSynth_loadSoundfont(self, NULL);

    MidiSynth_setState(STATIC_CAST(MidiSynth, self), state);
}

static void FSynth_stop(FSynth *self)
{
    MidiSynth *synth = STATIC_CAST(MidiSynth, self);
    ALsizei chan;

    /* Make sure all pending events are processed. */
    while(!(synth->SamplesToNext >= 1.0))
    {
        ALuint64 time = synth->NextEvtTime;
        if(time == UINT64_MAX)
            break;

        synth->SamplesSinceLast -= (time - synth->LastEvtTime) * synth->SamplesPerTick;
        synth->SamplesSinceLast = maxd(synth->SamplesSinceLast, 0.0);
        synth->LastEvtTime = time;
        FSynth_processQueue(self, time);

        synth->NextEvtTime = MidiSynth_getNextEvtTime(synth);
        if(synth->NextEvtTime != UINT64_MAX)
            synth->SamplesToNext += (synth->NextEvtTime - synth->LastEvtTime) * synth->SamplesPerTick;
    }

    /* All notes off */
    for(chan = 0;chan < 16;chan++)
        fluid_synth_cc(self->Synth, chan, CTRL_ALLNOTESOFF, 0);

    MidiSynth_stop(STATIC_CAST(MidiSynth, self));
}

static void FSynth_reset(FSynth *self)
{
    /* Reset to power-up status. */
    fluid_synth_system_reset(self->Synth);

    MidiSynth_reset(STATIC_CAST(MidiSynth, self));
}


static void FSynth_update(FSynth *self, ALCdevice *device)
{
    fluid_settings_setnum(self->Settings, "synth.sample-rate", device->Frequency);
    fluid_synth_set_sample_rate(self->Synth, device->Frequency);
    MidiSynth_update(STATIC_CAST(MidiSynth, self), device);
}


static void FSynth_processQueue(FSynth *self, ALuint64 time)
{
    EvtQueue *queue = &STATIC_CAST(MidiSynth, self)->EventQueue;

    while(queue->pos < queue->size && queue->events[queue->pos].time <= time)
    {
        const MidiEvent *evt = &queue->events[queue->pos];

        if(evt->event == SYSEX_EVENT)
        {
            static const ALbyte gm2_on[] = { 0x7E, 0x7F, 0x09, 0x03 };
            static const ALbyte gm2_off[] = { 0x7E, 0x7F, 0x09, 0x02 };
            int handled = 0;

            fluid_synth_sysex(self->Synth, evt->param.sysex.data, evt->param.sysex.size, NULL, NULL, &handled, 0);
            if(!handled && evt->param.sysex.size >= (ALsizei)sizeof(gm2_on))
            {
                if(memcmp(evt->param.sysex.data, gm2_on, sizeof(gm2_on)) == 0)
                    self->ForceGM2BankSelect = AL_TRUE;
                else if(memcmp(evt->param.sysex.data, gm2_off, sizeof(gm2_off)) == 0)
                    self->ForceGM2BankSelect = AL_FALSE;
            }
        }
        else switch((evt->event&0xF0))
        {
            case AL_NOTEOFF_SOFT:
                fluid_synth_noteoff(self->Synth, (evt->event&0x0F), evt->param.val[0]);
                break;
            case AL_NOTEON_SOFT:
                fluid_synth_noteon(self->Synth, (evt->event&0x0F), evt->param.val[0], evt->param.val[1]);
                break;
            case AL_AFTERTOUCH_SOFT:
                break;

            case AL_CONTROLLERCHANGE_SOFT:
                if(self->ForceGM2BankSelect)
                {
                    int chan = (evt->event&0x0F);
                    if(evt->param.val[0] == CTRL_BANKSELECT_MSB)
                    {
                        if(evt->param.val[1] == 120 && (chan == 9 || chan == 10))
                            fluid_synth_set_channel_type(self->Synth, chan, CHANNEL_TYPE_DRUM);
                        else if(evt->param.val[1] == 121)
                            fluid_synth_set_channel_type(self->Synth, chan, CHANNEL_TYPE_MELODIC);
                        break;
                    }
                    if(evt->param.val[0] == CTRL_BANKSELECT_LSB)
                    {
                        fluid_synth_bank_select(self->Synth, chan, evt->param.val[1]);
                        break;
                    }
                }
                fluid_synth_cc(self->Synth, (evt->event&0x0F), evt->param.val[0], evt->param.val[1]);
                break;
            case AL_PROGRAMCHANGE_SOFT:
                fluid_synth_program_change(self->Synth, (evt->event&0x0F), evt->param.val[0]);
                break;

            case AL_CHANNELPRESSURE_SOFT:
                fluid_synth_channel_pressure(self->Synth, (evt->event&0x0F), evt->param.val[0]);
                break;

            case AL_PITCHBEND_SOFT:
                fluid_synth_pitch_bend(self->Synth, (evt->event&0x0F), (evt->param.val[0]&0x7F) |
                                                                       ((evt->param.val[1]&0x7F)<<7));
                break;
        }

        queue->pos++;
    }
}

static void FSynth_process(FSynth *self, ALuint SamplesToDo, ALfloat (*restrict DryBuffer)[BUFFERSIZE])
{
    MidiSynth *synth = STATIC_CAST(MidiSynth, self);
    ALenum state = synth->State;
    ALuint total = 0;

    if(state == AL_INITIAL)
        return;
    if(state != AL_PLAYING)
    {
        fluid_synth_write_float(self->Synth, SamplesToDo, DryBuffer[FrontLeft], 0, 1,
                                                          DryBuffer[FrontRight], 0, 1);
        return;
    }

    while(total < SamplesToDo)
    {
        if(synth->SamplesToNext >= 1.0)
        {
            ALuint todo = minu(SamplesToDo - total, fastf2u(synth->SamplesToNext));

            fluid_synth_write_float(self->Synth, todo,
                                    &DryBuffer[FrontLeft][total], 0, 1,
                                    &DryBuffer[FrontRight][total], 0, 1);
            total += todo;
            synth->SamplesSinceLast += todo;
            synth->SamplesToNext -= todo;
        }
        else
        {
            ALuint64 time = synth->NextEvtTime;
            if(time == UINT64_MAX)
            {
                synth->SamplesSinceLast += SamplesToDo-total;
                fluid_synth_write_float(self->Synth, SamplesToDo-total,
                                        &DryBuffer[FrontLeft][total], 0, 1,
                                        &DryBuffer[FrontRight][total], 0, 1);
                break;
            }

            synth->SamplesSinceLast -= (time - synth->LastEvtTime) * synth->SamplesPerTick;
            synth->SamplesSinceLast = maxd(synth->SamplesSinceLast, 0.0);
            synth->LastEvtTime = time;
            FSynth_processQueue(self, time);

            synth->NextEvtTime = MidiSynth_getNextEvtTime(synth);
            if(synth->NextEvtTime != UINT64_MAX)
                synth->SamplesToNext += (synth->NextEvtTime - synth->LastEvtTime) * synth->SamplesPerTick;
        }
    }
}


static void FSynth_Delete(FSynth *self)
{
    free(self);
}


MidiSynth *FSynth_create(ALCdevice *device)
{
    FSynth *synth = calloc(1, sizeof(*synth));
    if(!synth)
    {
        ERR("Failed to allocate FSynth\n");
        return NULL;
    }
    FSynth_Construct(synth, device);

    if(FSynth_init(synth, device) == AL_FALSE)
    {
        DELETE_OBJ(STATIC_CAST(MidiSynth, synth));
        return NULL;
    }

    return STATIC_CAST(MidiSynth, synth);
}

#else

MidiSynth *FSynth_create(ALCdevice* UNUSED(device))
{
    return NULL;
}

#endif