aboutsummaryrefslogtreecommitdiff
path: root/src/audio.c
blob: 82d70f905449959c1868d9e84a8aef551529c3b4 (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
/*
 * audio.c
 *
 * Sound stuff
 *
 * (c) 2008 Thomas White <taw27@cam.ac.uk>
 *
 *  thrust3d - a silly game
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/errno.h>
#include <SDL.h>
#include <SDL_audio.h>
#include <vorbis/vorbisfile.h>
#include <vorbis/codec.h>
#include <pthread.h>

#include "types.h"

static void audio_mix(void *data, Uint8 *stream8, int len) {

	AudioContext *a = data;
	int i, j, clip_count;
	Sint16 *stream = (Sint16 *)stream8;
	
	len /= 2;	/* Number of samples to write */
	
	/* Zero the buffer */
	for ( j=0; j<len; j++ ) {
		stream[j] = 0;
	}
	
	/* For each currently playing sound... */
	clip_count = 0;
	for ( i=0; i<AUDIO_MAX_SOUNDS; i++ ) {
		
		/* Playing? */
		if ( !a->sounds[i].playing ) continue;
		
		for ( j=0; j<len; j++ ) {
		
			Sint16 samp;
			Sint32 test;
			
			samp = a->sounds[i].data[a->sounds[i].dpos++];
			test = stream[j] + samp*a->sounds[i].volume;
			if ( test > 32767 ) {
				if ( stream[j] != 32767 ) {
					clip_count++;
				}
				stream[j] = 32767;
			} else {
				stream[j] += samp * a->sounds[i].volume;
			}
			
			if ( a->sounds[i].dpos == a->sounds[i].dlen ) {
				if ( a->sounds[i].repeat ) {
					a->sounds[i].dpos = 0;
					if ( a->debug ) printf("AU: Looping sound %i at buffer offset %i/%i\n", i, j, len);
				} else {
					a->sounds[i].inuse = 0;
					a->sounds[i].playing = 0;
					free(a->sounds[i].data);
					if ( a->debug ) printf("AU: End of sound %i\n", i);
					break;
				}
			}
		
		}
		
	}
	
	/* Fast ramp-up of volume when starting program, avoids 'click' */
	if ( a->startup ) {
		for ( j=0; j<len; j++ ) {
			stream[j] *= a->startup_volume;
			a->startup_volume += 0.001;
			if ( a->startup_volume > 1.0 ) {
				if ( a->debug && a->startup ) printf("AU: Finished startup ramp.\n");
				a->startup = 0;
				a->startup_volume = 1.0;
			}
		}
		
	}
	
	if ( a->debug && (clip_count > 0) ) printf("AU: Clipped %i samples.\n", clip_count);
	
}

static void audio_play_wav(AudioContext *a, char *filename, float volume, int repeat) {

	int idx;
	SDL_AudioSpec wave;
	Uint8 *data;
	Uint32 dlen;
	SDL_AudioCVT cvt;
	
	/* Look for an empty sound slot */
	for ( idx=0; idx<AUDIO_MAX_SOUNDS; idx++ ) {
		if ( !a->sounds[idx].inuse ) break;
	}
	if ( idx == AUDIO_MAX_SOUNDS ) {
		fprintf(stderr, "Not enough audio channels to play '%s'\n", filename);
		return;
	}
	a->sounds[idx].inuse = 1;
	if ( a->debug ) printf("AU: Selected channel %i for sound '%s'\n", idx, filename);
	
	/* Load the sound file and convert it to 16-bit stereo at 44.1 kHz */
	if ( SDL_LoadWAV(filename, &wave, &data, &dlen) == NULL ) {
		fprintf(stderr, "Couldn't load %s: %s\n", filename, SDL_GetError());
		return;
	}
	SDL_BuildAudioCVT(&cvt, wave.format, wave.channels, wave.freq, AUDIO_S16, 2, 44100);
	cvt.buf = malloc(dlen*cvt.len_mult);
	memcpy(cvt.buf, data, dlen);
	cvt.len = dlen;
	SDL_ConvertAudio(&cvt);
	SDL_FreeWAV(data);
	
	/* Put the sound data in the slot */
	SDL_LockAudio();
	a->sounds[idx].data = (Sint16 *)cvt.buf;
	a->sounds[idx].dlen = cvt.len_cvt / 2;
	a->sounds[idx].dpos = 0;
	a->sounds[idx].playing = 1;
	a->sounds[idx].repeat = repeat;
	a->sounds[idx].volume = volume;
	SDL_UnlockAudio();
	
}

