DEADSOFTWARE

Minor formatting changes
[flatwaifu.git] / sound.c
1 #include "glob.h"
2 #include "files.h"
3 #include "sound.h"
4 #include <SDL.h>
5 #include <SDL_mixer.h>
7 #define NUM_CHANNELS 16
8 #define NUM_CHUNKS 300
10 short snd_vol = 50;
12 int snddisabled = 1;
14 struct {
15 snd_t *s;
16 Mix_Chunk *c;
17 } chunks[NUM_CHUNKS];
19 void S_init(void)
20 {
21 if (!SDL_WasInit(SDL_INIT_AUDIO)) {
22 if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
23 fprintf(stderr, "\nUnable to initialize audio: %s\n", SDL_GetError());
24 snddisabled=1;
25 return;
26 }
28 if (Mix_OpenAudio(22050, AUDIO_S16, 1, 1000) < 0) {
29 fprintf(stderr, "Error initializing SDL_mixer: %s\n", Mix_GetError());
30 snddisabled=1;
31 return;
32 }
34 if (Mix_AllocateChannels(NUM_CHANNELS)!=NUM_CHANNELS) {
35 fprintf(stderr, "Error allocation channels: %s\n", Mix_GetError());
36 snddisabled=1;
37 return;
38 }
39 }
41 int i;
42 for (i=0; i<NUM_CHUNKS; i++) {
43 chunks[i].s = NULL;
44 chunks[i].c = NULL;
45 }
47 snddisabled = (snd_vol==0);
49 S_volume(snd_vol);
50 }
52 void S_done(void)
53 {
54 free_chunks();
55 Mix_CloseAudio();
56 SDL_QuitSubSystem(SDL_INIT_AUDIO);
57 }
59 Mix_Chunk * get_chunk(snd_t *s, int r, int v)
60 {
61 int i, fi = -1;
62 for(i=0; i<NUM_CHUNKS; i++) {
63 if (chunks[i].s == s) return chunks[i].c;
64 if (chunks[i].s == NULL && fi==-1) fi = i;
65 }
67 if (fi==-1) return NULL;
69 Uint8 *data = (Uint8*)s+sizeof(snd_t);
70 Uint32 dlen = s->len;
71 SDL_AudioCVT cvt;
72 SDL_BuildAudioCVT(&cvt, AUDIO_S8, 1, s->rate, AUDIO_S16, 1, 22050);
73 if (!(cvt.buf = malloc(dlen*cvt.len_mult))) ERR_fatal("Out of memory\n");;
74 memcpy(cvt.buf, data, dlen);
75 cvt.len = dlen;
76 SDL_ConvertAudio(&cvt);
78 Mix_Chunk *chunk;
79 if (!(chunk = malloc(sizeof(Mix_Chunk)))) ERR_fatal("Out of memory\n");;
80 chunk->abuf=cvt.buf;
81 chunk->alen=cvt.len_cvt;
82 chunk->allocated=0;
83 chunk->volume=(float)v/255*SDL_MIX_MAXVOLUME;
85 chunks[fi].s = s;
86 chunks[fi].c = chunk;
88 return chunk;
89 }
91 void free_chunks()
92 {
93 if (snddisabled) return;
94 Mix_HaltChannel(-1);
95 int i;
96 for (i=0; i<NUM_CHUNKS; i++) {
97 if (chunks[i].c) {
98 free(chunks[i].c->abuf);
99 free(chunks[i].c);
100 chunks[i].c = NULL;
101 chunks[i].s = NULL;
106 short S_play(snd_t *s,short c,unsigned r,short v)
108 if (snddisabled) return 0;
109 Mix_Chunk *chunk = get_chunk(s,r,v);
110 if (chunk==NULL) return 0;
111 return Mix_PlayChannel(c, chunk, 0);
114 void S_stop(short c)
116 Mix_HaltChannel(c);
119 void S_volume(int v)
121 if (snddisabled) return;
122 snd_vol=v;
123 if (snd_vol>128) snd_vol=128;
124 if (snd_vol<0) snd_vol=0;
125 Mix_Volume(-1, snd_vol);
128 void S_wait()
130 if (snddisabled) return;
131 while (Mix_Playing(-1)) {
132 SDL_Delay(10);