support for fading music
[supertux.git] / src / audio / sound_manager.cpp
1 #include "sound_manager.hpp"
2
3 #include <stdexcept>
4 #include <iostream>
5 #include <sstream>
6 #include <memory>
7
8 #include "sound_file.hpp"
9 #include "sound_source.hpp"
10 #include "stream_sound_source.hpp"
11
12 SoundManager::SoundManager()
13   : device(0), context(0), sound_enabled(false), music_source(0),
14     next_music_source(0)
15 {
16   try {
17     device = alcOpenDevice(0);
18     if(device == 0) {
19       print_openal_version();
20       throw std::runtime_error("Couldn't open audio device.");
21     }
22
23     int attributes[] = { 0 };
24     context = alcCreateContext(device, attributes);
25     check_alc_error("Couldn't create audio context: ");
26     alcMakeContextCurrent(context);
27     check_alc_error("Couldn't select audio context: ");
28
29     check_al_error("Audio error after init: ");
30     sound_enabled = true;
31   } catch(std::exception& e) {
32     device = 0;
33     context = 0;
34     std::cerr << "Couldn't initialize audio device:" << e.what() << "\n";
35     print_openal_version();
36   }
37 }
38
39 SoundManager::~SoundManager()
40 {
41   delete music_source;
42   delete next_music_source;
43
44   for(SoundSources::iterator i = sources.begin(); i != sources.end(); ++i) {
45     delete *i;
46   }
47
48   for(SoundBuffers::iterator i = buffers.begin(); i != buffers.end(); ++i) {
49     ALuint buffer = i->second;
50     alDeleteBuffers(1, &buffer);
51   }
52
53   if(context != 0) {
54     alcMakeContextCurrent(0);
55     alcDestroyContext(context);
56   }
57   if(device != 0) {
58     alcCloseDevice(device);
59   }
60 }
61
62 ALuint
63 SoundManager::load_file_into_buffer(const std::string& filename)
64 {
65   // open sound file
66   std::auto_ptr<SoundFile> file (load_sound_file(filename));
67   
68   ALenum format = get_sample_format(file.get());
69   ALuint buffer;
70   alGenBuffers(1, &buffer);
71   check_al_error("Couldn't create audio buffer: ");
72   char* samples = new char[file->size];
73   try {
74     file->read(samples, file->size);
75     alBufferData(buffer, format, samples,
76         static_cast<ALsizei> (file->size),
77         static_cast<ALsizei> (file->rate));
78     check_al_error("Couldn't fill audio buffer: ");
79   } catch(...) {
80     delete[] samples;
81     throw;
82   }
83   delete[] samples;
84
85   return buffer;
86 }
87
88 SoundSource*
89 SoundManager::create_sound_source(const std::string& filename)
90 {
91   if(!sound_enabled)
92     return 0;
93
94   ALuint buffer;
95   
96   // reuse an existing static sound buffer            
97   SoundBuffers::iterator i = buffers.find(filename);
98   if(i != buffers.end()) {
99     buffer = i->second;
100   } else {
101     buffer = load_file_into_buffer(filename);
102     buffers.insert(std::make_pair(filename, buffer));
103   }
104   
105   SoundSource* source = new SoundSource();
106   alSourcei(source->source, AL_BUFFER, buffer);
107   return source;  
108 }
109
110 void
111 SoundManager::play(const std::string& filename, const Vector& pos)
112 {
113   try {
114     SoundSource* source = create_sound_source(filename);
115     if(source == 0)
116       return;
117     if(pos == Vector(-1, -1)) {
118       alSourcef(source->source, AL_ROLLOFF_FACTOR, 0);
119     } else {
120       source->set_position(pos);
121     }
122     source->play();
123     sources.push_back(source);
124   } catch(std::exception& e) {
125     std::cout << "Couldn't play sound " << filename << ": " << e.what() << "\n";
126   }
127 }
128
129 void
130 SoundManager::enable_sound(bool enable)
131 {
132   if(device == 0)
133     return;
134   sound_enabled = enable;
135 }
136
137 void
138 SoundManager::enable_music(bool enable)
139 {
140   if(device == 0)
141     return;
142   music_enabled = enable;
143   if(music_enabled) {
144     play_music(current_music);
145   } else {
146     if(music_source) {
147       delete music_source;
148       music_source = 0;
149     }
150   }
151 }
152
153 void
154 SoundManager::play_music(const std::string& filename, bool fade)
155 {
156   if(filename == current_music)
157     return;
158   current_music = filename;
159   if(!music_enabled)
160     return;
161
162   try {
163     StreamSoundSource* newmusic 
164       = new StreamSoundSource(load_sound_file(filename));
165
166     alSourcef(newmusic->source, AL_ROLLOFF_FACTOR, 0);
167  
168     if(fade) {
169       if(music_source)
170         music_source->setFading(StreamSoundSource::FadingOff, .25f);
171       delete next_music_source;
172       next_music_source = newmusic;
173     } else {
174       delete music_source;
175       music_source = newmusic;
176       music_source->play();
177       next_music_source = 0;
178     }
179   } catch(std::exception& e) {
180     std::cerr << "Couldn't play music file '" << filename << "': "
181       << e.what() << "\n";
182   }
183 }
184
185 void
186 SoundManager::set_listener_position(Vector pos)
187 {
188   alListener3f(AL_POSITION, pos.x, pos.y, 0);
189 }
190
191 void
192 SoundManager::set_listener_velocity(Vector vel)
193 {
194   alListener3f(AL_VELOCITY, vel.x, vel.y, 0);
195 }
196
197 void
198 SoundManager::update()
199 {
200   // check for finished sound sources
201   for(SoundSources::iterator i = sources.begin(); i != sources.end(); ) {
202     SoundSource* source = *i;
203     if(!source->playing()) {
204       delete source;
205       i = sources.erase(i);
206     } else {
207       ++i;
208     }
209   }
210   // check streaming sounds
211   if(music_source) {
212     music_source->update();
213   }
214   
215   if(next_music_source && !music_source || !music_source->playing()) {
216     delete music_source;
217     music_source = next_music_source;
218     //music_source->setFading(StreamSoundSource::FadingOn, 1.0f);
219     music_source->play();
220     next_music_source = 0;
221   }
222   
223   alcProcessContext(context);
224   check_alc_error("Error while processing audio context: ");
225 }
226
227 ALenum
228 SoundManager::get_sample_format(SoundFile* file)
229 {
230   if(file->channels == 2) {
231     if(file->bits_per_sample == 16) {
232       return AL_FORMAT_STEREO16;
233     } else if(file->bits_per_sample == 8) {
234       return AL_FORMAT_STEREO8;
235     } else {
236       throw std::runtime_error("Only 16 and 8 bit samples supported");
237     }
238   } else if(file->channels == 1) {
239     if(file->bits_per_sample == 16) {
240       return AL_FORMAT_MONO16;
241     } else if(file->bits_per_sample == 8) {
242       return AL_FORMAT_MONO8;
243     } else {
244       throw std::runtime_error("Only 16 and 8 bit samples supported");
245     }
246   }
247   
248   throw std::runtime_error("Only 1 and 2 channel samples supported");
249 }
250
251 void
252 SoundManager::print_openal_version()
253 {
254   std::cout << "OpenAL Vendor: " << alGetString(AL_VENDOR) << "\n"
255             << "OpenAL Version: " << alGetString(AL_VERSION) << "\n" 
256             << "OpenAL Renderer: " << alGetString(AL_RENDERER) << "\n"
257             << "OpenAl Extensions: " << alGetString(AL_RENDERER) << "\n";
258 }
259
260 void
261 SoundManager::check_alc_error(const char* message)
262 {
263   int err = alcGetError(device);
264   if(err != ALC_NO_ERROR) {
265     std::stringstream msg;
266     msg << message << alcGetString(device, err);
267     throw std::runtime_error(msg.str());
268   }                
269 }
270
271 void
272 SoundManager::check_al_error(const char* message)
273 {
274   int err = alGetError();
275   if(err != AL_NO_ERROR) {
276     std::stringstream msg;
277     msg << message << alGetString(err);
278     throw std::runtime_error(msg.str());
279   }  
280 }
281