static void *audio_play_vorbis(void *add_void) {

	AudioDispatchData *add = add_void;
	AudioContext *a = add->audiocontext;
	char *filename = add->filename;

	int idx;
	char *data;
	int len;
	OggVorbis_File vf;
	vorbis_info *vi;
	int finished, err, current_section;
	size_t offs;
	SDL_AudioCVT cvt;
	
	/* Look for an empty sound slot */
	for ( idx=0; idx<AUDIO_MAX_SOUNDS; idx++ ) {
		if ( !a->sounds[idx].inuse ) break;
	}
	if ( idx == AUDIO_MAX_SOUNDS ) {
		fprintf(stderr, "Not enough audio channels to play '%s'\n", filename);
		return NULL;
	}
	a->sounds[idx].inuse = 1;
	if ( a->debug ) printf("AU: Selected channel %i for sound '%s'\n", idx, filename);
	
	err = ov_fopen(filename, &vf);
	if ( err != 0 ) {
		fprintf(stderr, "Couldn't open Vorbis file '%s' (code %i,%i)\n", filename, err, errno);
		return NULL;
	}
	
	len = ov_pcm_total(&vf, -1);	/* Length in samples 'per channel' */
	if ( a->debug ) printf("AU: Length is %i samples 'per channel'\n", len);
	vi = ov_info(&vf,-1);
	if ( a->debug ) printf("AU: %i channels, %li Hz\n", vi->channels, vi->rate);
	data = malloc(vi->channels*2*len);	/* Two bytes per sample per channel */
	
	offs = 0;
	finished = 0;
	if ( a->debug ) printf("AU: Decoding Vorbis stream...\n");
	while ( finished == 0 ) {
		long rval;
		rval = ov_read(&vf, data+offs, 2*2*len, 0, 2, 1, &current_section);
		if ( rval == 0 ) {
			finished = 1;
		} else if ( rval < 0 ) {
			fprintf(stderr, "Vorbis stream error\n");
		} else {
			offs += rval;
		}
	}
	
	/* Convert to 44.1 kHz */
	SDL_BuildAudioCVT(&cvt, AUDIO_S16, vi->channels, vi->rate, AUDIO_S16, 2, 44100);
	cvt.buf = malloc(vi->channels*2*len*cvt.len_mult);
	memcpy(cvt.buf, data, vi->channels*2*len);
	cvt.len = vi->channels*2*len;
	SDL_ConvertAudio(&cvt);
	
	ov_clear(&vf);
	
	/* Put the sound data in the slot */
	SDL_LockAudio();
	a->sounds[idx].data = (Sint16 *)cvt.buf;
	a->sounds[idx].dlen = cvt.len_cvt / 2;
	a->sounds[idx].dpos = 0;
	a->sounds[idx].playing = 1;
	a->sounds[idx].repeat = add->repeat;
	a->sounds[idx].volume = add->volume;
	SDL_UnlockAudio();
	
	free(add->filename);
	free(add);
	if ( a->debug ) printf("AU: audio_play_vorbis dispatch thread completed.\n");
	return NULL;
	
}

void audio_play(AudioContext *a, char *name, float volume, int repeat) {

	char filename[128];
	struct stat statbuf;
	
	/* Try to find an Ogg/Vorbis file */
	snprintf(filename, 127, "%s%s.ogg", DATADIR"/sound/", name);
	if ( stat(filename, &statbuf) == 0 ) {
		
		int rval;
		AudioDispatchData *add;
		pthread_t thread;
		
		add = malloc(sizeof(AudioDispatchData));
		add->audiocontext = a;
		add->filename = strdup(filename);
		add->volume = volume;
		add->repeat = repeat;
		rval = pthread_create(&thread, NULL, audio_play_vorbis, add);
		if ( rval != 0 ) {
			fprintf(stderr, "Couldn't create audio dispatch thread (%i)\n", rval);
		}
		
		goto done;
		
	}
	
	/* Try to find a WAV file */
	snprintf(filename, 127, "%s%s.wav", DATADIR"/sound/", name);
	if ( stat(filename, &statbuf) == 0 ) {
		audio_play_wav(a, filename, volume, repeat);
		goto done;
	}
	
	/* Still not found */
	fprintf(stderr, "Couldn't find file for sound '%s'\n", name);
	return;
	
done:	/* Success */
	if ( a->paused == 1 ) {
		SDL_PauseAudio(0);
		a->paused = 0;
	}
	return;
		
}

/* SDL audio initial setup */
AudioContext *audio_setup(int debug) {
	
	AudioContext *a;
	SDL_AudioSpec fmt;
	int i;
	
	/* Create audio context */
	a = malloc(sizeof(AudioContext));
	if ( a == NULL ) return NULL;
	
	/* Initialise audio context */
	a->debug = debug;
	a->startup = 1;
	a->startup_volume = 0.0;
	a->paused = 1;
	for ( i=0; i<AUDIO_MAX_SOUNDS; i++ ) {
		a->sounds[i].inuse = 0;
		a->sounds[i].playing = 0;
	}
	
	/* 16-bit stereo audio at 44.1 kHz */
	fmt.freq = 44100;
	fmt.format = AUDIO_S16;
	fmt.channels = 2;
	fmt.samples = 512;
	fmt.callback = audio_mix;
	fmt.userdata = a;
	fmt.silence = 0;
	
	if ( SDL_OpenAudio(&fmt, NULL) < 0 ) {
		fprintf(stderr, "Unable to open audio: %s\n", SDL_GetError());
		free(a);
		return NULL;
	}
	
	audio_play(a, "kraftwerk", 0.5, 1);
	audio_play(a, "moan", 0.2, 1);
	
	return a;
	
}

void audio_shutdown(AudioContext *ctx) {
	SDL_CloseAudio();
	free(ctx);
}