Debian Codegraph @

dokidoki-support/mixer.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include "stb_vorbis.h"
6
7 //// Types, Constants, Globals ////////////////////////////////////////////////
8
9 typedef short sample_t;
10 typedef int calc_t;
11 #define SAMPLE_MIN (-0x8000)
12 #define SAMPLE_MAX 0x7FFF
13 #define PORTAUDIO_SAMPLE_TYPE paInt16
14 #define ALSA_SAMPLE_TYPE SND_PCM_FORMAT_S16
15
16 #define SAMPLE_RATE 44100
17 #define SAMPLE_TIME (1.0/SAMPLE_RATE)
18 #define CHANNELS 64
19 #define BUFFER_SIZE 256
20
21 typedef struct
22 {
23 size_t frames;
24 sample_t * samples;
25 } sound_data_t;
26
27 typedef struct
28 {
29 float volume[2];
30 } fade_t;
31
32 typedef struct
33 {
34 // shared
35 volatile int is_new;
36 const sound_data_t * volatile data;
37 int loop; // callback-only after init
38
39 volatile int new_fade_duration;
40 volatile fade_t new_fade;
41
42 // for use by callback only
43 size_t position;
44 int fade_duration;
45 int fade_remaining;
46 fade_t fade_start;
47 fade_t fade_end;
48 } channel_t;
49
50 static const char * error_string = NULL;
51
52 static int calc_buffer[BUFFER_SIZE * 2];
53
54 #define CHECK(condition, message) \
55 do \
56 { \
57 if(!(condition)) \
58 { \
59 if(message) \
60 error_string = message; \
61 return 0; \
62 } \
63 } while(0)
64
65 #define ERROR(message) CHECK(0, message)
66
67 //// Fades ////////////////////////////////////////////////////////////////////
68
69 static float interp(float t, float start, float end)
70 {
71 return (1-t) * start + t * end;
72 }
73
74 static void fade_interp(const channel_t * chan, fade_t *out)
75 {
76 const fade_t * start = &chan->fade_start;
77 const fade_t * end = &chan->fade_end;
78
79 float t = 1;
80
81 if(chan->fade_duration > 0)
82 t = 1 - (float)chan->fade_remaining / chan->fade_duration;
83
84 out->volume[0] = interp(t, start->volume[0], end->volume[0]);
85 out->volume[1] = interp(t, start->volume[1], end->volume[1]);
86 }
87
88 static void fade_init(fade_t * out)
89 {
90 out->volume[0] = 1;
91 out->volume[1] = 1;
92 }
93
94 //// Channels /////////////////////////////////////////////////////////////////
95
96 static channel_t channels[CHANNELS];
97
98 static int channel_is_valid(int channel)
99 {
100 return 0 <= channel && channel < CHANNELS;
101 }
102
103 static int channel_is_active(int channel)
104 {
105 assert(channel_is_valid(channel));
106 return channels[channel].data != NULL;
107 }
108
109 static void channel_stop(int channel)
110 {
111 assert(channel_is_valid(channel));
112 channels[channel].data = NULL;
113 }
114
115 static void channel_mix_into(int channel, calc_t * output,
116 size_t frame_count)
117 {
118 assert(channel_is_valid(channel));
119 assert(channel_is_active(channel));
120
121 int i;
122 channel_t * chan = &channels[channel];
123 const sound_data_t * data = chan->data;
124
125 if(chan->is_new)
126 {
127 chan->is_new = 0;
128 chan->position = 0;
129 chan->fade_duration = 0;
130 chan->fade_remaining = 0;
131 fade_init(&chan->fade_start);
132 fade_init(&chan->fade_end);
133 }
134
135 if(chan->new_fade_duration >= 0)
136 {
137 fade_t current;
138 fade_interp(chan, &current);
139 chan->fade_start = current;
140 chan->fade_end = chan->new_fade;
141 chan->fade_duration = chan->new_fade_duration;
142 chan->fade_remaining = chan->fade_duration;
143 chan->new_fade_duration = -1;
144 }
145
146 size_t position = chan->position;
147 size_t to_copy = data->frames - position;
148 if(to_copy > frame_count) to_copy = frame_count;
149
150 for(i = 0; i < to_copy; i++)
151 {
152 fade_t fade;
153 fade_interp(chan, &fade);
154
155 output[i*2] += data->samples[(position + i)*2] * fade.volume[0];
156 output[i*2+1] += data->samples[(position + i)*2+1] * fade.volume[1];
157
158 if(chan->fade_remaining > 0) chan->fade_remaining--;
159 }
160
161 chan->position = position + to_copy;
162
163 if(chan->position == data->frames)
164 {
165 // imprecise looping for now
166 if(chan->loop > 0)
167 {
168 chan->loop--;
169 if(chan->loop == 0)
170 channel_stop(channel);
171 else
172 chan->position = 0;
173 }
174 else
175 {
176 chan->position = 0;
177 }
178 }
179 }
180
181 //// General Audio ////////////////////////////////////////////////////////////
182
183 static void mix_into(sample_t * output, size_t frame_count)
184 {
185 memset(calc_buffer, 0, frame_count * 2 * sizeof(calc_t));
186
187 int c;
188 for(c = 0; c != CHANNELS; c++)
189 if(channel_is_active(c))
190 channel_mix_into(c, calc_buffer, frame_count);
191
192 int i;
193 for(i = 0; i != BUFFER_SIZE * 2; i++)
194 {
195 if(calc_buffer[i] <= SAMPLE_MIN)
196 output[i] = SAMPLE_MIN;
197 else if(calc_buffer[i] <= SAMPLE_MAX)
198 output[i] = calc_buffer[i];
199 else
200 output[i] = SAMPLE_MAX;
201 }
202 }
203
204 static int play_sound_effect(const sound_data_t * data, float left,
205 float right, int loop)
206 {
207 int c = 0;
208 while(c != CHANNELS && channel_is_active(c)) c++;
209 if(c == CHANNELS)
210 {
211 return -1;
212 }
213 else
214 {
215 channels[c].is_new = 1;
216 channels[c].loop = loop;
217
218 channels[c].new_fade.volume[0] = left;
219 channels[c].new_fade.volume[1] = right;
220 channels[c].new_fade_duration = 0;
221
222 // this marks the channel as ready, so after this the callback is free
223 // to jump on it
224 channels[c].data = data;
225
226 return c;
227 }
228 }
229
230 static void channel_fade_to(int channel, float duration, float left,
231 float right)
232 {
233 assert(channel_is_valid(channel));
234 if(channel_is_active(channel))
235 {
236 while(channels[channel].new_fade_duration >= 0)
237 /* wait for previous fade to be acknowledged */;
238
239 channels[channel].new_fade.volume[0] = left;
240 channels[channel].new_fade.volume[1] = right;
241 channels[channel].new_fade_duration = (int)(duration * SAMPLE_RATE);
242 }
243 }
244
245 //// Sound Data ///////////////////////////////////////////////////////////////
246
247 static sound_data_t * new_sound_data(size_t frames)
248 {
249 sound_data_t * data = (sound_data_t *)malloc(sizeof(sound_data_t));
250 data->frames = frames;
251 data->samples = (sample_t *)malloc(frames * sizeof(sample_t) * 2);
252 return data;
253 }
254
255 static void delete_sound_data(sound_data_t * data)
256 {
257 free(data->samples);
258 free(data);
259 }
260
261 //// WAV Loading //////////////////////////////////////////////////////////////
262
263 static unsigned char get_u8(FILE * file)
264 {
265 int n = fgetc(file);
266 return n == EOF ? 0 : (unsigned char)n;
267 }
268
269 static unsigned short get_u16(FILE * file)
270 {
271 unsigned n = get_u8(file);
272 return n + (get_u8(file) << 8);
273 }
274
275 static unsigned short get_s16(FILE * file)
276 {
277 return (signed short)get_u16(file);
278 }
279
280 static unsigned int get_u32(FILE * file)
281 {
282 unsigned n = get_u16(file);
283 return n + (get_u16(file) << 16);
284 }
285
286 static int get_chunk_id(const char * id, FILE * file)
287 {
288 size_t read;
289 char chunk_id[5];
290 chunk_id[4] = 0;
291 read = fread(chunk_id, 1, 4, file);
292 CHECK(read == 4 && strcmp(chunk_id, id) == 0, NULL);
293 return 1;
294 }
295
296 static sound_data_t * load_wav(const char * filename)
297 {
298 FILE * file = fopen(filename, "rb");
299 CHECK(file, "file not found");
300
301 char chunk_id[5];
302 chunk_id[4] = 0;
303
304 // read RIFF header
305 CHECK(get_chunk_id("RIFF", file), "didn't get expected \"RIFF\" chunk");
306 get_u32(file);
307 CHECK(get_chunk_id("WAVE", file), "didn't get expected \"WAVE\" type");
308
309 // read "fmt " chunk
310 CHECK(get_chunk_id("fmt ", file), "didn't get expected \"fmt \" chunk");
311 CHECK(get_u32(file) == 16, "unexpected \"fmt \" chunk size");
312 CHECK(get_u16(file) == 1, "unsupported compression type");
313 int channels = get_u16(file);
314 CHECK(channels == 1 || channels == 2, "unsupported number of channels");
315 CHECK(get_u32(file) == SAMPLE_RATE, "unsupported sample rate");
316 get_u32(file); // skip bytes per second
317 get_u16(file); // skip block align
318 int bits_per_sample = get_u16(file);
319 CHECK(bits_per_sample == 8 || bits_per_sample == 16,
320 "unsupported bits per sample");
321
322 // read "data" chunk
323 CHECK(get_chunk_id("data", file), "didn't get expected \"data\" chunk");
324 size_t size = get_u32(file);
325 size_t frames = size * 8 / bits_per_sample / channels; // two channels
326
327 sound_data_t * data = new_sound_data(frames);
328 sample_t * dest = data->samples;
329 sample_t * end = data->samples + frames * 2;
330
331 if(bits_per_sample == 8)
332 while(!feof(file) && !ferror(file) && dest != end)
333 {
334 sample_t sample = ((sample_t)get_u8(file) - 128) << 8;
335 *(dest++) = sample;
336 if(channels == 1) *(dest++) = sample;
337 }
338 else
339 while(!feof(file) && !ferror(file) && dest != end)
340 {
341 sample_t sample = get_s16(file);
342 *(dest++) = sample;
343 if(channels == 1) *(dest++) = sample;
344 }
345 if(dest != end)
346 {
347 delete_sound_data(data);
348 data = NULL;
349 ERROR("error or end of file before finished reading samples");
350 }
351
352 return data;
353 }
354
355 //// OGG Loading //////////////////////////////////////////////////////////////
356
357 static sound_data_t * load_ogg(const char * filename)
358 {
359 sound_data_t * data = new_sound_data(0);
360 int channels;
361 int ret = stb_vorbis_decode_filename(
362 (char *)filename,
363 &channels,
364 &data->samples);
365 if(channels != 2)
366 {
367 delete_sound_data(data);
368 data = NULL;
369 ERROR("only 2-channel ogg files are supported");
370 }
371 if(ret < 0)
372 {
373 delete_sound_data(data);
374 data = NULL;
375 ERROR("some sort of error in stb_vorbis_decode_filename");
376 }
377 data->frames = ret;
378
379 return data;
380 }
381
382 #if defined(DOKIDOKI_MACOSX) || defined(DOKIDOKI_MINGW)
383 //// Portaudio ////////////////////////////////////////////////////////////////
384
385 #include <portaudio.h>
386
387 #define PA_CHECK(error) \
388 do \
389 { \
390 PaError PA_CHECK__err = (error); \
391 if(PA_CHECK__err != paNoError) \
392 { \
393 error_string = Pa_GetErrorText(PA_CHECK__err); \
394 return 0; \
395 } \
396 } while(0)
397
398 static PaStream * stream = NULL;
399
400 static int callback(const void *input, void *output, unsigned long frame_count,
401 const PaStreamCallbackTimeInfo *time_info,
402 PaStreamCallbackFlags status_flags, void *unused)
403 {
404 mix_into((sample_t *)output, frame_count);
405 return paContinue;
406 }
407
408 static int init()
409 {
410 int c;
411 for(c = 0; c < CHANNELS; c++) channels[c].data = NULL;
412
413 PA_CHECK(Pa_Initialize());
414
415 PaError err;
416 err = Pa_OpenDefaultStream(&stream, 0, 2, PORTAUDIO_SAMPLE_TYPE,
417 SAMPLE_RATE, BUFFER_SIZE, callback, NULL);
418 if(err != paNoError)
419 {
420 Pa_Terminate();
421 PA_CHECK(err);
422 }
423
424 err = Pa_StartStream(stream);
425 if(err != paNoError)
426 {
427 Pa_Terminate();
428 PA_CHECK(err);
429 }
430
431 return 1;
432 }
433
434 static int uninit()
435 {
436 PA_CHECK(Pa_StopStream(stream));
437 PA_CHECK(Pa_CloseStream(stream));
438 PA_CHECK(Pa_Terminate());
439
440 return 1;
441 }
442
443 //// ALSA /////////////////////////////////////////////////////////////////////
444 #elif defined(DOKIDOKI_LINUX)
445
446 #define ALSA_CHECK(error) \
447 do \
448 { \
449 int ALSA_CHECK__err = (error); \
450 if(ALSA_CHECK__err < 0) \
451 { \
452 error_string = snd_strerror(ALSA_CHECK__err); \
453 return 0; \
454 } \
455 } while(0)
456
457 #include <alsa/asoundlib.h>
•458 #include <stdatomic.h>
459 #include <pthread.h>
460
461 static snd_pcm_t * sound_device = NULL;
462
•463 static pthread_t audio_thread;
464 static volatile atomic_flag running = ATOMIC_FLAG_INIT;
465
•466 static void* audio_loop(void *data)
467 {
468 sample_t buffer[BUFFER_SIZE*2];
469
•470 while(atomic_flag_test_and_set(&running))
471 {
472 mix_into(buffer, BUFFER_SIZE);
473 int err = snd_pcm_writei(sound_device, buffer, BUFFER_SIZE);
474 if(err < 0)
475 err = snd_pcm_recover(sound_device, err, 0);
476
477 if(err < 0)
478 break;
479 }
•480
481 return NULL;
482 }
483
484 static int init()
485 {
486 ALSA_CHECK(snd_pcm_open(&sound_device, "default", SND_PCM_STREAM_PLAYBACK, 0));
487
488 ALSA_CHECK(snd_pcm_set_params(sound_device,
489 ALSA_SAMPLE_TYPE, // format
490 SND_PCM_ACCESS_RW_INTERLEAVED, // access type
491 2, // channels
492 SAMPLE_RATE, // rate
493 1, // resample
494 (unsigned)((float)BUFFER_SIZE/SAMPLE_RATE*1000000*20))); // latency in us
495
496 ALSA_CHECK(snd_pcm_prepare(sound_device));
497
•498 atomic_flag_test_and_set(&running);
499 CHECK(pthread_create(&audio_thread, NULL, audio_loop, NULL) == 0, "error creating alsa thread");
500
501 return 1;
502 }
503
504 static int uninit()
505 {
•506 atomic_flag_clear(&running);
507 pthread_join(audio_thread, NULL);
508
509 ALSA_CHECK(snd_pcm_close(sound_device));
510 sound_device = NULL;
511
512 return 1;
513 }
514
515 //// No Audio /////////////////////////////////////////////////////////////////
516 #else
517
518 static int init()
519 {
520 return 1;
521 }
522
523 static int uninit()
524 {
525 return 1;
526 }
527
528 #endif
529
530 //// Lua //////////////////////////////////////////////////////////////////////
531
532 #include <lua.h>
533 #include <lualib.h>
534 #include <lauxlib.h>
535
536 #define LUA_CHECK(L, condition, message) \
537 do \
538 { \
539 if(!(condition)) \
540 { \
541 lua_pushnil(L); \
542 lua_pushstring(L, message); \
543 return 2; \
544 } \
545 } while(0)
546
547 #define LUA_ERROR(L, message) LUA_CHECK(L, 0, message)
548
549 static int mixer__initted = 0;
550
551 static void check_initted(lua_State *L)
552 {
553 if(!mixer__initted) luaL_error(L, "please call mixer.init() first");
554 }
555
556 static int mixer__init(lua_State *L)
557 {
558 if(!mixer__initted)
559 {
560 mixer__initted = init();
561 LUA_CHECK(L, mixer__initted, error_string);
562 }
563 lua_pushboolean(L, 1);
564 return 1;
565 }
566
567 static int mixer__uninit(lua_State *L)
568 {
569 if(mixer__initted)
570 {
571 mixer__initted = 0;
572 LUA_CHECK(L, uninit(), error_string);
573 }
574 lua_pushboolean(L, 1);
575 return 1;
576 }
577
578 static int generic_sound_loader(
579 lua_State *L,
580 sound_data_t * (*loader) (const char *filename))
581 {
582 const char * filename = luaL_checkstring(L, 1);
583 sound_data_t * sound = loader(filename);
584
585 if(sound == NULL)
586 {
587 lua_pushnil(L);
588 lua_pushstring(L, error_string);
589 return 2;
590 }
591 else
592 {
593 *(sound_data_t **)lua_newuserdata(L, sizeof(sound)) = sound;
594 luaL_getmetatable(L, "mixer.sound_effect");
595 lua_setmetatable(L, -2);
596 return 1;
597 }
598 }
599
600 static int mixer__load_wav(lua_State *L)
601 {
602 return generic_sound_loader(L, load_wav);
603 }
604
605 static int mixer__load_ogg(lua_State *L)
606 {
607 return generic_sound_loader(L, load_ogg);
608 }
609
610 static int mixer__channel_fade_to(lua_State *L)
611 {
612 check_initted(L);
613 int channel = luaL_checkint(L, 1);
614 float duration = luaL_checknumber(L, 2);
615 float left = luaL_checknumber(L, 3);
616 float right = luaL_optnumber(L, 4, left);
617
618 luaL_argcheck(L, channel_is_valid(channel), 1, "invalid channel given");
619 luaL_argcheck(L, duration >= 0, 1, "invalid duration given");
620
621 channel_fade_to(channel, duration, left, right);
622
623 return 0;
624 }
625
626 static int mixer__channel_stop(lua_State *L)
627 {
628 check_initted(L);
629 int channel = luaL_checkint(L, 1);
630
631 luaL_argcheck(L, channel_is_valid(channel), 1, "invalid channel given");
632
633 channel_stop(channel);
634
635 return 0;
636 }
637
638 static sound_data_t * check_sound_effect(lua_State *L, int index)
639 {
640 return *(sound_data_t **)luaL_checkudata(L, index, "mixer.sound_effect");
641 }
642
643 static int sound_effect__play(lua_State *L)
644 {
645 check_initted(L);
646 sound_data_t * sound = check_sound_effect(L, 1);
647 float left = luaL_optnumber(L, 2, 1.0);
648 float right = luaL_optnumber(L, 3, left);
649 int loop = luaL_optint(L, 4, 1);
650
651 int channel = play_sound_effect(sound, left, right, loop);
652
653 if(channel < 0)
654 lua_pushnil(L);
655 else
656 lua_pushnumber(L, channel);
657 return 1;
658 }
659
660 static const luaL_reg sound_effect_lib[] =
661 {
662 {"play", sound_effect__play},
663 {NULL, NULL}
664 };
665
666 static const luaL_Reg mixer_lib[] =
667 {
668 {"init", mixer__init},
669 {"uninit", mixer__uninit},
670 {"load_wav", mixer__load_wav},
671 {"load_ogg", mixer__load_ogg},
672 {"channel_fade_to", mixer__channel_fade_to},
673 {"channel_stop", mixer__channel_stop},
674 {NULL, NULL}
675 };
676
677 int luaopen_mixer(lua_State *L)
678 {
679 lua_newuserdata(L, 0);
680 lua_newtable(L);
681 lua_pushcfunction(L, mixer__uninit);
682 lua_setfield(L, -2, "__gc");
683 lua_setmetatable(L, -2);
684 lua_setfield(L, LUA_REGISTRYINDEX, "mixer.uninitializer");
685
686 luaL_newmetatable(L, "mixer.sound_effect");
687 lua_pushvalue(L, -1);
688 lua_setfield(L, -2, "__index");
689 luaL_register(L, NULL, sound_effect_lib);
690
691 lua_newtable(L);
692 luaL_register(L, NULL, mixer_lib);
693 return 1;
694 }
695