summaryrefslogtreecommitdiff
path: root/music/extmidi.c
blob: d474b3acb3459168499ad0dd3ee503cb8e65ee4b (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
/* $Id$ */

#ifndef __MORPHOS__
#include "../stdafx.h"
#include "../openttd.h"
#include "../sound.h"
#include "../string.h"
#include "../variables.h"
#include "extmidi.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <errno.h>

static struct {
	char song[MAX_PATH];
	int pid;
} _midi;

static void DoPlay(void);
static void DoStop(void);

static const char* ExtMidiStart(const char* const * parm)
{
	_midi.song[0] = '\0';
	_midi.pid = -1;
	return NULL;
}

static void ExtMidiStop(void)
{
	_midi.song[0] = '\0';
	DoStop();
}

static void ExtMidiPlaySong(const char* filename)
{
	ttd_strlcpy(_midi.song, filename, lengthof(_midi.song));
	DoStop();
}

static void ExtMidiStopSong(void)
{
	_midi.song[0] = '\0';
	DoStop();
}

static bool ExtMidiIsPlaying(void)
{
	if (_midi.pid != -1 && waitpid(_midi.pid, NULL, WNOHANG) == _midi.pid)
		_midi.pid = -1;
	if (_midi.pid == -1 && _midi.song[0] != '\0') DoPlay();
	return _midi.pid != -1;
}

static void ExtMidiSetVolume(byte vol)
{
	fprintf(stderr, "extmidi: set volume not implemented\n");
}

static void DoPlay(void)
{
	_midi.pid = fork();
	switch (_midi.pid) {
		case 0: {
			int d;

			close(0);
			d = open("/dev/null", O_RDONLY);
			if (d != -1 && dup2(d, 1) != -1 && dup2(d, 2) != -1) {
				#if defined(MIDI_ARG)
					execlp(msf.extmidi, "extmidi", MIDI_ARG, _midi.song, (char*)0);
				#else
					execlp(msf.extmidi, "extmidi", _midi.song, (char*)0);
				#endif
			}
			_exit(1);
		}

		case -1:
			fprintf(stderr, "extmidi: couldn't fork: %s\n", strerror(errno));
			/* FALLTHROUGH */

		default:
			_midi.song[0] = '\0';
			break;
	}
}

static void DoStop(void)
{
	if (_midi.pid != -1) kill(_midi.pid, SIGTERM);
}

const HalMusicDriver _extmidi_music_driver = {
	ExtMidiStart,
	ExtMidiStop,
	ExtMidiPlaySong,
	ExtMidiStopSong,
	ExtMidiIsPlaying,
	ExtMidiSetVolume,
};

#endif /* __MORPHOS__ */