summary refs log tree commit diff
path: root/src/modules/fluidsynth.c
blob: eeaa7959d71e1ff931428f92a530ccb6267c4880 (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
#include <stdio.h>
#include <stdlib.h>
#include "../include.h"

#include <fluidsynth.h>

static struct fluidsynth_userdata {
	fluid_settings_t *settings;
	fluid_synth_t *synth;
	int soundfont;
} *fs;


static void fluidsynth_callback(void *userdata, unsigned char *stream, int const length) {
	//fluid_player_t *player = userdata;
	(void) userdata;
	fluid_synth_write_float(fs->synth, length / sizeof (float) / 2, stream, 0, 2, stream, 1, 2);
}

static void fluidsynth_free(void *ptr) {
	fluid_player_t *player = ptr;
	fluid_player_stop(player);
	delete_fluid_player(player);
	//fluid_synth_all_notes_off(fs->synth, -1);
	fluid_synth_system_reset(fs->synth);
	#if 0
	fluid_synth_sfunload(fs->synth, fs->soundfont, 0);
	delete_fluid_synth(fs->synth);
	delete_fluid_settings(fs->settings);
	free(fs);
	#endif
}

int module_fluidsynth(struct blob *file, struct userdata *userdata) {
	if (fs == NULL) {
		fs = malloc(sizeof (struct fluidsynth_userdata));
		if (fs == NULL) {
			return 1;
		}
		fs->settings = new_fluid_settings(); // wasteful, but when trying to 'fix' it it just caused more errors
		fluid_settings_setnum(fs->settings, "synth.gain", 0.5);
		fluid_settings_setint(fs->settings, "player.reset-synth", 0);
		fluid_settings_setnum(fs->settings, "synth.sample-rate", SAMPLE_RATE);
		fs->synth = new_fluid_synth(fs->settings);
		char *soundfont_path = getenv("SOUNDFONT");
		if (soundfont_path == NULL) {
			soundfont_path = "/usr/share/sounds/sf2/default-GM.sf2";
		}
		fs->soundfont = fluid_synth_sfload(fs->synth, soundfont_path, 1); // ugly hack
	}
	fluid_player_t *player = new_fluid_player(fs->synth);
	fluid_player_set_loop(player, -1);
	if (fluid_player_add_mem(player, file->data, file->size) == FLUID_FAILED) {
		fluidsynth_free(fs);
		fs = NULL;
		return 1;
	}
	fluid_player_play(player);
	userdata->callback = fluidsynth_callback;
	userdata->user = player;
	userdata->freefunc = fluidsynth_free;
	return 0;
}